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.

278540 lines
7.5MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC || JUCE_IOS
  76. #if defined (DEBUG) || defined (_DEBUG) || ! (defined (NDEBUG) || defined (_NDEBUG))
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #if ! (defined (DEBUG) || defined (_DEBUG) || defined (NDEBUG) || defined (_NDEBUG))
  80. #warning "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build,"
  81. #endif
  82. #ifdef __LITTLE_ENDIAN__
  83. #define JUCE_LITTLE_ENDIAN 1
  84. #else
  85. #define JUCE_BIG_ENDIAN 1
  86. #endif
  87. #endif
  88. #if JUCE_MAC
  89. #if defined (__ppc__) || defined (__ppc64__)
  90. #define JUCE_PPC 1
  91. #else
  92. #define JUCE_INTEL 1
  93. #endif
  94. #ifdef __LP64__
  95. #define JUCE_64BIT 1
  96. #else
  97. #define JUCE_32BIT 1
  98. #endif
  99. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  100. #error "Building for OSX 10.3 is no longer supported!"
  101. #endif
  102. #ifndef MAC_OS_X_VERSION_10_5
  103. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  104. #endif
  105. #endif
  106. #if JUCE_LINUX
  107. #ifdef _DEBUG
  108. #define JUCE_DEBUG 1
  109. #endif
  110. // Allow override for big-endian Linux platforms
  111. #ifndef JUCE_BIG_ENDIAN
  112. #define JUCE_LITTLE_ENDIAN 1
  113. #endif
  114. #if defined (__LP64__) || defined (_LP64)
  115. #define JUCE_64BIT 1
  116. #else
  117. #define JUCE_32BIT 1
  118. #endif
  119. #define JUCE_INTEL 1
  120. #endif
  121. // Compiler type macros.
  122. #ifdef __GNUC__
  123. #define JUCE_GCC 1
  124. #elif defined (_MSC_VER)
  125. #define JUCE_MSVC 1
  126. #if _MSC_VER < 1500
  127. #define JUCE_VC8_OR_EARLIER 1
  128. #if _MSC_VER < 1400
  129. #define JUCE_VC7_OR_EARLIER 1
  130. #if _MSC_VER < 1300
  131. #define JUCE_VC6 1
  132. #endif
  133. #endif
  134. #endif
  135. #if ! JUCE_VC7_OR_EARLIER
  136. #define JUCE_USE_INTRINSICS 1
  137. #endif
  138. #else
  139. #error unknown compiler
  140. #endif
  141. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  142. /*** End of inlined file: juce_TargetPlatform.h ***/
  143. // FORCE_AMALGAMATOR_INCLUDE
  144. /*** Start of inlined file: juce_Config.h ***/
  145. #ifndef __JUCE_CONFIG_JUCEHEADER__
  146. #define __JUCE_CONFIG_JUCEHEADER__
  147. /*
  148. This file contains macros that enable/disable various JUCE features.
  149. */
  150. /** The name of the namespace that all Juce classes and functions will be
  151. put inside. If this is not defined, no namespace will be used.
  152. */
  153. #ifndef JUCE_NAMESPACE
  154. #define JUCE_NAMESPACE juce
  155. #endif
  156. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  157. project settings, but if you define this value, you can override this to force
  158. it to be true or false.
  159. */
  160. #ifndef JUCE_FORCE_DEBUG
  161. //#define JUCE_FORCE_DEBUG 0
  162. #endif
  163. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  164. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  165. Enabling it will also leave this turned on in release builds. When it's disabled,
  166. however, the jassert and jassertfalse macros will not be compiled in a
  167. release build.
  168. @see jassert, jassertfalse, Logger
  169. */
  170. #ifndef JUCE_LOG_ASSERTIONS
  171. #define JUCE_LOG_ASSERTIONS 0
  172. #endif
  173. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  174. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  175. on your Windows build machine.
  176. See the comments in the ASIOAudioIODevice class's header file for more
  177. info about this.
  178. */
  179. #ifndef JUCE_ASIO
  180. #define JUCE_ASIO 0
  181. #endif
  182. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  183. */
  184. #ifndef JUCE_WASAPI
  185. #define JUCE_WASAPI 0
  186. #endif
  187. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  188. */
  189. #ifndef JUCE_DIRECTSOUND
  190. #define JUCE_DIRECTSOUND 1
  191. #endif
  192. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  193. #ifndef JUCE_ALSA
  194. #define JUCE_ALSA 1
  195. #endif
  196. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  197. #ifndef JUCE_JACK
  198. #define JUCE_JACK 0
  199. #endif
  200. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  201. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  202. installed, and its header files will need to be on your include path.
  203. */
  204. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  205. #define JUCE_QUICKTIME 0
  206. #endif
  207. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  208. #undef JUCE_QUICKTIME
  209. #endif
  210. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  211. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  212. */
  213. #ifndef JUCE_OPENGL
  214. #define JUCE_OPENGL 1
  215. #endif
  216. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  217. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  218. */
  219. #ifndef JUCE_DIRECT2D
  220. #define JUCE_DIRECT2D 0
  221. #endif
  222. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  223. If your app doesn't need to read FLAC files, you might want to disable this to
  224. reduce the size of your codebase and build time.
  225. */
  226. #ifndef JUCE_USE_FLAC
  227. #define JUCE_USE_FLAC 1
  228. #endif
  229. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  230. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  231. reduce the size of your codebase and build time.
  232. */
  233. #ifndef JUCE_USE_OGGVORBIS
  234. #define JUCE_USE_OGGVORBIS 1
  235. #endif
  236. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  237. Unless you're using CD-burning, you should probably turn this flag off to
  238. reduce code size.
  239. */
  240. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  241. #define JUCE_USE_CDBURNER 1
  242. #endif
  243. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  244. Unless you're using CD-reading, you should probably turn this flag off to
  245. reduce code size.
  246. */
  247. #ifndef JUCE_USE_CDREADER
  248. #define JUCE_USE_CDREADER 1
  249. #endif
  250. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  251. */
  252. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  253. #define JUCE_USE_CAMERA 0
  254. #endif
  255. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  256. gets repainted will flash in a random colour, so that you can check exactly how much and how
  257. often your components are being drawn.
  258. */
  259. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  260. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  261. #endif
  262. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  263. Unless you specifically want to disable this, it's best to leave this option turned on.
  264. */
  265. #ifndef JUCE_USE_XINERAMA
  266. #define JUCE_USE_XINERAMA 1
  267. #endif
  268. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  269. turned on unless you have a good reason to disable it.
  270. */
  271. #ifndef JUCE_USE_XSHM
  272. #define JUCE_USE_XSHM 1
  273. #endif
  274. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  275. */
  276. #ifndef JUCE_USE_XRENDER
  277. #define JUCE_USE_XRENDER 0
  278. #endif
  279. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  280. unless you have a good reason to disable it.
  281. */
  282. #ifndef JUCE_USE_XCURSOR
  283. #define JUCE_USE_XCURSOR 1
  284. #endif
  285. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  286. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  287. you're building a plugin hosting app.
  288. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  289. */
  290. #ifndef JUCE_PLUGINHOST_VST
  291. #define JUCE_PLUGINHOST_VST 0
  292. #endif
  293. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  294. of course, and should only be enabled if you're building a plugin hosting app.
  295. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  296. */
  297. #ifndef JUCE_PLUGINHOST_AU
  298. #define JUCE_PLUGINHOST_AU 0
  299. #endif
  300. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  301. This should be enabled if you're writing a console application.
  302. */
  303. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  304. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  305. #endif
  306. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  307. If you're not using any embedded web-pages, turning this off may reduce your code size.
  308. */
  309. #ifndef JUCE_WEB_BROWSER
  310. #define JUCE_WEB_BROWSER 1
  311. #endif
  312. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  313. Carbon isn't required for a normal app, but may be needed by specialised classes like
  314. plugin-hosts, which support older APIs.
  315. */
  316. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  317. #define JUCE_SUPPORT_CARBON 1
  318. #endif
  319. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  320. You might need to tweak this if you're linking to an external zlib library in your app,
  321. but for normal apps, this option should be left alone.
  322. */
  323. #ifndef JUCE_INCLUDE_ZLIB_CODE
  324. #define JUCE_INCLUDE_ZLIB_CODE 1
  325. #endif
  326. #ifndef JUCE_INCLUDE_FLAC_CODE
  327. #define JUCE_INCLUDE_FLAC_CODE 1
  328. #endif
  329. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  330. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  331. #endif
  332. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  333. #define JUCE_INCLUDE_PNGLIB_CODE 1
  334. #endif
  335. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  336. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  337. #endif
  338. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  339. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  340. macro for more details about enabling leak checking for specific classes.
  341. */
  342. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  343. #define JUCE_CHECK_MEMORY_LEAKS 1
  344. #endif
  345. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  346. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  347. are passed to the JUCEApplication::unhandledException() callback for logging.
  348. */
  349. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  350. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  351. #endif
  352. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  353. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  354. #undef JUCE_QUICKTIME
  355. #define JUCE_QUICKTIME 0
  356. #undef JUCE_OPENGL
  357. #define JUCE_OPENGL 0
  358. #undef JUCE_USE_CDBURNER
  359. #define JUCE_USE_CDBURNER 0
  360. #undef JUCE_USE_CDREADER
  361. #define JUCE_USE_CDREADER 0
  362. #undef JUCE_WEB_BROWSER
  363. #define JUCE_WEB_BROWSER 0
  364. #undef JUCE_PLUGINHOST_AU
  365. #define JUCE_PLUGINHOST_AU 0
  366. #undef JUCE_PLUGINHOST_VST
  367. #define JUCE_PLUGINHOST_VST 0
  368. #endif
  369. #endif
  370. /*** End of inlined file: juce_Config.h ***/
  371. // FORCE_AMALGAMATOR_INCLUDE
  372. #ifndef JUCE_BUILD_CORE
  373. #define JUCE_BUILD_CORE 1
  374. #endif
  375. #ifndef JUCE_BUILD_MISC
  376. #define JUCE_BUILD_MISC 1
  377. #endif
  378. #ifndef JUCE_BUILD_GUI
  379. #define JUCE_BUILD_GUI 1
  380. #endif
  381. #ifndef JUCE_BUILD_NATIVE
  382. #define JUCE_BUILD_NATIVE 1
  383. #endif
  384. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  385. #undef JUCE_BUILD_MISC
  386. #undef JUCE_BUILD_GUI
  387. #endif
  388. //==============================================================================
  389. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  390. #if JUCE_WINDOWS
  391. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  392. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  393. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  394. #ifndef STRICT
  395. #define STRICT 1
  396. #endif
  397. #undef WIN32_LEAN_AND_MEAN
  398. #define WIN32_LEAN_AND_MEAN 1
  399. #if JUCE_MSVC
  400. #pragma warning (push)
  401. #pragma warning (disable : 4100 4201 4514 4312 4995)
  402. #endif
  403. #define _WIN32_WINNT 0x0500
  404. #define _UNICODE 1
  405. #define UNICODE 1
  406. #ifndef _WIN32_IE
  407. #define _WIN32_IE 0x0400
  408. #endif
  409. #include <windows.h>
  410. #include <windowsx.h>
  411. #include <commdlg.h>
  412. #include <shellapi.h>
  413. #include <mmsystem.h>
  414. #include <vfw.h>
  415. #include <tchar.h>
  416. #include <stddef.h>
  417. #include <ctime>
  418. #include <wininet.h>
  419. #include <nb30.h>
  420. #include <iphlpapi.h>
  421. #include <mapi.h>
  422. #include <float.h>
  423. #include <process.h>
  424. #include <Exdisp.h>
  425. #include <exdispid.h>
  426. #include <shlobj.h>
  427. #if ! JUCE_MINGW
  428. #include <crtdbg.h>
  429. #include <comutil.h>
  430. #endif
  431. #if JUCE_OPENGL
  432. #include <gl/gl.h>
  433. #endif
  434. #undef PACKED
  435. #if JUCE_ASIO && JUCE_BUILD_NATIVE
  436. /*
  437. This is very frustrating - we only need to use a handful of definitions from
  438. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  439. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  440. implementation...
  441. ..unfortunately that would break Steinberg's license agreement for use of
  442. their SDK, so I'm not allowed to do this.
  443. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  444. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  445. (see www.steinberg.net/Steinberg/Developers.asp).
  446. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  447. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  448. if you prefer). Make sure that your header search path will find the
  449. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  450. files are actually needed - so to simplify things, you could just copy
  451. these into your JUCE directory).
  452. If you're compiling and you get an error here because you don't have the
  453. ASIO SDK installed, you can disable ASIO support by commenting-out the
  454. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  455. */
  456. #include <iasiodrv.h>
  457. #endif
  458. #if JUCE_USE_CDBURNER && JUCE_BUILD_NATIVE
  459. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  460. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  461. flag in juce_Config.h to avoid these includes.
  462. */
  463. #include <imapi.h>
  464. #include <imapierror.h>
  465. #endif
  466. #if JUCE_USE_CAMERA && JUCE_BUILD_NATIVE
  467. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  468. These files are provided in the normal Windows SDK, but some Microsoft plonker
  469. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  470. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  471. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  472. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  473. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  474. The dummy file just needs to contain the following content:
  475. #define __IDxtCompositor_INTERFACE_DEFINED__
  476. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  477. #define __IDxtJpeg_INTERFACE_DEFINED__
  478. #define __IDxtKey_INTERFACE_DEFINED__
  479. ..and that should be enough to convince qedit.h that you have the SDK!
  480. */
  481. #include <dshow.h>
  482. #include <qedit.h>
  483. #include <dshowasf.h>
  484. #endif
  485. #if JUCE_WASAPI && JUCE_BUILD_NATIVE
  486. #include <MMReg.h>
  487. #include <mmdeviceapi.h>
  488. #include <Audioclient.h>
  489. #include <Avrt.h>
  490. #include <functiondiscoverykeys.h>
  491. #endif
  492. #if JUCE_QUICKTIME
  493. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  494. add its header directory to your include path.
  495. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  496. flag in juce_Config.h
  497. */
  498. #include <Movies.h>
  499. #include <QTML.h>
  500. #include <QuickTimeComponents.h>
  501. #include <MediaHandlers.h>
  502. #include <ImageCodec.h>
  503. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  504. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  505. your include search path to make these import statements work.
  506. */
  507. #import <QTOLibrary.dll>
  508. #import <QTOControl.dll>
  509. #endif
  510. #if JUCE_MSVC
  511. #pragma warning (pop)
  512. #endif
  513. #if JUCE_DIRECT2D && JUCE_BUILD_NATIVE
  514. #include <d2d1.h>
  515. #include <dwrite.h>
  516. #endif
  517. /** A simple COM smart pointer.
  518. Avoids having to include ATL just to get one of these.
  519. */
  520. template <class ComClass>
  521. class ComSmartPtr
  522. {
  523. public:
  524. ComSmartPtr() throw() : p (0) {}
  525. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  526. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  527. ~ComSmartPtr() { release(); }
  528. operator ComClass*() const throw() { return p; }
  529. ComClass& operator*() const throw() { return *p; }
  530. ComClass* operator->() const throw() { return p; }
  531. ComSmartPtr& operator= (ComClass* const newP)
  532. {
  533. if (newP != 0) newP->AddRef();
  534. release();
  535. p = newP;
  536. return *this;
  537. }
  538. ComSmartPtr& operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  539. // Releases and nullifies this pointer and returns its address
  540. ComClass** resetAndGetPointerAddress()
  541. {
  542. release();
  543. p = 0;
  544. return &p;
  545. }
  546. HRESULT CoCreateInstance (REFCLSID classUUID, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  547. {
  548. #ifndef __MINGW32__
  549. return ::CoCreateInstance (classUUID, 0, dwClsContext, __uuidof (ComClass), (void**) resetAndGetPointerAddress());
  550. #else
  551. return E_NOTIMPL;
  552. #endif
  553. }
  554. template <class OtherComClass>
  555. HRESULT QueryInterface (REFCLSID classUUID, ComSmartPtr<OtherComClass>& destObject) const
  556. {
  557. if (p == 0)
  558. return E_POINTER;
  559. return p->QueryInterface (classUUID, (void**) destObject.resetAndGetPointerAddress());
  560. }
  561. private:
  562. ComClass* p;
  563. void release() { if (p != 0) p->Release(); }
  564. ComClass** operator&() throw(); // private to avoid it being used accidentally
  565. };
  566. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  567. */
  568. template <class ComClass>
  569. class ComBaseClassHelper : public ComClass
  570. {
  571. public:
  572. ComBaseClassHelper() : refCount (1) {}
  573. virtual ~ComBaseClassHelper() {}
  574. HRESULT __stdcall QueryInterface (REFIID refId, void** result)
  575. {
  576. #ifndef __MINGW32__
  577. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  578. #endif
  579. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  580. *result = 0;
  581. return E_NOINTERFACE;
  582. }
  583. ULONG __stdcall AddRef() { return ++refCount; }
  584. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  585. protected:
  586. int refCount;
  587. };
  588. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  589. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  590. #elif JUCE_LINUX
  591. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  592. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  593. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  594. /*
  595. This file wraps together all the linux-specific headers, so
  596. that we can include them all just once, and compile all our
  597. platform-specific stuff in one big lump, keeping it out of the
  598. way of the rest of the codebase.
  599. */
  600. #include <sched.h>
  601. #include <pthread.h>
  602. #include <sys/time.h>
  603. #include <errno.h>
  604. #include <sys/stat.h>
  605. #include <sys/dir.h>
  606. #include <sys/ptrace.h>
  607. #include <sys/vfs.h>
  608. #include <sys/wait.h>
  609. #include <fnmatch.h>
  610. #include <utime.h>
  611. #include <pwd.h>
  612. #include <fcntl.h>
  613. #include <dlfcn.h>
  614. #include <netdb.h>
  615. #include <arpa/inet.h>
  616. #include <netinet/in.h>
  617. #include <sys/types.h>
  618. #include <sys/ioctl.h>
  619. #include <sys/socket.h>
  620. #include <net/if.h>
  621. #include <sys/sysinfo.h>
  622. #include <sys/file.h>
  623. #include <signal.h>
  624. /* Got a build error here? You'll need to install the freetype library...
  625. The name of the package to install is "libfreetype6-dev".
  626. */
  627. #include <ft2build.h>
  628. #include FT_FREETYPE_H
  629. #include <X11/Xlib.h>
  630. #include <X11/Xatom.h>
  631. #include <X11/Xresource.h>
  632. #include <X11/Xutil.h>
  633. #include <X11/Xmd.h>
  634. #include <X11/keysym.h>
  635. #include <X11/cursorfont.h>
  636. #if JUCE_USE_XINERAMA
  637. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  638. #include <X11/extensions/Xinerama.h>
  639. #endif
  640. #if JUCE_USE_XSHM
  641. #include <X11/extensions/XShm.h>
  642. #include <sys/shm.h>
  643. #include <sys/ipc.h>
  644. #endif
  645. #if JUCE_USE_XRENDER
  646. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  647. #include <X11/extensions/Xrender.h>
  648. #include <X11/extensions/Xcomposite.h>
  649. #endif
  650. #if JUCE_USE_XCURSOR
  651. // If you're missing this header, try installing the libxcursor-dev package
  652. #include <X11/Xcursor/Xcursor.h>
  653. #endif
  654. #if JUCE_OPENGL
  655. /* Got an include error here?
  656. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  657. and "freeglut3-dev".
  658. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  659. want to disable it.
  660. */
  661. #include <GL/glx.h>
  662. #endif
  663. #undef KeyPress
  664. #if JUCE_ALSA
  665. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  666. not got your paths set up correctly to find its header files.
  667. The package you need to install to get ASLA support is "libasound2-dev".
  668. If you don't have the ALSA library and don't want to build Juce with audio support,
  669. just disable the JUCE_ALSA flag in juce_Config.h
  670. */
  671. #include <alsa/asoundlib.h>
  672. #endif
  673. #if JUCE_JACK
  674. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  675. installed, or you've not got your paths set up correctly to find its header files.
  676. The package you need to install to get JACK support is "libjack-dev".
  677. If you don't have the jack-audio-connection-kit library and don't want to build
  678. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  679. */
  680. #include <jack/jack.h>
  681. //#include <jack/transport.h>
  682. #endif
  683. #undef SIZEOF
  684. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  685. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  686. #elif JUCE_MAC || JUCE_IPHONE
  687. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  688. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  689. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  690. /*
  691. This file wraps together all the mac-specific code, so that
  692. we can include all the native headers just once, and compile all our
  693. platform-specific stuff in one big lump, keeping it out of the way of
  694. the rest of the codebase.
  695. */
  696. #define USE_COREGRAPHICS_RENDERING 1
  697. #if JUCE_IOS
  698. #import <Foundation/Foundation.h>
  699. #import <UIKit/UIKit.h>
  700. #import <AudioToolbox/AudioToolbox.h>
  701. #import <AVFoundation/AVFoundation.h>
  702. #import <CoreData/CoreData.h>
  703. #import <MobileCoreServices/MobileCoreServices.h>
  704. #import <QuartzCore/QuartzCore.h>
  705. #include <sys/fcntl.h>
  706. #if JUCE_OPENGL
  707. #include <OpenGLES/ES1/gl.h>
  708. #include <OpenGLES/ES1/glext.h>
  709. #endif
  710. #else
  711. #import <Cocoa/Cocoa.h>
  712. #import <CoreAudio/HostTime.h>
  713. #if JUCE_BUILD_NATIVE
  714. #import <CoreAudio/AudioHardware.h>
  715. #import <CoreMIDI/MIDIServices.h>
  716. #import <QTKit/QTKit.h>
  717. #import <WebKit/WebKit.h>
  718. #import <DiscRecording/DiscRecording.h>
  719. #import <IOKit/IOKitLib.h>
  720. #import <IOKit/IOCFPlugIn.h>
  721. #import <IOKit/hid/IOHIDLib.h>
  722. #import <IOKit/hid/IOHIDKeys.h>
  723. #import <IOKit/pwr_mgt/IOPMLib.h>
  724. #endif
  725. #if (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU)) \
  726. || ! (defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6)
  727. #include <Carbon/Carbon.h>
  728. #endif
  729. #include <sys/dir.h>
  730. #endif
  731. #include <sys/socket.h>
  732. #include <sys/sysctl.h>
  733. #include <sys/stat.h>
  734. #include <sys/param.h>
  735. #include <sys/mount.h>
  736. #include <fnmatch.h>
  737. #include <utime.h>
  738. #include <dlfcn.h>
  739. #include <ifaddrs.h>
  740. #include <net/if_dl.h>
  741. #include <mach/mach_time.h>
  742. #include <mach-o/dyld.h>
  743. #if MACOS_10_4_OR_EARLIER
  744. #include <GLUT/glut.h>
  745. #endif
  746. #if ! CGFLOAT_DEFINED
  747. #define CGFloat float
  748. #endif
  749. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  750. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  751. #else
  752. #error "Unknown platform!"
  753. #endif
  754. #endif
  755. //==============================================================================
  756. #define DONT_SET_USING_JUCE_NAMESPACE 1
  757. #undef max
  758. #undef min
  759. #define NO_DUMMY_DECL
  760. #define JUCE_AMALGAMATED_TEMPLATE 1
  761. #if JUCE_BUILD_NATIVE
  762. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  763. #endif
  764. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  765. #pragma warning (disable: 4309 4305)
  766. #endif
  767. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  768. BEGIN_JUCE_NAMESPACE
  769. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  770. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  771. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  772. /**
  773. Creates a floating carbon window that can be used to hold a carbon UI.
  774. This is a handy class that's designed to be inlined where needed, e.g.
  775. in the audio plugin hosting code.
  776. */
  777. class CarbonViewWrapperComponent : public Component,
  778. public ComponentMovementWatcher,
  779. public Timer
  780. {
  781. public:
  782. CarbonViewWrapperComponent()
  783. : ComponentMovementWatcher (this),
  784. wrapperWindow (0),
  785. carbonWindow (0),
  786. embeddedView (0),
  787. recursiveResize (false)
  788. {
  789. }
  790. virtual ~CarbonViewWrapperComponent()
  791. {
  792. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  793. }
  794. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  795. virtual void removeView (HIViewRef embeddedView) = 0;
  796. virtual void mouseDown (int, int) {}
  797. virtual void paint() {}
  798. virtual bool getEmbeddedViewSize (int& w, int& h)
  799. {
  800. if (embeddedView == 0)
  801. return false;
  802. HIRect bounds;
  803. HIViewGetBounds (embeddedView, &bounds);
  804. w = jmax (1, roundToInt (bounds.size.width));
  805. h = jmax (1, roundToInt (bounds.size.height));
  806. return true;
  807. }
  808. void createWindow()
  809. {
  810. if (wrapperWindow == 0)
  811. {
  812. Rect r;
  813. r.left = getScreenX();
  814. r.top = getScreenY();
  815. r.right = r.left + getWidth();
  816. r.bottom = r.top + getHeight();
  817. CreateNewWindow (kDocumentWindowClass,
  818. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  819. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  820. &r, &wrapperWindow);
  821. jassert (wrapperWindow != 0);
  822. if (wrapperWindow == 0)
  823. return;
  824. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  825. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  826. [ownerWindow addChildWindow: carbonWindow
  827. ordered: NSWindowAbove];
  828. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  829. EventTypeSpec windowEventTypes[] =
  830. {
  831. { kEventClassWindow, kEventWindowGetClickActivation },
  832. { kEventClassWindow, kEventWindowHandleDeactivate },
  833. { kEventClassWindow, kEventWindowBoundsChanging },
  834. { kEventClassMouse, kEventMouseDown },
  835. { kEventClassMouse, kEventMouseMoved },
  836. { kEventClassMouse, kEventMouseDragged },
  837. { kEventClassMouse, kEventMouseUp},
  838. { kEventClassWindow, kEventWindowDrawContent },
  839. { kEventClassWindow, kEventWindowShown },
  840. { kEventClassWindow, kEventWindowHidden }
  841. };
  842. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  843. InstallWindowEventHandler (wrapperWindow, upp,
  844. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  845. windowEventTypes, this, &eventHandlerRef);
  846. setOurSizeToEmbeddedViewSize();
  847. setEmbeddedWindowToOurSize();
  848. creationTime = Time::getCurrentTime();
  849. }
  850. }
  851. void deleteWindow()
  852. {
  853. removeView (embeddedView);
  854. embeddedView = 0;
  855. if (wrapperWindow != 0)
  856. {
  857. RemoveEventHandler (eventHandlerRef);
  858. DisposeWindow (wrapperWindow);
  859. wrapperWindow = 0;
  860. }
  861. }
  862. void setOurSizeToEmbeddedViewSize()
  863. {
  864. int w, h;
  865. if (getEmbeddedViewSize (w, h))
  866. {
  867. if (w != getWidth() || h != getHeight())
  868. {
  869. startTimer (50);
  870. setSize (w, h);
  871. if (getParentComponent() != 0)
  872. getParentComponent()->setSize (w, h);
  873. }
  874. else
  875. {
  876. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  877. }
  878. }
  879. else
  880. {
  881. stopTimer();
  882. }
  883. }
  884. void setEmbeddedWindowToOurSize()
  885. {
  886. if (! recursiveResize)
  887. {
  888. recursiveResize = true;
  889. if (embeddedView != 0)
  890. {
  891. HIRect r;
  892. r.origin.x = 0;
  893. r.origin.y = 0;
  894. r.size.width = (float) getWidth();
  895. r.size.height = (float) getHeight();
  896. HIViewSetFrame (embeddedView, &r);
  897. }
  898. if (wrapperWindow != 0)
  899. {
  900. Rect wr;
  901. wr.left = getScreenX();
  902. wr.top = getScreenY();
  903. wr.right = wr.left + getWidth();
  904. wr.bottom = wr.top + getHeight();
  905. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  906. ShowWindow (wrapperWindow);
  907. }
  908. recursiveResize = false;
  909. }
  910. }
  911. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  912. {
  913. setEmbeddedWindowToOurSize();
  914. }
  915. void componentPeerChanged()
  916. {
  917. deleteWindow();
  918. createWindow();
  919. }
  920. void componentVisibilityChanged()
  921. {
  922. if (isShowing())
  923. createWindow();
  924. else
  925. deleteWindow();
  926. setEmbeddedWindowToOurSize();
  927. }
  928. static void recursiveHIViewRepaint (HIViewRef view)
  929. {
  930. HIViewSetNeedsDisplay (view, true);
  931. HIViewRef child = HIViewGetFirstSubview (view);
  932. while (child != 0)
  933. {
  934. recursiveHIViewRepaint (child);
  935. child = HIViewGetNextView (child);
  936. }
  937. }
  938. void timerCallback()
  939. {
  940. setOurSizeToEmbeddedViewSize();
  941. // To avoid strange overpainting problems when the UI is first opened, we'll
  942. // repaint it a few times during the first second that it's on-screen..
  943. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  944. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  945. }
  946. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  947. {
  948. switch (GetEventKind (event))
  949. {
  950. case kEventWindowHandleDeactivate:
  951. ActivateWindow (wrapperWindow, TRUE);
  952. return noErr;
  953. case kEventWindowGetClickActivation:
  954. {
  955. getTopLevelComponent()->toFront (false);
  956. [carbonWindow makeKeyAndOrderFront: nil];
  957. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  958. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  959. sizeof (ClickActivationResult), &howToHandleClick);
  960. HIViewSetNeedsDisplay (embeddedView, true);
  961. return noErr;
  962. }
  963. }
  964. return eventNotHandledErr;
  965. }
  966. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  967. {
  968. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  969. }
  970. protected:
  971. WindowRef wrapperWindow;
  972. NSWindow* carbonWindow;
  973. HIViewRef embeddedView;
  974. bool recursiveResize;
  975. Time creationTime;
  976. EventHandlerRef eventHandlerRef;
  977. };
  978. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  979. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  980. END_JUCE_NAMESPACE
  981. #endif
  982. //==============================================================================
  983. #if JUCE_BUILD_CORE
  984. /*** Start of inlined file: juce_FileLogger.cpp ***/
  985. BEGIN_JUCE_NAMESPACE
  986. FileLogger::FileLogger (const File& logFile_,
  987. const String& welcomeMessage,
  988. const int maxInitialFileSizeBytes)
  989. : logFile (logFile_)
  990. {
  991. if (maxInitialFileSizeBytes >= 0)
  992. trimFileSize (maxInitialFileSizeBytes);
  993. if (! logFile_.exists())
  994. {
  995. // do this so that the parent directories get created..
  996. logFile_.create();
  997. }
  998. String welcome;
  999. welcome << newLine
  1000. << "**********************************************************" << newLine
  1001. << welcomeMessage << newLine
  1002. << "Log started: " << Time::getCurrentTime().toString (true, true) << newLine;
  1003. logMessage (welcome);
  1004. }
  1005. FileLogger::~FileLogger()
  1006. {
  1007. }
  1008. void FileLogger::logMessage (const String& message)
  1009. {
  1010. DBG (message);
  1011. const ScopedLock sl (logLock);
  1012. FileOutputStream out (logFile, 256);
  1013. out << message << newLine;
  1014. }
  1015. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1016. {
  1017. if (maxFileSizeBytes <= 0)
  1018. {
  1019. logFile.deleteFile();
  1020. }
  1021. else
  1022. {
  1023. const int64 fileSize = logFile.getSize();
  1024. if (fileSize > maxFileSizeBytes)
  1025. {
  1026. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1027. jassert (in != 0);
  1028. if (in != 0)
  1029. {
  1030. in->setPosition (fileSize - maxFileSizeBytes);
  1031. String content;
  1032. {
  1033. MemoryBlock contentToSave;
  1034. contentToSave.setSize (maxFileSizeBytes + 4);
  1035. contentToSave.fillWith (0);
  1036. in->read (contentToSave.getData(), maxFileSizeBytes);
  1037. in = 0;
  1038. content = contentToSave.toString();
  1039. }
  1040. int newStart = 0;
  1041. while (newStart < fileSize
  1042. && content[newStart] != '\n'
  1043. && content[newStart] != '\r')
  1044. ++newStart;
  1045. logFile.deleteFile();
  1046. logFile.appendText (content.substring (newStart), false, false);
  1047. }
  1048. }
  1049. }
  1050. }
  1051. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1052. const String& logFileName,
  1053. const String& welcomeMessage,
  1054. const int maxInitialFileSizeBytes)
  1055. {
  1056. #if JUCE_MAC
  1057. File logFile ("~/Library/Logs");
  1058. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1059. .getChildFile (logFileName);
  1060. #else
  1061. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1062. if (logFile.isDirectory())
  1063. {
  1064. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1065. .getChildFile (logFileName);
  1066. }
  1067. #endif
  1068. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1069. }
  1070. END_JUCE_NAMESPACE
  1071. /*** End of inlined file: juce_FileLogger.cpp ***/
  1072. /*** Start of inlined file: juce_Logger.cpp ***/
  1073. BEGIN_JUCE_NAMESPACE
  1074. Logger::Logger()
  1075. {
  1076. }
  1077. Logger::~Logger()
  1078. {
  1079. }
  1080. Logger* Logger::currentLogger = 0;
  1081. void Logger::setCurrentLogger (Logger* const newLogger,
  1082. const bool deleteOldLogger)
  1083. {
  1084. Logger* const oldLogger = currentLogger;
  1085. currentLogger = newLogger;
  1086. if (deleteOldLogger)
  1087. delete oldLogger;
  1088. }
  1089. void Logger::writeToLog (const String& message)
  1090. {
  1091. if (currentLogger != 0)
  1092. currentLogger->logMessage (message);
  1093. else
  1094. outputDebugString (message);
  1095. }
  1096. #if JUCE_LOG_ASSERTIONS
  1097. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1098. {
  1099. String m ("JUCE Assertion failure in ");
  1100. m << filename << ", line " << lineNum;
  1101. Logger::writeToLog (m);
  1102. }
  1103. #endif
  1104. END_JUCE_NAMESPACE
  1105. /*** End of inlined file: juce_Logger.cpp ***/
  1106. /*** Start of inlined file: juce_Random.cpp ***/
  1107. BEGIN_JUCE_NAMESPACE
  1108. Random::Random (const int64 seedValue) throw()
  1109. : seed (seedValue)
  1110. {
  1111. }
  1112. Random::~Random() throw()
  1113. {
  1114. }
  1115. void Random::setSeed (const int64 newSeed) throw()
  1116. {
  1117. seed = newSeed;
  1118. }
  1119. void Random::combineSeed (const int64 seedValue) throw()
  1120. {
  1121. seed ^= nextInt64() ^ seedValue;
  1122. }
  1123. void Random::setSeedRandomly()
  1124. {
  1125. combineSeed ((int64) (pointer_sized_int) this);
  1126. combineSeed (Time::getMillisecondCounter());
  1127. combineSeed (Time::getHighResolutionTicks());
  1128. combineSeed (Time::getHighResolutionTicksPerSecond());
  1129. combineSeed (Time::currentTimeMillis());
  1130. }
  1131. int Random::nextInt() throw()
  1132. {
  1133. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1134. return (int) (seed >> 16);
  1135. }
  1136. int Random::nextInt (const int maxValue) throw()
  1137. {
  1138. jassert (maxValue > 0);
  1139. return (nextInt() & 0x7fffffff) % maxValue;
  1140. }
  1141. int64 Random::nextInt64() throw()
  1142. {
  1143. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1144. }
  1145. bool Random::nextBool() throw()
  1146. {
  1147. return (nextInt() & 0x80000000) != 0;
  1148. }
  1149. float Random::nextFloat() throw()
  1150. {
  1151. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1152. }
  1153. double Random::nextDouble() throw()
  1154. {
  1155. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1156. }
  1157. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1158. {
  1159. BigInteger n;
  1160. do
  1161. {
  1162. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1163. }
  1164. while (n >= maximumValue);
  1165. return n;
  1166. }
  1167. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1168. {
  1169. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1170. while ((startBit & 31) != 0 && numBits > 0)
  1171. {
  1172. arrayToChange.setBit (startBit++, nextBool());
  1173. --numBits;
  1174. }
  1175. while (numBits >= 32)
  1176. {
  1177. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1178. startBit += 32;
  1179. numBits -= 32;
  1180. }
  1181. while (--numBits >= 0)
  1182. arrayToChange.setBit (startBit + numBits, nextBool());
  1183. }
  1184. Random& Random::getSystemRandom() throw()
  1185. {
  1186. static Random sysRand (1);
  1187. return sysRand;
  1188. }
  1189. END_JUCE_NAMESPACE
  1190. /*** End of inlined file: juce_Random.cpp ***/
  1191. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1192. BEGIN_JUCE_NAMESPACE
  1193. RelativeTime::RelativeTime (const double seconds_) throw()
  1194. : seconds (seconds_)
  1195. {
  1196. }
  1197. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1198. : seconds (other.seconds)
  1199. {
  1200. }
  1201. RelativeTime::~RelativeTime() throw()
  1202. {
  1203. }
  1204. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1205. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1206. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw() { return RelativeTime (numberOfMinutes * 60.0); }
  1207. const RelativeTime RelativeTime::hours (const double numberOfHours) throw() { return RelativeTime (numberOfHours * (60.0 * 60.0)); }
  1208. const RelativeTime RelativeTime::days (const double numberOfDays) throw() { return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0)); }
  1209. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw() { return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0)); }
  1210. int64 RelativeTime::inMilliseconds() const throw() { return (int64) (seconds * 1000.0); }
  1211. double RelativeTime::inMinutes() const throw() { return seconds / 60.0; }
  1212. double RelativeTime::inHours() const throw() { return seconds / (60.0 * 60.0); }
  1213. double RelativeTime::inDays() const throw() { return seconds / (60.0 * 60.0 * 24.0); }
  1214. double RelativeTime::inWeeks() const throw() { return seconds / (60.0 * 60.0 * 24.0 * 7.0); }
  1215. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1216. {
  1217. if (seconds < 0.001 && seconds > -0.001)
  1218. return returnValueForZeroTime;
  1219. String result;
  1220. result.preallocateStorage (16);
  1221. if (seconds < 0)
  1222. result << '-';
  1223. int fieldsShown = 0;
  1224. int n = std::abs ((int) inWeeks());
  1225. if (n > 0)
  1226. {
  1227. result << n << (n == 1 ? TRANS(" week ")
  1228. : TRANS(" weeks "));
  1229. ++fieldsShown;
  1230. }
  1231. n = std::abs ((int) inDays()) % 7;
  1232. if (n > 0)
  1233. {
  1234. result << n << (n == 1 ? TRANS(" day ")
  1235. : TRANS(" days "));
  1236. ++fieldsShown;
  1237. }
  1238. if (fieldsShown < 2)
  1239. {
  1240. n = std::abs ((int) inHours()) % 24;
  1241. if (n > 0)
  1242. {
  1243. result << n << (n == 1 ? TRANS(" hr ")
  1244. : TRANS(" hrs "));
  1245. ++fieldsShown;
  1246. }
  1247. if (fieldsShown < 2)
  1248. {
  1249. n = std::abs ((int) inMinutes()) % 60;
  1250. if (n > 0)
  1251. {
  1252. result << n << (n == 1 ? TRANS(" min ")
  1253. : TRANS(" mins "));
  1254. ++fieldsShown;
  1255. }
  1256. if (fieldsShown < 2)
  1257. {
  1258. n = std::abs ((int) inSeconds()) % 60;
  1259. if (n > 0)
  1260. {
  1261. result << n << (n == 1 ? TRANS(" sec ")
  1262. : TRANS(" secs "));
  1263. ++fieldsShown;
  1264. }
  1265. if (fieldsShown == 0)
  1266. {
  1267. n = std::abs ((int) inMilliseconds()) % 1000;
  1268. if (n > 0)
  1269. result << n << TRANS(" ms");
  1270. }
  1271. }
  1272. }
  1273. }
  1274. return result.trimEnd();
  1275. }
  1276. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1277. {
  1278. seconds = other.seconds;
  1279. return *this;
  1280. }
  1281. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1282. {
  1283. seconds += timeToAdd.seconds;
  1284. return *this;
  1285. }
  1286. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1287. {
  1288. seconds -= timeToSubtract.seconds;
  1289. return *this;
  1290. }
  1291. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1292. {
  1293. seconds += secondsToAdd;
  1294. return *this;
  1295. }
  1296. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1297. {
  1298. seconds -= secondsToSubtract;
  1299. return *this;
  1300. }
  1301. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() == t2.inSeconds(); }
  1302. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() != t2.inSeconds(); }
  1303. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() > t2.inSeconds(); }
  1304. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() < t2.inSeconds(); }
  1305. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() >= t2.inSeconds(); }
  1306. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() <= t2.inSeconds(); }
  1307. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t += t2; }
  1308. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t -= t2; }
  1309. END_JUCE_NAMESPACE
  1310. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1311. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1312. BEGIN_JUCE_NAMESPACE
  1313. SystemStats::CPUFlags SystemStats::cpuFlags;
  1314. const String SystemStats::getJUCEVersion()
  1315. {
  1316. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1317. + "." + String (JUCE_MINOR_VERSION)
  1318. + "." + String (JUCE_BUILDNUMBER);
  1319. }
  1320. #ifdef JUCE_DLL
  1321. void* juce_Malloc (int size) { return malloc (size); }
  1322. void* juce_Calloc (int size) { return calloc (1, size); }
  1323. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1324. void juce_Free (void* block) { free (block); }
  1325. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1326. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1327. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1328. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1329. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1330. #endif
  1331. #endif
  1332. END_JUCE_NAMESPACE
  1333. /*** End of inlined file: juce_SystemStats.cpp ***/
  1334. /*** Start of inlined file: juce_Time.cpp ***/
  1335. #if JUCE_MSVC
  1336. #pragma warning (push)
  1337. #pragma warning (disable: 4514)
  1338. #endif
  1339. #ifndef JUCE_WINDOWS
  1340. #include <sys/time.h>
  1341. #else
  1342. #include <ctime>
  1343. #endif
  1344. #include <sys/timeb.h>
  1345. #if JUCE_MSVC
  1346. #pragma warning (pop)
  1347. #ifdef _INC_TIME_INL
  1348. #define USE_NEW_SECURE_TIME_FNS
  1349. #endif
  1350. #endif
  1351. BEGIN_JUCE_NAMESPACE
  1352. namespace TimeHelpers
  1353. {
  1354. static struct tm millisToLocal (const int64 millis) throw()
  1355. {
  1356. struct tm result;
  1357. const int64 seconds = millis / 1000;
  1358. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1359. {
  1360. // use extended maths for dates beyond 1970 to 2037..
  1361. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1362. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1363. const int days = (int) (jdm / literal64bit (86400));
  1364. const int a = 32044 + days;
  1365. const int b = (4 * a + 3) / 146097;
  1366. const int c = a - (b * 146097) / 4;
  1367. const int d = (4 * c + 3) / 1461;
  1368. const int e = c - (d * 1461) / 4;
  1369. const int m = (5 * e + 2) / 153;
  1370. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1371. result.tm_mon = m + 2 - 12 * (m / 10);
  1372. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1373. result.tm_wday = (days + 1) % 7;
  1374. result.tm_yday = -1;
  1375. int t = (int) (jdm % literal64bit (86400));
  1376. result.tm_hour = t / 3600;
  1377. t %= 3600;
  1378. result.tm_min = t / 60;
  1379. result.tm_sec = t % 60;
  1380. result.tm_isdst = -1;
  1381. }
  1382. else
  1383. {
  1384. time_t now = static_cast <time_t> (seconds);
  1385. #if JUCE_WINDOWS
  1386. #ifdef USE_NEW_SECURE_TIME_FNS
  1387. if (now >= 0 && now <= 0x793406fff)
  1388. localtime_s (&result, &now);
  1389. else
  1390. zeromem (&result, sizeof (result));
  1391. #else
  1392. result = *localtime (&now);
  1393. #endif
  1394. #else
  1395. // more thread-safe
  1396. localtime_r (&now, &result);
  1397. #endif
  1398. }
  1399. return result;
  1400. }
  1401. static int extendedModulo (const int64 value, const int modulo) throw()
  1402. {
  1403. return (int) (value >= 0 ? (value % modulo)
  1404. : (value - ((value / modulo) + 1) * modulo));
  1405. }
  1406. static uint32 lastMSCounterValue = 0;
  1407. }
  1408. Time::Time() throw()
  1409. : millisSinceEpoch (0)
  1410. {
  1411. }
  1412. Time::Time (const Time& other) throw()
  1413. : millisSinceEpoch (other.millisSinceEpoch)
  1414. {
  1415. }
  1416. Time::Time (const int64 ms) throw()
  1417. : millisSinceEpoch (ms)
  1418. {
  1419. }
  1420. Time::Time (const int year,
  1421. const int month,
  1422. const int day,
  1423. const int hours,
  1424. const int minutes,
  1425. const int seconds,
  1426. const int milliseconds,
  1427. const bool useLocalTime) throw()
  1428. {
  1429. jassert (year > 100); // year must be a 4-digit version
  1430. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1431. {
  1432. // use extended maths for dates beyond 1970 to 2037..
  1433. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1434. : 0;
  1435. const int a = (13 - month) / 12;
  1436. const int y = year + 4800 - a;
  1437. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1438. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1439. - 32045;
  1440. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1441. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1442. + milliseconds;
  1443. }
  1444. else
  1445. {
  1446. struct tm t;
  1447. t.tm_year = year - 1900;
  1448. t.tm_mon = month;
  1449. t.tm_mday = day;
  1450. t.tm_hour = hours;
  1451. t.tm_min = minutes;
  1452. t.tm_sec = seconds;
  1453. t.tm_isdst = -1;
  1454. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1455. if (millisSinceEpoch < 0)
  1456. millisSinceEpoch = 0;
  1457. else
  1458. millisSinceEpoch += milliseconds;
  1459. }
  1460. }
  1461. Time::~Time() throw()
  1462. {
  1463. }
  1464. Time& Time::operator= (const Time& other) throw()
  1465. {
  1466. millisSinceEpoch = other.millisSinceEpoch;
  1467. return *this;
  1468. }
  1469. int64 Time::currentTimeMillis() throw()
  1470. {
  1471. static uint32 lastCounterResult = 0xffffffff;
  1472. static int64 correction = 0;
  1473. const uint32 now = getMillisecondCounter();
  1474. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1475. if (now < lastCounterResult)
  1476. {
  1477. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1478. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1479. {
  1480. // get the time once using normal library calls, and store the difference needed to
  1481. // turn the millisecond counter into a real time.
  1482. #if JUCE_WINDOWS
  1483. struct _timeb t;
  1484. #ifdef USE_NEW_SECURE_TIME_FNS
  1485. _ftime_s (&t);
  1486. #else
  1487. _ftime (&t);
  1488. #endif
  1489. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1490. #else
  1491. struct timeval tv;
  1492. struct timezone tz;
  1493. gettimeofday (&tv, &tz);
  1494. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1495. #endif
  1496. }
  1497. }
  1498. lastCounterResult = now;
  1499. return correction + now;
  1500. }
  1501. uint32 juce_millisecondsSinceStartup() throw();
  1502. uint32 Time::getMillisecondCounter() throw()
  1503. {
  1504. const uint32 now = juce_millisecondsSinceStartup();
  1505. if (now < TimeHelpers::lastMSCounterValue)
  1506. {
  1507. // in multi-threaded apps this might be called concurrently, so
  1508. // make sure that our last counter value only increases and doesn't
  1509. // go backwards..
  1510. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1511. TimeHelpers::lastMSCounterValue = now;
  1512. }
  1513. else
  1514. {
  1515. TimeHelpers::lastMSCounterValue = now;
  1516. }
  1517. return now;
  1518. }
  1519. uint32 Time::getApproximateMillisecondCounter() throw()
  1520. {
  1521. jassert (TimeHelpers::lastMSCounterValue != 0);
  1522. return TimeHelpers::lastMSCounterValue;
  1523. }
  1524. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1525. {
  1526. for (;;)
  1527. {
  1528. const uint32 now = getMillisecondCounter();
  1529. if (now >= targetTime)
  1530. break;
  1531. const int toWait = targetTime - now;
  1532. if (toWait > 2)
  1533. {
  1534. Thread::sleep (jmin (20, toWait >> 1));
  1535. }
  1536. else
  1537. {
  1538. // xxx should consider using mutex_pause on the mac as it apparently
  1539. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1540. for (int i = 10; --i >= 0;)
  1541. Thread::yield();
  1542. }
  1543. }
  1544. }
  1545. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1546. {
  1547. return ticks / (double) getHighResolutionTicksPerSecond();
  1548. }
  1549. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1550. {
  1551. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1552. }
  1553. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1554. {
  1555. return Time (currentTimeMillis());
  1556. }
  1557. const String Time::toString (const bool includeDate,
  1558. const bool includeTime,
  1559. const bool includeSeconds,
  1560. const bool use24HourClock) const throw()
  1561. {
  1562. String result;
  1563. if (includeDate)
  1564. {
  1565. result << getDayOfMonth() << ' '
  1566. << getMonthName (true) << ' '
  1567. << getYear();
  1568. if (includeTime)
  1569. result << ' ';
  1570. }
  1571. if (includeTime)
  1572. {
  1573. const int mins = getMinutes();
  1574. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1575. << (mins < 10 ? ":0" : ":") << mins;
  1576. if (includeSeconds)
  1577. {
  1578. const int secs = getSeconds();
  1579. result << (secs < 10 ? ":0" : ":") << secs;
  1580. }
  1581. if (! use24HourClock)
  1582. result << (isAfternoon() ? "pm" : "am");
  1583. }
  1584. return result.trimEnd();
  1585. }
  1586. const String Time::formatted (const String& format) const
  1587. {
  1588. String buffer;
  1589. int bufferSize = 128;
  1590. buffer.preallocateStorage (bufferSize);
  1591. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1592. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1593. {
  1594. bufferSize += 128;
  1595. buffer.preallocateStorage (bufferSize);
  1596. }
  1597. return buffer;
  1598. }
  1599. int Time::getYear() const throw()
  1600. {
  1601. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1602. }
  1603. int Time::getMonth() const throw()
  1604. {
  1605. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1606. }
  1607. int Time::getDayOfMonth() const throw()
  1608. {
  1609. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1610. }
  1611. int Time::getDayOfWeek() const throw()
  1612. {
  1613. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1614. }
  1615. int Time::getHours() const throw()
  1616. {
  1617. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1618. }
  1619. int Time::getHoursInAmPmFormat() const throw()
  1620. {
  1621. const int hours = getHours();
  1622. if (hours == 0)
  1623. return 12;
  1624. else if (hours <= 12)
  1625. return hours;
  1626. else
  1627. return hours - 12;
  1628. }
  1629. bool Time::isAfternoon() const throw()
  1630. {
  1631. return getHours() >= 12;
  1632. }
  1633. int Time::getMinutes() const throw()
  1634. {
  1635. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1636. }
  1637. int Time::getSeconds() const throw()
  1638. {
  1639. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1640. }
  1641. int Time::getMilliseconds() const throw()
  1642. {
  1643. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1644. }
  1645. bool Time::isDaylightSavingTime() const throw()
  1646. {
  1647. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1648. }
  1649. const String Time::getTimeZone() const throw()
  1650. {
  1651. String zone[2];
  1652. #if JUCE_WINDOWS
  1653. _tzset();
  1654. #ifdef USE_NEW_SECURE_TIME_FNS
  1655. {
  1656. char name [128];
  1657. size_t length;
  1658. for (int i = 0; i < 2; ++i)
  1659. {
  1660. zeromem (name, sizeof (name));
  1661. _get_tzname (&length, name, 127, i);
  1662. zone[i] = name;
  1663. }
  1664. }
  1665. #else
  1666. const char** const zonePtr = (const char**) _tzname;
  1667. zone[0] = zonePtr[0];
  1668. zone[1] = zonePtr[1];
  1669. #endif
  1670. #else
  1671. tzset();
  1672. const char** const zonePtr = (const char**) tzname;
  1673. zone[0] = zonePtr[0];
  1674. zone[1] = zonePtr[1];
  1675. #endif
  1676. if (isDaylightSavingTime())
  1677. {
  1678. zone[0] = zone[1];
  1679. if (zone[0].length() > 3
  1680. && zone[0].containsIgnoreCase ("daylight")
  1681. && zone[0].contains ("GMT"))
  1682. zone[0] = "BST";
  1683. }
  1684. return zone[0].substring (0, 3);
  1685. }
  1686. const String Time::getMonthName (const bool threeLetterVersion) const
  1687. {
  1688. return getMonthName (getMonth(), threeLetterVersion);
  1689. }
  1690. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1691. {
  1692. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1693. }
  1694. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1695. {
  1696. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1697. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1698. monthNumber %= 12;
  1699. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1700. : longMonthNames [monthNumber]);
  1701. }
  1702. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1703. {
  1704. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1705. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1706. day %= 7;
  1707. return TRANS (threeLetterVersion ? shortDayNames [day]
  1708. : longDayNames [day]);
  1709. }
  1710. Time& Time::operator+= (const RelativeTime& delta) { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  1711. Time& Time::operator-= (const RelativeTime& delta) { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  1712. const Time operator+ (const Time& time, const RelativeTime& delta) { Time t (time); return t += delta; }
  1713. const Time operator- (const Time& time, const RelativeTime& delta) { Time t (time); return t -= delta; }
  1714. const Time operator+ (const RelativeTime& delta, const Time& time) { Time t (time); return t += delta; }
  1715. const RelativeTime operator- (const Time& time1, const Time& time2) { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  1716. bool operator== (const Time& time1, const Time& time2) { return time1.toMilliseconds() == time2.toMilliseconds(); }
  1717. bool operator!= (const Time& time1, const Time& time2) { return time1.toMilliseconds() != time2.toMilliseconds(); }
  1718. bool operator< (const Time& time1, const Time& time2) { return time1.toMilliseconds() < time2.toMilliseconds(); }
  1719. bool operator> (const Time& time1, const Time& time2) { return time1.toMilliseconds() > time2.toMilliseconds(); }
  1720. bool operator<= (const Time& time1, const Time& time2) { return time1.toMilliseconds() <= time2.toMilliseconds(); }
  1721. bool operator>= (const Time& time1, const Time& time2) { return time1.toMilliseconds() >= time2.toMilliseconds(); }
  1722. END_JUCE_NAMESPACE
  1723. /*** End of inlined file: juce_Time.cpp ***/
  1724. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1725. BEGIN_JUCE_NAMESPACE
  1726. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1727. #endif
  1728. #if JUCE_WINDOWS
  1729. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1730. #endif
  1731. #if JUCE_DEBUG
  1732. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1733. #endif
  1734. static bool juceInitialisedNonGUI = false;
  1735. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1736. {
  1737. if (! juceInitialisedNonGUI)
  1738. {
  1739. juceInitialisedNonGUI = true;
  1740. JUCE_AUTORELEASEPOOL
  1741. DBG (SystemStats::getJUCEVersion());
  1742. SystemStats::initialiseStats();
  1743. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1744. }
  1745. // Some basic tests, to keep an eye on things and make sure these types work ok
  1746. // on all platforms. Let me know if any of these assertions fail on your system!
  1747. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1748. static_jassert (sizeof (int8) == 1);
  1749. static_jassert (sizeof (uint8) == 1);
  1750. static_jassert (sizeof (int16) == 2);
  1751. static_jassert (sizeof (uint16) == 2);
  1752. static_jassert (sizeof (int32) == 4);
  1753. static_jassert (sizeof (uint32) == 4);
  1754. static_jassert (sizeof (int64) == 8);
  1755. static_jassert (sizeof (uint64) == 8);
  1756. }
  1757. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1758. {
  1759. if (juceInitialisedNonGUI)
  1760. {
  1761. juceInitialisedNonGUI = false;
  1762. JUCE_AUTORELEASEPOOL
  1763. LocalisedStrings::setCurrentMappings (0);
  1764. Thread::stopAllThreads (3000);
  1765. #if JUCE_WINDOWS
  1766. juce_shutdownWin32Sockets();
  1767. #endif
  1768. #if JUCE_DEBUG
  1769. juce_CheckForDanglingStreams();
  1770. #endif
  1771. }
  1772. }
  1773. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1774. static bool juceInitialisedGUI = false;
  1775. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1776. {
  1777. if (! juceInitialisedGUI)
  1778. {
  1779. juceInitialisedGUI = true;
  1780. JUCE_AUTORELEASEPOOL
  1781. initialiseJuce_NonGUI();
  1782. MessageManager::getInstance();
  1783. LookAndFeel::setDefaultLookAndFeel (0);
  1784. #if JUCE_DEBUG
  1785. try // This section is just a safety-net for catching builds without RTTI enabled..
  1786. {
  1787. MemoryOutputStream mo;
  1788. OutputStream* o = &mo;
  1789. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1790. o = dynamic_cast <MemoryOutputStream*> (o);
  1791. jassert (o != 0);
  1792. }
  1793. catch (...)
  1794. {
  1795. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1796. jassertfalse;
  1797. }
  1798. #endif
  1799. }
  1800. }
  1801. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1802. {
  1803. if (juceInitialisedGUI)
  1804. {
  1805. juceInitialisedGUI = false;
  1806. JUCE_AUTORELEASEPOOL
  1807. DeletedAtShutdown::deleteAll();
  1808. LookAndFeel::clearDefaultLookAndFeel();
  1809. delete MessageManager::getInstance();
  1810. shutdownJuce_NonGUI();
  1811. }
  1812. }
  1813. #endif
  1814. #if JUCE_UNIT_TESTS
  1815. class AtomicTests : public UnitTest
  1816. {
  1817. public:
  1818. AtomicTests() : UnitTest ("Atomics") {}
  1819. void runTest()
  1820. {
  1821. beginTest ("Misc");
  1822. char a1[7];
  1823. expect (numElementsInArray(a1) == 7);
  1824. int a2[3];
  1825. expect (numElementsInArray(a2) == 3);
  1826. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1827. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1828. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1829. beginTest ("Atomic types");
  1830. AtomicTester <int>::testInteger (*this);
  1831. AtomicTester <unsigned int>::testInteger (*this);
  1832. AtomicTester <int32>::testInteger (*this);
  1833. AtomicTester <uint32>::testInteger (*this);
  1834. AtomicTester <long>::testInteger (*this);
  1835. AtomicTester <void*>::testInteger (*this);
  1836. AtomicTester <int*>::testInteger (*this);
  1837. AtomicTester <float>::testFloat (*this);
  1838. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1839. AtomicTester <int64>::testInteger (*this);
  1840. AtomicTester <uint64>::testInteger (*this);
  1841. AtomicTester <double>::testFloat (*this);
  1842. #endif
  1843. }
  1844. template <typename Type>
  1845. class AtomicTester
  1846. {
  1847. public:
  1848. AtomicTester() {}
  1849. static void testInteger (UnitTest& test)
  1850. {
  1851. Atomic<Type> a, b;
  1852. a.set ((Type) 10);
  1853. a += (Type) 15;
  1854. a.memoryBarrier();
  1855. a -= (Type) 5;
  1856. ++a; ++a; --a;
  1857. a.memoryBarrier();
  1858. testFloat (test);
  1859. }
  1860. static void testFloat (UnitTest& test)
  1861. {
  1862. Atomic<Type> a, b;
  1863. a = (Type) 21;
  1864. a.memoryBarrier();
  1865. /* These are some simple test cases to check the atomics - let me know
  1866. if any of these assertions fail on your system!
  1867. */
  1868. test.expect (a.get() == (Type) 21);
  1869. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1870. test.expect (a.get() == (Type) 21);
  1871. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1872. test.expect (a.get() == (Type) 101);
  1873. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1874. test.expect (a.get() == (Type) 101);
  1875. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1876. test.expect (a.get() == (Type) 200);
  1877. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1878. test.expect (a.get() == (Type) 300);
  1879. b = a;
  1880. test.expect (b.get() == a.get());
  1881. }
  1882. };
  1883. };
  1884. static AtomicTests atomicUnitTests;
  1885. #endif
  1886. END_JUCE_NAMESPACE
  1887. /*** End of inlined file: juce_Initialisation.cpp ***/
  1888. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1889. BEGIN_JUCE_NAMESPACE
  1890. AbstractFifo::AbstractFifo (const int capacity) throw()
  1891. : bufferSize (capacity)
  1892. {
  1893. jassert (bufferSize > 0);
  1894. }
  1895. AbstractFifo::~AbstractFifo() {}
  1896. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1897. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1898. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1899. void AbstractFifo::reset() throw()
  1900. {
  1901. validEnd = 0;
  1902. validStart = 0;
  1903. }
  1904. void AbstractFifo::setTotalSize (int newSize) throw()
  1905. {
  1906. jassert (newSize > 0);
  1907. reset();
  1908. bufferSize = newSize;
  1909. }
  1910. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1911. {
  1912. const int vs = validStart.get();
  1913. const int ve = validEnd.get();
  1914. const int freeSpace = bufferSize - (ve - vs);
  1915. numToWrite = jmin (numToWrite, freeSpace);
  1916. if (numToWrite <= 0)
  1917. {
  1918. startIndex1 = 0;
  1919. startIndex2 = 0;
  1920. blockSize1 = 0;
  1921. blockSize2 = 0;
  1922. }
  1923. else
  1924. {
  1925. startIndex1 = (int) (ve % bufferSize);
  1926. startIndex2 = 0;
  1927. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1928. numToWrite -= blockSize1;
  1929. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  1930. }
  1931. }
  1932. void AbstractFifo::finishedWrite (int numWritten) throw()
  1933. {
  1934. jassert (numWritten >= 0 && numWritten < bufferSize);
  1935. validEnd += numWritten;
  1936. }
  1937. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1938. {
  1939. const int vs = validStart.get();
  1940. const int ve = validEnd.get();
  1941. const int numReady = ve - vs;
  1942. numWanted = jmin (numWanted, numReady);
  1943. if (numWanted <= 0)
  1944. {
  1945. startIndex1 = 0;
  1946. startIndex2 = 0;
  1947. blockSize1 = 0;
  1948. blockSize2 = 0;
  1949. }
  1950. else
  1951. {
  1952. startIndex1 = (int) (vs % bufferSize);
  1953. startIndex2 = 0;
  1954. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  1955. numWanted -= blockSize1;
  1956. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  1957. }
  1958. }
  1959. void AbstractFifo::finishedRead (int numRead) throw()
  1960. {
  1961. jassert (numRead >= 0 && numRead < bufferSize);
  1962. validStart += numRead;
  1963. }
  1964. END_JUCE_NAMESPACE
  1965. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  1966. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1967. BEGIN_JUCE_NAMESPACE
  1968. BigInteger::BigInteger()
  1969. : numValues (4),
  1970. highestBit (-1),
  1971. negative (false)
  1972. {
  1973. values.calloc (numValues + 1);
  1974. }
  1975. BigInteger::BigInteger (const int32 value)
  1976. : numValues (4),
  1977. highestBit (31),
  1978. negative (value < 0)
  1979. {
  1980. values.calloc (numValues + 1);
  1981. values[0] = abs (value);
  1982. highestBit = getHighestBit();
  1983. }
  1984. BigInteger::BigInteger (const uint32 value)
  1985. : numValues (4),
  1986. highestBit (31),
  1987. negative (false)
  1988. {
  1989. values.calloc (numValues + 1);
  1990. values[0] = value;
  1991. highestBit = getHighestBit();
  1992. }
  1993. BigInteger::BigInteger (int64 value)
  1994. : numValues (4),
  1995. highestBit (63),
  1996. negative (value < 0)
  1997. {
  1998. values.calloc (numValues + 1);
  1999. if (value < 0)
  2000. value = -value;
  2001. values[0] = (uint32) value;
  2002. values[1] = (uint32) (value >> 32);
  2003. highestBit = getHighestBit();
  2004. }
  2005. BigInteger::BigInteger (const BigInteger& other)
  2006. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2007. highestBit (other.getHighestBit()),
  2008. negative (other.negative)
  2009. {
  2010. values.malloc (numValues + 1);
  2011. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2012. }
  2013. BigInteger::~BigInteger()
  2014. {
  2015. }
  2016. void BigInteger::swapWith (BigInteger& other) throw()
  2017. {
  2018. values.swapWith (other.values);
  2019. swapVariables (numValues, other.numValues);
  2020. swapVariables (highestBit, other.highestBit);
  2021. swapVariables (negative, other.negative);
  2022. }
  2023. BigInteger& BigInteger::operator= (const BigInteger& other)
  2024. {
  2025. if (this != &other)
  2026. {
  2027. highestBit = other.getHighestBit();
  2028. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2029. negative = other.negative;
  2030. values.malloc (numValues + 1);
  2031. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2032. }
  2033. return *this;
  2034. }
  2035. void BigInteger::ensureSize (const int numVals)
  2036. {
  2037. if (numVals + 2 >= numValues)
  2038. {
  2039. int oldSize = numValues;
  2040. numValues = ((numVals + 2) * 3) / 2;
  2041. values.realloc (numValues + 1);
  2042. while (oldSize < numValues)
  2043. values [oldSize++] = 0;
  2044. }
  2045. }
  2046. bool BigInteger::operator[] (const int bit) const throw()
  2047. {
  2048. return bit <= highestBit && bit >= 0
  2049. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2050. }
  2051. int BigInteger::toInteger() const throw()
  2052. {
  2053. const int n = (int) (values[0] & 0x7fffffff);
  2054. return negative ? -n : n;
  2055. }
  2056. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2057. {
  2058. BigInteger r;
  2059. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2060. r.ensureSize (bitToIndex (numBits));
  2061. r.highestBit = numBits;
  2062. int i = 0;
  2063. while (numBits > 0)
  2064. {
  2065. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2066. numBits -= 32;
  2067. startBit += 32;
  2068. }
  2069. r.highestBit = r.getHighestBit();
  2070. return r;
  2071. }
  2072. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2073. {
  2074. if (numBits > 32)
  2075. {
  2076. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2077. numBits = 32;
  2078. }
  2079. numBits = jmin (numBits, highestBit + 1 - startBit);
  2080. if (numBits <= 0)
  2081. return 0;
  2082. const int pos = bitToIndex (startBit);
  2083. const int offset = startBit & 31;
  2084. const int endSpace = 32 - numBits;
  2085. uint32 n = ((uint32) values [pos]) >> offset;
  2086. if (offset > endSpace)
  2087. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2088. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2089. }
  2090. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2091. {
  2092. if (numBits > 32)
  2093. {
  2094. jassertfalse;
  2095. numBits = 32;
  2096. }
  2097. for (int i = 0; i < numBits; ++i)
  2098. {
  2099. setBit (startBit + i, (valueToSet & 1) != 0);
  2100. valueToSet >>= 1;
  2101. }
  2102. }
  2103. void BigInteger::clear()
  2104. {
  2105. if (numValues > 16)
  2106. {
  2107. numValues = 4;
  2108. values.calloc (numValues + 1);
  2109. }
  2110. else
  2111. {
  2112. zeromem (values, sizeof (uint32) * (numValues + 1));
  2113. }
  2114. highestBit = -1;
  2115. negative = false;
  2116. }
  2117. void BigInteger::setBit (const int bit)
  2118. {
  2119. if (bit >= 0)
  2120. {
  2121. if (bit > highestBit)
  2122. {
  2123. ensureSize (bitToIndex (bit));
  2124. highestBit = bit;
  2125. }
  2126. values [bitToIndex (bit)] |= bitToMask (bit);
  2127. }
  2128. }
  2129. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2130. {
  2131. if (shouldBeSet)
  2132. setBit (bit);
  2133. else
  2134. clearBit (bit);
  2135. }
  2136. void BigInteger::clearBit (const int bit) throw()
  2137. {
  2138. if (bit >= 0 && bit <= highestBit)
  2139. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2140. }
  2141. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2142. {
  2143. while (--numBits >= 0)
  2144. setBit (startBit++, shouldBeSet);
  2145. }
  2146. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2147. {
  2148. if (bit >= 0)
  2149. shiftBits (1, bit);
  2150. setBit (bit, shouldBeSet);
  2151. }
  2152. bool BigInteger::isZero() const throw()
  2153. {
  2154. return getHighestBit() < 0;
  2155. }
  2156. bool BigInteger::isOne() const throw()
  2157. {
  2158. return getHighestBit() == 0 && ! negative;
  2159. }
  2160. bool BigInteger::isNegative() const throw()
  2161. {
  2162. return negative && ! isZero();
  2163. }
  2164. void BigInteger::setNegative (const bool neg) throw()
  2165. {
  2166. negative = neg;
  2167. }
  2168. void BigInteger::negate() throw()
  2169. {
  2170. negative = (! negative) && ! isZero();
  2171. }
  2172. #if JUCE_USE_INTRINSICS
  2173. #pragma intrinsic (_BitScanReverse)
  2174. #endif
  2175. namespace BitFunctions
  2176. {
  2177. inline int countBitsInInt32 (uint32 n) throw()
  2178. {
  2179. n -= ((n >> 1) & 0x55555555);
  2180. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2181. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2182. n += (n >> 8);
  2183. n += (n >> 16);
  2184. return n & 0x3f;
  2185. }
  2186. inline int highestBitInInt (uint32 n) throw()
  2187. {
  2188. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2189. #if JUCE_GCC
  2190. return 31 - __builtin_clz (n);
  2191. #elif JUCE_USE_INTRINSICS
  2192. unsigned long highest;
  2193. _BitScanReverse (&highest, n);
  2194. return (int) highest;
  2195. #else
  2196. n |= (n >> 1);
  2197. n |= (n >> 2);
  2198. n |= (n >> 4);
  2199. n |= (n >> 8);
  2200. n |= (n >> 16);
  2201. return countBitsInInt32 (n >> 1);
  2202. #endif
  2203. }
  2204. }
  2205. int BigInteger::countNumberOfSetBits() const throw()
  2206. {
  2207. int total = 0;
  2208. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2209. total += BitFunctions::countBitsInInt32 (values[i]);
  2210. return total;
  2211. }
  2212. int BigInteger::getHighestBit() const throw()
  2213. {
  2214. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2215. {
  2216. const uint32 n = values[i];
  2217. if (n != 0)
  2218. return BitFunctions::highestBitInInt (n) + (i << 5);
  2219. }
  2220. return -1;
  2221. }
  2222. int BigInteger::findNextSetBit (int i) const throw()
  2223. {
  2224. for (; i <= highestBit; ++i)
  2225. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2226. return i;
  2227. return -1;
  2228. }
  2229. int BigInteger::findNextClearBit (int i) const throw()
  2230. {
  2231. for (; i <= highestBit; ++i)
  2232. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2233. break;
  2234. return i;
  2235. }
  2236. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2237. {
  2238. if (other.isNegative())
  2239. return operator-= (-other);
  2240. if (isNegative())
  2241. {
  2242. if (compareAbsolute (other) < 0)
  2243. {
  2244. BigInteger temp (*this);
  2245. temp.negate();
  2246. *this = other;
  2247. operator-= (temp);
  2248. }
  2249. else
  2250. {
  2251. negate();
  2252. operator-= (other);
  2253. negate();
  2254. }
  2255. }
  2256. else
  2257. {
  2258. if (other.highestBit > highestBit)
  2259. highestBit = other.highestBit;
  2260. ++highestBit;
  2261. const int numInts = bitToIndex (highestBit) + 1;
  2262. ensureSize (numInts);
  2263. int64 remainder = 0;
  2264. for (int i = 0; i <= numInts; ++i)
  2265. {
  2266. if (i < numValues)
  2267. remainder += values[i];
  2268. if (i < other.numValues)
  2269. remainder += other.values[i];
  2270. values[i] = (uint32) remainder;
  2271. remainder >>= 32;
  2272. }
  2273. jassert (remainder == 0);
  2274. highestBit = getHighestBit();
  2275. }
  2276. return *this;
  2277. }
  2278. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2279. {
  2280. if (other.isNegative())
  2281. return operator+= (-other);
  2282. if (! isNegative())
  2283. {
  2284. if (compareAbsolute (other) < 0)
  2285. {
  2286. BigInteger temp (other);
  2287. swapWith (temp);
  2288. operator-= (temp);
  2289. negate();
  2290. return *this;
  2291. }
  2292. }
  2293. else
  2294. {
  2295. negate();
  2296. operator+= (other);
  2297. negate();
  2298. return *this;
  2299. }
  2300. const int numInts = bitToIndex (highestBit) + 1;
  2301. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2302. int64 amountToSubtract = 0;
  2303. for (int i = 0; i <= numInts; ++i)
  2304. {
  2305. if (i <= maxOtherInts)
  2306. amountToSubtract += (int64) other.values[i];
  2307. if (values[i] >= amountToSubtract)
  2308. {
  2309. values[i] = (uint32) (values[i] - amountToSubtract);
  2310. amountToSubtract = 0;
  2311. }
  2312. else
  2313. {
  2314. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2315. values[i] = (uint32) n;
  2316. amountToSubtract = 1;
  2317. }
  2318. }
  2319. return *this;
  2320. }
  2321. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2322. {
  2323. BigInteger total;
  2324. highestBit = getHighestBit();
  2325. const bool wasNegative = isNegative();
  2326. setNegative (false);
  2327. for (int i = 0; i <= highestBit; ++i)
  2328. {
  2329. if (operator[](i))
  2330. {
  2331. BigInteger n (other);
  2332. n.setNegative (false);
  2333. n <<= i;
  2334. total += n;
  2335. }
  2336. }
  2337. total.setNegative (wasNegative ^ other.isNegative());
  2338. swapWith (total);
  2339. return *this;
  2340. }
  2341. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2342. {
  2343. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2344. const int divHB = divisor.getHighestBit();
  2345. const int ourHB = getHighestBit();
  2346. if (divHB < 0 || ourHB < 0)
  2347. {
  2348. // division by zero
  2349. remainder.clear();
  2350. clear();
  2351. }
  2352. else
  2353. {
  2354. const bool wasNegative = isNegative();
  2355. swapWith (remainder);
  2356. remainder.setNegative (false);
  2357. clear();
  2358. BigInteger temp (divisor);
  2359. temp.setNegative (false);
  2360. int leftShift = ourHB - divHB;
  2361. temp <<= leftShift;
  2362. while (leftShift >= 0)
  2363. {
  2364. if (remainder.compareAbsolute (temp) >= 0)
  2365. {
  2366. remainder -= temp;
  2367. setBit (leftShift);
  2368. }
  2369. if (--leftShift >= 0)
  2370. temp >>= 1;
  2371. }
  2372. negative = wasNegative ^ divisor.isNegative();
  2373. remainder.setNegative (wasNegative);
  2374. }
  2375. }
  2376. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2377. {
  2378. BigInteger remainder;
  2379. divideBy (other, remainder);
  2380. return *this;
  2381. }
  2382. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2383. {
  2384. // this operation doesn't take into account negative values..
  2385. jassert (isNegative() == other.isNegative());
  2386. if (other.highestBit >= 0)
  2387. {
  2388. ensureSize (bitToIndex (other.highestBit));
  2389. int n = bitToIndex (other.highestBit) + 1;
  2390. while (--n >= 0)
  2391. values[n] |= other.values[n];
  2392. if (other.highestBit > highestBit)
  2393. highestBit = other.highestBit;
  2394. highestBit = getHighestBit();
  2395. }
  2396. return *this;
  2397. }
  2398. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2399. {
  2400. // this operation doesn't take into account negative values..
  2401. jassert (isNegative() == other.isNegative());
  2402. int n = numValues;
  2403. while (n > other.numValues)
  2404. values[--n] = 0;
  2405. while (--n >= 0)
  2406. values[n] &= other.values[n];
  2407. if (other.highestBit < highestBit)
  2408. highestBit = other.highestBit;
  2409. highestBit = getHighestBit();
  2410. return *this;
  2411. }
  2412. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2413. {
  2414. // this operation will only work with the absolute values
  2415. jassert (isNegative() == other.isNegative());
  2416. if (other.highestBit >= 0)
  2417. {
  2418. ensureSize (bitToIndex (other.highestBit));
  2419. int n = bitToIndex (other.highestBit) + 1;
  2420. while (--n >= 0)
  2421. values[n] ^= other.values[n];
  2422. if (other.highestBit > highestBit)
  2423. highestBit = other.highestBit;
  2424. highestBit = getHighestBit();
  2425. }
  2426. return *this;
  2427. }
  2428. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2429. {
  2430. BigInteger remainder;
  2431. divideBy (divisor, remainder);
  2432. swapWith (remainder);
  2433. return *this;
  2434. }
  2435. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2436. {
  2437. shiftBits (numBitsToShift, 0);
  2438. return *this;
  2439. }
  2440. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2441. {
  2442. return operator<<= (-numBitsToShift);
  2443. }
  2444. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2445. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2446. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2447. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2448. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2449. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2450. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2451. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2452. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2453. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2454. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2455. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2456. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2457. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2458. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2459. int BigInteger::compare (const BigInteger& other) const throw()
  2460. {
  2461. if (isNegative() == other.isNegative())
  2462. {
  2463. const int absComp = compareAbsolute (other);
  2464. return isNegative() ? -absComp : absComp;
  2465. }
  2466. else
  2467. {
  2468. return isNegative() ? -1 : 1;
  2469. }
  2470. }
  2471. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2472. {
  2473. const int h1 = getHighestBit();
  2474. const int h2 = other.getHighestBit();
  2475. if (h1 > h2)
  2476. return 1;
  2477. else if (h1 < h2)
  2478. return -1;
  2479. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2480. if (values[i] != other.values[i])
  2481. return (values[i] > other.values[i]) ? 1 : -1;
  2482. return 0;
  2483. }
  2484. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2485. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2486. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2487. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2488. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2489. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2490. void BigInteger::shiftBits (int bits, const int startBit)
  2491. {
  2492. if (highestBit < 0)
  2493. return;
  2494. if (startBit > 0)
  2495. {
  2496. if (bits < 0)
  2497. {
  2498. // right shift
  2499. for (int i = startBit; i <= highestBit; ++i)
  2500. setBit (i, operator[] (i - bits));
  2501. highestBit = getHighestBit();
  2502. }
  2503. else if (bits > 0)
  2504. {
  2505. // left shift
  2506. for (int i = highestBit + 1; --i >= startBit;)
  2507. setBit (i + bits, operator[] (i));
  2508. while (--bits >= 0)
  2509. clearBit (bits + startBit);
  2510. }
  2511. }
  2512. else
  2513. {
  2514. if (bits < 0)
  2515. {
  2516. // right shift
  2517. bits = -bits;
  2518. if (bits > highestBit)
  2519. {
  2520. clear();
  2521. }
  2522. else
  2523. {
  2524. const int wordsToMove = bitToIndex (bits);
  2525. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2526. highestBit -= bits;
  2527. if (wordsToMove > 0)
  2528. {
  2529. int i;
  2530. for (i = 0; i < top; ++i)
  2531. values [i] = values [i + wordsToMove];
  2532. for (i = 0; i < wordsToMove; ++i)
  2533. values [top + i] = 0;
  2534. bits &= 31;
  2535. }
  2536. if (bits != 0)
  2537. {
  2538. const int invBits = 32 - bits;
  2539. --top;
  2540. for (int i = 0; i < top; ++i)
  2541. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2542. values[top] = (values[top] >> bits);
  2543. }
  2544. highestBit = getHighestBit();
  2545. }
  2546. }
  2547. else if (bits > 0)
  2548. {
  2549. // left shift
  2550. ensureSize (bitToIndex (highestBit + bits) + 1);
  2551. const int wordsToMove = bitToIndex (bits);
  2552. int top = 1 + bitToIndex (highestBit);
  2553. highestBit += bits;
  2554. if (wordsToMove > 0)
  2555. {
  2556. int i;
  2557. for (i = top; --i >= 0;)
  2558. values [i + wordsToMove] = values [i];
  2559. for (i = 0; i < wordsToMove; ++i)
  2560. values [i] = 0;
  2561. bits &= 31;
  2562. }
  2563. if (bits != 0)
  2564. {
  2565. const int invBits = 32 - bits;
  2566. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2567. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2568. values [wordsToMove] = values [wordsToMove] << bits;
  2569. }
  2570. highestBit = getHighestBit();
  2571. }
  2572. }
  2573. }
  2574. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2575. {
  2576. while (! m->isZero())
  2577. {
  2578. if (n->compareAbsolute (*m) > 0)
  2579. swapVariables (m, n);
  2580. *m -= *n;
  2581. }
  2582. return *n;
  2583. }
  2584. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2585. {
  2586. BigInteger m (*this);
  2587. while (! n.isZero())
  2588. {
  2589. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2590. return simpleGCD (&m, &n);
  2591. BigInteger temp1 (m), temp2;
  2592. temp1.divideBy (n, temp2);
  2593. m = n;
  2594. n = temp2;
  2595. }
  2596. return m;
  2597. }
  2598. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2599. {
  2600. BigInteger exp (exponent);
  2601. exp %= modulus;
  2602. BigInteger value (1);
  2603. swapWith (value);
  2604. value %= modulus;
  2605. while (! exp.isZero())
  2606. {
  2607. if (exp [0])
  2608. {
  2609. operator*= (value);
  2610. operator%= (modulus);
  2611. }
  2612. value *= value;
  2613. value %= modulus;
  2614. exp >>= 1;
  2615. }
  2616. }
  2617. void BigInteger::inverseModulo (const BigInteger& modulus)
  2618. {
  2619. if (modulus.isOne() || modulus.isNegative())
  2620. {
  2621. clear();
  2622. return;
  2623. }
  2624. if (isNegative() || compareAbsolute (modulus) >= 0)
  2625. operator%= (modulus);
  2626. if (isOne())
  2627. return;
  2628. if (! (*this)[0])
  2629. {
  2630. // not invertible
  2631. clear();
  2632. return;
  2633. }
  2634. BigInteger a1 (modulus);
  2635. BigInteger a2 (*this);
  2636. BigInteger b1 (modulus);
  2637. BigInteger b2 (1);
  2638. while (! a2.isOne())
  2639. {
  2640. BigInteger temp1, temp2, multiplier (a1);
  2641. multiplier.divideBy (a2, temp1);
  2642. temp1 = a2;
  2643. temp1 *= multiplier;
  2644. temp2 = a1;
  2645. temp2 -= temp1;
  2646. a1 = a2;
  2647. a2 = temp2;
  2648. temp1 = b2;
  2649. temp1 *= multiplier;
  2650. temp2 = b1;
  2651. temp2 -= temp1;
  2652. b1 = b2;
  2653. b2 = temp2;
  2654. }
  2655. while (b2.isNegative())
  2656. b2 += modulus;
  2657. b2 %= modulus;
  2658. swapWith (b2);
  2659. }
  2660. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2661. {
  2662. return stream << value.toString (10);
  2663. }
  2664. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2665. {
  2666. String s;
  2667. BigInteger v (*this);
  2668. if (base == 2 || base == 8 || base == 16)
  2669. {
  2670. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2671. static const char* const hexDigits = "0123456789abcdef";
  2672. for (;;)
  2673. {
  2674. const int remainder = v.getBitRangeAsInt (0, bits);
  2675. v >>= bits;
  2676. if (remainder == 0 && v.isZero())
  2677. break;
  2678. s = String::charToString (hexDigits [remainder]) + s;
  2679. }
  2680. }
  2681. else if (base == 10)
  2682. {
  2683. const BigInteger ten (10);
  2684. BigInteger remainder;
  2685. for (;;)
  2686. {
  2687. v.divideBy (ten, remainder);
  2688. if (remainder.isZero() && v.isZero())
  2689. break;
  2690. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2691. }
  2692. }
  2693. else
  2694. {
  2695. jassertfalse; // can't do the specified base!
  2696. return String::empty;
  2697. }
  2698. s = s.paddedLeft ('0', minimumNumCharacters);
  2699. return isNegative() ? "-" + s : s;
  2700. }
  2701. void BigInteger::parseString (const String& text, const int base)
  2702. {
  2703. clear();
  2704. const juce_wchar* t = text;
  2705. if (base == 2 || base == 8 || base == 16)
  2706. {
  2707. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2708. for (;;)
  2709. {
  2710. const juce_wchar c = *t++;
  2711. const int digit = CharacterFunctions::getHexDigitValue (c);
  2712. if (((uint32) digit) < (uint32) base)
  2713. {
  2714. operator<<= (bits);
  2715. operator+= (digit);
  2716. }
  2717. else if (c == 0)
  2718. {
  2719. break;
  2720. }
  2721. }
  2722. }
  2723. else if (base == 10)
  2724. {
  2725. const BigInteger ten ((uint32) 10);
  2726. for (;;)
  2727. {
  2728. const juce_wchar c = *t++;
  2729. if (c >= '0' && c <= '9')
  2730. {
  2731. operator*= (ten);
  2732. operator+= ((int) (c - '0'));
  2733. }
  2734. else if (c == 0)
  2735. {
  2736. break;
  2737. }
  2738. }
  2739. }
  2740. setNegative (text.trimStart().startsWithChar ('-'));
  2741. }
  2742. const MemoryBlock BigInteger::toMemoryBlock() const
  2743. {
  2744. const int numBytes = (getHighestBit() + 8) >> 3;
  2745. MemoryBlock mb ((size_t) numBytes);
  2746. for (int i = 0; i < numBytes; ++i)
  2747. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2748. return mb;
  2749. }
  2750. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2751. {
  2752. clear();
  2753. for (int i = (int) data.getSize(); --i >= 0;)
  2754. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2755. }
  2756. END_JUCE_NAMESPACE
  2757. /*** End of inlined file: juce_BigInteger.cpp ***/
  2758. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2759. BEGIN_JUCE_NAMESPACE
  2760. MemoryBlock::MemoryBlock() throw()
  2761. : size (0)
  2762. {
  2763. }
  2764. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2765. {
  2766. if (initialSize > 0)
  2767. {
  2768. size = initialSize;
  2769. data.allocate (initialSize, initialiseToZero);
  2770. }
  2771. else
  2772. {
  2773. size = 0;
  2774. }
  2775. }
  2776. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2777. : size (other.size)
  2778. {
  2779. if (size > 0)
  2780. {
  2781. jassert (other.data != 0);
  2782. data.malloc (size);
  2783. memcpy (data, other.data, size);
  2784. }
  2785. }
  2786. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2787. : size (jmax ((size_t) 0, sizeInBytes))
  2788. {
  2789. jassert (sizeInBytes >= 0);
  2790. if (size > 0)
  2791. {
  2792. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2793. data.malloc (size);
  2794. if (dataToInitialiseFrom != 0)
  2795. memcpy (data, dataToInitialiseFrom, size);
  2796. }
  2797. }
  2798. MemoryBlock::~MemoryBlock() throw()
  2799. {
  2800. jassert (size >= 0); // should never happen
  2801. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2802. }
  2803. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2804. {
  2805. if (this != &other)
  2806. {
  2807. setSize (other.size, false);
  2808. memcpy (data, other.data, size);
  2809. }
  2810. return *this;
  2811. }
  2812. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2813. {
  2814. return matches (other.data, other.size);
  2815. }
  2816. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2817. {
  2818. return ! operator== (other);
  2819. }
  2820. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2821. {
  2822. return size == dataSize
  2823. && memcmp (data, dataToCompare, size) == 0;
  2824. }
  2825. // this will resize the block to this size
  2826. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2827. {
  2828. if (size != newSize)
  2829. {
  2830. if (newSize <= 0)
  2831. {
  2832. data.free();
  2833. size = 0;
  2834. }
  2835. else
  2836. {
  2837. if (data != 0)
  2838. {
  2839. data.realloc (newSize);
  2840. if (initialiseToZero && (newSize > size))
  2841. zeromem (data + size, newSize - size);
  2842. }
  2843. else
  2844. {
  2845. data.allocate (newSize, initialiseToZero);
  2846. }
  2847. size = newSize;
  2848. }
  2849. }
  2850. }
  2851. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2852. {
  2853. if (size < minimumSize)
  2854. setSize (minimumSize, initialiseToZero);
  2855. }
  2856. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2857. {
  2858. swapVariables (size, other.size);
  2859. data.swapWith (other.data);
  2860. }
  2861. void MemoryBlock::fillWith (const uint8 value) throw()
  2862. {
  2863. memset (data, (int) value, size);
  2864. }
  2865. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2866. {
  2867. if (numBytes > 0)
  2868. {
  2869. const size_t oldSize = size;
  2870. setSize (size + numBytes);
  2871. memcpy (data + oldSize, srcData, numBytes);
  2872. }
  2873. }
  2874. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2875. {
  2876. const char* d = static_cast<const char*> (src);
  2877. if (offset < 0)
  2878. {
  2879. d -= offset;
  2880. num -= offset;
  2881. offset = 0;
  2882. }
  2883. if (offset + num > size)
  2884. num = size - offset;
  2885. if (num > 0)
  2886. memcpy (data + offset, d, num);
  2887. }
  2888. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2889. {
  2890. char* d = static_cast<char*> (dst);
  2891. if (offset < 0)
  2892. {
  2893. zeromem (d, -offset);
  2894. d -= offset;
  2895. num += offset;
  2896. offset = 0;
  2897. }
  2898. if (offset + num > size)
  2899. {
  2900. const size_t newNum = size - offset;
  2901. zeromem (d + newNum, num - newNum);
  2902. num = newNum;
  2903. }
  2904. if (num > 0)
  2905. memcpy (d, data + offset, num);
  2906. }
  2907. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2908. {
  2909. if (startByte < 0)
  2910. {
  2911. numBytesToRemove += startByte;
  2912. startByte = 0;
  2913. }
  2914. if (startByte + numBytesToRemove >= size)
  2915. {
  2916. setSize (startByte);
  2917. }
  2918. else if (numBytesToRemove > 0)
  2919. {
  2920. memmove (data + startByte,
  2921. data + startByte + numBytesToRemove,
  2922. size - (startByte + numBytesToRemove));
  2923. setSize (size - numBytesToRemove);
  2924. }
  2925. }
  2926. const String MemoryBlock::toString() const
  2927. {
  2928. return String (static_cast <const char*> (getData()), size);
  2929. }
  2930. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2931. {
  2932. int res = 0;
  2933. size_t byte = bitRangeStart >> 3;
  2934. int offsetInByte = (int) bitRangeStart & 7;
  2935. size_t bitsSoFar = 0;
  2936. while (numBits > 0 && (size_t) byte < size)
  2937. {
  2938. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2939. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2940. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2941. bitsSoFar += bitsThisTime;
  2942. numBits -= bitsThisTime;
  2943. ++byte;
  2944. offsetInByte = 0;
  2945. }
  2946. return res;
  2947. }
  2948. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2949. {
  2950. size_t byte = bitRangeStart >> 3;
  2951. int offsetInByte = (int) bitRangeStart & 7;
  2952. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2953. while (numBits > 0 && (size_t) byte < size)
  2954. {
  2955. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2956. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2957. const unsigned int tempBits = bitsToSet << offsetInByte;
  2958. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2959. ++byte;
  2960. numBits -= bitsThisTime;
  2961. bitsToSet >>= bitsThisTime;
  2962. mask >>= bitsThisTime;
  2963. offsetInByte = 0;
  2964. }
  2965. }
  2966. void MemoryBlock::loadFromHexString (const String& hex)
  2967. {
  2968. ensureSize (hex.length() >> 1);
  2969. char* dest = data;
  2970. int i = 0;
  2971. for (;;)
  2972. {
  2973. int byte = 0;
  2974. for (int loop = 2; --loop >= 0;)
  2975. {
  2976. byte <<= 4;
  2977. for (;;)
  2978. {
  2979. const juce_wchar c = hex [i++];
  2980. if (c >= '0' && c <= '9')
  2981. {
  2982. byte |= c - '0';
  2983. break;
  2984. }
  2985. else if (c >= 'a' && c <= 'z')
  2986. {
  2987. byte |= c - ('a' - 10);
  2988. break;
  2989. }
  2990. else if (c >= 'A' && c <= 'Z')
  2991. {
  2992. byte |= c - ('A' - 10);
  2993. break;
  2994. }
  2995. else if (c == 0)
  2996. {
  2997. setSize (static_cast <size_t> (dest - data));
  2998. return;
  2999. }
  3000. }
  3001. }
  3002. *dest++ = (char) byte;
  3003. }
  3004. }
  3005. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3006. const String MemoryBlock::toBase64Encoding() const
  3007. {
  3008. const size_t numChars = ((size << 3) + 5) / 6;
  3009. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3010. const int initialLen = destString.length();
  3011. destString.preallocateStorage (initialLen + 2 + numChars);
  3012. juce_wchar* d = destString;
  3013. d += initialLen;
  3014. *d++ = '.';
  3015. for (size_t i = 0; i < numChars; ++i)
  3016. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3017. *d++ = 0;
  3018. return destString;
  3019. }
  3020. bool MemoryBlock::fromBase64Encoding (const String& s)
  3021. {
  3022. const int startPos = s.indexOfChar ('.') + 1;
  3023. if (startPos <= 0)
  3024. return false;
  3025. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3026. setSize (numBytesNeeded, true);
  3027. const int numChars = s.length() - startPos;
  3028. const juce_wchar* srcChars = s;
  3029. srcChars += startPos;
  3030. int pos = 0;
  3031. for (int i = 0; i < numChars; ++i)
  3032. {
  3033. const char c = (char) srcChars[i];
  3034. for (int j = 0; j < 64; ++j)
  3035. {
  3036. if (encodingTable[j] == c)
  3037. {
  3038. setBitRange (pos, 6, j);
  3039. pos += 6;
  3040. break;
  3041. }
  3042. }
  3043. }
  3044. return true;
  3045. }
  3046. END_JUCE_NAMESPACE
  3047. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3048. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3049. BEGIN_JUCE_NAMESPACE
  3050. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3051. : properties (ignoreCaseOfKeyNames),
  3052. fallbackProperties (0),
  3053. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3054. {
  3055. }
  3056. PropertySet::PropertySet (const PropertySet& other)
  3057. : properties (other.properties),
  3058. fallbackProperties (other.fallbackProperties),
  3059. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3060. {
  3061. }
  3062. PropertySet& PropertySet::operator= (const PropertySet& other)
  3063. {
  3064. properties = other.properties;
  3065. fallbackProperties = other.fallbackProperties;
  3066. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3067. propertyChanged();
  3068. return *this;
  3069. }
  3070. PropertySet::~PropertySet()
  3071. {
  3072. }
  3073. void PropertySet::clear()
  3074. {
  3075. const ScopedLock sl (lock);
  3076. if (properties.size() > 0)
  3077. {
  3078. properties.clear();
  3079. propertyChanged();
  3080. }
  3081. }
  3082. const String PropertySet::getValue (const String& keyName,
  3083. const String& defaultValue) const throw()
  3084. {
  3085. const ScopedLock sl (lock);
  3086. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3087. if (index >= 0)
  3088. return properties.getAllValues() [index];
  3089. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3090. : defaultValue;
  3091. }
  3092. int PropertySet::getIntValue (const String& keyName,
  3093. const int defaultValue) const throw()
  3094. {
  3095. const ScopedLock sl (lock);
  3096. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3097. if (index >= 0)
  3098. return properties.getAllValues() [index].getIntValue();
  3099. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3100. : defaultValue;
  3101. }
  3102. double PropertySet::getDoubleValue (const String& keyName,
  3103. const double defaultValue) const throw()
  3104. {
  3105. const ScopedLock sl (lock);
  3106. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3107. if (index >= 0)
  3108. return properties.getAllValues()[index].getDoubleValue();
  3109. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3110. : defaultValue;
  3111. }
  3112. bool PropertySet::getBoolValue (const String& keyName,
  3113. const bool defaultValue) const throw()
  3114. {
  3115. const ScopedLock sl (lock);
  3116. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3117. if (index >= 0)
  3118. return properties.getAllValues() [index].getIntValue() != 0;
  3119. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3120. : defaultValue;
  3121. }
  3122. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3123. {
  3124. return XmlDocument::parse (getValue (keyName));
  3125. }
  3126. void PropertySet::setValue (const String& keyName, const var& v)
  3127. {
  3128. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3129. if (keyName.isNotEmpty())
  3130. {
  3131. const String value (v.toString());
  3132. const ScopedLock sl (lock);
  3133. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3134. if (index < 0 || properties.getAllValues() [index] != value)
  3135. {
  3136. properties.set (keyName, value);
  3137. propertyChanged();
  3138. }
  3139. }
  3140. }
  3141. void PropertySet::removeValue (const String& keyName)
  3142. {
  3143. if (keyName.isNotEmpty())
  3144. {
  3145. const ScopedLock sl (lock);
  3146. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3147. if (index >= 0)
  3148. {
  3149. properties.remove (keyName);
  3150. propertyChanged();
  3151. }
  3152. }
  3153. }
  3154. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3155. {
  3156. setValue (keyName, xml == 0 ? var::null
  3157. : var (xml->createDocument (String::empty, true)));
  3158. }
  3159. bool PropertySet::containsKey (const String& keyName) const throw()
  3160. {
  3161. const ScopedLock sl (lock);
  3162. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3163. }
  3164. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3165. {
  3166. const ScopedLock sl (lock);
  3167. fallbackProperties = fallbackProperties_;
  3168. }
  3169. XmlElement* PropertySet::createXml (const String& nodeName) const
  3170. {
  3171. const ScopedLock sl (lock);
  3172. XmlElement* const xml = new XmlElement (nodeName);
  3173. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3174. {
  3175. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3176. e->setAttribute ("name", properties.getAllKeys()[i]);
  3177. e->setAttribute ("val", properties.getAllValues()[i]);
  3178. }
  3179. return xml;
  3180. }
  3181. void PropertySet::restoreFromXml (const XmlElement& xml)
  3182. {
  3183. const ScopedLock sl (lock);
  3184. clear();
  3185. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3186. {
  3187. if (e->hasAttribute ("name")
  3188. && e->hasAttribute ("val"))
  3189. {
  3190. properties.set (e->getStringAttribute ("name"),
  3191. e->getStringAttribute ("val"));
  3192. }
  3193. }
  3194. if (properties.size() > 0)
  3195. propertyChanged();
  3196. }
  3197. void PropertySet::propertyChanged()
  3198. {
  3199. }
  3200. END_JUCE_NAMESPACE
  3201. /*** End of inlined file: juce_PropertySet.cpp ***/
  3202. /*** Start of inlined file: juce_Identifier.cpp ***/
  3203. BEGIN_JUCE_NAMESPACE
  3204. StringPool& Identifier::getPool()
  3205. {
  3206. static StringPool pool;
  3207. return pool;
  3208. }
  3209. Identifier::Identifier() throw()
  3210. : name (0)
  3211. {
  3212. }
  3213. Identifier::Identifier (const Identifier& other) throw()
  3214. : name (other.name)
  3215. {
  3216. }
  3217. Identifier& Identifier::operator= (const Identifier& other) throw()
  3218. {
  3219. name = other.name;
  3220. return *this;
  3221. }
  3222. Identifier::Identifier (const String& name_)
  3223. : name (Identifier::getPool().getPooledString (name_))
  3224. {
  3225. /* An Identifier string must be suitable for use as a script variable or XML
  3226. attribute, so it can only contain this limited set of characters.. */
  3227. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3228. }
  3229. Identifier::Identifier (const char* const name_)
  3230. : name (Identifier::getPool().getPooledString (name_))
  3231. {
  3232. /* An Identifier string must be suitable for use as a script variable or XML
  3233. attribute, so it can only contain this limited set of characters.. */
  3234. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3235. }
  3236. Identifier::~Identifier()
  3237. {
  3238. }
  3239. END_JUCE_NAMESPACE
  3240. /*** End of inlined file: juce_Identifier.cpp ***/
  3241. /*** Start of inlined file: juce_Variant.cpp ***/
  3242. BEGIN_JUCE_NAMESPACE
  3243. class var::VariantType
  3244. {
  3245. public:
  3246. VariantType() {}
  3247. virtual ~VariantType() {}
  3248. virtual int toInt (const ValueUnion&) const { return 0; }
  3249. virtual double toDouble (const ValueUnion&) const { return 0; }
  3250. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3251. virtual bool toBool (const ValueUnion&) const { return false; }
  3252. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3253. virtual bool isVoid() const throw() { return false; }
  3254. virtual bool isInt() const throw() { return false; }
  3255. virtual bool isBool() const throw() { return false; }
  3256. virtual bool isDouble() const throw() { return false; }
  3257. virtual bool isString() const throw() { return false; }
  3258. virtual bool isObject() const throw() { return false; }
  3259. virtual bool isMethod() const throw() { return false; }
  3260. virtual void cleanUp (ValueUnion&) const throw() {}
  3261. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3262. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3263. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3264. };
  3265. class var::VariantType_Void : public var::VariantType
  3266. {
  3267. public:
  3268. VariantType_Void() {}
  3269. static const VariantType_Void instance;
  3270. bool isVoid() const throw() { return true; }
  3271. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3272. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3273. };
  3274. class var::VariantType_Int : public var::VariantType
  3275. {
  3276. public:
  3277. VariantType_Int() {}
  3278. static const VariantType_Int instance;
  3279. int toInt (const ValueUnion& data) const { return data.intValue; };
  3280. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3281. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3282. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3283. bool isInt() const throw() { return true; }
  3284. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3285. {
  3286. return otherType.toInt (otherData) == data.intValue;
  3287. }
  3288. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3289. {
  3290. output.writeCompressedInt (5);
  3291. output.writeByte (1);
  3292. output.writeInt (data.intValue);
  3293. }
  3294. };
  3295. class var::VariantType_Double : public var::VariantType
  3296. {
  3297. public:
  3298. VariantType_Double() {}
  3299. static const VariantType_Double instance;
  3300. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3301. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3302. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3303. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3304. bool isDouble() const throw() { return true; }
  3305. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3306. {
  3307. return otherType.toDouble (otherData) == data.doubleValue;
  3308. }
  3309. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3310. {
  3311. output.writeCompressedInt (9);
  3312. output.writeByte (4);
  3313. output.writeDouble (data.doubleValue);
  3314. }
  3315. };
  3316. class var::VariantType_Bool : public var::VariantType
  3317. {
  3318. public:
  3319. VariantType_Bool() {}
  3320. static const VariantType_Bool instance;
  3321. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3322. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3323. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3324. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3325. bool isBool() const throw() { return true; }
  3326. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3327. {
  3328. return otherType.toBool (otherData) == data.boolValue;
  3329. }
  3330. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3331. {
  3332. output.writeCompressedInt (1);
  3333. output.writeByte (data.boolValue ? 2 : 3);
  3334. }
  3335. };
  3336. class var::VariantType_String : public var::VariantType
  3337. {
  3338. public:
  3339. VariantType_String() {}
  3340. static const VariantType_String instance;
  3341. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3342. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3343. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3344. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3345. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3346. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3347. || data.stringValue->trim().equalsIgnoreCase ("true")
  3348. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3349. bool isString() const throw() { return true; }
  3350. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3351. {
  3352. return otherType.toString (otherData) == *data.stringValue;
  3353. }
  3354. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3355. {
  3356. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3357. output.writeCompressedInt (len + 1);
  3358. output.writeByte (5);
  3359. HeapBlock<char> temp (len);
  3360. data.stringValue->copyToUTF8 (temp, len);
  3361. output.write (temp, len);
  3362. }
  3363. };
  3364. class var::VariantType_Object : public var::VariantType
  3365. {
  3366. public:
  3367. VariantType_Object() {}
  3368. static const VariantType_Object instance;
  3369. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3370. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3371. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3372. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3373. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3374. bool isObject() const throw() { return true; }
  3375. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3376. {
  3377. return otherType.toObject (otherData) == data.objectValue;
  3378. }
  3379. void writeToStream (const ValueUnion&, OutputStream& output) const
  3380. {
  3381. jassertfalse; // Can't write an object to a stream!
  3382. output.writeCompressedInt (0);
  3383. }
  3384. };
  3385. class var::VariantType_Method : public var::VariantType
  3386. {
  3387. public:
  3388. VariantType_Method() {}
  3389. static const VariantType_Method instance;
  3390. const String toString (const ValueUnion&) const { return "Method"; }
  3391. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3392. bool isMethod() const throw() { return true; }
  3393. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3394. {
  3395. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3396. }
  3397. void writeToStream (const ValueUnion&, OutputStream& output) const
  3398. {
  3399. jassertfalse; // Can't write a method to a stream!
  3400. output.writeCompressedInt (0);
  3401. }
  3402. };
  3403. const var::VariantType_Void var::VariantType_Void::instance;
  3404. const var::VariantType_Int var::VariantType_Int::instance;
  3405. const var::VariantType_Bool var::VariantType_Bool::instance;
  3406. const var::VariantType_Double var::VariantType_Double::instance;
  3407. const var::VariantType_String var::VariantType_String::instance;
  3408. const var::VariantType_Object var::VariantType_Object::instance;
  3409. const var::VariantType_Method var::VariantType_Method::instance;
  3410. var::var() throw() : type (&VariantType_Void::instance)
  3411. {
  3412. }
  3413. var::~var() throw()
  3414. {
  3415. type->cleanUp (value);
  3416. }
  3417. const var var::null;
  3418. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3419. {
  3420. type->createCopy (value, valueToCopy.value);
  3421. }
  3422. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3423. {
  3424. value.intValue = value_;
  3425. }
  3426. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3427. {
  3428. value.boolValue = value_;
  3429. }
  3430. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3431. {
  3432. value.doubleValue = value_;
  3433. }
  3434. var::var (const String& value_) : type (&VariantType_String::instance)
  3435. {
  3436. value.stringValue = new String (value_);
  3437. }
  3438. var::var (const char* const value_) : type (&VariantType_String::instance)
  3439. {
  3440. value.stringValue = new String (value_);
  3441. }
  3442. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3443. {
  3444. value.stringValue = new String (value_);
  3445. }
  3446. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3447. {
  3448. value.objectValue = object;
  3449. if (object != 0)
  3450. object->incReferenceCount();
  3451. }
  3452. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3453. {
  3454. value.methodValue = method_;
  3455. }
  3456. bool var::isVoid() const throw() { return type->isVoid(); }
  3457. bool var::isInt() const throw() { return type->isInt(); }
  3458. bool var::isBool() const throw() { return type->isBool(); }
  3459. bool var::isDouble() const throw() { return type->isDouble(); }
  3460. bool var::isString() const throw() { return type->isString(); }
  3461. bool var::isObject() const throw() { return type->isObject(); }
  3462. bool var::isMethod() const throw() { return type->isMethod(); }
  3463. var::operator int() const { return type->toInt (value); }
  3464. var::operator bool() const { return type->toBool (value); }
  3465. var::operator float() const { return (float) type->toDouble (value); }
  3466. var::operator double() const { return type->toDouble (value); }
  3467. const String var::toString() const { return type->toString (value); }
  3468. var::operator const String() const { return type->toString (value); }
  3469. DynamicObject* var::getObject() const { return type->toObject (value); }
  3470. void var::swapWith (var& other) throw()
  3471. {
  3472. swapVariables (type, other.type);
  3473. swapVariables (value, other.value);
  3474. }
  3475. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3476. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3477. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3478. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3479. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3480. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3481. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3482. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3483. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3484. bool var::equals (const var& other) const throw()
  3485. {
  3486. return type->equals (value, other.value, *other.type);
  3487. }
  3488. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3489. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3490. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3491. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3492. void var::writeToStream (OutputStream& output) const
  3493. {
  3494. type->writeToStream (value, output);
  3495. }
  3496. const var var::readFromStream (InputStream& input)
  3497. {
  3498. const int numBytes = input.readCompressedInt();
  3499. if (numBytes > 0)
  3500. {
  3501. switch (input.readByte())
  3502. {
  3503. case 1: return var (input.readInt());
  3504. case 2: return var (true);
  3505. case 3: return var (false);
  3506. case 4: return var (input.readDouble());
  3507. case 5:
  3508. {
  3509. MemoryOutputStream mo;
  3510. mo.writeFromInputStream (input, numBytes - 1);
  3511. return var (mo.toUTF8());
  3512. }
  3513. default: input.skipNextBytes (numBytes - 1); break;
  3514. }
  3515. }
  3516. return var::null;
  3517. }
  3518. const var var::operator[] (const Identifier& propertyName) const
  3519. {
  3520. DynamicObject* const o = getObject();
  3521. return o != 0 ? o->getProperty (propertyName) : var::null;
  3522. }
  3523. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3524. {
  3525. DynamicObject* const o = getObject();
  3526. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3527. }
  3528. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3529. {
  3530. if (isMethod())
  3531. {
  3532. DynamicObject* const target = targetObject.getObject();
  3533. if (target != 0)
  3534. return (target->*(value.methodValue)) (arguments, numArguments);
  3535. }
  3536. return var::null;
  3537. }
  3538. const var var::call (const Identifier& method) const
  3539. {
  3540. return invoke (method, 0, 0);
  3541. }
  3542. const var var::call (const Identifier& method, const var& arg1) const
  3543. {
  3544. return invoke (method, &arg1, 1);
  3545. }
  3546. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3547. {
  3548. var args[] = { arg1, arg2 };
  3549. return invoke (method, args, 2);
  3550. }
  3551. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3552. {
  3553. var args[] = { arg1, arg2, arg3 };
  3554. return invoke (method, args, 3);
  3555. }
  3556. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3557. {
  3558. var args[] = { arg1, arg2, arg3, arg4 };
  3559. return invoke (method, args, 4);
  3560. }
  3561. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3562. {
  3563. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3564. return invoke (method, args, 5);
  3565. }
  3566. END_JUCE_NAMESPACE
  3567. /*** End of inlined file: juce_Variant.cpp ***/
  3568. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3569. BEGIN_JUCE_NAMESPACE
  3570. NamedValueSet::NamedValue::NamedValue() throw()
  3571. {
  3572. }
  3573. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3574. : name (name_), value (value_)
  3575. {
  3576. }
  3577. NamedValueSet::NamedValue::NamedValue (const NamedValue& other)
  3578. : name (other.name), value (other.value)
  3579. {
  3580. }
  3581. NamedValueSet::NamedValue& NamedValueSet::NamedValue::operator= (const NamedValueSet::NamedValue& other)
  3582. {
  3583. name = other.name;
  3584. value = other.value;
  3585. return *this;
  3586. }
  3587. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3588. {
  3589. return name == other.name && value == other.value;
  3590. }
  3591. NamedValueSet::NamedValueSet() throw()
  3592. {
  3593. }
  3594. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3595. {
  3596. values.addCopyOfList (other.values);
  3597. }
  3598. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3599. {
  3600. clear();
  3601. values.addCopyOfList (other.values);
  3602. return *this;
  3603. }
  3604. NamedValueSet::~NamedValueSet()
  3605. {
  3606. clear();
  3607. }
  3608. void NamedValueSet::clear()
  3609. {
  3610. values.deleteAll();
  3611. }
  3612. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3613. {
  3614. const NamedValue* i1 = values;
  3615. const NamedValue* i2 = other.values;
  3616. while (i1 != 0 && i2 != 0)
  3617. {
  3618. if (! (*i1 == *i2))
  3619. return false;
  3620. i1 = i1->nextListItem;
  3621. i2 = i2->nextListItem;
  3622. }
  3623. return true;
  3624. }
  3625. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3626. {
  3627. return ! operator== (other);
  3628. }
  3629. int NamedValueSet::size() const throw()
  3630. {
  3631. return values.size();
  3632. }
  3633. const var& NamedValueSet::operator[] (const Identifier& name) const
  3634. {
  3635. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3636. if (i->name == name)
  3637. return i->value;
  3638. return var::null;
  3639. }
  3640. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3641. {
  3642. const var* v = getVarPointer (name);
  3643. return v != 0 ? *v : defaultReturnValue;
  3644. }
  3645. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3646. {
  3647. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3648. if (i->name == name)
  3649. return &(i->value);
  3650. return 0;
  3651. }
  3652. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3653. {
  3654. LinkedListPointer<NamedValue>* i = &values;
  3655. while (i->get() != 0)
  3656. {
  3657. NamedValue* const v = i->get();
  3658. if (v->name == name)
  3659. {
  3660. if (v->value == newValue)
  3661. return false;
  3662. v->value = newValue;
  3663. return true;
  3664. }
  3665. i = &(v->nextListItem);
  3666. }
  3667. i->insertNext (new NamedValue (name, newValue));
  3668. return true;
  3669. }
  3670. bool NamedValueSet::contains (const Identifier& name) const
  3671. {
  3672. return getVarPointer (name) != 0;
  3673. }
  3674. bool NamedValueSet::remove (const Identifier& name)
  3675. {
  3676. LinkedListPointer<NamedValue>* i = &values;
  3677. for (;;)
  3678. {
  3679. NamedValue* const v = i->get();
  3680. if (v == 0)
  3681. break;
  3682. if (v->name == name)
  3683. {
  3684. delete i->removeNext();
  3685. return true;
  3686. }
  3687. i = &(v->nextListItem);
  3688. }
  3689. return false;
  3690. }
  3691. const Identifier NamedValueSet::getName (const int index) const
  3692. {
  3693. const NamedValue* const v = values[index];
  3694. jassert (v != 0);
  3695. return v->name;
  3696. }
  3697. const var NamedValueSet::getValueAt (const int index) const
  3698. {
  3699. const NamedValue* const v = values[index];
  3700. jassert (v != 0);
  3701. return v->value;
  3702. }
  3703. void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
  3704. {
  3705. clear();
  3706. LinkedListPointer<NamedValue>::Appender appender (values);
  3707. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  3708. for (int i = 0; i < numAtts; ++i)
  3709. appender.append (new NamedValue (xml.getAttributeName (i), var (xml.getAttributeValue (i))));
  3710. }
  3711. void NamedValueSet::copyToXmlAttributes (XmlElement& xml) const
  3712. {
  3713. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3714. {
  3715. jassert (! i->value.isObject()); // DynamicObjects can't be stored as XML!
  3716. xml.setAttribute (i->name.toString(),
  3717. i->value.toString());
  3718. }
  3719. }
  3720. END_JUCE_NAMESPACE
  3721. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3722. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3723. BEGIN_JUCE_NAMESPACE
  3724. DynamicObject::DynamicObject()
  3725. {
  3726. }
  3727. DynamicObject::~DynamicObject()
  3728. {
  3729. }
  3730. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3731. {
  3732. var* const v = properties.getVarPointer (propertyName);
  3733. return v != 0 && ! v->isMethod();
  3734. }
  3735. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3736. {
  3737. return properties [propertyName];
  3738. }
  3739. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3740. {
  3741. properties.set (propertyName, newValue);
  3742. }
  3743. void DynamicObject::removeProperty (const Identifier& propertyName)
  3744. {
  3745. properties.remove (propertyName);
  3746. }
  3747. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3748. {
  3749. return getProperty (methodName).isMethod();
  3750. }
  3751. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3752. const var* parameters,
  3753. int numParameters)
  3754. {
  3755. return properties [methodName].invoke (var (this), parameters, numParameters);
  3756. }
  3757. void DynamicObject::setMethod (const Identifier& name,
  3758. var::MethodFunction methodFunction)
  3759. {
  3760. properties.set (name, var (methodFunction));
  3761. }
  3762. void DynamicObject::clear()
  3763. {
  3764. properties.clear();
  3765. }
  3766. END_JUCE_NAMESPACE
  3767. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3768. /*** Start of inlined file: juce_Expression.cpp ***/
  3769. BEGIN_JUCE_NAMESPACE
  3770. class Expression::Helpers
  3771. {
  3772. public:
  3773. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3774. // This helper function is needed to work around VC6 scoping bugs
  3775. static const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3776. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3777. class Constant : public Term
  3778. {
  3779. public:
  3780. Constant (const double value_, bool isResolutionTarget_)
  3781. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3782. Type getType() const throw() { return constantType; }
  3783. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3784. double evaluate (const EvaluationContext&, int) const { return value; }
  3785. int getNumInputs() const { return 0; }
  3786. Term* getInput (int) const { return 0; }
  3787. const TermPtr negated()
  3788. {
  3789. return new Constant (-value, isResolutionTarget);
  3790. }
  3791. const String toString() const
  3792. {
  3793. if (isResolutionTarget)
  3794. return "@" + String (value);
  3795. return String (value);
  3796. }
  3797. double value;
  3798. bool isResolutionTarget;
  3799. };
  3800. class Symbol : public Term
  3801. {
  3802. public:
  3803. explicit Symbol (const String& symbol_)
  3804. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3805. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3806. {}
  3807. Symbol (const String& symbol_, const String& member_)
  3808. : mainSymbol (symbol_),
  3809. member (member_)
  3810. {}
  3811. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3812. {
  3813. if (++recursionDepth > 256)
  3814. throw EvaluationError ("Recursive symbol references");
  3815. try
  3816. {
  3817. return getTermFor (c.getSymbolValue (mainSymbol, member))->evaluate (c, recursionDepth);
  3818. }
  3819. catch (...)
  3820. {}
  3821. return 0;
  3822. }
  3823. Type getType() const throw() { return symbolType; }
  3824. Term* clone() const { return new Symbol (mainSymbol, member); }
  3825. int getNumInputs() const { return 0; }
  3826. Term* getInput (int) const { return 0; }
  3827. const String toString() const { return joinParts (mainSymbol, member); }
  3828. void getSymbolParts (String& objectName, String& memberName) const { objectName = mainSymbol; memberName = member; }
  3829. static const String joinParts (const String& mainSymbol, const String& member)
  3830. {
  3831. return member.isEmpty() ? mainSymbol
  3832. : mainSymbol + "." + member;
  3833. }
  3834. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3835. {
  3836. if (s == mainSymbol || (s.containsChar ('.') && s == toString()))
  3837. return true;
  3838. if (++recursionDepth > 256)
  3839. throw EvaluationError ("Recursive symbol references");
  3840. try
  3841. {
  3842. return c != 0 && getTermFor (c->getSymbolValue (mainSymbol, member))->referencesSymbol (s, c, recursionDepth);
  3843. }
  3844. catch (EvaluationError&)
  3845. {
  3846. return false;
  3847. }
  3848. }
  3849. String mainSymbol, member;
  3850. };
  3851. class Function : public Term
  3852. {
  3853. public:
  3854. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3855. : functionName (functionName_), parameters (parameters_)
  3856. {}
  3857. Term* clone() const { return new Function (functionName, parameters); }
  3858. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3859. {
  3860. HeapBlock <double> params (parameters.size());
  3861. for (int i = 0; i < parameters.size(); ++i)
  3862. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3863. return c.evaluateFunction (functionName, params, parameters.size());
  3864. }
  3865. Type getType() const throw() { return functionType; }
  3866. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3867. int getNumInputs() const { return parameters.size(); }
  3868. Term* getInput (int i) const { return parameters [i]; }
  3869. const String getFunctionName() const { return functionName; }
  3870. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3871. {
  3872. for (int i = 0; i < parameters.size(); ++i)
  3873. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3874. return true;
  3875. return false;
  3876. }
  3877. const String toString() const
  3878. {
  3879. if (parameters.size() == 0)
  3880. return functionName + "()";
  3881. String s (functionName + " (");
  3882. for (int i = 0; i < parameters.size(); ++i)
  3883. {
  3884. s << parameters.getUnchecked(i)->toString();
  3885. if (i < parameters.size() - 1)
  3886. s << ", ";
  3887. }
  3888. s << ')';
  3889. return s;
  3890. }
  3891. const String functionName;
  3892. ReferenceCountedArray<Term> parameters;
  3893. };
  3894. class Negate : public Term
  3895. {
  3896. public:
  3897. explicit Negate (const TermPtr& input_) : input (input_)
  3898. {
  3899. jassert (input_ != 0);
  3900. }
  3901. Type getType() const throw() { return operatorType; }
  3902. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3903. int getNumInputs() const { return 1; }
  3904. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3905. Term* clone() const { return new Negate (input->clone()); }
  3906. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3907. const String getFunctionName() const { return "-"; }
  3908. const TermPtr negated()
  3909. {
  3910. return input;
  3911. }
  3912. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3913. {
  3914. (void) input_;
  3915. jassert (input_ == input);
  3916. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3917. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3918. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3919. }
  3920. const String toString() const
  3921. {
  3922. if (input->getOperatorPrecedence() > 0)
  3923. return "-(" + input->toString() + ")";
  3924. else
  3925. return "-" + input->toString();
  3926. }
  3927. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3928. {
  3929. return input->referencesSymbol (s, c, recursionDepth);
  3930. }
  3931. private:
  3932. const TermPtr input;
  3933. };
  3934. class BinaryTerm : public Term
  3935. {
  3936. public:
  3937. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3938. {
  3939. jassert (left_ != 0 && right_ != 0);
  3940. }
  3941. int getInputIndexFor (const Term* possibleInput) const
  3942. {
  3943. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3944. }
  3945. Type getType() const throw() { return operatorType; }
  3946. int getNumInputs() const { return 2; }
  3947. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3948. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3949. {
  3950. return left->referencesSymbol (s, c, recursionDepth)
  3951. || right->referencesSymbol (s, c, recursionDepth);
  3952. }
  3953. const String toString() const
  3954. {
  3955. String s;
  3956. const int ourPrecendence = getOperatorPrecedence();
  3957. if (left->getOperatorPrecedence() > ourPrecendence)
  3958. s << '(' << left->toString() << ')';
  3959. else
  3960. s = left->toString();
  3961. s << ' ' << getFunctionName() << ' ';
  3962. if (right->getOperatorPrecedence() >= ourPrecendence)
  3963. s << '(' << right->toString() << ')';
  3964. else
  3965. s << right->toString();
  3966. return s;
  3967. }
  3968. protected:
  3969. const TermPtr left, right;
  3970. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3971. {
  3972. jassert (input == left || input == right);
  3973. if (input != left && input != right)
  3974. return 0;
  3975. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3976. if (dest == 0)
  3977. return new Constant (overallTarget, false);
  3978. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3979. }
  3980. };
  3981. class Add : public BinaryTerm
  3982. {
  3983. public:
  3984. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3985. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3986. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3987. int getOperatorPrecedence() const { return 2; }
  3988. const String getFunctionName() const { return "+"; }
  3989. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3990. {
  3991. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3992. if (newDest == 0)
  3993. return 0;
  3994. return new Subtract (newDest, (input == left ? right : left)->clone());
  3995. }
  3996. private:
  3997. JUCE_DECLARE_NON_COPYABLE (Add);
  3998. };
  3999. class Subtract : public BinaryTerm
  4000. {
  4001. public:
  4002. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4003. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4004. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  4005. int getOperatorPrecedence() const { return 2; }
  4006. const String getFunctionName() const { return "-"; }
  4007. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4008. {
  4009. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4010. if (newDest == 0)
  4011. return 0;
  4012. if (input == left)
  4013. return new Add (newDest, right->clone());
  4014. else
  4015. return new Subtract (left->clone(), newDest);
  4016. }
  4017. private:
  4018. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4019. };
  4020. class Multiply : public BinaryTerm
  4021. {
  4022. public:
  4023. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4024. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4025. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4026. const String getFunctionName() const { return "*"; }
  4027. int getOperatorPrecedence() const { return 1; }
  4028. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4029. {
  4030. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4031. if (newDest == 0)
  4032. return 0;
  4033. return new Divide (newDest, (input == left ? right : left)->clone());
  4034. }
  4035. private:
  4036. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4037. };
  4038. class Divide : public BinaryTerm
  4039. {
  4040. public:
  4041. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4042. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4043. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4044. const String getFunctionName() const { return "/"; }
  4045. int getOperatorPrecedence() const { return 1; }
  4046. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4047. {
  4048. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4049. if (newDest == 0)
  4050. return 0;
  4051. if (input == left)
  4052. return new Multiply (newDest, right->clone());
  4053. else
  4054. return new Divide (left->clone(), newDest);
  4055. }
  4056. private:
  4057. JUCE_DECLARE_NON_COPYABLE (Divide);
  4058. };
  4059. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4060. {
  4061. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4062. if (inputIndex >= 0)
  4063. return topLevel;
  4064. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4065. {
  4066. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4067. if (t != 0)
  4068. return t;
  4069. }
  4070. return 0;
  4071. }
  4072. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4073. {
  4074. {
  4075. Constant* const c = dynamic_cast<Constant*> (term);
  4076. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4077. return c;
  4078. }
  4079. if (dynamic_cast<Function*> (term) != 0)
  4080. return 0;
  4081. int i;
  4082. const int numIns = term->getNumInputs();
  4083. for (i = 0; i < numIns; ++i)
  4084. {
  4085. Constant* const c = dynamic_cast<Constant*> (term->getInput (i));
  4086. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4087. return c;
  4088. }
  4089. for (i = 0; i < numIns; ++i)
  4090. {
  4091. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4092. if (c != 0)
  4093. return c;
  4094. }
  4095. return 0;
  4096. }
  4097. static bool containsAnySymbols (const Term* const t)
  4098. {
  4099. if (t->getType() == Expression::symbolType)
  4100. return true;
  4101. for (int i = t->getNumInputs(); --i >= 0;)
  4102. if (containsAnySymbols (t->getInput (i)))
  4103. return true;
  4104. return false;
  4105. }
  4106. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4107. {
  4108. Symbol* const sym = dynamic_cast<Symbol*> (t);
  4109. if (sym != 0 && sym->mainSymbol == oldName)
  4110. {
  4111. sym->mainSymbol = newName;
  4112. return true;
  4113. }
  4114. bool anyChanged = false;
  4115. for (int i = t->getNumInputs(); --i >= 0;)
  4116. if (renameSymbol (t->getInput (i), oldName, newName))
  4117. anyChanged = true;
  4118. return anyChanged;
  4119. }
  4120. class Parser
  4121. {
  4122. public:
  4123. Parser (const String& stringToParse, int& textIndex_)
  4124. : textString (stringToParse), textIndex (textIndex_)
  4125. {
  4126. text = textString;
  4127. }
  4128. const TermPtr readExpression()
  4129. {
  4130. TermPtr lhs (readMultiplyOrDivideExpression());
  4131. char opType;
  4132. while (lhs != 0 && readOperator ("+-", &opType))
  4133. {
  4134. TermPtr rhs (readMultiplyOrDivideExpression());
  4135. if (rhs == 0)
  4136. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4137. if (opType == '+')
  4138. lhs = new Add (lhs, rhs);
  4139. else
  4140. lhs = new Subtract (lhs, rhs);
  4141. }
  4142. return lhs;
  4143. }
  4144. private:
  4145. const String textString;
  4146. const juce_wchar* text;
  4147. int& textIndex;
  4148. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4149. {
  4150. return c >= '0' && c <= '9';
  4151. }
  4152. void skipWhitespace (int& i) throw()
  4153. {
  4154. while (CharacterFunctions::isWhitespace (text [i]))
  4155. ++i;
  4156. }
  4157. bool readChar (const juce_wchar required) throw()
  4158. {
  4159. if (text[textIndex] == required)
  4160. {
  4161. ++textIndex;
  4162. return true;
  4163. }
  4164. return false;
  4165. }
  4166. bool readOperator (const char* ops, char* const opType = 0) throw()
  4167. {
  4168. skipWhitespace (textIndex);
  4169. while (*ops != 0)
  4170. {
  4171. if (readChar (*ops))
  4172. {
  4173. if (opType != 0)
  4174. *opType = *ops;
  4175. return true;
  4176. }
  4177. ++ops;
  4178. }
  4179. return false;
  4180. }
  4181. bool readIdentifier (String& identifier) throw()
  4182. {
  4183. skipWhitespace (textIndex);
  4184. int i = textIndex;
  4185. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4186. {
  4187. ++i;
  4188. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4189. ++i;
  4190. }
  4191. if (i > textIndex)
  4192. {
  4193. identifier = String (text + textIndex, i - textIndex);
  4194. textIndex = i;
  4195. return true;
  4196. }
  4197. return false;
  4198. }
  4199. Term* readNumber() throw()
  4200. {
  4201. skipWhitespace (textIndex);
  4202. int i = textIndex;
  4203. const bool isResolutionTarget = (text[i] == '@');
  4204. if (isResolutionTarget)
  4205. {
  4206. ++i;
  4207. skipWhitespace (i);
  4208. textIndex = i;
  4209. }
  4210. if (text[i] == '-')
  4211. {
  4212. ++i;
  4213. skipWhitespace (i);
  4214. }
  4215. int numDigits = 0;
  4216. while (isDecimalDigit (text[i]))
  4217. {
  4218. ++i;
  4219. ++numDigits;
  4220. }
  4221. const bool hasPoint = (text[i] == '.');
  4222. if (hasPoint)
  4223. {
  4224. ++i;
  4225. while (isDecimalDigit (text[i]))
  4226. {
  4227. ++i;
  4228. ++numDigits;
  4229. }
  4230. }
  4231. if (numDigits == 0)
  4232. return 0;
  4233. juce_wchar c = text[i];
  4234. const bool hasExponent = (c == 'e' || c == 'E');
  4235. if (hasExponent)
  4236. {
  4237. ++i;
  4238. c = text[i];
  4239. if (c == '+' || c == '-')
  4240. ++i;
  4241. int numExpDigits = 0;
  4242. while (isDecimalDigit (text[i]))
  4243. {
  4244. ++i;
  4245. ++numExpDigits;
  4246. }
  4247. if (numExpDigits == 0)
  4248. return 0;
  4249. }
  4250. const int start = textIndex;
  4251. textIndex = i;
  4252. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4253. }
  4254. const TermPtr readMultiplyOrDivideExpression()
  4255. {
  4256. TermPtr lhs (readUnaryExpression());
  4257. char opType;
  4258. while (lhs != 0 && readOperator ("*/", &opType))
  4259. {
  4260. TermPtr rhs (readUnaryExpression());
  4261. if (rhs == 0)
  4262. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4263. if (opType == '*')
  4264. lhs = new Multiply (lhs, rhs);
  4265. else
  4266. lhs = new Divide (lhs, rhs);
  4267. }
  4268. return lhs;
  4269. }
  4270. const TermPtr readUnaryExpression()
  4271. {
  4272. char opType;
  4273. if (readOperator ("+-", &opType))
  4274. {
  4275. TermPtr term (readUnaryExpression());
  4276. if (term == 0)
  4277. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4278. if (opType == '-')
  4279. term = term->negated();
  4280. return term;
  4281. }
  4282. return readPrimaryExpression();
  4283. }
  4284. const TermPtr readPrimaryExpression()
  4285. {
  4286. TermPtr e (readParenthesisedExpression());
  4287. if (e != 0)
  4288. return e;
  4289. e = readNumber();
  4290. if (e != 0)
  4291. return e;
  4292. String identifier;
  4293. if (readIdentifier (identifier))
  4294. {
  4295. if (readOperator ("(")) // method call...
  4296. {
  4297. Function* const f = new Function (identifier, ReferenceCountedArray<Term>());
  4298. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4299. TermPtr param (readExpression());
  4300. if (param == 0)
  4301. {
  4302. if (readOperator (")"))
  4303. return func.release();
  4304. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4305. }
  4306. f->parameters.add (param);
  4307. while (readOperator (","))
  4308. {
  4309. param = readExpression();
  4310. if (param == 0)
  4311. throw ParseError ("Expected expression after \",\"");
  4312. f->parameters.add (param);
  4313. }
  4314. if (readOperator (")"))
  4315. return func.release();
  4316. throw ParseError ("Expected \")\"");
  4317. }
  4318. else // just a symbol..
  4319. {
  4320. return new Symbol (identifier);
  4321. }
  4322. }
  4323. return 0;
  4324. }
  4325. const TermPtr readParenthesisedExpression()
  4326. {
  4327. if (! readOperator ("("))
  4328. return 0;
  4329. const TermPtr e (readExpression());
  4330. if (e == 0 || ! readOperator (")"))
  4331. return 0;
  4332. return e;
  4333. }
  4334. JUCE_DECLARE_NON_COPYABLE (Parser);
  4335. };
  4336. };
  4337. Expression::Expression()
  4338. : term (new Expression::Helpers::Constant (0, false))
  4339. {
  4340. }
  4341. Expression::~Expression()
  4342. {
  4343. }
  4344. Expression::Expression (Term* const term_)
  4345. : term (term_)
  4346. {
  4347. jassert (term != 0);
  4348. }
  4349. Expression::Expression (const double constant)
  4350. : term (new Expression::Helpers::Constant (constant, false))
  4351. {
  4352. }
  4353. Expression::Expression (const Expression& other)
  4354. : term (other.term)
  4355. {
  4356. }
  4357. Expression& Expression::operator= (const Expression& other)
  4358. {
  4359. term = other.term;
  4360. return *this;
  4361. }
  4362. Expression::Expression (const String& stringToParse)
  4363. {
  4364. int i = 0;
  4365. Helpers::Parser parser (stringToParse, i);
  4366. term = parser.readExpression();
  4367. if (term == 0)
  4368. term = new Helpers::Constant (0, false);
  4369. }
  4370. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4371. {
  4372. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4373. const Helpers::TermPtr term (parser.readExpression());
  4374. if (term != 0)
  4375. return Expression (term);
  4376. return Expression();
  4377. }
  4378. double Expression::evaluate() const
  4379. {
  4380. return evaluate (Expression::EvaluationContext());
  4381. }
  4382. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4383. {
  4384. return term->evaluate (context, 0);
  4385. }
  4386. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4387. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4388. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4389. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4390. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4391. const String Expression::toString() const
  4392. {
  4393. return term->toString();
  4394. }
  4395. const Expression Expression::symbol (const String& symbol)
  4396. {
  4397. return Expression (new Helpers::Symbol (symbol));
  4398. }
  4399. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4400. {
  4401. ReferenceCountedArray<Term> params;
  4402. for (int i = 0; i < parameters.size(); ++i)
  4403. params.add (parameters.getReference(i).term);
  4404. return Expression (new Helpers::Function (functionName, params));
  4405. }
  4406. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4407. const Expression::EvaluationContext& context) const
  4408. {
  4409. ScopedPointer<Term> newTerm (term->clone());
  4410. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4411. if (termToAdjust == 0)
  4412. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4413. if (termToAdjust == 0)
  4414. {
  4415. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4416. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4417. }
  4418. jassert (termToAdjust != 0);
  4419. const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4420. if (parent == 0)
  4421. {
  4422. termToAdjust->value = targetValue;
  4423. }
  4424. else
  4425. {
  4426. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4427. if (reverseTerm == 0)
  4428. return Expression (targetValue);
  4429. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4430. }
  4431. return Expression (newTerm.release());
  4432. }
  4433. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4434. {
  4435. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4436. if (oldSymbol == newSymbol)
  4437. return *this;
  4438. Expression newExpression (term->clone());
  4439. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4440. return newExpression;
  4441. }
  4442. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4443. {
  4444. return term->referencesSymbol (symbol, context, 0);
  4445. }
  4446. bool Expression::usesAnySymbols() const
  4447. {
  4448. return Helpers::containsAnySymbols (term);
  4449. }
  4450. Expression::Type Expression::getType() const throw()
  4451. {
  4452. return term->getType();
  4453. }
  4454. const String Expression::getSymbol() const
  4455. {
  4456. String objectName, memberName;
  4457. term->getSymbolParts (objectName, memberName);
  4458. return Expression::Helpers::Symbol::joinParts (objectName, memberName);
  4459. }
  4460. void Expression::getSymbolParts (String& objectName, String& memberName) const
  4461. {
  4462. term->getSymbolParts (objectName, memberName);
  4463. }
  4464. const String Expression::getFunction() const
  4465. {
  4466. return term->getFunctionName();
  4467. }
  4468. const String Expression::getOperator() const
  4469. {
  4470. return term->getFunctionName();
  4471. }
  4472. int Expression::getNumInputs() const
  4473. {
  4474. return term->getNumInputs();
  4475. }
  4476. const Expression Expression::getInput (int index) const
  4477. {
  4478. return Expression (term->getInput (index));
  4479. }
  4480. int Expression::Term::getOperatorPrecedence() const
  4481. {
  4482. return 0;
  4483. }
  4484. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4485. {
  4486. return false;
  4487. }
  4488. int Expression::Term::getInputIndexFor (const Term*) const
  4489. {
  4490. return -1;
  4491. }
  4492. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4493. {
  4494. jassertfalse;
  4495. return 0;
  4496. }
  4497. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4498. {
  4499. return new Helpers::Negate (this);
  4500. }
  4501. void Expression::Term::getSymbolParts (String&, String&) const
  4502. {
  4503. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4504. }
  4505. const String Expression::Term::getFunctionName() const
  4506. {
  4507. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4508. return String::empty;
  4509. }
  4510. Expression::ParseError::ParseError (const String& message)
  4511. : description (message)
  4512. {
  4513. DBG ("Expression::ParseError: " + message);
  4514. }
  4515. Expression::EvaluationError::EvaluationError (const String& message)
  4516. : description (message)
  4517. {
  4518. DBG ("Expression::EvaluationError: " + description);
  4519. }
  4520. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4521. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4522. {
  4523. DBG ("Expression::EvaluationError: " + description);
  4524. }
  4525. Expression::EvaluationContext::EvaluationContext() {}
  4526. Expression::EvaluationContext::~EvaluationContext() {}
  4527. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4528. {
  4529. throw EvaluationError (symbol, member);
  4530. }
  4531. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4532. {
  4533. if (numParams > 0)
  4534. {
  4535. if (functionName == "min")
  4536. {
  4537. double v = parameters[0];
  4538. for (int i = 1; i < numParams; ++i)
  4539. v = jmin (v, parameters[i]);
  4540. return v;
  4541. }
  4542. else if (functionName == "max")
  4543. {
  4544. double v = parameters[0];
  4545. for (int i = 1; i < numParams; ++i)
  4546. v = jmax (v, parameters[i]);
  4547. return v;
  4548. }
  4549. else if (numParams == 1)
  4550. {
  4551. if (functionName == "sin") return sin (parameters[0]);
  4552. else if (functionName == "cos") return cos (parameters[0]);
  4553. else if (functionName == "tan") return tan (parameters[0]);
  4554. else if (functionName == "abs") return std::abs (parameters[0]);
  4555. }
  4556. }
  4557. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4558. }
  4559. END_JUCE_NAMESPACE
  4560. /*** End of inlined file: juce_Expression.cpp ***/
  4561. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4562. BEGIN_JUCE_NAMESPACE
  4563. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4564. {
  4565. jassert (keyData != 0);
  4566. jassert (keyBytes > 0);
  4567. static const uint32 initialPValues [18] =
  4568. {
  4569. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4570. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4571. 0x9216d5d9, 0x8979fb1b
  4572. };
  4573. static const uint32 initialSValues [4 * 256] =
  4574. {
  4575. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4576. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4577. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4578. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4579. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4580. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4581. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4582. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4583. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4584. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4585. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4586. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4587. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4588. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4589. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4590. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4591. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4592. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4593. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4594. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4595. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4596. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4597. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4598. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4599. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4600. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4601. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4602. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4603. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4604. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4605. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4606. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4607. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4608. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4609. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4610. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4611. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4612. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4613. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4614. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4615. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4616. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4617. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4618. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4619. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4620. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4621. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4622. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4623. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4624. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4625. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4626. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4627. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4628. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4629. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4630. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4631. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4632. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4633. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4634. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4635. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4636. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4637. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4638. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4639. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4640. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4641. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4642. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4643. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4644. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4645. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4646. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4647. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4648. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4649. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4650. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4651. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4652. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4653. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4654. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4655. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4656. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4657. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4658. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4659. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4660. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4661. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4662. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4663. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4664. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4665. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4666. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4667. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4668. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4669. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4670. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4671. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4672. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4673. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4674. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4675. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4676. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4677. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4678. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4679. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4680. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4681. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4682. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4683. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4684. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4685. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4686. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4687. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4688. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4689. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4690. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4691. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4692. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4693. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4694. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4695. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4696. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4697. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4698. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4699. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4700. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4701. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4702. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4703. };
  4704. memcpy (p, initialPValues, sizeof (p));
  4705. int i, j = 0;
  4706. for (i = 4; --i >= 0;)
  4707. {
  4708. s[i].malloc (256);
  4709. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4710. }
  4711. for (i = 0; i < 18; ++i)
  4712. {
  4713. uint32 d = 0;
  4714. for (int k = 0; k < 4; ++k)
  4715. {
  4716. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4717. if (++j >= keyBytes)
  4718. j = 0;
  4719. }
  4720. p[i] = initialPValues[i] ^ d;
  4721. }
  4722. uint32 l = 0, r = 0;
  4723. for (i = 0; i < 18; i += 2)
  4724. {
  4725. encrypt (l, r);
  4726. p[i] = l;
  4727. p[i + 1] = r;
  4728. }
  4729. for (i = 0; i < 4; ++i)
  4730. {
  4731. for (j = 0; j < 256; j += 2)
  4732. {
  4733. encrypt (l, r);
  4734. s[i][j] = l;
  4735. s[i][j + 1] = r;
  4736. }
  4737. }
  4738. }
  4739. BlowFish::BlowFish (const BlowFish& other)
  4740. {
  4741. for (int i = 4; --i >= 0;)
  4742. s[i].malloc (256);
  4743. operator= (other);
  4744. }
  4745. BlowFish& BlowFish::operator= (const BlowFish& other)
  4746. {
  4747. memcpy (p, other.p, sizeof (p));
  4748. for (int i = 4; --i >= 0;)
  4749. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4750. return *this;
  4751. }
  4752. BlowFish::~BlowFish()
  4753. {
  4754. }
  4755. uint32 BlowFish::F (const uint32 x) const throw()
  4756. {
  4757. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4758. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4759. }
  4760. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4761. {
  4762. uint32 l = data1;
  4763. uint32 r = data2;
  4764. for (int i = 0; i < 16; ++i)
  4765. {
  4766. l ^= p[i];
  4767. r ^= F(l);
  4768. swapVariables (l, r);
  4769. }
  4770. data1 = r ^ p[17];
  4771. data2 = l ^ p[16];
  4772. }
  4773. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4774. {
  4775. uint32 l = data1;
  4776. uint32 r = data2;
  4777. for (int i = 17; i > 1; --i)
  4778. {
  4779. l ^= p[i];
  4780. r ^= F(l);
  4781. swapVariables (l, r);
  4782. }
  4783. data1 = r ^ p[0];
  4784. data2 = l ^ p[1];
  4785. }
  4786. END_JUCE_NAMESPACE
  4787. /*** End of inlined file: juce_BlowFish.cpp ***/
  4788. /*** Start of inlined file: juce_MD5.cpp ***/
  4789. BEGIN_JUCE_NAMESPACE
  4790. MD5::MD5()
  4791. {
  4792. zerostruct (result);
  4793. }
  4794. MD5::MD5 (const MD5& other)
  4795. {
  4796. memcpy (result, other.result, sizeof (result));
  4797. }
  4798. MD5& MD5::operator= (const MD5& other)
  4799. {
  4800. memcpy (result, other.result, sizeof (result));
  4801. return *this;
  4802. }
  4803. MD5::MD5 (const MemoryBlock& data)
  4804. {
  4805. ProcessContext context;
  4806. context.processBlock (data.getData(), data.getSize());
  4807. context.finish (result);
  4808. }
  4809. MD5::MD5 (const void* data, const size_t numBytes)
  4810. {
  4811. ProcessContext context;
  4812. context.processBlock (data, numBytes);
  4813. context.finish (result);
  4814. }
  4815. MD5::MD5 (const String& text)
  4816. {
  4817. ProcessContext context;
  4818. const int len = text.length();
  4819. const juce_wchar* const t = text;
  4820. for (int i = 0; i < len; ++i)
  4821. {
  4822. // force the string into integer-sized unicode characters, to try to make it
  4823. // get the same results on all platforms + compilers.
  4824. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4825. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4826. }
  4827. context.finish (result);
  4828. }
  4829. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4830. {
  4831. ProcessContext context;
  4832. if (numBytesToRead < 0)
  4833. numBytesToRead = std::numeric_limits<int64>::max();
  4834. while (numBytesToRead > 0)
  4835. {
  4836. uint8 tempBuffer [512];
  4837. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4838. if (bytesRead <= 0)
  4839. break;
  4840. numBytesToRead -= bytesRead;
  4841. context.processBlock (tempBuffer, bytesRead);
  4842. }
  4843. context.finish (result);
  4844. }
  4845. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4846. {
  4847. processStream (input, numBytesToRead);
  4848. }
  4849. MD5::MD5 (const File& file)
  4850. {
  4851. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4852. if (fin != 0)
  4853. processStream (*fin, -1);
  4854. else
  4855. zerostruct (result);
  4856. }
  4857. MD5::~MD5()
  4858. {
  4859. }
  4860. namespace MD5Functions
  4861. {
  4862. void encode (void* const output, const void* const input, const int numBytes) throw()
  4863. {
  4864. for (int i = 0; i < (numBytes >> 2); ++i)
  4865. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4866. }
  4867. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4868. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4869. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4870. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4871. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4872. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4873. {
  4874. a += F (b, c, d) + x + ac;
  4875. a = rotateLeft (a, s) + b;
  4876. }
  4877. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4878. {
  4879. a += G (b, c, d) + x + ac;
  4880. a = rotateLeft (a, s) + b;
  4881. }
  4882. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4883. {
  4884. a += H (b, c, d) + x + ac;
  4885. a = rotateLeft (a, s) + b;
  4886. }
  4887. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4888. {
  4889. a += I (b, c, d) + x + ac;
  4890. a = rotateLeft (a, s) + b;
  4891. }
  4892. }
  4893. MD5::ProcessContext::ProcessContext()
  4894. {
  4895. state[0] = 0x67452301;
  4896. state[1] = 0xefcdab89;
  4897. state[2] = 0x98badcfe;
  4898. state[3] = 0x10325476;
  4899. count[0] = 0;
  4900. count[1] = 0;
  4901. }
  4902. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4903. {
  4904. int bufferPos = ((count[0] >> 3) & 0x3F);
  4905. count[0] += (uint32) (dataSize << 3);
  4906. if (count[0] < ((uint32) dataSize << 3))
  4907. count[1]++;
  4908. count[1] += (uint32) (dataSize >> 29);
  4909. const size_t spaceLeft = 64 - bufferPos;
  4910. size_t i = 0;
  4911. if (dataSize >= spaceLeft)
  4912. {
  4913. memcpy (buffer + bufferPos, data, spaceLeft);
  4914. transform (buffer);
  4915. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4916. transform (static_cast <const char*> (data) + i);
  4917. bufferPos = 0;
  4918. }
  4919. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4920. }
  4921. void MD5::ProcessContext::finish (void* const result)
  4922. {
  4923. unsigned char encodedLength[8];
  4924. MD5Functions::encode (encodedLength, count, 8);
  4925. // Pad out to 56 mod 64.
  4926. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4927. const int paddingLength = (index < 56) ? (56 - index)
  4928. : (120 - index);
  4929. uint8 paddingBuffer [64];
  4930. zeromem (paddingBuffer, paddingLength);
  4931. paddingBuffer [0] = 0x80;
  4932. processBlock (paddingBuffer, paddingLength);
  4933. processBlock (encodedLength, 8);
  4934. MD5Functions::encode (result, state, 16);
  4935. zerostruct (buffer);
  4936. }
  4937. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4938. {
  4939. using namespace MD5Functions;
  4940. uint32 a = state[0];
  4941. uint32 b = state[1];
  4942. uint32 c = state[2];
  4943. uint32 d = state[3];
  4944. uint32 x[16];
  4945. encode (x, bufferToTransform, 64);
  4946. enum Constants
  4947. {
  4948. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4949. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4950. };
  4951. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4952. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4953. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4954. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4955. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4956. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4957. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4958. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4959. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4960. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4961. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4962. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4963. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4964. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4965. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4966. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4967. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4968. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4969. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4970. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4971. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4972. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4973. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4974. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4975. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4976. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4977. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4978. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4979. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4980. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4981. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4982. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4983. state[0] += a;
  4984. state[1] += b;
  4985. state[2] += c;
  4986. state[3] += d;
  4987. zerostruct (x);
  4988. }
  4989. const MemoryBlock MD5::getRawChecksumData() const
  4990. {
  4991. return MemoryBlock (result, sizeof (result));
  4992. }
  4993. const String MD5::toHexString() const
  4994. {
  4995. return String::toHexString (result, sizeof (result), 0);
  4996. }
  4997. bool MD5::operator== (const MD5& other) const
  4998. {
  4999. return memcmp (result, other.result, sizeof (result)) == 0;
  5000. }
  5001. bool MD5::operator!= (const MD5& other) const
  5002. {
  5003. return ! operator== (other);
  5004. }
  5005. END_JUCE_NAMESPACE
  5006. /*** End of inlined file: juce_MD5.cpp ***/
  5007. /*** Start of inlined file: juce_Primes.cpp ***/
  5008. BEGIN_JUCE_NAMESPACE
  5009. namespace PrimesHelpers
  5010. {
  5011. void createSmallSieve (const int numBits, BigInteger& result)
  5012. {
  5013. result.setBit (numBits);
  5014. result.clearBit (numBits); // to enlarge the array
  5015. result.setBit (0);
  5016. int n = 2;
  5017. do
  5018. {
  5019. for (int i = n + n; i < numBits; i += n)
  5020. result.setBit (i);
  5021. n = result.findNextClearBit (n + 1);
  5022. }
  5023. while (n <= (numBits >> 1));
  5024. }
  5025. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5026. const BigInteger& smallSieve, const int smallSieveSize)
  5027. {
  5028. jassert (! base[0]); // must be even!
  5029. result.setBit (numBits);
  5030. result.clearBit (numBits); // to enlarge the array
  5031. int index = smallSieve.findNextClearBit (0);
  5032. do
  5033. {
  5034. const int prime = (index << 1) + 1;
  5035. BigInteger r (base), remainder;
  5036. r.divideBy (prime, remainder);
  5037. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5038. if (r.isZero())
  5039. i += prime;
  5040. if ((i & 1) == 0)
  5041. i += prime;
  5042. i = (i - 1) >> 1;
  5043. while (i < numBits)
  5044. {
  5045. result.setBit (i);
  5046. i += prime;
  5047. }
  5048. index = smallSieve.findNextClearBit (index + 1);
  5049. }
  5050. while (index < smallSieveSize);
  5051. }
  5052. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5053. const int numBits, BigInteger& result, const int certainty)
  5054. {
  5055. for (int i = 0; i < numBits; ++i)
  5056. {
  5057. if (! sieve[i])
  5058. {
  5059. result = base + (unsigned int) ((i << 1) + 1);
  5060. if (Primes::isProbablyPrime (result, certainty))
  5061. return true;
  5062. }
  5063. }
  5064. return false;
  5065. }
  5066. bool passesMillerRabin (const BigInteger& n, int iterations)
  5067. {
  5068. const BigInteger one (1), two (2);
  5069. const BigInteger nMinusOne (n - one);
  5070. BigInteger d (nMinusOne);
  5071. const int s = d.findNextSetBit (0);
  5072. d >>= s;
  5073. BigInteger smallPrimes;
  5074. int numBitsInSmallPrimes = 0;
  5075. for (;;)
  5076. {
  5077. numBitsInSmallPrimes += 256;
  5078. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5079. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5080. if (numPrimesFound > iterations + 1)
  5081. break;
  5082. }
  5083. int smallPrime = 2;
  5084. while (--iterations >= 0)
  5085. {
  5086. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5087. BigInteger r (smallPrime);
  5088. r.exponentModulo (d, n);
  5089. if (r != one && r != nMinusOne)
  5090. {
  5091. for (int j = 0; j < s; ++j)
  5092. {
  5093. r.exponentModulo (two, n);
  5094. if (r == nMinusOne)
  5095. break;
  5096. }
  5097. if (r != nMinusOne)
  5098. return false;
  5099. }
  5100. }
  5101. return true;
  5102. }
  5103. }
  5104. const BigInteger Primes::createProbablePrime (const int bitLength,
  5105. const int certainty,
  5106. const int* randomSeeds,
  5107. int numRandomSeeds)
  5108. {
  5109. using namespace PrimesHelpers;
  5110. int defaultSeeds [16];
  5111. if (numRandomSeeds <= 0)
  5112. {
  5113. randomSeeds = defaultSeeds;
  5114. numRandomSeeds = numElementsInArray (defaultSeeds);
  5115. Random r (0);
  5116. for (int j = 10; --j >= 0;)
  5117. {
  5118. r.setSeedRandomly();
  5119. for (int i = numRandomSeeds; --i >= 0;)
  5120. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5121. }
  5122. }
  5123. BigInteger smallSieve;
  5124. const int smallSieveSize = 15000;
  5125. createSmallSieve (smallSieveSize, smallSieve);
  5126. BigInteger p;
  5127. for (int i = numRandomSeeds; --i >= 0;)
  5128. {
  5129. BigInteger p2;
  5130. Random r (randomSeeds[i]);
  5131. r.fillBitsRandomly (p2, 0, bitLength);
  5132. p ^= p2;
  5133. }
  5134. p.setBit (bitLength - 1);
  5135. p.clearBit (0);
  5136. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5137. while (p.getHighestBit() < bitLength)
  5138. {
  5139. p += 2 * searchLen;
  5140. BigInteger sieve;
  5141. bigSieve (p, searchLen, sieve,
  5142. smallSieve, smallSieveSize);
  5143. BigInteger candidate;
  5144. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5145. return candidate;
  5146. }
  5147. jassertfalse;
  5148. return BigInteger();
  5149. }
  5150. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5151. {
  5152. using namespace PrimesHelpers;
  5153. if (! number[0])
  5154. return false;
  5155. if (number.getHighestBit() <= 10)
  5156. {
  5157. const int num = number.getBitRangeAsInt (0, 10);
  5158. for (int i = num / 2; --i > 1;)
  5159. if (num % i == 0)
  5160. return false;
  5161. return true;
  5162. }
  5163. else
  5164. {
  5165. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5166. return false;
  5167. return passesMillerRabin (number, certainty);
  5168. }
  5169. }
  5170. END_JUCE_NAMESPACE
  5171. /*** End of inlined file: juce_Primes.cpp ***/
  5172. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5173. BEGIN_JUCE_NAMESPACE
  5174. RSAKey::RSAKey()
  5175. {
  5176. }
  5177. RSAKey::RSAKey (const String& s)
  5178. {
  5179. if (s.containsChar (','))
  5180. {
  5181. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5182. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5183. }
  5184. else
  5185. {
  5186. // the string needs to be two hex numbers, comma-separated..
  5187. jassertfalse;
  5188. }
  5189. }
  5190. RSAKey::~RSAKey()
  5191. {
  5192. }
  5193. bool RSAKey::operator== (const RSAKey& other) const throw()
  5194. {
  5195. return part1 == other.part1 && part2 == other.part2;
  5196. }
  5197. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5198. {
  5199. return ! operator== (other);
  5200. }
  5201. const String RSAKey::toString() const
  5202. {
  5203. return part1.toString (16) + "," + part2.toString (16);
  5204. }
  5205. bool RSAKey::applyToValue (BigInteger& value) const
  5206. {
  5207. if (part1.isZero() || part2.isZero() || value <= 0)
  5208. {
  5209. jassertfalse; // using an uninitialised key
  5210. value.clear();
  5211. return false;
  5212. }
  5213. BigInteger result;
  5214. while (! value.isZero())
  5215. {
  5216. result *= part2;
  5217. BigInteger remainder;
  5218. value.divideBy (part2, remainder);
  5219. remainder.exponentModulo (part1, part2);
  5220. result += remainder;
  5221. }
  5222. value.swapWith (result);
  5223. return true;
  5224. }
  5225. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5226. {
  5227. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5228. // are fast to divide + multiply
  5229. for (int i = 2; i <= 65536; i *= 2)
  5230. {
  5231. const BigInteger e (1 + i);
  5232. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5233. return e;
  5234. }
  5235. BigInteger e (4);
  5236. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5237. ++e;
  5238. return e;
  5239. }
  5240. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5241. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5242. {
  5243. jassert (numBits > 16); // not much point using less than this..
  5244. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5245. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5246. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5247. const BigInteger n (p * q);
  5248. const BigInteger m (--p * --q);
  5249. const BigInteger e (findBestCommonDivisor (p, q));
  5250. BigInteger d (e);
  5251. d.inverseModulo (m);
  5252. publicKey.part1 = e;
  5253. publicKey.part2 = n;
  5254. privateKey.part1 = d;
  5255. privateKey.part2 = n;
  5256. }
  5257. END_JUCE_NAMESPACE
  5258. /*** End of inlined file: juce_RSAKey.cpp ***/
  5259. /*** Start of inlined file: juce_InputStream.cpp ***/
  5260. BEGIN_JUCE_NAMESPACE
  5261. char InputStream::readByte()
  5262. {
  5263. char temp = 0;
  5264. read (&temp, 1);
  5265. return temp;
  5266. }
  5267. bool InputStream::readBool()
  5268. {
  5269. return readByte() != 0;
  5270. }
  5271. short InputStream::readShort()
  5272. {
  5273. char temp[2];
  5274. if (read (temp, 2) == 2)
  5275. return (short) ByteOrder::littleEndianShort (temp);
  5276. return 0;
  5277. }
  5278. short InputStream::readShortBigEndian()
  5279. {
  5280. char temp[2];
  5281. if (read (temp, 2) == 2)
  5282. return (short) ByteOrder::bigEndianShort (temp);
  5283. return 0;
  5284. }
  5285. int InputStream::readInt()
  5286. {
  5287. char temp[4];
  5288. if (read (temp, 4) == 4)
  5289. return (int) ByteOrder::littleEndianInt (temp);
  5290. return 0;
  5291. }
  5292. int InputStream::readIntBigEndian()
  5293. {
  5294. char temp[4];
  5295. if (read (temp, 4) == 4)
  5296. return (int) ByteOrder::bigEndianInt (temp);
  5297. return 0;
  5298. }
  5299. int InputStream::readCompressedInt()
  5300. {
  5301. const unsigned char sizeByte = readByte();
  5302. if (sizeByte == 0)
  5303. return 0;
  5304. const int numBytes = (sizeByte & 0x7f);
  5305. if (numBytes > 4)
  5306. {
  5307. jassertfalse; // trying to read corrupt data - this method must only be used
  5308. // to read data that was written by OutputStream::writeCompressedInt()
  5309. return 0;
  5310. }
  5311. char bytes[4] = { 0, 0, 0, 0 };
  5312. if (read (bytes, numBytes) != numBytes)
  5313. return 0;
  5314. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5315. return (sizeByte >> 7) ? -num : num;
  5316. }
  5317. int64 InputStream::readInt64()
  5318. {
  5319. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5320. if (read (n.asBytes, 8) == 8)
  5321. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5322. return 0;
  5323. }
  5324. int64 InputStream::readInt64BigEndian()
  5325. {
  5326. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5327. if (read (n.asBytes, 8) == 8)
  5328. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5329. return 0;
  5330. }
  5331. float InputStream::readFloat()
  5332. {
  5333. // the union below relies on these types being the same size...
  5334. static_jassert (sizeof (int32) == sizeof (float));
  5335. union { int32 asInt; float asFloat; } n;
  5336. n.asInt = (int32) readInt();
  5337. return n.asFloat;
  5338. }
  5339. float InputStream::readFloatBigEndian()
  5340. {
  5341. union { int32 asInt; float asFloat; } n;
  5342. n.asInt = (int32) readIntBigEndian();
  5343. return n.asFloat;
  5344. }
  5345. double InputStream::readDouble()
  5346. {
  5347. union { int64 asInt; double asDouble; } n;
  5348. n.asInt = readInt64();
  5349. return n.asDouble;
  5350. }
  5351. double InputStream::readDoubleBigEndian()
  5352. {
  5353. union { int64 asInt; double asDouble; } n;
  5354. n.asInt = readInt64BigEndian();
  5355. return n.asDouble;
  5356. }
  5357. const String InputStream::readString()
  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 (++i >= buffer.getSize())
  5365. {
  5366. buffer.setSize (buffer.getSize() + 512);
  5367. data = static_cast<char*> (buffer.getData());
  5368. }
  5369. }
  5370. return String::fromUTF8 (data, (int) i);
  5371. }
  5372. const String InputStream::readNextLine()
  5373. {
  5374. MemoryBlock buffer (256);
  5375. char* data = static_cast<char*> (buffer.getData());
  5376. size_t i = 0;
  5377. while ((data[i] = readByte()) != 0)
  5378. {
  5379. if (data[i] == '\n')
  5380. break;
  5381. if (data[i] == '\r')
  5382. {
  5383. const int64 lastPos = getPosition();
  5384. if (readByte() != '\n')
  5385. setPosition (lastPos);
  5386. break;
  5387. }
  5388. if (++i >= buffer.getSize())
  5389. {
  5390. buffer.setSize (buffer.getSize() + 512);
  5391. data = static_cast<char*> (buffer.getData());
  5392. }
  5393. }
  5394. return String::fromUTF8 (data, (int) i);
  5395. }
  5396. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5397. {
  5398. MemoryOutputStream mo (block, true);
  5399. return mo.writeFromInputStream (*this, numBytes);
  5400. }
  5401. const String InputStream::readEntireStreamAsString()
  5402. {
  5403. MemoryOutputStream mo;
  5404. mo.writeFromInputStream (*this, -1);
  5405. return mo.toString();
  5406. }
  5407. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5408. {
  5409. if (numBytesToSkip > 0)
  5410. {
  5411. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5412. HeapBlock<char> temp (skipBufferSize);
  5413. while (numBytesToSkip > 0 && ! isExhausted())
  5414. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5415. }
  5416. }
  5417. END_JUCE_NAMESPACE
  5418. /*** End of inlined file: juce_InputStream.cpp ***/
  5419. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5420. BEGIN_JUCE_NAMESPACE
  5421. #if JUCE_DEBUG
  5422. static Array<void*, CriticalSection> activeStreams;
  5423. void juce_CheckForDanglingStreams()
  5424. {
  5425. /*
  5426. It's always a bad idea to leak any object, but if you're leaking output
  5427. streams, then there's a good chance that you're failing to flush a file
  5428. to disk properly, which could result in corrupted data and other similar
  5429. nastiness..
  5430. */
  5431. jassert (activeStreams.size() == 0);
  5432. };
  5433. #endif
  5434. OutputStream::OutputStream()
  5435. : newLineString (NewLine::getDefault())
  5436. {
  5437. #if JUCE_DEBUG
  5438. activeStreams.add (this);
  5439. #endif
  5440. }
  5441. OutputStream::~OutputStream()
  5442. {
  5443. #if JUCE_DEBUG
  5444. activeStreams.removeValue (this);
  5445. #endif
  5446. }
  5447. void OutputStream::writeBool (const bool b)
  5448. {
  5449. writeByte (b ? (char) 1
  5450. : (char) 0);
  5451. }
  5452. void OutputStream::writeByte (char byte)
  5453. {
  5454. write (&byte, 1);
  5455. }
  5456. void OutputStream::writeShort (short value)
  5457. {
  5458. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5459. write (&v, 2);
  5460. }
  5461. void OutputStream::writeShortBigEndian (short value)
  5462. {
  5463. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5464. write (&v, 2);
  5465. }
  5466. void OutputStream::writeInt (int value)
  5467. {
  5468. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5469. write (&v, 4);
  5470. }
  5471. void OutputStream::writeIntBigEndian (int value)
  5472. {
  5473. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5474. write (&v, 4);
  5475. }
  5476. void OutputStream::writeCompressedInt (int value)
  5477. {
  5478. unsigned int un = (value < 0) ? (unsigned int) -value
  5479. : (unsigned int) value;
  5480. uint8 data[5];
  5481. int num = 0;
  5482. while (un > 0)
  5483. {
  5484. data[++num] = (uint8) un;
  5485. un >>= 8;
  5486. }
  5487. data[0] = (uint8) num;
  5488. if (value < 0)
  5489. data[0] |= 0x80;
  5490. write (data, num + 1);
  5491. }
  5492. void OutputStream::writeInt64 (int64 value)
  5493. {
  5494. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5495. write (&v, 8);
  5496. }
  5497. void OutputStream::writeInt64BigEndian (int64 value)
  5498. {
  5499. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5500. write (&v, 8);
  5501. }
  5502. void OutputStream::writeFloat (float value)
  5503. {
  5504. union { int asInt; float asFloat; } n;
  5505. n.asFloat = value;
  5506. writeInt (n.asInt);
  5507. }
  5508. void OutputStream::writeFloatBigEndian (float value)
  5509. {
  5510. union { int asInt; float asFloat; } n;
  5511. n.asFloat = value;
  5512. writeIntBigEndian (n.asInt);
  5513. }
  5514. void OutputStream::writeDouble (double value)
  5515. {
  5516. union { int64 asInt; double asDouble; } n;
  5517. n.asDouble = value;
  5518. writeInt64 (n.asInt);
  5519. }
  5520. void OutputStream::writeDoubleBigEndian (double value)
  5521. {
  5522. union { int64 asInt; double asDouble; } n;
  5523. n.asDouble = value;
  5524. writeInt64BigEndian (n.asInt);
  5525. }
  5526. void OutputStream::writeString (const String& text)
  5527. {
  5528. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5529. // if lots of large, persistent strings were to be written to streams).
  5530. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5531. HeapBlock<char> temp (numBytes);
  5532. text.copyToUTF8 (temp, numBytes);
  5533. write (temp, numBytes);
  5534. }
  5535. void OutputStream::writeText (const String& text, const bool asUnicode,
  5536. const bool writeUnicodeHeaderBytes)
  5537. {
  5538. if (asUnicode)
  5539. {
  5540. if (writeUnicodeHeaderBytes)
  5541. write ("\x0ff\x0fe", 2);
  5542. const juce_wchar* src = text;
  5543. bool lastCharWasReturn = false;
  5544. while (*src != 0)
  5545. {
  5546. if (*src == L'\n' && ! lastCharWasReturn)
  5547. writeShort ((short) L'\r');
  5548. lastCharWasReturn = (*src == L'\r');
  5549. writeShort ((short) *src++);
  5550. }
  5551. }
  5552. else
  5553. {
  5554. const char* src = text.toUTF8();
  5555. const char* t = src;
  5556. for (;;)
  5557. {
  5558. if (*t == '\n')
  5559. {
  5560. if (t > src)
  5561. write (src, (int) (t - src));
  5562. write ("\r\n", 2);
  5563. src = t + 1;
  5564. }
  5565. else if (*t == '\r')
  5566. {
  5567. if (t[1] == '\n')
  5568. ++t;
  5569. }
  5570. else if (*t == 0)
  5571. {
  5572. if (t > src)
  5573. write (src, (int) (t - src));
  5574. break;
  5575. }
  5576. ++t;
  5577. }
  5578. }
  5579. }
  5580. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5581. {
  5582. if (numBytesToWrite < 0)
  5583. numBytesToWrite = std::numeric_limits<int64>::max();
  5584. int numWritten = 0;
  5585. while (numBytesToWrite > 0 && ! source.isExhausted())
  5586. {
  5587. char buffer [8192];
  5588. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5589. if (num <= 0)
  5590. break;
  5591. write (buffer, num);
  5592. numBytesToWrite -= num;
  5593. numWritten += num;
  5594. }
  5595. return numWritten;
  5596. }
  5597. void OutputStream::setNewLineString (const String& newLineString_)
  5598. {
  5599. newLineString = newLineString_;
  5600. }
  5601. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5602. {
  5603. return stream << String (number);
  5604. }
  5605. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5606. {
  5607. return stream << String (number);
  5608. }
  5609. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5610. {
  5611. stream.writeByte (character);
  5612. return stream;
  5613. }
  5614. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5615. {
  5616. stream.write (text, (int) strlen (text));
  5617. return stream;
  5618. }
  5619. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5620. {
  5621. stream.write (data.getData(), (int) data.getSize());
  5622. return stream;
  5623. }
  5624. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5625. {
  5626. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5627. if (in != 0)
  5628. stream.writeFromInputStream (*in, -1);
  5629. return stream;
  5630. }
  5631. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
  5632. {
  5633. return stream << stream.getNewLineString();
  5634. }
  5635. END_JUCE_NAMESPACE
  5636. /*** End of inlined file: juce_OutputStream.cpp ***/
  5637. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5638. BEGIN_JUCE_NAMESPACE
  5639. DirectoryIterator::DirectoryIterator (const File& directory,
  5640. bool isRecursive_,
  5641. const String& wildCard_,
  5642. const int whatToLookFor_)
  5643. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5644. wildCard (wildCard_),
  5645. path (File::addTrailingSeparator (directory.getFullPathName())),
  5646. index (-1),
  5647. totalNumFiles (-1),
  5648. whatToLookFor (whatToLookFor_),
  5649. isRecursive (isRecursive_),
  5650. hasBeenAdvanced (false)
  5651. {
  5652. // you have to specify the type of files you're looking for!
  5653. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5654. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5655. }
  5656. DirectoryIterator::~DirectoryIterator()
  5657. {
  5658. }
  5659. bool DirectoryIterator::next()
  5660. {
  5661. return next (0, 0, 0, 0, 0, 0);
  5662. }
  5663. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5664. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5665. {
  5666. hasBeenAdvanced = true;
  5667. if (subIterator != 0)
  5668. {
  5669. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5670. return true;
  5671. subIterator = 0;
  5672. }
  5673. String filename;
  5674. bool isDirectory, isHidden;
  5675. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5676. {
  5677. ++index;
  5678. if (! filename.containsOnly ("."))
  5679. {
  5680. const File fileFound (path + filename, 0);
  5681. bool matches = false;
  5682. if (isDirectory)
  5683. {
  5684. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5685. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5686. matches = (whatToLookFor & File::findDirectories) != 0;
  5687. }
  5688. else
  5689. {
  5690. matches = (whatToLookFor & File::findFiles) != 0;
  5691. }
  5692. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5693. if (matches && isRecursive)
  5694. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5695. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5696. matches = ! isHidden;
  5697. if (matches)
  5698. {
  5699. currentFile = fileFound;
  5700. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5701. if (isDirResult != 0) *isDirResult = isDirectory;
  5702. return true;
  5703. }
  5704. else if (subIterator != 0)
  5705. {
  5706. return next();
  5707. }
  5708. }
  5709. }
  5710. return false;
  5711. }
  5712. const File DirectoryIterator::getFile() const
  5713. {
  5714. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5715. return subIterator->getFile();
  5716. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5717. jassert (hasBeenAdvanced);
  5718. return currentFile;
  5719. }
  5720. float DirectoryIterator::getEstimatedProgress() const
  5721. {
  5722. if (totalNumFiles < 0)
  5723. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5724. if (totalNumFiles <= 0)
  5725. return 0.0f;
  5726. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5727. : (float) index;
  5728. return detailedIndex / totalNumFiles;
  5729. }
  5730. END_JUCE_NAMESPACE
  5731. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5732. /*** Start of inlined file: juce_File.cpp ***/
  5733. #if ! JUCE_WINDOWS
  5734. #include <pwd.h>
  5735. #endif
  5736. BEGIN_JUCE_NAMESPACE
  5737. File::File (const String& fullPathName)
  5738. : fullPath (parseAbsolutePath (fullPathName))
  5739. {
  5740. }
  5741. File::File (const String& path, int)
  5742. : fullPath (path)
  5743. {
  5744. }
  5745. const File File::createFileWithoutCheckingPath (const String& path)
  5746. {
  5747. return File (path, 0);
  5748. }
  5749. File::File (const File& other)
  5750. : fullPath (other.fullPath)
  5751. {
  5752. }
  5753. File& File::operator= (const String& newPath)
  5754. {
  5755. fullPath = parseAbsolutePath (newPath);
  5756. return *this;
  5757. }
  5758. File& File::operator= (const File& other)
  5759. {
  5760. fullPath = other.fullPath;
  5761. return *this;
  5762. }
  5763. const File File::nonexistent;
  5764. const String File::parseAbsolutePath (const String& p)
  5765. {
  5766. if (p.isEmpty())
  5767. return String::empty;
  5768. #if JUCE_WINDOWS
  5769. // Windows..
  5770. String path (p.replaceCharacter ('/', '\\'));
  5771. if (path.startsWithChar (File::separator))
  5772. {
  5773. if (path[1] != File::separator)
  5774. {
  5775. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5776. If you're trying to parse a string that may be either a relative path or an absolute path,
  5777. you MUST provide a context against which the partial path can be evaluated - you can do
  5778. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5779. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5780. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5781. */
  5782. jassertfalse;
  5783. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5784. }
  5785. }
  5786. else if (! path.containsChar (':'))
  5787. {
  5788. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5789. If you're trying to parse a string that may be either a relative path or an absolute path,
  5790. you MUST provide a context against which the partial path can be evaluated - you can do
  5791. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5792. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5793. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5794. */
  5795. jassertfalse;
  5796. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5797. }
  5798. #else
  5799. // Mac or Linux..
  5800. String path (p.replaceCharacter ('\\', '/'));
  5801. if (path.startsWithChar ('~'))
  5802. {
  5803. if (path[1] == File::separator || path[1] == 0)
  5804. {
  5805. // expand a name of the form "~/abc"
  5806. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5807. + path.substring (1);
  5808. }
  5809. else
  5810. {
  5811. // expand a name of type "~dave/abc"
  5812. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5813. struct passwd* const pw = getpwnam (userName.toUTF8());
  5814. if (pw != 0)
  5815. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5816. }
  5817. }
  5818. else if (! path.startsWithChar (File::separator))
  5819. {
  5820. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5821. If you're trying to parse a string that may be either a relative path or an absolute path,
  5822. you MUST provide a context against which the partial path can be evaluated - you can do
  5823. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5824. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5825. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5826. */
  5827. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5828. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5829. }
  5830. #endif
  5831. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5832. path = path.dropLastCharacters (1);
  5833. return path;
  5834. }
  5835. const String File::addTrailingSeparator (const String& path)
  5836. {
  5837. return path.endsWithChar (File::separator) ? path
  5838. : path + File::separator;
  5839. }
  5840. #if JUCE_LINUX
  5841. #define NAMES_ARE_CASE_SENSITIVE 1
  5842. #endif
  5843. bool File::areFileNamesCaseSensitive()
  5844. {
  5845. #if NAMES_ARE_CASE_SENSITIVE
  5846. return true;
  5847. #else
  5848. return false;
  5849. #endif
  5850. }
  5851. bool File::operator== (const File& other) const
  5852. {
  5853. #if NAMES_ARE_CASE_SENSITIVE
  5854. return fullPath == other.fullPath;
  5855. #else
  5856. return fullPath.equalsIgnoreCase (other.fullPath);
  5857. #endif
  5858. }
  5859. bool File::operator!= (const File& other) const
  5860. {
  5861. return ! operator== (other);
  5862. }
  5863. bool File::operator< (const File& other) const
  5864. {
  5865. #if NAMES_ARE_CASE_SENSITIVE
  5866. return fullPath < other.fullPath;
  5867. #else
  5868. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5869. #endif
  5870. }
  5871. bool File::operator> (const File& other) const
  5872. {
  5873. #if NAMES_ARE_CASE_SENSITIVE
  5874. return fullPath > other.fullPath;
  5875. #else
  5876. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5877. #endif
  5878. }
  5879. bool File::setReadOnly (const bool shouldBeReadOnly,
  5880. const bool applyRecursively) const
  5881. {
  5882. bool worked = true;
  5883. if (applyRecursively && isDirectory())
  5884. {
  5885. Array <File> subFiles;
  5886. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5887. for (int i = subFiles.size(); --i >= 0;)
  5888. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5889. }
  5890. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5891. }
  5892. bool File::deleteRecursively() const
  5893. {
  5894. bool worked = true;
  5895. if (isDirectory())
  5896. {
  5897. Array<File> subFiles;
  5898. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5899. for (int i = subFiles.size(); --i >= 0;)
  5900. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5901. }
  5902. return deleteFile() && worked;
  5903. }
  5904. bool File::moveFileTo (const File& newFile) const
  5905. {
  5906. if (newFile.fullPath == fullPath)
  5907. return true;
  5908. #if ! NAMES_ARE_CASE_SENSITIVE
  5909. if (*this != newFile)
  5910. #endif
  5911. if (! newFile.deleteFile())
  5912. return false;
  5913. return moveInternal (newFile);
  5914. }
  5915. bool File::copyFileTo (const File& newFile) const
  5916. {
  5917. return (*this == newFile)
  5918. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5919. }
  5920. bool File::copyDirectoryTo (const File& newDirectory) const
  5921. {
  5922. if (isDirectory() && newDirectory.createDirectory())
  5923. {
  5924. Array<File> subFiles;
  5925. findChildFiles (subFiles, File::findFiles, false);
  5926. int i;
  5927. for (i = 0; i < subFiles.size(); ++i)
  5928. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5929. return false;
  5930. subFiles.clear();
  5931. findChildFiles (subFiles, File::findDirectories, false);
  5932. for (i = 0; i < subFiles.size(); ++i)
  5933. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5934. return false;
  5935. return true;
  5936. }
  5937. return false;
  5938. }
  5939. const String File::getPathUpToLastSlash() const
  5940. {
  5941. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5942. if (lastSlash > 0)
  5943. return fullPath.substring (0, lastSlash);
  5944. else if (lastSlash == 0)
  5945. return separatorString;
  5946. else
  5947. return fullPath;
  5948. }
  5949. const File File::getParentDirectory() const
  5950. {
  5951. return File (getPathUpToLastSlash(), (int) 0);
  5952. }
  5953. const String File::getFileName() const
  5954. {
  5955. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5956. }
  5957. int File::hashCode() const
  5958. {
  5959. return fullPath.hashCode();
  5960. }
  5961. int64 File::hashCode64() const
  5962. {
  5963. return fullPath.hashCode64();
  5964. }
  5965. const String File::getFileNameWithoutExtension() const
  5966. {
  5967. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5968. const int lastDot = fullPath.lastIndexOfChar ('.');
  5969. if (lastDot > lastSlash)
  5970. return fullPath.substring (lastSlash, lastDot);
  5971. else
  5972. return fullPath.substring (lastSlash);
  5973. }
  5974. bool File::isAChildOf (const File& potentialParent) const
  5975. {
  5976. if (potentialParent == File::nonexistent)
  5977. return false;
  5978. const String ourPath (getPathUpToLastSlash());
  5979. #if NAMES_ARE_CASE_SENSITIVE
  5980. if (potentialParent.fullPath == ourPath)
  5981. #else
  5982. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5983. #endif
  5984. {
  5985. return true;
  5986. }
  5987. else if (potentialParent.fullPath.length() >= ourPath.length())
  5988. {
  5989. return false;
  5990. }
  5991. else
  5992. {
  5993. return getParentDirectory().isAChildOf (potentialParent);
  5994. }
  5995. }
  5996. bool File::isAbsolutePath (const String& path)
  5997. {
  5998. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5999. #if JUCE_WINDOWS
  6000. || (path.isNotEmpty() && path[1] == ':');
  6001. #else
  6002. || path.startsWithChar ('~');
  6003. #endif
  6004. }
  6005. const File File::getChildFile (String relativePath) const
  6006. {
  6007. if (isAbsolutePath (relativePath))
  6008. {
  6009. // the path is really absolute..
  6010. return File (relativePath);
  6011. }
  6012. else
  6013. {
  6014. // it's relative, so remove any ../ or ./ bits at the start.
  6015. String path (fullPath);
  6016. if (relativePath[0] == '.')
  6017. {
  6018. #if JUCE_WINDOWS
  6019. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6020. #else
  6021. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6022. #endif
  6023. while (relativePath[0] == '.')
  6024. {
  6025. if (relativePath[1] == '.')
  6026. {
  6027. if (relativePath [2] == 0 || relativePath[2] == separator)
  6028. {
  6029. const int lastSlash = path.lastIndexOfChar (separator);
  6030. if (lastSlash >= 0)
  6031. path = path.substring (0, lastSlash);
  6032. relativePath = relativePath.substring (3);
  6033. }
  6034. else
  6035. {
  6036. break;
  6037. }
  6038. }
  6039. else if (relativePath[1] == separator)
  6040. {
  6041. relativePath = relativePath.substring (2);
  6042. }
  6043. else
  6044. {
  6045. break;
  6046. }
  6047. }
  6048. }
  6049. return File (addTrailingSeparator (path) + relativePath);
  6050. }
  6051. }
  6052. const File File::getSiblingFile (const String& fileName) const
  6053. {
  6054. return getParentDirectory().getChildFile (fileName);
  6055. }
  6056. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6057. {
  6058. if (bytes == 1)
  6059. {
  6060. return "1 byte";
  6061. }
  6062. else if (bytes < 1024)
  6063. {
  6064. return String ((int) bytes) + " bytes";
  6065. }
  6066. else if (bytes < 1024 * 1024)
  6067. {
  6068. return String (bytes / 1024.0, 1) + " KB";
  6069. }
  6070. else if (bytes < 1024 * 1024 * 1024)
  6071. {
  6072. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6073. }
  6074. else
  6075. {
  6076. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6077. }
  6078. }
  6079. bool File::create() const
  6080. {
  6081. if (exists())
  6082. return true;
  6083. {
  6084. const File parentDir (getParentDirectory());
  6085. if (parentDir == *this || ! parentDir.createDirectory())
  6086. return false;
  6087. FileOutputStream fo (*this, 8);
  6088. }
  6089. return exists();
  6090. }
  6091. bool File::createDirectory() const
  6092. {
  6093. if (! isDirectory())
  6094. {
  6095. const File parentDir (getParentDirectory());
  6096. if (parentDir == *this || ! parentDir.createDirectory())
  6097. return false;
  6098. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6099. return isDirectory();
  6100. }
  6101. return true;
  6102. }
  6103. const Time File::getCreationTime() const
  6104. {
  6105. int64 m, a, c;
  6106. getFileTimesInternal (m, a, c);
  6107. return Time (c);
  6108. }
  6109. const Time File::getLastModificationTime() const
  6110. {
  6111. int64 m, a, c;
  6112. getFileTimesInternal (m, a, c);
  6113. return Time (m);
  6114. }
  6115. const Time File::getLastAccessTime() const
  6116. {
  6117. int64 m, a, c;
  6118. getFileTimesInternal (m, a, c);
  6119. return Time (a);
  6120. }
  6121. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6122. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6123. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6124. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6125. {
  6126. if (! existsAsFile())
  6127. return false;
  6128. FileInputStream in (*this);
  6129. return getSize() == in.readIntoMemoryBlock (destBlock);
  6130. }
  6131. const String File::loadFileAsString() const
  6132. {
  6133. if (! existsAsFile())
  6134. return String::empty;
  6135. FileInputStream in (*this);
  6136. return in.readEntireStreamAsString();
  6137. }
  6138. int File::findChildFiles (Array<File>& results,
  6139. const int whatToLookFor,
  6140. const bool searchRecursively,
  6141. const String& wildCardPattern) const
  6142. {
  6143. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6144. int total = 0;
  6145. while (di.next())
  6146. {
  6147. results.add (di.getFile());
  6148. ++total;
  6149. }
  6150. return total;
  6151. }
  6152. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6153. {
  6154. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6155. int total = 0;
  6156. while (di.next())
  6157. ++total;
  6158. return total;
  6159. }
  6160. bool File::containsSubDirectories() const
  6161. {
  6162. if (isDirectory())
  6163. {
  6164. DirectoryIterator di (*this, false, "*", findDirectories);
  6165. return di.next();
  6166. }
  6167. return false;
  6168. }
  6169. const File File::getNonexistentChildFile (const String& prefix_,
  6170. const String& suffix,
  6171. bool putNumbersInBrackets) const
  6172. {
  6173. File f (getChildFile (prefix_ + suffix));
  6174. if (f.exists())
  6175. {
  6176. int num = 2;
  6177. String prefix (prefix_);
  6178. // remove any bracketed numbers that may already be on the end..
  6179. if (prefix.trim().endsWithChar (')'))
  6180. {
  6181. putNumbersInBrackets = true;
  6182. const int openBracks = prefix.lastIndexOfChar ('(');
  6183. const int closeBracks = prefix.lastIndexOfChar (')');
  6184. if (openBracks > 0
  6185. && closeBracks > openBracks
  6186. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6187. {
  6188. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6189. prefix = prefix.substring (0, openBracks);
  6190. }
  6191. }
  6192. // also use brackets if it ends in a digit.
  6193. putNumbersInBrackets = putNumbersInBrackets
  6194. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6195. do
  6196. {
  6197. if (putNumbersInBrackets)
  6198. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6199. else
  6200. f = getChildFile (prefix + String (num++) + suffix);
  6201. } while (f.exists());
  6202. }
  6203. return f;
  6204. }
  6205. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6206. {
  6207. if (exists())
  6208. {
  6209. return getParentDirectory()
  6210. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6211. getFileExtension(),
  6212. putNumbersInBrackets);
  6213. }
  6214. else
  6215. {
  6216. return *this;
  6217. }
  6218. }
  6219. const String File::getFileExtension() const
  6220. {
  6221. String ext;
  6222. if (! isDirectory())
  6223. {
  6224. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6225. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6226. ext = fullPath.substring (indexOfDot);
  6227. }
  6228. return ext;
  6229. }
  6230. bool File::hasFileExtension (const String& possibleSuffix) const
  6231. {
  6232. if (possibleSuffix.isEmpty())
  6233. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6234. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6235. if (semicolon >= 0)
  6236. {
  6237. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6238. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6239. }
  6240. else
  6241. {
  6242. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6243. {
  6244. if (possibleSuffix.startsWithChar ('.'))
  6245. return true;
  6246. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6247. if (dotPos >= 0)
  6248. return fullPath [dotPos] == '.';
  6249. }
  6250. }
  6251. return false;
  6252. }
  6253. const File File::withFileExtension (const String& newExtension) const
  6254. {
  6255. if (fullPath.isEmpty())
  6256. return File::nonexistent;
  6257. String filePart (getFileName());
  6258. int i = filePart.lastIndexOfChar ('.');
  6259. if (i >= 0)
  6260. filePart = filePart.substring (0, i);
  6261. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6262. filePart << '.';
  6263. return getSiblingFile (filePart + newExtension);
  6264. }
  6265. bool File::startAsProcess (const String& parameters) const
  6266. {
  6267. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6268. }
  6269. FileInputStream* File::createInputStream() const
  6270. {
  6271. if (existsAsFile())
  6272. return new FileInputStream (*this);
  6273. return 0;
  6274. }
  6275. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6276. {
  6277. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6278. if (out->failedToOpen())
  6279. return 0;
  6280. return out.release();
  6281. }
  6282. bool File::appendData (const void* const dataToAppend,
  6283. const int numberOfBytes) const
  6284. {
  6285. if (numberOfBytes > 0)
  6286. {
  6287. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6288. if (out == 0)
  6289. return false;
  6290. out->write (dataToAppend, numberOfBytes);
  6291. }
  6292. return true;
  6293. }
  6294. bool File::replaceWithData (const void* const dataToWrite,
  6295. const int numberOfBytes) const
  6296. {
  6297. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6298. if (numberOfBytes <= 0)
  6299. return deleteFile();
  6300. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6301. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6302. return tempFile.overwriteTargetFileWithTemporary();
  6303. }
  6304. bool File::appendText (const String& text,
  6305. const bool asUnicode,
  6306. const bool writeUnicodeHeaderBytes) const
  6307. {
  6308. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6309. if (out != 0)
  6310. {
  6311. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6312. return true;
  6313. }
  6314. return false;
  6315. }
  6316. bool File::replaceWithText (const String& textToWrite,
  6317. const bool asUnicode,
  6318. const bool writeUnicodeHeaderBytes) const
  6319. {
  6320. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6321. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6322. return tempFile.overwriteTargetFileWithTemporary();
  6323. }
  6324. bool File::hasIdenticalContentTo (const File& other) const
  6325. {
  6326. if (other == *this)
  6327. return true;
  6328. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6329. {
  6330. FileInputStream in1 (*this), in2 (other);
  6331. const int bufferSize = 4096;
  6332. HeapBlock <char> buffer1, buffer2;
  6333. buffer1.malloc (bufferSize);
  6334. buffer2.malloc (bufferSize);
  6335. for (;;)
  6336. {
  6337. const int num1 = in1.read (buffer1, bufferSize);
  6338. const int num2 = in2.read (buffer2, bufferSize);
  6339. if (num1 != num2)
  6340. break;
  6341. if (num1 <= 0)
  6342. return true;
  6343. if (memcmp (buffer1, buffer2, num1) != 0)
  6344. break;
  6345. }
  6346. }
  6347. return false;
  6348. }
  6349. const String File::createLegalPathName (const String& original)
  6350. {
  6351. String s (original);
  6352. String start;
  6353. if (s[1] == ':')
  6354. {
  6355. start = s.substring (0, 2);
  6356. s = s.substring (2);
  6357. }
  6358. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6359. .substring (0, 1024);
  6360. }
  6361. const String File::createLegalFileName (const String& original)
  6362. {
  6363. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6364. const int maxLength = 128; // only the length of the filename, not the whole path
  6365. const int len = s.length();
  6366. if (len > maxLength)
  6367. {
  6368. const int lastDot = s.lastIndexOfChar ('.');
  6369. if (lastDot > jmax (0, len - 12))
  6370. {
  6371. s = s.substring (0, maxLength - (len - lastDot))
  6372. + s.substring (lastDot);
  6373. }
  6374. else
  6375. {
  6376. s = s.substring (0, maxLength);
  6377. }
  6378. }
  6379. return s;
  6380. }
  6381. const String File::getRelativePathFrom (const File& dir) const
  6382. {
  6383. String thisPath (fullPath);
  6384. {
  6385. int len = thisPath.length();
  6386. while (--len >= 0 && thisPath [len] == File::separator)
  6387. thisPath [len] = 0;
  6388. }
  6389. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6390. : dir.fullPath));
  6391. const int len = jmin (thisPath.length(), dirPath.length());
  6392. int commonBitLength = 0;
  6393. for (int i = 0; i < len; ++i)
  6394. {
  6395. #if NAMES_ARE_CASE_SENSITIVE
  6396. if (thisPath[i] != dirPath[i])
  6397. #else
  6398. if (CharacterFunctions::toLowerCase (thisPath[i])
  6399. != CharacterFunctions::toLowerCase (dirPath[i]))
  6400. #endif
  6401. {
  6402. break;
  6403. }
  6404. ++commonBitLength;
  6405. }
  6406. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6407. --commonBitLength;
  6408. // if the only common bit is the root, then just return the full path..
  6409. if (commonBitLength <= 0
  6410. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6411. return fullPath;
  6412. thisPath = thisPath.substring (commonBitLength);
  6413. dirPath = dirPath.substring (commonBitLength);
  6414. while (dirPath.isNotEmpty())
  6415. {
  6416. #if JUCE_WINDOWS
  6417. thisPath = "..\\" + thisPath;
  6418. #else
  6419. thisPath = "../" + thisPath;
  6420. #endif
  6421. const int sep = dirPath.indexOfChar (separator);
  6422. if (sep >= 0)
  6423. dirPath = dirPath.substring (sep + 1);
  6424. else
  6425. dirPath = String::empty;
  6426. }
  6427. return thisPath;
  6428. }
  6429. const File File::createTempFile (const String& fileNameEnding)
  6430. {
  6431. const File tempFile (getSpecialLocation (tempDirectory)
  6432. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6433. .withFileExtension (fileNameEnding));
  6434. if (tempFile.exists())
  6435. return createTempFile (fileNameEnding);
  6436. else
  6437. return tempFile;
  6438. }
  6439. #if JUCE_UNIT_TESTS
  6440. class FileTests : public UnitTest
  6441. {
  6442. public:
  6443. FileTests() : UnitTest ("Files") {}
  6444. void runTest()
  6445. {
  6446. beginTest ("Reading");
  6447. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6448. const File temp (File::getSpecialLocation (File::tempDirectory));
  6449. expect (! File::nonexistent.exists());
  6450. expect (home.isDirectory());
  6451. expect (home.exists());
  6452. expect (! home.existsAsFile());
  6453. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6454. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6455. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6456. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6457. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6458. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6459. expect (home.getBytesFreeOnVolume() > 0);
  6460. expect (! home.isHidden());
  6461. expect (home.isOnHardDisk());
  6462. expect (! home.isOnCDRomDrive());
  6463. expect (File::getCurrentWorkingDirectory().exists());
  6464. expect (home.setAsCurrentWorkingDirectory());
  6465. expect (File::getCurrentWorkingDirectory() == home);
  6466. {
  6467. Array<File> roots;
  6468. File::findFileSystemRoots (roots);
  6469. expect (roots.size() > 0);
  6470. int numRootsExisting = 0;
  6471. for (int i = 0; i < roots.size(); ++i)
  6472. if (roots[i].exists())
  6473. ++numRootsExisting;
  6474. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6475. expect (numRootsExisting > 0);
  6476. }
  6477. beginTest ("Writing");
  6478. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6479. expect (demoFolder.deleteRecursively());
  6480. expect (demoFolder.createDirectory());
  6481. expect (demoFolder.isDirectory());
  6482. expect (demoFolder.getParentDirectory() == temp);
  6483. expect (temp.isDirectory());
  6484. {
  6485. Array<File> files;
  6486. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6487. expect (files.contains (demoFolder));
  6488. }
  6489. {
  6490. Array<File> files;
  6491. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6492. expect (files.contains (demoFolder));
  6493. }
  6494. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6495. expect (tempFile.getFileExtension() == ".txt");
  6496. expect (tempFile.hasFileExtension (".txt"));
  6497. expect (tempFile.hasFileExtension ("txt"));
  6498. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6499. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6500. expect (tempFile.hasWriteAccess());
  6501. {
  6502. FileOutputStream fo (tempFile);
  6503. fo.write ("0123456789", 10);
  6504. }
  6505. expect (tempFile.exists());
  6506. expect (tempFile.getSize() == 10);
  6507. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6508. expect (tempFile.loadFileAsString() == "0123456789");
  6509. expect (! demoFolder.containsSubDirectories());
  6510. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6511. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6512. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6513. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6514. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6515. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6516. expect (demoFolder.containsSubDirectories());
  6517. expect (tempFile.hasWriteAccess());
  6518. tempFile.setReadOnly (true);
  6519. expect (! tempFile.hasWriteAccess());
  6520. tempFile.setReadOnly (false);
  6521. expect (tempFile.hasWriteAccess());
  6522. Time t (Time::getCurrentTime());
  6523. tempFile.setLastModificationTime (t);
  6524. Time t2 = tempFile.getLastModificationTime();
  6525. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6526. {
  6527. MemoryBlock mb;
  6528. tempFile.loadFileAsData (mb);
  6529. expect (mb.getSize() == 10);
  6530. expect (mb[0] == '0');
  6531. }
  6532. expect (tempFile.appendData ("abcdefghij", 10));
  6533. expect (tempFile.getSize() == 20);
  6534. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6535. expect (tempFile.getSize() == 10);
  6536. File tempFile2 (tempFile.getNonexistentSibling (false));
  6537. expect (tempFile.copyFileTo (tempFile2));
  6538. expect (tempFile2.exists());
  6539. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6540. expect (tempFile.deleteFile());
  6541. expect (! tempFile.exists());
  6542. expect (tempFile2.moveFileTo (tempFile));
  6543. expect (tempFile.exists());
  6544. expect (! tempFile2.exists());
  6545. expect (demoFolder.deleteRecursively());
  6546. expect (! demoFolder.exists());
  6547. }
  6548. };
  6549. static FileTests fileUnitTests;
  6550. #endif
  6551. END_JUCE_NAMESPACE
  6552. /*** End of inlined file: juce_File.cpp ***/
  6553. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6554. BEGIN_JUCE_NAMESPACE
  6555. int64 juce_fileSetPosition (void* handle, int64 pos);
  6556. FileInputStream::FileInputStream (const File& f)
  6557. : file (f),
  6558. fileHandle (0),
  6559. currentPosition (0),
  6560. totalSize (0),
  6561. needToSeek (true)
  6562. {
  6563. openHandle();
  6564. }
  6565. FileInputStream::~FileInputStream()
  6566. {
  6567. closeHandle();
  6568. }
  6569. int64 FileInputStream::getTotalLength()
  6570. {
  6571. return totalSize;
  6572. }
  6573. int FileInputStream::read (void* buffer, int bytesToRead)
  6574. {
  6575. if (needToSeek)
  6576. {
  6577. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6578. return 0;
  6579. needToSeek = false;
  6580. }
  6581. const size_t num = readInternal (buffer, bytesToRead);
  6582. currentPosition += num;
  6583. return (int) num;
  6584. }
  6585. bool FileInputStream::isExhausted()
  6586. {
  6587. return currentPosition >= totalSize;
  6588. }
  6589. int64 FileInputStream::getPosition()
  6590. {
  6591. return currentPosition;
  6592. }
  6593. bool FileInputStream::setPosition (int64 pos)
  6594. {
  6595. pos = jlimit ((int64) 0, totalSize, pos);
  6596. needToSeek |= (currentPosition != pos);
  6597. currentPosition = pos;
  6598. return true;
  6599. }
  6600. END_JUCE_NAMESPACE
  6601. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6602. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6603. BEGIN_JUCE_NAMESPACE
  6604. int64 juce_fileSetPosition (void* handle, int64 pos);
  6605. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6606. : file (f),
  6607. fileHandle (0),
  6608. currentPosition (0),
  6609. bufferSize (bufferSize_),
  6610. bytesInBuffer (0),
  6611. buffer (jmax (bufferSize_, 16))
  6612. {
  6613. openHandle();
  6614. }
  6615. FileOutputStream::~FileOutputStream()
  6616. {
  6617. flush();
  6618. closeHandle();
  6619. }
  6620. int64 FileOutputStream::getPosition()
  6621. {
  6622. return currentPosition;
  6623. }
  6624. bool FileOutputStream::setPosition (int64 newPosition)
  6625. {
  6626. if (newPosition != currentPosition)
  6627. {
  6628. flush();
  6629. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6630. }
  6631. return newPosition == currentPosition;
  6632. }
  6633. void FileOutputStream::flush()
  6634. {
  6635. if (bytesInBuffer > 0)
  6636. {
  6637. writeInternal (buffer, bytesInBuffer);
  6638. bytesInBuffer = 0;
  6639. }
  6640. flushInternal();
  6641. }
  6642. bool FileOutputStream::write (const void* const src, const int numBytes)
  6643. {
  6644. if (bytesInBuffer + numBytes < bufferSize)
  6645. {
  6646. memcpy (buffer + bytesInBuffer, src, numBytes);
  6647. bytesInBuffer += numBytes;
  6648. currentPosition += numBytes;
  6649. }
  6650. else
  6651. {
  6652. if (bytesInBuffer > 0)
  6653. {
  6654. // flush the reservoir
  6655. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6656. bytesInBuffer = 0;
  6657. if (! wroteOk)
  6658. return false;
  6659. }
  6660. if (numBytes < bufferSize)
  6661. {
  6662. memcpy (buffer + bytesInBuffer, src, numBytes);
  6663. bytesInBuffer += numBytes;
  6664. currentPosition += numBytes;
  6665. }
  6666. else
  6667. {
  6668. const int bytesWritten = writeInternal (src, numBytes);
  6669. if (bytesWritten < 0)
  6670. return false;
  6671. currentPosition += bytesWritten;
  6672. return bytesWritten == numBytes;
  6673. }
  6674. }
  6675. return true;
  6676. }
  6677. END_JUCE_NAMESPACE
  6678. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6679. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6680. BEGIN_JUCE_NAMESPACE
  6681. FileSearchPath::FileSearchPath()
  6682. {
  6683. }
  6684. FileSearchPath::FileSearchPath (const String& path)
  6685. {
  6686. init (path);
  6687. }
  6688. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6689. : directories (other.directories)
  6690. {
  6691. }
  6692. FileSearchPath::~FileSearchPath()
  6693. {
  6694. }
  6695. FileSearchPath& FileSearchPath::operator= (const String& path)
  6696. {
  6697. init (path);
  6698. return *this;
  6699. }
  6700. void FileSearchPath::init (const String& path)
  6701. {
  6702. directories.clear();
  6703. directories.addTokens (path, ";", "\"");
  6704. directories.trim();
  6705. directories.removeEmptyStrings();
  6706. for (int i = directories.size(); --i >= 0;)
  6707. directories.set (i, directories[i].unquoted());
  6708. }
  6709. int FileSearchPath::getNumPaths() const
  6710. {
  6711. return directories.size();
  6712. }
  6713. const File FileSearchPath::operator[] (const int index) const
  6714. {
  6715. return File (directories [index]);
  6716. }
  6717. const String FileSearchPath::toString() const
  6718. {
  6719. StringArray directories2 (directories);
  6720. for (int i = directories2.size(); --i >= 0;)
  6721. if (directories2[i].containsChar (';'))
  6722. directories2.set (i, directories2[i].quoted());
  6723. return directories2.joinIntoString (";");
  6724. }
  6725. void FileSearchPath::add (const File& dir, const int insertIndex)
  6726. {
  6727. directories.insert (insertIndex, dir.getFullPathName());
  6728. }
  6729. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6730. {
  6731. for (int i = 0; i < directories.size(); ++i)
  6732. if (File (directories[i]) == dir)
  6733. return;
  6734. add (dir);
  6735. }
  6736. void FileSearchPath::remove (const int index)
  6737. {
  6738. directories.remove (index);
  6739. }
  6740. void FileSearchPath::addPath (const FileSearchPath& other)
  6741. {
  6742. for (int i = 0; i < other.getNumPaths(); ++i)
  6743. addIfNotAlreadyThere (other[i]);
  6744. }
  6745. void FileSearchPath::removeRedundantPaths()
  6746. {
  6747. for (int i = directories.size(); --i >= 0;)
  6748. {
  6749. const File d1 (directories[i]);
  6750. for (int j = directories.size(); --j >= 0;)
  6751. {
  6752. const File d2 (directories[j]);
  6753. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6754. {
  6755. directories.remove (i);
  6756. break;
  6757. }
  6758. }
  6759. }
  6760. }
  6761. void FileSearchPath::removeNonExistentPaths()
  6762. {
  6763. for (int i = directories.size(); --i >= 0;)
  6764. if (! File (directories[i]).isDirectory())
  6765. directories.remove (i);
  6766. }
  6767. int FileSearchPath::findChildFiles (Array<File>& results,
  6768. const int whatToLookFor,
  6769. const bool searchRecursively,
  6770. const String& wildCardPattern) const
  6771. {
  6772. int total = 0;
  6773. for (int i = 0; i < directories.size(); ++i)
  6774. total += operator[] (i).findChildFiles (results,
  6775. whatToLookFor,
  6776. searchRecursively,
  6777. wildCardPattern);
  6778. return total;
  6779. }
  6780. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6781. const bool checkRecursively) const
  6782. {
  6783. for (int i = directories.size(); --i >= 0;)
  6784. {
  6785. const File d (directories[i]);
  6786. if (checkRecursively)
  6787. {
  6788. if (fileToCheck.isAChildOf (d))
  6789. return true;
  6790. }
  6791. else
  6792. {
  6793. if (fileToCheck.getParentDirectory() == d)
  6794. return true;
  6795. }
  6796. }
  6797. return false;
  6798. }
  6799. END_JUCE_NAMESPACE
  6800. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6801. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6802. BEGIN_JUCE_NAMESPACE
  6803. NamedPipe::NamedPipe()
  6804. : internal (0)
  6805. {
  6806. }
  6807. NamedPipe::~NamedPipe()
  6808. {
  6809. close();
  6810. }
  6811. bool NamedPipe::openExisting (const String& pipeName)
  6812. {
  6813. currentPipeName = pipeName;
  6814. return openInternal (pipeName, false);
  6815. }
  6816. bool NamedPipe::createNewPipe (const String& pipeName)
  6817. {
  6818. currentPipeName = pipeName;
  6819. return openInternal (pipeName, true);
  6820. }
  6821. bool NamedPipe::isOpen() const
  6822. {
  6823. return internal != 0;
  6824. }
  6825. const String NamedPipe::getName() const
  6826. {
  6827. return currentPipeName;
  6828. }
  6829. // other methods for this class are implemented in the platform-specific files
  6830. END_JUCE_NAMESPACE
  6831. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6832. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6833. BEGIN_JUCE_NAMESPACE
  6834. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6835. {
  6836. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6837. "temp_" + String (Random::getSystemRandom().nextInt()),
  6838. suffix,
  6839. optionFlags);
  6840. }
  6841. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6842. : targetFile (targetFile_)
  6843. {
  6844. // If you use this constructor, you need to give it a valid target file!
  6845. jassert (targetFile != File::nonexistent);
  6846. createTempFile (targetFile.getParentDirectory(),
  6847. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6848. targetFile.getFileExtension(),
  6849. optionFlags);
  6850. }
  6851. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6852. const String& suffix, const int optionFlags)
  6853. {
  6854. if ((optionFlags & useHiddenFile) != 0)
  6855. name = "." + name;
  6856. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6857. }
  6858. TemporaryFile::~TemporaryFile()
  6859. {
  6860. if (! deleteTemporaryFile())
  6861. {
  6862. /* Failed to delete our temporary file! The most likely reason for this would be
  6863. that you've not closed an output stream that was being used to write to file.
  6864. If you find that something beyond your control is changing permissions on
  6865. your temporary files and preventing them from being deleted, you may want to
  6866. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6867. handle them appropriately.
  6868. */
  6869. jassertfalse;
  6870. }
  6871. }
  6872. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6873. {
  6874. // This method only works if you created this object with the constructor
  6875. // that takes a target file!
  6876. jassert (targetFile != File::nonexistent);
  6877. if (temporaryFile.exists())
  6878. {
  6879. // Have a few attempts at overwriting the file before giving up..
  6880. for (int i = 5; --i >= 0;)
  6881. {
  6882. if (temporaryFile.moveFileTo (targetFile))
  6883. return true;
  6884. Thread::sleep (100);
  6885. }
  6886. }
  6887. else
  6888. {
  6889. // There's no temporary file to use. If your write failed, you should
  6890. // probably check, and not bother calling this method.
  6891. jassertfalse;
  6892. }
  6893. return false;
  6894. }
  6895. bool TemporaryFile::deleteTemporaryFile() const
  6896. {
  6897. // Have a few attempts at deleting the file before giving up..
  6898. for (int i = 5; --i >= 0;)
  6899. {
  6900. if (temporaryFile.deleteFile())
  6901. return true;
  6902. Thread::sleep (50);
  6903. }
  6904. return false;
  6905. }
  6906. END_JUCE_NAMESPACE
  6907. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6908. /*** Start of inlined file: juce_Socket.cpp ***/
  6909. #if JUCE_WINDOWS
  6910. #include <winsock2.h>
  6911. #if JUCE_MSVC
  6912. #pragma warning (push)
  6913. #pragma warning (disable : 4127 4389 4018)
  6914. #endif
  6915. #else
  6916. #if JUCE_LINUX
  6917. #include <sys/types.h>
  6918. #include <sys/socket.h>
  6919. #include <sys/errno.h>
  6920. #include <unistd.h>
  6921. #include <netinet/in.h>
  6922. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6923. #include <CoreServices/CoreServices.h>
  6924. #endif
  6925. #include <fcntl.h>
  6926. #include <netdb.h>
  6927. #include <arpa/inet.h>
  6928. #include <netinet/tcp.h>
  6929. #endif
  6930. BEGIN_JUCE_NAMESPACE
  6931. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6932. typedef socklen_t juce_socklen_t;
  6933. #else
  6934. typedef int juce_socklen_t;
  6935. #endif
  6936. #if JUCE_WINDOWS
  6937. namespace SocketHelpers
  6938. {
  6939. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6940. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6941. void initWin32Sockets()
  6942. {
  6943. static CriticalSection lock;
  6944. const ScopedLock sl (lock);
  6945. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6946. {
  6947. WSADATA wsaData;
  6948. const WORD wVersionRequested = MAKEWORD (1, 1);
  6949. WSAStartup (wVersionRequested, &wsaData);
  6950. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6951. }
  6952. }
  6953. }
  6954. void juce_shutdownWin32Sockets()
  6955. {
  6956. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6957. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6958. }
  6959. #endif
  6960. namespace SocketHelpers
  6961. {
  6962. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6963. {
  6964. const int sndBufSize = 65536;
  6965. const int rcvBufSize = 65536;
  6966. const int one = 1;
  6967. return handle > 0
  6968. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6969. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6970. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6971. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6972. }
  6973. bool bindSocketToPort (const int handle, const int port) throw()
  6974. {
  6975. if (handle <= 0 || port <= 0)
  6976. return false;
  6977. struct sockaddr_in servTmpAddr;
  6978. zerostruct (servTmpAddr);
  6979. servTmpAddr.sin_family = PF_INET;
  6980. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6981. servTmpAddr.sin_port = htons ((uint16) port);
  6982. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6983. }
  6984. int readSocket (const int handle,
  6985. void* const destBuffer, const int maxBytesToRead,
  6986. bool volatile& connected,
  6987. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6988. {
  6989. int bytesRead = 0;
  6990. while (bytesRead < maxBytesToRead)
  6991. {
  6992. int bytesThisTime;
  6993. #if JUCE_WINDOWS
  6994. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6995. #else
  6996. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6997. && errno == EINTR
  6998. && connected)
  6999. {
  7000. }
  7001. #endif
  7002. if (bytesThisTime <= 0 || ! connected)
  7003. {
  7004. if (bytesRead == 0)
  7005. bytesRead = -1;
  7006. break;
  7007. }
  7008. bytesRead += bytesThisTime;
  7009. if (! blockUntilSpecifiedAmountHasArrived)
  7010. break;
  7011. }
  7012. return bytesRead;
  7013. }
  7014. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  7015. {
  7016. struct timeval timeout;
  7017. struct timeval* timeoutp;
  7018. if (timeoutMsecs >= 0)
  7019. {
  7020. timeout.tv_sec = timeoutMsecs / 1000;
  7021. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7022. timeoutp = &timeout;
  7023. }
  7024. else
  7025. {
  7026. timeoutp = 0;
  7027. }
  7028. fd_set rset, wset;
  7029. FD_ZERO (&rset);
  7030. FD_SET (handle, &rset);
  7031. FD_ZERO (&wset);
  7032. FD_SET (handle, &wset);
  7033. fd_set* const prset = forReading ? &rset : 0;
  7034. fd_set* const pwset = forReading ? 0 : &wset;
  7035. #if JUCE_WINDOWS
  7036. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7037. return -1;
  7038. #else
  7039. {
  7040. int result;
  7041. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7042. && errno == EINTR)
  7043. {
  7044. }
  7045. if (result < 0)
  7046. return -1;
  7047. }
  7048. #endif
  7049. {
  7050. int opt;
  7051. juce_socklen_t len = sizeof (opt);
  7052. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7053. || opt != 0)
  7054. return -1;
  7055. }
  7056. if ((forReading && FD_ISSET (handle, &rset))
  7057. || ((! forReading) && FD_ISSET (handle, &wset)))
  7058. return 1;
  7059. return 0;
  7060. }
  7061. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7062. {
  7063. #if JUCE_WINDOWS
  7064. u_long nonBlocking = shouldBlock ? 0 : 1;
  7065. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7066. return false;
  7067. #else
  7068. int socketFlags = fcntl (handle, F_GETFL, 0);
  7069. if (socketFlags == -1)
  7070. return false;
  7071. if (shouldBlock)
  7072. socketFlags &= ~O_NONBLOCK;
  7073. else
  7074. socketFlags |= O_NONBLOCK;
  7075. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7076. return false;
  7077. #endif
  7078. return true;
  7079. }
  7080. bool connectSocket (int volatile& handle,
  7081. const bool isDatagram,
  7082. void** serverAddress,
  7083. const String& hostName,
  7084. const int portNumber,
  7085. const int timeOutMillisecs) throw()
  7086. {
  7087. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7088. if (hostEnt == 0)
  7089. return false;
  7090. struct in_addr targetAddress;
  7091. memcpy (&targetAddress.s_addr,
  7092. *(hostEnt->h_addr_list),
  7093. sizeof (targetAddress.s_addr));
  7094. struct sockaddr_in servTmpAddr;
  7095. zerostruct (servTmpAddr);
  7096. servTmpAddr.sin_family = PF_INET;
  7097. servTmpAddr.sin_addr = targetAddress;
  7098. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7099. if (handle < 0)
  7100. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7101. if (handle < 0)
  7102. return false;
  7103. if (isDatagram)
  7104. {
  7105. *serverAddress = new struct sockaddr_in();
  7106. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7107. return true;
  7108. }
  7109. setSocketBlockingState (handle, false);
  7110. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7111. if (result < 0)
  7112. {
  7113. #if JUCE_WINDOWS
  7114. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7115. #else
  7116. if (errno == EINPROGRESS)
  7117. #endif
  7118. {
  7119. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7120. {
  7121. setSocketBlockingState (handle, true);
  7122. return false;
  7123. }
  7124. }
  7125. }
  7126. setSocketBlockingState (handle, true);
  7127. resetSocketOptions (handle, false, false);
  7128. return true;
  7129. }
  7130. }
  7131. StreamingSocket::StreamingSocket()
  7132. : portNumber (0),
  7133. handle (-1),
  7134. connected (false),
  7135. isListener (false)
  7136. {
  7137. #if JUCE_WINDOWS
  7138. SocketHelpers::initWin32Sockets();
  7139. #endif
  7140. }
  7141. StreamingSocket::StreamingSocket (const String& hostName_,
  7142. const int portNumber_,
  7143. const int handle_)
  7144. : hostName (hostName_),
  7145. portNumber (portNumber_),
  7146. handle (handle_),
  7147. connected (true),
  7148. isListener (false)
  7149. {
  7150. #if JUCE_WINDOWS
  7151. SocketHelpers::initWin32Sockets();
  7152. #endif
  7153. SocketHelpers::resetSocketOptions (handle_, false, false);
  7154. }
  7155. StreamingSocket::~StreamingSocket()
  7156. {
  7157. close();
  7158. }
  7159. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7160. {
  7161. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7162. : -1;
  7163. }
  7164. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7165. {
  7166. if (isListener || ! connected)
  7167. return -1;
  7168. #if JUCE_WINDOWS
  7169. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7170. #else
  7171. int result;
  7172. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7173. && errno == EINTR)
  7174. {
  7175. }
  7176. return result;
  7177. #endif
  7178. }
  7179. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7180. const int timeoutMsecs) const
  7181. {
  7182. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7183. : -1;
  7184. }
  7185. bool StreamingSocket::bindToPort (const int port)
  7186. {
  7187. return SocketHelpers::bindSocketToPort (handle, port);
  7188. }
  7189. bool StreamingSocket::connect (const String& remoteHostName,
  7190. const int remotePortNumber,
  7191. const int timeOutMillisecs)
  7192. {
  7193. if (isListener)
  7194. {
  7195. jassertfalse; // a listener socket can't connect to another one!
  7196. return false;
  7197. }
  7198. if (connected)
  7199. close();
  7200. hostName = remoteHostName;
  7201. portNumber = remotePortNumber;
  7202. isListener = false;
  7203. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7204. remotePortNumber, timeOutMillisecs);
  7205. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7206. {
  7207. close();
  7208. return false;
  7209. }
  7210. return true;
  7211. }
  7212. void StreamingSocket::close()
  7213. {
  7214. #if JUCE_WINDOWS
  7215. if (handle != SOCKET_ERROR || connected)
  7216. closesocket (handle);
  7217. connected = false;
  7218. #else
  7219. if (connected)
  7220. {
  7221. connected = false;
  7222. if (isListener)
  7223. {
  7224. // need to do this to interrupt the accept() function..
  7225. StreamingSocket temp;
  7226. temp.connect ("localhost", portNumber, 1000);
  7227. }
  7228. }
  7229. if (handle != -1)
  7230. ::close (handle);
  7231. #endif
  7232. hostName = String::empty;
  7233. portNumber = 0;
  7234. handle = -1;
  7235. isListener = false;
  7236. }
  7237. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7238. {
  7239. if (connected)
  7240. close();
  7241. hostName = "listener";
  7242. portNumber = newPortNumber;
  7243. isListener = true;
  7244. struct sockaddr_in servTmpAddr;
  7245. zerostruct (servTmpAddr);
  7246. servTmpAddr.sin_family = PF_INET;
  7247. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7248. if (localHostName.isNotEmpty())
  7249. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7250. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7251. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7252. if (handle < 0)
  7253. return false;
  7254. const int reuse = 1;
  7255. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7256. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7257. || listen (handle, SOMAXCONN) < 0)
  7258. {
  7259. close();
  7260. return false;
  7261. }
  7262. connected = true;
  7263. return true;
  7264. }
  7265. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7266. {
  7267. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7268. // prepare this socket as a listener.
  7269. if (connected && isListener)
  7270. {
  7271. struct sockaddr address;
  7272. juce_socklen_t len = sizeof (sockaddr);
  7273. const int newSocket = (int) accept (handle, &address, &len);
  7274. if (newSocket >= 0 && connected)
  7275. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7276. portNumber, newSocket);
  7277. }
  7278. return 0;
  7279. }
  7280. bool StreamingSocket::isLocal() const throw()
  7281. {
  7282. return hostName == "127.0.0.1";
  7283. }
  7284. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7285. : portNumber (0),
  7286. handle (-1),
  7287. connected (true),
  7288. allowBroadcast (allowBroadcast_),
  7289. serverAddress (0)
  7290. {
  7291. #if JUCE_WINDOWS
  7292. SocketHelpers::initWin32Sockets();
  7293. #endif
  7294. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7295. bindToPort (localPortNumber);
  7296. }
  7297. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7298. const int handle_, const int localPortNumber)
  7299. : hostName (hostName_),
  7300. portNumber (portNumber_),
  7301. handle (handle_),
  7302. connected (true),
  7303. allowBroadcast (false),
  7304. serverAddress (0)
  7305. {
  7306. #if JUCE_WINDOWS
  7307. SocketHelpers::initWin32Sockets();
  7308. #endif
  7309. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7310. bindToPort (localPortNumber);
  7311. }
  7312. DatagramSocket::~DatagramSocket()
  7313. {
  7314. close();
  7315. delete static_cast <struct sockaddr_in*> (serverAddress);
  7316. serverAddress = 0;
  7317. }
  7318. void DatagramSocket::close()
  7319. {
  7320. #if JUCE_WINDOWS
  7321. closesocket (handle);
  7322. connected = false;
  7323. #else
  7324. connected = false;
  7325. ::close (handle);
  7326. #endif
  7327. hostName = String::empty;
  7328. portNumber = 0;
  7329. handle = -1;
  7330. }
  7331. bool DatagramSocket::bindToPort (const int port)
  7332. {
  7333. return SocketHelpers::bindSocketToPort (handle, port);
  7334. }
  7335. bool DatagramSocket::connect (const String& remoteHostName,
  7336. const int remotePortNumber,
  7337. const int timeOutMillisecs)
  7338. {
  7339. if (connected)
  7340. close();
  7341. hostName = remoteHostName;
  7342. portNumber = remotePortNumber;
  7343. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7344. remoteHostName, remotePortNumber,
  7345. timeOutMillisecs);
  7346. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7347. {
  7348. close();
  7349. return false;
  7350. }
  7351. return true;
  7352. }
  7353. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7354. {
  7355. struct sockaddr address;
  7356. juce_socklen_t len = sizeof (sockaddr);
  7357. while (waitUntilReady (true, -1) == 1)
  7358. {
  7359. char buf[1];
  7360. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7361. {
  7362. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7363. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7364. -1, -1);
  7365. }
  7366. }
  7367. return 0;
  7368. }
  7369. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7370. const int timeoutMsecs) const
  7371. {
  7372. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7373. : -1;
  7374. }
  7375. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7376. {
  7377. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7378. : -1;
  7379. }
  7380. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7381. {
  7382. // You need to call connect() first to set the server address..
  7383. jassert (serverAddress != 0 && connected);
  7384. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7385. numBytesToWrite, 0,
  7386. (const struct sockaddr*) serverAddress,
  7387. sizeof (struct sockaddr_in))
  7388. : -1;
  7389. }
  7390. bool DatagramSocket::isLocal() const throw()
  7391. {
  7392. return hostName == "127.0.0.1";
  7393. }
  7394. #if JUCE_MSVC
  7395. #pragma warning (pop)
  7396. #endif
  7397. END_JUCE_NAMESPACE
  7398. /*** End of inlined file: juce_Socket.cpp ***/
  7399. /*** Start of inlined file: juce_URL.cpp ***/
  7400. BEGIN_JUCE_NAMESPACE
  7401. URL::URL()
  7402. {
  7403. }
  7404. URL::URL (const String& url_)
  7405. : url (url_)
  7406. {
  7407. int i = url.indexOfChar ('?');
  7408. if (i >= 0)
  7409. {
  7410. do
  7411. {
  7412. const int nextAmp = url.indexOfChar (i + 1, '&');
  7413. const int equalsPos = url.indexOfChar (i + 1, '=');
  7414. if (equalsPos > i + 1)
  7415. {
  7416. if (nextAmp < 0)
  7417. {
  7418. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7419. removeEscapeChars (url.substring (equalsPos + 1)));
  7420. }
  7421. else if (nextAmp > 0 && equalsPos < nextAmp)
  7422. {
  7423. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7424. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7425. }
  7426. }
  7427. i = nextAmp;
  7428. }
  7429. while (i >= 0);
  7430. url = url.upToFirstOccurrenceOf ("?", false, false);
  7431. }
  7432. }
  7433. URL::URL (const URL& other)
  7434. : url (other.url),
  7435. postData (other.postData),
  7436. parameters (other.parameters),
  7437. filesToUpload (other.filesToUpload),
  7438. mimeTypes (other.mimeTypes)
  7439. {
  7440. }
  7441. URL& URL::operator= (const URL& other)
  7442. {
  7443. url = other.url;
  7444. postData = other.postData;
  7445. parameters = other.parameters;
  7446. filesToUpload = other.filesToUpload;
  7447. mimeTypes = other.mimeTypes;
  7448. return *this;
  7449. }
  7450. URL::~URL()
  7451. {
  7452. }
  7453. namespace URLHelpers
  7454. {
  7455. const String getMangledParameters (const StringPairArray& parameters)
  7456. {
  7457. String p;
  7458. for (int i = 0; i < parameters.size(); ++i)
  7459. {
  7460. if (i > 0)
  7461. p << '&';
  7462. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7463. << '='
  7464. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7465. }
  7466. return p;
  7467. }
  7468. int findStartOfDomain (const String& url)
  7469. {
  7470. int i = 0;
  7471. while (CharacterFunctions::isLetterOrDigit (url[i])
  7472. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7473. ++i;
  7474. return url[i] == ':' ? i + 1 : 0;
  7475. }
  7476. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7477. {
  7478. MemoryOutputStream data (postData, false);
  7479. if (url.getFilesToUpload().size() > 0)
  7480. {
  7481. // need to upload some files, so do it as multi-part...
  7482. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7483. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7484. data << "--" << boundary;
  7485. int i;
  7486. for (i = 0; i < url.getParameters().size(); ++i)
  7487. {
  7488. data << "\r\nContent-Disposition: form-data; name=\""
  7489. << url.getParameters().getAllKeys() [i]
  7490. << "\"\r\n\r\n"
  7491. << url.getParameters().getAllValues() [i]
  7492. << "\r\n--"
  7493. << boundary;
  7494. }
  7495. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7496. {
  7497. const File file (url.getFilesToUpload().getAllValues() [i]);
  7498. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7499. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7500. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7501. const String mimeType (url.getMimeTypesOfUploadFiles()
  7502. .getValue (paramName, String::empty));
  7503. if (mimeType.isNotEmpty())
  7504. data << "Content-Type: " << mimeType << "\r\n";
  7505. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7506. << file << "\r\n--" << boundary;
  7507. }
  7508. data << "--\r\n";
  7509. data.flush();
  7510. }
  7511. else
  7512. {
  7513. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7514. data.flush();
  7515. // just a short text attachment, so use simple url encoding..
  7516. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7517. << (unsigned int) postData.getSize() << "\r\n";
  7518. }
  7519. }
  7520. }
  7521. const String URL::toString (const bool includeGetParameters) const
  7522. {
  7523. if (includeGetParameters && parameters.size() > 0)
  7524. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7525. else
  7526. return url;
  7527. }
  7528. bool URL::isWellFormed() const
  7529. {
  7530. //xxx TODO
  7531. return url.isNotEmpty();
  7532. }
  7533. const String URL::getDomain() const
  7534. {
  7535. int start = URLHelpers::findStartOfDomain (url);
  7536. while (url[start] == '/')
  7537. ++start;
  7538. const int end1 = url.indexOfChar (start, '/');
  7539. const int end2 = url.indexOfChar (start, ':');
  7540. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7541. : jmin (end1, end2);
  7542. return url.substring (start, end);
  7543. }
  7544. const String URL::getSubPath() const
  7545. {
  7546. int start = URLHelpers::findStartOfDomain (url);
  7547. while (url[start] == '/')
  7548. ++start;
  7549. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7550. return startOfPath <= 0 ? String::empty
  7551. : url.substring (startOfPath);
  7552. }
  7553. const String URL::getScheme() const
  7554. {
  7555. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7556. }
  7557. const URL URL::withNewSubPath (const String& newPath) const
  7558. {
  7559. int start = URLHelpers::findStartOfDomain (url);
  7560. while (url[start] == '/')
  7561. ++start;
  7562. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7563. URL u (*this);
  7564. if (startOfPath > 0)
  7565. u.url = url.substring (0, startOfPath);
  7566. if (! u.url.endsWithChar ('/'))
  7567. u.url << '/';
  7568. if (newPath.startsWithChar ('/'))
  7569. u.url << newPath.substring (1);
  7570. else
  7571. u.url << newPath;
  7572. return u;
  7573. }
  7574. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7575. {
  7576. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7577. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7578. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7579. return true;
  7580. if (possibleURL.containsChar ('@')
  7581. || possibleURL.containsChar (' '))
  7582. return false;
  7583. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7584. .fromLastOccurrenceOf (".", false, false));
  7585. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7586. }
  7587. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7588. {
  7589. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7590. return atSign > 0
  7591. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7592. && (! possibleEmailAddress.endsWithChar ('.'));
  7593. }
  7594. InputStream* URL::createInputStream (const bool usePostCommand,
  7595. OpenStreamProgressCallback* const progressCallback,
  7596. void* const progressCallbackContext,
  7597. const String& extraHeaders,
  7598. const int timeOutMs,
  7599. StringPairArray* const responseHeaders) const
  7600. {
  7601. String headers;
  7602. MemoryBlock headersAndPostData;
  7603. if (usePostCommand)
  7604. URLHelpers::createHeadersAndPostData (*this, headers, headersAndPostData);
  7605. headers += extraHeaders;
  7606. if (! headers.endsWithChar ('\n'))
  7607. headers << "\r\n";
  7608. return createNativeStream (toString (! usePostCommand), usePostCommand, headersAndPostData,
  7609. progressCallback, progressCallbackContext,
  7610. headers, timeOutMs, responseHeaders);
  7611. }
  7612. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7613. const bool usePostCommand) const
  7614. {
  7615. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7616. if (in != 0)
  7617. {
  7618. in->readIntoMemoryBlock (destData);
  7619. return true;
  7620. }
  7621. return false;
  7622. }
  7623. const String URL::readEntireTextStream (const bool usePostCommand) const
  7624. {
  7625. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7626. if (in != 0)
  7627. return in->readEntireStreamAsString();
  7628. return String::empty;
  7629. }
  7630. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7631. {
  7632. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7633. }
  7634. const URL URL::withParameter (const String& parameterName,
  7635. const String& parameterValue) const
  7636. {
  7637. URL u (*this);
  7638. u.parameters.set (parameterName, parameterValue);
  7639. return u;
  7640. }
  7641. const URL URL::withFileToUpload (const String& parameterName,
  7642. const File& fileToUpload,
  7643. const String& mimeType) const
  7644. {
  7645. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7646. URL u (*this);
  7647. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7648. u.mimeTypes.set (parameterName, mimeType);
  7649. return u;
  7650. }
  7651. const URL URL::withPOSTData (const String& postData_) const
  7652. {
  7653. URL u (*this);
  7654. u.postData = postData_;
  7655. return u;
  7656. }
  7657. const StringPairArray& URL::getParameters() const
  7658. {
  7659. return parameters;
  7660. }
  7661. const StringPairArray& URL::getFilesToUpload() const
  7662. {
  7663. return filesToUpload;
  7664. }
  7665. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7666. {
  7667. return mimeTypes;
  7668. }
  7669. const String URL::removeEscapeChars (const String& s)
  7670. {
  7671. String result (s.replaceCharacter ('+', ' '));
  7672. if (! result.containsChar ('%'))
  7673. return result;
  7674. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7675. // after all the replacements have been made, so that multi-byte chars are handled.
  7676. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7677. for (int i = 0; i < utf8.size(); ++i)
  7678. {
  7679. if (utf8.getUnchecked(i) == '%')
  7680. {
  7681. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7682. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7683. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7684. {
  7685. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7686. utf8.removeRange (i + 1, 2);
  7687. }
  7688. }
  7689. }
  7690. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7691. }
  7692. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7693. {
  7694. const char* const legalChars = isParameter ? "_-.*!'()"
  7695. : ",$_-.*!'()";
  7696. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7697. for (int i = 0; i < utf8.size(); ++i)
  7698. {
  7699. const char c = utf8.getUnchecked(i);
  7700. if (! (CharacterFunctions::isLetterOrDigit (c)
  7701. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7702. {
  7703. if (c == ' ')
  7704. {
  7705. utf8.set (i, '+');
  7706. }
  7707. else
  7708. {
  7709. static const char* const hexDigits = "0123456789abcdef";
  7710. utf8.set (i, '%');
  7711. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7712. utf8.insert (++i, hexDigits [c & 15]);
  7713. }
  7714. }
  7715. }
  7716. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7717. }
  7718. bool URL::launchInDefaultBrowser() const
  7719. {
  7720. String u (toString (true));
  7721. if (u.containsChar ('@') && ! u.containsChar (':'))
  7722. u = "mailto:" + u;
  7723. return PlatformUtilities::openDocument (u, String::empty);
  7724. }
  7725. END_JUCE_NAMESPACE
  7726. /*** End of inlined file: juce_URL.cpp ***/
  7727. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7728. BEGIN_JUCE_NAMESPACE
  7729. MACAddress::MACAddress()
  7730. : asInt64 (0)
  7731. {
  7732. }
  7733. MACAddress::MACAddress (const MACAddress& other)
  7734. : asInt64 (other.asInt64)
  7735. {
  7736. }
  7737. MACAddress& MACAddress::operator= (const MACAddress& other)
  7738. {
  7739. asInt64 = other.asInt64;
  7740. return *this;
  7741. }
  7742. MACAddress::MACAddress (const uint8 bytes[6])
  7743. : asInt64 (0)
  7744. {
  7745. memcpy (asBytes, bytes, sizeof (asBytes));
  7746. }
  7747. const String MACAddress::toString() const
  7748. {
  7749. String s;
  7750. s.preallocateStorage (18);
  7751. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7752. {
  7753. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7754. if (i < numElementsInArray (asBytes) - 1)
  7755. s << '-';
  7756. }
  7757. return s;
  7758. }
  7759. int64 MACAddress::toInt64() const throw()
  7760. {
  7761. int64 n = 0;
  7762. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7763. n = (n << 8) | asBytes[i];
  7764. return n;
  7765. }
  7766. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7767. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7768. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7769. END_JUCE_NAMESPACE
  7770. /*** End of inlined file: juce_MACAddress.cpp ***/
  7771. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7772. BEGIN_JUCE_NAMESPACE
  7773. namespace
  7774. {
  7775. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7776. {
  7777. // You need to supply a real stream when creating a BufferedInputStream
  7778. jassert (source != 0);
  7779. requestedSize = jmax (256, requestedSize);
  7780. const int64 sourceSize = source->getTotalLength();
  7781. if (sourceSize >= 0 && sourceSize < requestedSize)
  7782. requestedSize = jmax (32, (int) sourceSize);
  7783. return requestedSize;
  7784. }
  7785. }
  7786. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7787. const bool deleteSourceWhenDestroyed)
  7788. : source (sourceStream),
  7789. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  7790. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  7791. position (sourceStream->getPosition()),
  7792. lastReadPos (0),
  7793. bufferStart (position),
  7794. bufferOverlap (128)
  7795. {
  7796. buffer.malloc (bufferSize);
  7797. }
  7798. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  7799. : source (&sourceStream),
  7800. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  7801. position (sourceStream.getPosition()),
  7802. lastReadPos (0),
  7803. bufferStart (position),
  7804. bufferOverlap (128)
  7805. {
  7806. buffer.malloc (bufferSize);
  7807. }
  7808. BufferedInputStream::~BufferedInputStream()
  7809. {
  7810. }
  7811. int64 BufferedInputStream::getTotalLength()
  7812. {
  7813. return source->getTotalLength();
  7814. }
  7815. int64 BufferedInputStream::getPosition()
  7816. {
  7817. return position;
  7818. }
  7819. bool BufferedInputStream::setPosition (int64 newPosition)
  7820. {
  7821. position = jmax ((int64) 0, newPosition);
  7822. return true;
  7823. }
  7824. bool BufferedInputStream::isExhausted()
  7825. {
  7826. return (position >= lastReadPos)
  7827. && source->isExhausted();
  7828. }
  7829. void BufferedInputStream::ensureBuffered()
  7830. {
  7831. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7832. if (position < bufferStart || position >= bufferEndOverlap)
  7833. {
  7834. int bytesRead;
  7835. if (position < lastReadPos
  7836. && position >= bufferEndOverlap
  7837. && position >= bufferStart)
  7838. {
  7839. const int bytesToKeep = (int) (lastReadPos - position);
  7840. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7841. bufferStart = position;
  7842. bytesRead = source->read (buffer + bytesToKeep,
  7843. bufferSize - bytesToKeep);
  7844. lastReadPos += bytesRead;
  7845. bytesRead += bytesToKeep;
  7846. }
  7847. else
  7848. {
  7849. bufferStart = position;
  7850. source->setPosition (bufferStart);
  7851. bytesRead = source->read (buffer, bufferSize);
  7852. lastReadPos = bufferStart + bytesRead;
  7853. }
  7854. while (bytesRead < bufferSize)
  7855. buffer [bytesRead++] = 0;
  7856. }
  7857. }
  7858. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7859. {
  7860. if (position >= bufferStart
  7861. && position + maxBytesToRead <= lastReadPos)
  7862. {
  7863. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7864. position += maxBytesToRead;
  7865. return maxBytesToRead;
  7866. }
  7867. else
  7868. {
  7869. if (position < bufferStart || position >= lastReadPos)
  7870. ensureBuffered();
  7871. int bytesRead = 0;
  7872. while (maxBytesToRead > 0)
  7873. {
  7874. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7875. if (bytesAvailable > 0)
  7876. {
  7877. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7878. maxBytesToRead -= bytesAvailable;
  7879. bytesRead += bytesAvailable;
  7880. position += bytesAvailable;
  7881. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7882. }
  7883. const int64 oldLastReadPos = lastReadPos;
  7884. ensureBuffered();
  7885. if (oldLastReadPos == lastReadPos)
  7886. break; // if ensureBuffered() failed to read any more data, bail out
  7887. if (isExhausted())
  7888. break;
  7889. }
  7890. return bytesRead;
  7891. }
  7892. }
  7893. const String BufferedInputStream::readString()
  7894. {
  7895. if (position >= bufferStart
  7896. && position < lastReadPos)
  7897. {
  7898. const int maxChars = (int) (lastReadPos - position);
  7899. const char* const src = buffer + (int) (position - bufferStart);
  7900. for (int i = 0; i < maxChars; ++i)
  7901. {
  7902. if (src[i] == 0)
  7903. {
  7904. position += i + 1;
  7905. return String::fromUTF8 (src, i);
  7906. }
  7907. }
  7908. }
  7909. return InputStream::readString();
  7910. }
  7911. END_JUCE_NAMESPACE
  7912. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7913. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7914. BEGIN_JUCE_NAMESPACE
  7915. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  7916. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  7917. {
  7918. }
  7919. FileInputSource::~FileInputSource()
  7920. {
  7921. }
  7922. InputStream* FileInputSource::createInputStream()
  7923. {
  7924. return file.createInputStream();
  7925. }
  7926. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7927. {
  7928. return file.getSiblingFile (relatedItemPath).createInputStream();
  7929. }
  7930. int64 FileInputSource::hashCode() const
  7931. {
  7932. int64 h = file.hashCode();
  7933. if (useFileTimeInHashGeneration)
  7934. h ^= file.getLastModificationTime().toMilliseconds();
  7935. return h;
  7936. }
  7937. END_JUCE_NAMESPACE
  7938. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7939. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7940. BEGIN_JUCE_NAMESPACE
  7941. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7942. const size_t sourceDataSize,
  7943. const bool keepInternalCopy)
  7944. : data (static_cast <const char*> (sourceData)),
  7945. dataSize (sourceDataSize),
  7946. position (0)
  7947. {
  7948. if (keepInternalCopy)
  7949. {
  7950. internalCopy.append (data, sourceDataSize);
  7951. data = static_cast <const char*> (internalCopy.getData());
  7952. }
  7953. }
  7954. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7955. const bool keepInternalCopy)
  7956. : data (static_cast <const char*> (sourceData.getData())),
  7957. dataSize (sourceData.getSize()),
  7958. position (0)
  7959. {
  7960. if (keepInternalCopy)
  7961. {
  7962. internalCopy = sourceData;
  7963. data = static_cast <const char*> (internalCopy.getData());
  7964. }
  7965. }
  7966. MemoryInputStream::~MemoryInputStream()
  7967. {
  7968. }
  7969. int64 MemoryInputStream::getTotalLength()
  7970. {
  7971. return dataSize;
  7972. }
  7973. int MemoryInputStream::read (void* const buffer, const int howMany)
  7974. {
  7975. jassert (howMany >= 0);
  7976. const int num = jmin (howMany, (int) (dataSize - position));
  7977. memcpy (buffer, data + position, num);
  7978. position += num;
  7979. return (int) num;
  7980. }
  7981. bool MemoryInputStream::isExhausted()
  7982. {
  7983. return (position >= dataSize);
  7984. }
  7985. bool MemoryInputStream::setPosition (const int64 pos)
  7986. {
  7987. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7988. return true;
  7989. }
  7990. int64 MemoryInputStream::getPosition()
  7991. {
  7992. return position;
  7993. }
  7994. #if JUCE_UNIT_TESTS
  7995. class MemoryStreamTests : public UnitTest
  7996. {
  7997. public:
  7998. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  7999. void runTest()
  8000. {
  8001. beginTest ("Basics");
  8002. int randomInt = Random::getSystemRandom().nextInt();
  8003. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8004. double randomDouble = Random::getSystemRandom().nextDouble();
  8005. String randomString;
  8006. for (int i = 50; --i >= 0;)
  8007. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8008. MemoryOutputStream mo;
  8009. mo.writeInt (randomInt);
  8010. mo.writeIntBigEndian (randomInt);
  8011. mo.writeCompressedInt (randomInt);
  8012. mo.writeString (randomString);
  8013. mo.writeInt64 (randomInt64);
  8014. mo.writeInt64BigEndian (randomInt64);
  8015. mo.writeDouble (randomDouble);
  8016. mo.writeDoubleBigEndian (randomDouble);
  8017. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8018. expect (mi.readInt() == randomInt);
  8019. expect (mi.readIntBigEndian() == randomInt);
  8020. expect (mi.readCompressedInt() == randomInt);
  8021. expect (mi.readString() == randomString);
  8022. expect (mi.readInt64() == randomInt64);
  8023. expect (mi.readInt64BigEndian() == randomInt64);
  8024. expect (mi.readDouble() == randomDouble);
  8025. expect (mi.readDoubleBigEndian() == randomDouble);
  8026. }
  8027. };
  8028. static MemoryStreamTests memoryInputStreamUnitTests;
  8029. #endif
  8030. END_JUCE_NAMESPACE
  8031. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8032. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8033. BEGIN_JUCE_NAMESPACE
  8034. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8035. : data (internalBlock),
  8036. position (0),
  8037. size (0)
  8038. {
  8039. internalBlock.setSize (initialSize, false);
  8040. }
  8041. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8042. const bool appendToExistingBlockContent)
  8043. : data (memoryBlockToWriteTo),
  8044. position (0),
  8045. size (0)
  8046. {
  8047. if (appendToExistingBlockContent)
  8048. position = size = memoryBlockToWriteTo.getSize();
  8049. }
  8050. MemoryOutputStream::~MemoryOutputStream()
  8051. {
  8052. flush();
  8053. }
  8054. void MemoryOutputStream::flush()
  8055. {
  8056. if (&data != &internalBlock)
  8057. data.setSize (size, false);
  8058. }
  8059. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8060. {
  8061. data.ensureSize (bytesToPreallocate + 1);
  8062. }
  8063. void MemoryOutputStream::reset() throw()
  8064. {
  8065. position = 0;
  8066. size = 0;
  8067. }
  8068. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8069. {
  8070. if (howMany > 0)
  8071. {
  8072. const size_t storageNeeded = position + howMany;
  8073. if (storageNeeded >= data.getSize())
  8074. data.ensureSize ((storageNeeded + jmin ((int) (storageNeeded / 2), 1024 * 1024) + 32) & ~31);
  8075. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8076. position += howMany;
  8077. size = jmax (size, position);
  8078. }
  8079. return true;
  8080. }
  8081. const void* MemoryOutputStream::getData() const throw()
  8082. {
  8083. void* const d = data.getData();
  8084. if (data.getSize() > size)
  8085. static_cast <char*> (d) [size] = 0;
  8086. return d;
  8087. }
  8088. bool MemoryOutputStream::setPosition (int64 newPosition)
  8089. {
  8090. if (newPosition <= (int64) size)
  8091. {
  8092. // ok to seek backwards
  8093. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8094. return true;
  8095. }
  8096. else
  8097. {
  8098. // trying to make it bigger isn't a good thing to do..
  8099. return false;
  8100. }
  8101. }
  8102. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8103. {
  8104. // before writing from an input, see if we can preallocate to make it more efficient..
  8105. int64 availableData = source.getTotalLength() - source.getPosition();
  8106. if (availableData > 0)
  8107. {
  8108. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8109. availableData = maxNumBytesToWrite;
  8110. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8111. }
  8112. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8113. }
  8114. const String MemoryOutputStream::toUTF8() const
  8115. {
  8116. return String (static_cast <const char*> (getData()), getDataSize());
  8117. }
  8118. const String MemoryOutputStream::toString() const
  8119. {
  8120. return String::createStringFromData (getData(), (int) getDataSize());
  8121. }
  8122. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8123. {
  8124. stream.write (streamToRead.getData(), (int) streamToRead.getDataSize());
  8125. return stream;
  8126. }
  8127. END_JUCE_NAMESPACE
  8128. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8129. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8130. BEGIN_JUCE_NAMESPACE
  8131. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8132. const int64 startPositionInSourceStream_,
  8133. const int64 lengthOfSourceStream_,
  8134. const bool deleteSourceWhenDestroyed)
  8135. : source (sourceStream),
  8136. startPositionInSourceStream (startPositionInSourceStream_),
  8137. lengthOfSourceStream (lengthOfSourceStream_)
  8138. {
  8139. if (deleteSourceWhenDestroyed)
  8140. sourceToDelete = source;
  8141. setPosition (0);
  8142. }
  8143. SubregionStream::~SubregionStream()
  8144. {
  8145. }
  8146. int64 SubregionStream::getTotalLength()
  8147. {
  8148. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8149. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8150. : srcLen;
  8151. }
  8152. int64 SubregionStream::getPosition()
  8153. {
  8154. return source->getPosition() - startPositionInSourceStream;
  8155. }
  8156. bool SubregionStream::setPosition (int64 newPosition)
  8157. {
  8158. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8159. }
  8160. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8161. {
  8162. if (lengthOfSourceStream < 0)
  8163. {
  8164. return source->read (destBuffer, maxBytesToRead);
  8165. }
  8166. else
  8167. {
  8168. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8169. if (maxBytesToRead <= 0)
  8170. return 0;
  8171. return source->read (destBuffer, maxBytesToRead);
  8172. }
  8173. }
  8174. bool SubregionStream::isExhausted()
  8175. {
  8176. if (lengthOfSourceStream >= 0)
  8177. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8178. else
  8179. return source->isExhausted();
  8180. }
  8181. END_JUCE_NAMESPACE
  8182. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8183. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8184. BEGIN_JUCE_NAMESPACE
  8185. PerformanceCounter::PerformanceCounter (const String& name_,
  8186. int runsPerPrintout,
  8187. const File& loggingFile)
  8188. : name (name_),
  8189. numRuns (0),
  8190. runsPerPrint (runsPerPrintout),
  8191. totalTime (0),
  8192. outputFile (loggingFile)
  8193. {
  8194. if (outputFile != File::nonexistent)
  8195. {
  8196. String s ("**** Counter for \"");
  8197. s << name_ << "\" started at: "
  8198. << Time::getCurrentTime().toString (true, true)
  8199. << newLine;
  8200. outputFile.appendText (s, false, false);
  8201. }
  8202. }
  8203. PerformanceCounter::~PerformanceCounter()
  8204. {
  8205. printStatistics();
  8206. }
  8207. void PerformanceCounter::start()
  8208. {
  8209. started = Time::getHighResolutionTicks();
  8210. }
  8211. void PerformanceCounter::stop()
  8212. {
  8213. const int64 now = Time::getHighResolutionTicks();
  8214. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8215. if (++numRuns == runsPerPrint)
  8216. printStatistics();
  8217. }
  8218. void PerformanceCounter::printStatistics()
  8219. {
  8220. if (numRuns > 0)
  8221. {
  8222. String s ("Performance count for \"");
  8223. s << name << "\" - average over " << numRuns << " run(s) = ";
  8224. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8225. if (micros > 10000)
  8226. s << (micros/1000) << " millisecs";
  8227. else
  8228. s << micros << " microsecs";
  8229. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8230. Logger::outputDebugString (s);
  8231. s << newLine;
  8232. if (outputFile != File::nonexistent)
  8233. outputFile.appendText (s, false, false);
  8234. numRuns = 0;
  8235. totalTime = 0;
  8236. }
  8237. }
  8238. END_JUCE_NAMESPACE
  8239. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8240. /*** Start of inlined file: juce_Uuid.cpp ***/
  8241. BEGIN_JUCE_NAMESPACE
  8242. Uuid::Uuid()
  8243. {
  8244. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8245. // to make it very very unlikely that two UUIDs will ever be the same..
  8246. static int64 macAddresses[2];
  8247. static bool hasCheckedMacAddresses = false;
  8248. if (! hasCheckedMacAddresses)
  8249. {
  8250. hasCheckedMacAddresses = true;
  8251. Array<MACAddress> result;
  8252. MACAddress::findAllAddresses (result);
  8253. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8254. macAddresses[i] = result[i].toInt64();
  8255. }
  8256. value.asInt64[0] = macAddresses[0];
  8257. value.asInt64[1] = macAddresses[1];
  8258. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8259. // whose seed will carry over between calls to this method.
  8260. Random r (macAddresses[0] ^ macAddresses[1]
  8261. ^ Random::getSystemRandom().nextInt64());
  8262. for (int i = 4; --i >= 0;)
  8263. {
  8264. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8265. value.asInt[i] ^= r.nextInt();
  8266. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8267. }
  8268. }
  8269. Uuid::~Uuid() throw()
  8270. {
  8271. }
  8272. Uuid::Uuid (const Uuid& other)
  8273. : value (other.value)
  8274. {
  8275. }
  8276. Uuid& Uuid::operator= (const Uuid& other)
  8277. {
  8278. value = other.value;
  8279. return *this;
  8280. }
  8281. bool Uuid::operator== (const Uuid& other) const
  8282. {
  8283. return value.asInt64[0] == other.value.asInt64[0]
  8284. && value.asInt64[1] == other.value.asInt64[1];
  8285. }
  8286. bool Uuid::operator!= (const Uuid& other) const
  8287. {
  8288. return ! operator== (other);
  8289. }
  8290. bool Uuid::isNull() const throw()
  8291. {
  8292. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8293. }
  8294. const String Uuid::toString() const
  8295. {
  8296. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8297. }
  8298. Uuid::Uuid (const String& uuidString)
  8299. {
  8300. operator= (uuidString);
  8301. }
  8302. Uuid& Uuid::operator= (const String& uuidString)
  8303. {
  8304. MemoryBlock mb;
  8305. mb.loadFromHexString (uuidString);
  8306. mb.ensureSize (sizeof (value.asBytes), true);
  8307. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8308. return *this;
  8309. }
  8310. Uuid::Uuid (const uint8* const rawData)
  8311. {
  8312. operator= (rawData);
  8313. }
  8314. Uuid& Uuid::operator= (const uint8* const rawData)
  8315. {
  8316. if (rawData != 0)
  8317. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8318. else
  8319. zeromem (value.asBytes, sizeof (value.asBytes));
  8320. return *this;
  8321. }
  8322. END_JUCE_NAMESPACE
  8323. /*** End of inlined file: juce_Uuid.cpp ***/
  8324. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8325. BEGIN_JUCE_NAMESPACE
  8326. class ZipFile::ZipEntryInfo
  8327. {
  8328. public:
  8329. ZipFile::ZipEntry entry;
  8330. int streamOffset;
  8331. int compressedSize;
  8332. bool compressed;
  8333. };
  8334. class ZipFile::ZipInputStream : public InputStream
  8335. {
  8336. public:
  8337. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8338. : file (file_),
  8339. zipEntryInfo (zei),
  8340. pos (0),
  8341. headerSize (0),
  8342. inputStream (0)
  8343. {
  8344. inputStream = file_.inputStream;
  8345. if (file_.inputSource != 0)
  8346. {
  8347. inputStream = streamToDelete = file.inputSource->createInputStream();
  8348. }
  8349. else
  8350. {
  8351. #if JUCE_DEBUG
  8352. file_.numOpenStreams++;
  8353. #endif
  8354. }
  8355. char buffer [30];
  8356. if (inputStream != 0
  8357. && inputStream->setPosition (zei.streamOffset)
  8358. && inputStream->read (buffer, 30) == 30
  8359. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8360. {
  8361. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8362. + ByteOrder::littleEndianShort (buffer + 28);
  8363. }
  8364. }
  8365. ~ZipInputStream()
  8366. {
  8367. #if JUCE_DEBUG
  8368. if (inputStream != 0 && inputStream == file.inputStream)
  8369. file.numOpenStreams--;
  8370. #endif
  8371. }
  8372. int64 getTotalLength()
  8373. {
  8374. return zipEntryInfo.compressedSize;
  8375. }
  8376. int read (void* buffer, int howMany)
  8377. {
  8378. if (headerSize <= 0)
  8379. return 0;
  8380. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8381. if (inputStream == 0)
  8382. return 0;
  8383. int num;
  8384. if (inputStream == file.inputStream)
  8385. {
  8386. const ScopedLock sl (file.lock);
  8387. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8388. num = inputStream->read (buffer, howMany);
  8389. }
  8390. else
  8391. {
  8392. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8393. num = inputStream->read (buffer, howMany);
  8394. }
  8395. pos += num;
  8396. return num;
  8397. }
  8398. bool isExhausted()
  8399. {
  8400. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8401. }
  8402. int64 getPosition()
  8403. {
  8404. return pos;
  8405. }
  8406. bool setPosition (int64 newPos)
  8407. {
  8408. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8409. return true;
  8410. }
  8411. private:
  8412. ZipFile& file;
  8413. ZipEntryInfo zipEntryInfo;
  8414. int64 pos;
  8415. int headerSize;
  8416. InputStream* inputStream;
  8417. ScopedPointer<InputStream> streamToDelete;
  8418. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8419. };
  8420. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8421. : inputStream (source_)
  8422. #if JUCE_DEBUG
  8423. , numOpenStreams (0)
  8424. #endif
  8425. {
  8426. if (deleteStreamWhenDestroyed)
  8427. streamToDelete = inputStream;
  8428. init();
  8429. }
  8430. ZipFile::ZipFile (const File& file)
  8431. : inputStream (0)
  8432. #if JUCE_DEBUG
  8433. , numOpenStreams (0)
  8434. #endif
  8435. {
  8436. inputSource = new FileInputSource (file);
  8437. init();
  8438. }
  8439. ZipFile::ZipFile (InputSource* const inputSource_)
  8440. : inputStream (0),
  8441. inputSource (inputSource_)
  8442. #if JUCE_DEBUG
  8443. , numOpenStreams (0)
  8444. #endif
  8445. {
  8446. init();
  8447. }
  8448. ZipFile::~ZipFile()
  8449. {
  8450. #if JUCE_DEBUG
  8451. entries.clear();
  8452. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8453. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8454. Streams can't be kept open after the file is deleted because they need to share the input
  8455. stream that the file uses to read itself.
  8456. */
  8457. jassert (numOpenStreams == 0);
  8458. #endif
  8459. }
  8460. int ZipFile::getNumEntries() const throw()
  8461. {
  8462. return entries.size();
  8463. }
  8464. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8465. {
  8466. ZipEntryInfo* const zei = entries [index];
  8467. return zei != 0 ? &(zei->entry) : 0;
  8468. }
  8469. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8470. {
  8471. for (int i = 0; i < entries.size(); ++i)
  8472. if (entries.getUnchecked (i)->entry.filename == fileName)
  8473. return i;
  8474. return -1;
  8475. }
  8476. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8477. {
  8478. return getEntry (getIndexOfFileName (fileName));
  8479. }
  8480. InputStream* ZipFile::createStreamForEntry (const int index)
  8481. {
  8482. ZipEntryInfo* const zei = entries[index];
  8483. InputStream* stream = 0;
  8484. if (zei != 0)
  8485. {
  8486. stream = new ZipInputStream (*this, *zei);
  8487. if (zei->compressed)
  8488. {
  8489. stream = new GZIPDecompressorInputStream (stream, true, true,
  8490. zei->entry.uncompressedSize);
  8491. // (much faster to unzip in big blocks using a buffer..)
  8492. stream = new BufferedInputStream (stream, 32768, true);
  8493. }
  8494. }
  8495. return stream;
  8496. }
  8497. class ZipFile::ZipFilenameComparator
  8498. {
  8499. public:
  8500. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8501. {
  8502. return first->entry.filename.compare (second->entry.filename);
  8503. }
  8504. };
  8505. void ZipFile::sortEntriesByFilename()
  8506. {
  8507. ZipFilenameComparator sorter;
  8508. entries.sort (sorter);
  8509. }
  8510. void ZipFile::init()
  8511. {
  8512. ScopedPointer <InputStream> toDelete;
  8513. InputStream* in = inputStream;
  8514. if (inputSource != 0)
  8515. {
  8516. in = inputSource->createInputStream();
  8517. toDelete = in;
  8518. }
  8519. if (in != 0)
  8520. {
  8521. int numEntries = 0;
  8522. int pos = findEndOfZipEntryTable (*in, numEntries);
  8523. if (pos >= 0 && pos < in->getTotalLength())
  8524. {
  8525. const int size = (int) (in->getTotalLength() - pos);
  8526. in->setPosition (pos);
  8527. MemoryBlock headerData;
  8528. if (in->readIntoMemoryBlock (headerData, size) == size)
  8529. {
  8530. pos = 0;
  8531. for (int i = 0; i < numEntries; ++i)
  8532. {
  8533. if (pos + 46 > size)
  8534. break;
  8535. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8536. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8537. if (pos + 46 + fileNameLen > size)
  8538. break;
  8539. ZipEntryInfo* const zei = new ZipEntryInfo();
  8540. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8541. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8542. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8543. const int year = 1980 + (date >> 9);
  8544. const int month = ((date >> 5) & 15) - 1;
  8545. const int day = date & 31;
  8546. const int hours = time >> 11;
  8547. const int minutes = (time >> 5) & 63;
  8548. const int seconds = (time & 31) << 1;
  8549. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8550. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8551. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8552. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8553. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8554. entries.add (zei);
  8555. pos += 46 + fileNameLen
  8556. + ByteOrder::littleEndianShort (buffer + 30)
  8557. + ByteOrder::littleEndianShort (buffer + 32);
  8558. }
  8559. }
  8560. }
  8561. }
  8562. }
  8563. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8564. {
  8565. BufferedInputStream in (input, 8192);
  8566. in.setPosition (in.getTotalLength());
  8567. int64 pos = in.getPosition();
  8568. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8569. char buffer [32];
  8570. zeromem (buffer, sizeof (buffer));
  8571. while (pos > lowestPos)
  8572. {
  8573. in.setPosition (pos - 22);
  8574. pos = in.getPosition();
  8575. memcpy (buffer + 22, buffer, 4);
  8576. if (in.read (buffer, 22) != 22)
  8577. return 0;
  8578. for (int i = 0; i < 22; ++i)
  8579. {
  8580. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8581. {
  8582. in.setPosition (pos + i);
  8583. in.read (buffer, 22);
  8584. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8585. return ByteOrder::littleEndianInt (buffer + 16);
  8586. }
  8587. }
  8588. }
  8589. return 0;
  8590. }
  8591. bool ZipFile::uncompressTo (const File& targetDirectory,
  8592. const bool shouldOverwriteFiles)
  8593. {
  8594. for (int i = 0; i < entries.size(); ++i)
  8595. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8596. return false;
  8597. return true;
  8598. }
  8599. bool ZipFile::uncompressEntry (const int index,
  8600. const File& targetDirectory,
  8601. bool shouldOverwriteFiles)
  8602. {
  8603. const ZipEntryInfo* zei = entries [index];
  8604. if (zei != 0)
  8605. {
  8606. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8607. if (zei->entry.filename.endsWithChar ('/'))
  8608. {
  8609. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8610. }
  8611. else
  8612. {
  8613. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8614. if (in != 0)
  8615. {
  8616. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8617. return false;
  8618. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8619. {
  8620. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8621. if (out != 0)
  8622. {
  8623. out->writeFromInputStream (*in, -1);
  8624. out = 0;
  8625. targetFile.setCreationTime (zei->entry.fileTime);
  8626. targetFile.setLastModificationTime (zei->entry.fileTime);
  8627. targetFile.setLastAccessTime (zei->entry.fileTime);
  8628. return true;
  8629. }
  8630. }
  8631. }
  8632. }
  8633. }
  8634. return false;
  8635. }
  8636. END_JUCE_NAMESPACE
  8637. /*** End of inlined file: juce_ZipFile.cpp ***/
  8638. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8639. #if JUCE_MSVC
  8640. #pragma warning (push)
  8641. #pragma warning (disable: 4514 4996)
  8642. #endif
  8643. #include <cwctype>
  8644. #include <cctype>
  8645. #include <ctime>
  8646. BEGIN_JUCE_NAMESPACE
  8647. int CharacterFunctions::length (const char* const s) throw()
  8648. {
  8649. return (int) strlen (s);
  8650. }
  8651. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8652. {
  8653. return (int) wcslen (s);
  8654. }
  8655. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8656. {
  8657. strncpy (dest, src, maxChars);
  8658. }
  8659. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8660. {
  8661. wcsncpy (dest, src, maxChars);
  8662. }
  8663. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8664. {
  8665. mbstowcs (dest, src, maxChars);
  8666. }
  8667. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8668. {
  8669. wcstombs (dest, src, maxChars);
  8670. }
  8671. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8672. {
  8673. return (int) wcstombs (0, src, 0);
  8674. }
  8675. void CharacterFunctions::append (char* dest, const char* src) throw()
  8676. {
  8677. strcat (dest, src);
  8678. }
  8679. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8680. {
  8681. wcscat (dest, src);
  8682. }
  8683. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8684. {
  8685. return strcmp (s1, s2);
  8686. }
  8687. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8688. {
  8689. jassert (s1 != 0 && s2 != 0);
  8690. return wcscmp (s1, s2);
  8691. }
  8692. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8693. {
  8694. jassert (s1 != 0 && s2 != 0);
  8695. return strncmp (s1, s2, maxChars);
  8696. }
  8697. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8698. {
  8699. jassert (s1 != 0 && s2 != 0);
  8700. return wcsncmp (s1, s2, maxChars);
  8701. }
  8702. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8703. {
  8704. jassert (s1 != 0 && s2 != 0);
  8705. for (;;)
  8706. {
  8707. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8708. if (diff != 0)
  8709. return diff;
  8710. else if (*s1 == 0)
  8711. break;
  8712. ++s1;
  8713. ++s2;
  8714. }
  8715. return 0;
  8716. }
  8717. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8718. {
  8719. return -compare (s2, s1);
  8720. }
  8721. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8722. {
  8723. jassert (s1 != 0 && s2 != 0);
  8724. #if JUCE_WINDOWS
  8725. return stricmp (s1, s2);
  8726. #else
  8727. return strcasecmp (s1, s2);
  8728. #endif
  8729. }
  8730. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8731. {
  8732. jassert (s1 != 0 && s2 != 0);
  8733. #if JUCE_WINDOWS
  8734. return _wcsicmp (s1, s2);
  8735. #else
  8736. for (;;)
  8737. {
  8738. if (*s1 != *s2)
  8739. {
  8740. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8741. if (diff != 0)
  8742. return diff < 0 ? -1 : 1;
  8743. }
  8744. else if (*s1 == 0)
  8745. break;
  8746. ++s1;
  8747. ++s2;
  8748. }
  8749. return 0;
  8750. #endif
  8751. }
  8752. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8753. {
  8754. jassert (s1 != 0 && s2 != 0);
  8755. for (;;)
  8756. {
  8757. if (*s1 != *s2)
  8758. {
  8759. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8760. if (diff != 0)
  8761. return diff < 0 ? -1 : 1;
  8762. }
  8763. else if (*s1 == 0)
  8764. break;
  8765. ++s1;
  8766. ++s2;
  8767. }
  8768. return 0;
  8769. }
  8770. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8771. {
  8772. jassert (s1 != 0 && s2 != 0);
  8773. #if JUCE_WINDOWS
  8774. return strnicmp (s1, s2, maxChars);
  8775. #else
  8776. return strncasecmp (s1, s2, maxChars);
  8777. #endif
  8778. }
  8779. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8780. {
  8781. jassert (s1 != 0 && s2 != 0);
  8782. #if JUCE_WINDOWS
  8783. return _wcsnicmp (s1, s2, maxChars);
  8784. #else
  8785. while (--maxChars >= 0)
  8786. {
  8787. if (*s1 != *s2)
  8788. {
  8789. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8790. if (diff != 0)
  8791. return diff < 0 ? -1 : 1;
  8792. }
  8793. else if (*s1 == 0)
  8794. break;
  8795. ++s1;
  8796. ++s2;
  8797. }
  8798. return 0;
  8799. #endif
  8800. }
  8801. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8802. {
  8803. return strstr (haystack, needle);
  8804. }
  8805. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8806. {
  8807. return wcsstr (haystack, needle);
  8808. }
  8809. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8810. {
  8811. if (haystack != 0)
  8812. {
  8813. int i = 0;
  8814. if (ignoreCase)
  8815. {
  8816. const char n1 = toLowerCase (needle);
  8817. const char n2 = toUpperCase (needle);
  8818. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8819. {
  8820. while (haystack[i] != 0)
  8821. {
  8822. if (haystack[i] == n1 || haystack[i] == n2)
  8823. return i;
  8824. ++i;
  8825. }
  8826. return -1;
  8827. }
  8828. jassert (n1 == needle);
  8829. }
  8830. while (haystack[i] != 0)
  8831. {
  8832. if (haystack[i] == needle)
  8833. return i;
  8834. ++i;
  8835. }
  8836. }
  8837. return -1;
  8838. }
  8839. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8840. {
  8841. if (haystack != 0)
  8842. {
  8843. int i = 0;
  8844. if (ignoreCase)
  8845. {
  8846. const juce_wchar n1 = toLowerCase (needle);
  8847. const juce_wchar n2 = toUpperCase (needle);
  8848. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8849. {
  8850. while (haystack[i] != 0)
  8851. {
  8852. if (haystack[i] == n1 || haystack[i] == n2)
  8853. return i;
  8854. ++i;
  8855. }
  8856. return -1;
  8857. }
  8858. jassert (n1 == needle);
  8859. }
  8860. while (haystack[i] != 0)
  8861. {
  8862. if (haystack[i] == needle)
  8863. return i;
  8864. ++i;
  8865. }
  8866. }
  8867. return -1;
  8868. }
  8869. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8870. {
  8871. jassert (haystack != 0);
  8872. int i = 0;
  8873. while (haystack[i] != 0)
  8874. {
  8875. if (haystack[i] == needle)
  8876. return i;
  8877. ++i;
  8878. }
  8879. return -1;
  8880. }
  8881. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8882. {
  8883. jassert (haystack != 0);
  8884. int i = 0;
  8885. while (haystack[i] != 0)
  8886. {
  8887. if (haystack[i] == needle)
  8888. return i;
  8889. ++i;
  8890. }
  8891. return -1;
  8892. }
  8893. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8894. {
  8895. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8896. }
  8897. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8898. {
  8899. if (allowedChars == 0)
  8900. return 0;
  8901. int i = 0;
  8902. for (;;)
  8903. {
  8904. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8905. break;
  8906. ++i;
  8907. }
  8908. return i;
  8909. }
  8910. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8911. {
  8912. return (int) strftime (dest, maxChars, format, tm);
  8913. }
  8914. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8915. {
  8916. return (int) wcsftime (dest, maxChars, format, tm);
  8917. }
  8918. int CharacterFunctions::getIntValue (const char* const s) throw()
  8919. {
  8920. return atoi (s);
  8921. }
  8922. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8923. {
  8924. #if JUCE_WINDOWS
  8925. return _wtoi (s);
  8926. #else
  8927. int v = 0;
  8928. while (isWhitespace (*s))
  8929. ++s;
  8930. const bool isNeg = *s == '-';
  8931. if (isNeg)
  8932. ++s;
  8933. for (;;)
  8934. {
  8935. const wchar_t c = *s++;
  8936. if (c >= '0' && c <= '9')
  8937. v = v * 10 + (int) (c - '0');
  8938. else
  8939. break;
  8940. }
  8941. return isNeg ? -v : v;
  8942. #endif
  8943. }
  8944. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8945. {
  8946. #if JUCE_LINUX
  8947. return atoll (s);
  8948. #elif JUCE_WINDOWS
  8949. return _atoi64 (s);
  8950. #else
  8951. int64 v = 0;
  8952. while (isWhitespace (*s))
  8953. ++s;
  8954. const bool isNeg = *s == '-';
  8955. if (isNeg)
  8956. ++s;
  8957. for (;;)
  8958. {
  8959. const char c = *s++;
  8960. if (c >= '0' && c <= '9')
  8961. v = v * 10 + (int64) (c - '0');
  8962. else
  8963. break;
  8964. }
  8965. return isNeg ? -v : v;
  8966. #endif
  8967. }
  8968. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8969. {
  8970. #if JUCE_WINDOWS
  8971. return _wtoi64 (s);
  8972. #else
  8973. int64 v = 0;
  8974. while (isWhitespace (*s))
  8975. ++s;
  8976. const bool isNeg = *s == '-';
  8977. if (isNeg)
  8978. ++s;
  8979. for (;;)
  8980. {
  8981. const juce_wchar c = *s++;
  8982. if (c >= '0' && c <= '9')
  8983. v = v * 10 + (int64) (c - '0');
  8984. else
  8985. break;
  8986. }
  8987. return isNeg ? -v : v;
  8988. #endif
  8989. }
  8990. namespace
  8991. {
  8992. double juce_mulexp10 (const double value, int exponent) throw()
  8993. {
  8994. if (exponent == 0)
  8995. return value;
  8996. if (value == 0)
  8997. return 0;
  8998. const bool negative = (exponent < 0);
  8999. if (negative)
  9000. exponent = -exponent;
  9001. double result = 1.0, power = 10.0;
  9002. for (int bit = 1; exponent != 0; bit <<= 1)
  9003. {
  9004. if ((exponent & bit) != 0)
  9005. {
  9006. exponent ^= bit;
  9007. result *= power;
  9008. if (exponent == 0)
  9009. break;
  9010. }
  9011. power *= power;
  9012. }
  9013. return negative ? (value / result) : (value * result);
  9014. }
  9015. template <class CharType>
  9016. double juce_atof (const CharType* const original) throw()
  9017. {
  9018. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9019. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9020. int exponent = 0, decPointIndex = 0, digit = 0;
  9021. int lastDigit = 0, numSignificantDigits = 0;
  9022. bool isNegative = false, digitsFound = false;
  9023. const int maxSignificantDigits = 15 + 2;
  9024. const CharType* s = original;
  9025. while (CharacterFunctions::isWhitespace (*s))
  9026. ++s;
  9027. switch (*s)
  9028. {
  9029. case '-': isNegative = true; // fall-through..
  9030. case '+': ++s;
  9031. }
  9032. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9033. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9034. for (;;)
  9035. {
  9036. if (CharacterFunctions::isDigit (*s))
  9037. {
  9038. lastDigit = digit;
  9039. digit = *s++ - '0';
  9040. digitsFound = true;
  9041. if (decPointIndex != 0)
  9042. exponentAdjustment[1]++;
  9043. if (numSignificantDigits == 0 && digit == 0)
  9044. continue;
  9045. if (++numSignificantDigits > maxSignificantDigits)
  9046. {
  9047. if (digit > 5)
  9048. ++accumulator [decPointIndex];
  9049. else if (digit == 5 && (lastDigit & 1) != 0)
  9050. ++accumulator [decPointIndex];
  9051. if (decPointIndex > 0)
  9052. exponentAdjustment[1]--;
  9053. else
  9054. exponentAdjustment[0]++;
  9055. while (CharacterFunctions::isDigit (*s))
  9056. {
  9057. ++s;
  9058. if (decPointIndex == 0)
  9059. exponentAdjustment[0]++;
  9060. }
  9061. }
  9062. else
  9063. {
  9064. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9065. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9066. {
  9067. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9068. + accumulator [decPointIndex];
  9069. accumulator [decPointIndex] = 0;
  9070. exponentAccumulator [decPointIndex] = 0;
  9071. }
  9072. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9073. exponentAccumulator [decPointIndex]++;
  9074. }
  9075. }
  9076. else if (decPointIndex == 0 && *s == '.')
  9077. {
  9078. ++s;
  9079. decPointIndex = 1;
  9080. if (numSignificantDigits > maxSignificantDigits)
  9081. {
  9082. while (CharacterFunctions::isDigit (*s))
  9083. ++s;
  9084. break;
  9085. }
  9086. }
  9087. else
  9088. {
  9089. break;
  9090. }
  9091. }
  9092. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9093. if (decPointIndex != 0)
  9094. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9095. if ((*s == 'e' || *s == 'E') && digitsFound)
  9096. {
  9097. bool negativeExponent = false;
  9098. switch (*++s)
  9099. {
  9100. case '-': negativeExponent = true; // fall-through..
  9101. case '+': ++s;
  9102. }
  9103. while (CharacterFunctions::isDigit (*s))
  9104. exponent = (exponent * 10) + (*s++ - '0');
  9105. if (negativeExponent)
  9106. exponent = -exponent;
  9107. }
  9108. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9109. if (decPointIndex != 0)
  9110. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9111. return isNegative ? -r : r;
  9112. }
  9113. }
  9114. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9115. {
  9116. return juce_atof <char> (s);
  9117. }
  9118. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9119. {
  9120. return juce_atof <juce_wchar> (s);
  9121. }
  9122. char CharacterFunctions::toUpperCase (const char character) throw()
  9123. {
  9124. return (char) toupper (character);
  9125. }
  9126. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9127. {
  9128. return towupper (character);
  9129. }
  9130. void CharacterFunctions::toUpperCase (char* s) throw()
  9131. {
  9132. #if JUCE_WINDOWS
  9133. strupr (s);
  9134. #else
  9135. while (*s != 0)
  9136. {
  9137. *s = toUpperCase (*s);
  9138. ++s;
  9139. }
  9140. #endif
  9141. }
  9142. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9143. {
  9144. #if JUCE_WINDOWS
  9145. _wcsupr (s);
  9146. #else
  9147. while (*s != 0)
  9148. {
  9149. *s = toUpperCase (*s);
  9150. ++s;
  9151. }
  9152. #endif
  9153. }
  9154. bool CharacterFunctions::isUpperCase (const char character) throw()
  9155. {
  9156. return isupper (character) != 0;
  9157. }
  9158. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9159. {
  9160. #if JUCE_WINDOWS
  9161. return iswupper (character) != 0;
  9162. #else
  9163. return toLowerCase (character) != character;
  9164. #endif
  9165. }
  9166. char CharacterFunctions::toLowerCase (const char character) throw()
  9167. {
  9168. return (char) tolower (character);
  9169. }
  9170. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9171. {
  9172. return towlower (character);
  9173. }
  9174. void CharacterFunctions::toLowerCase (char* s) throw()
  9175. {
  9176. #if JUCE_WINDOWS
  9177. strlwr (s);
  9178. #else
  9179. while (*s != 0)
  9180. {
  9181. *s = toLowerCase (*s);
  9182. ++s;
  9183. }
  9184. #endif
  9185. }
  9186. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9187. {
  9188. #if JUCE_WINDOWS
  9189. _wcslwr (s);
  9190. #else
  9191. while (*s != 0)
  9192. {
  9193. *s = toLowerCase (*s);
  9194. ++s;
  9195. }
  9196. #endif
  9197. }
  9198. bool CharacterFunctions::isLowerCase (const char character) throw()
  9199. {
  9200. return islower (character) != 0;
  9201. }
  9202. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9203. {
  9204. #if JUCE_WINDOWS
  9205. return iswlower (character) != 0;
  9206. #else
  9207. return toUpperCase (character) != character;
  9208. #endif
  9209. }
  9210. bool CharacterFunctions::isWhitespace (const char character) throw()
  9211. {
  9212. return character == ' ' || (character <= 13 && character >= 9);
  9213. }
  9214. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9215. {
  9216. return iswspace (character) != 0;
  9217. }
  9218. bool CharacterFunctions::isDigit (const char character) throw()
  9219. {
  9220. return (character >= '0' && character <= '9');
  9221. }
  9222. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9223. {
  9224. return iswdigit (character) != 0;
  9225. }
  9226. bool CharacterFunctions::isLetter (const char character) throw()
  9227. {
  9228. return (character >= 'a' && character <= 'z')
  9229. || (character >= 'A' && character <= 'Z');
  9230. }
  9231. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9232. {
  9233. return iswalpha (character) != 0;
  9234. }
  9235. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9236. {
  9237. return (character >= 'a' && character <= 'z')
  9238. || (character >= 'A' && character <= 'Z')
  9239. || (character >= '0' && character <= '9');
  9240. }
  9241. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9242. {
  9243. return iswalnum (character) != 0;
  9244. }
  9245. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9246. {
  9247. unsigned int d = digit - '0';
  9248. if (d < (unsigned int) 10)
  9249. return (int) d;
  9250. d += (unsigned int) ('0' - 'a');
  9251. if (d < (unsigned int) 6)
  9252. return (int) d + 10;
  9253. d += (unsigned int) ('a' - 'A');
  9254. if (d < (unsigned int) 6)
  9255. return (int) d + 10;
  9256. return -1;
  9257. }
  9258. #if JUCE_MSVC
  9259. #pragma warning (pop)
  9260. #endif
  9261. END_JUCE_NAMESPACE
  9262. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9263. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9264. BEGIN_JUCE_NAMESPACE
  9265. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9266. {
  9267. loadFromText (fileContents);
  9268. }
  9269. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9270. {
  9271. loadFromText (fileToLoad.loadFileAsString());
  9272. }
  9273. LocalisedStrings::~LocalisedStrings()
  9274. {
  9275. }
  9276. const String LocalisedStrings::translate (const String& text) const
  9277. {
  9278. return translations.getValue (text, text);
  9279. }
  9280. namespace
  9281. {
  9282. CriticalSection currentMappingsLock;
  9283. LocalisedStrings* currentMappings = 0;
  9284. int findCloseQuote (const String& text, int startPos)
  9285. {
  9286. juce_wchar lastChar = 0;
  9287. for (;;)
  9288. {
  9289. const juce_wchar c = text [startPos];
  9290. if (c == 0 || (c == '"' && lastChar != '\\'))
  9291. break;
  9292. lastChar = c;
  9293. ++startPos;
  9294. }
  9295. return startPos;
  9296. }
  9297. const String unescapeString (const String& s)
  9298. {
  9299. return s.replace ("\\\"", "\"")
  9300. .replace ("\\\'", "\'")
  9301. .replace ("\\t", "\t")
  9302. .replace ("\\r", "\r")
  9303. .replace ("\\n", "\n");
  9304. }
  9305. }
  9306. void LocalisedStrings::loadFromText (const String& fileContents)
  9307. {
  9308. StringArray lines;
  9309. lines.addLines (fileContents);
  9310. for (int i = 0; i < lines.size(); ++i)
  9311. {
  9312. String line (lines[i].trim());
  9313. if (line.startsWithChar ('"'))
  9314. {
  9315. int closeQuote = findCloseQuote (line, 1);
  9316. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9317. if (originalText.isNotEmpty())
  9318. {
  9319. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9320. closeQuote = findCloseQuote (line, openingQuote + 1);
  9321. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9322. if (newText.isNotEmpty())
  9323. translations.set (originalText, newText);
  9324. }
  9325. }
  9326. else if (line.startsWithIgnoreCase ("language:"))
  9327. {
  9328. languageName = line.substring (9).trim();
  9329. }
  9330. else if (line.startsWithIgnoreCase ("countries:"))
  9331. {
  9332. countryCodes.addTokens (line.substring (10).trim(), true);
  9333. countryCodes.trim();
  9334. countryCodes.removeEmptyStrings();
  9335. }
  9336. }
  9337. }
  9338. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9339. {
  9340. translations.setIgnoresCase (shouldIgnoreCase);
  9341. }
  9342. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9343. {
  9344. const ScopedLock sl (currentMappingsLock);
  9345. delete currentMappings;
  9346. currentMappings = newTranslations;
  9347. }
  9348. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9349. {
  9350. return currentMappings;
  9351. }
  9352. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9353. {
  9354. const ScopedLock sl (currentMappingsLock);
  9355. if (currentMappings != 0)
  9356. return currentMappings->translate (text);
  9357. return text;
  9358. }
  9359. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9360. {
  9361. return translateWithCurrentMappings (String (text));
  9362. }
  9363. END_JUCE_NAMESPACE
  9364. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9365. /*** Start of inlined file: juce_String.cpp ***/
  9366. #if JUCE_MSVC
  9367. #pragma warning (push)
  9368. #pragma warning (disable: 4514)
  9369. #endif
  9370. #include <locale>
  9371. BEGIN_JUCE_NAMESPACE
  9372. #if JUCE_MSVC
  9373. #pragma warning (pop)
  9374. #endif
  9375. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9376. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9377. #endif
  9378. NewLine newLine;
  9379. class StringHolder
  9380. {
  9381. public:
  9382. StringHolder()
  9383. : refCount (0x3fffffff), allocatedNumChars (0)
  9384. {
  9385. text[0] = 0;
  9386. }
  9387. static juce_wchar* createUninitialised (const size_t numChars)
  9388. {
  9389. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9390. s->refCount.value = 0;
  9391. s->allocatedNumChars = numChars;
  9392. return &(s->text[0]);
  9393. }
  9394. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9395. {
  9396. juce_wchar* const dest = createUninitialised (numChars);
  9397. copyChars (dest, src, numChars);
  9398. return dest;
  9399. }
  9400. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9401. {
  9402. juce_wchar* const dest = createUninitialised (numChars);
  9403. CharacterFunctions::copy (dest, src, (int) numChars);
  9404. dest [numChars] = 0;
  9405. return dest;
  9406. }
  9407. static inline juce_wchar* getEmpty() throw()
  9408. {
  9409. return &(empty.text[0]);
  9410. }
  9411. static void retain (juce_wchar* const text) throw()
  9412. {
  9413. ++(bufferFromText (text)->refCount);
  9414. }
  9415. static inline void release (StringHolder* const b) throw()
  9416. {
  9417. if (--(b->refCount) == -1 && b != &empty)
  9418. delete[] reinterpret_cast <char*> (b);
  9419. }
  9420. static void release (juce_wchar* const text) throw()
  9421. {
  9422. release (bufferFromText (text));
  9423. }
  9424. static juce_wchar* makeUnique (juce_wchar* const text)
  9425. {
  9426. StringHolder* const b = bufferFromText (text);
  9427. if (b->refCount.get() <= 0)
  9428. return text;
  9429. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9430. release (b);
  9431. return newText;
  9432. }
  9433. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9434. {
  9435. StringHolder* const b = bufferFromText (text);
  9436. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9437. return text;
  9438. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9439. copyChars (newText, text, b->allocatedNumChars);
  9440. release (b);
  9441. return newText;
  9442. }
  9443. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9444. {
  9445. return bufferFromText (text)->allocatedNumChars;
  9446. }
  9447. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9448. {
  9449. jassert (src != 0 && dest != 0);
  9450. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9451. dest [numChars] = 0;
  9452. }
  9453. Atomic<int> refCount;
  9454. size_t allocatedNumChars;
  9455. juce_wchar text[1];
  9456. static StringHolder empty;
  9457. private:
  9458. static inline StringHolder* bufferFromText (void* const text) throw()
  9459. {
  9460. // (Can't use offsetof() here because of warnings about this not being a POD)
  9461. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9462. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9463. }
  9464. };
  9465. StringHolder StringHolder::empty;
  9466. const String String::empty;
  9467. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9468. {
  9469. jassert (t[numChars] == 0); // must have a null terminator
  9470. text = StringHolder::createCopy (t, numChars);
  9471. }
  9472. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9473. {
  9474. if (numExtraChars > 0)
  9475. {
  9476. const int oldLen = length();
  9477. const int newTotalLen = oldLen + numExtraChars;
  9478. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9479. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9480. }
  9481. }
  9482. void String::preallocateStorage (const size_t numChars)
  9483. {
  9484. text = StringHolder::makeUniqueWithSize (text, numChars);
  9485. }
  9486. String::String() throw()
  9487. : text (StringHolder::getEmpty())
  9488. {
  9489. }
  9490. String::~String() throw()
  9491. {
  9492. StringHolder::release (text);
  9493. }
  9494. String::String (const String& other) throw()
  9495. : text (other.text)
  9496. {
  9497. StringHolder::retain (text);
  9498. }
  9499. void String::swapWith (String& other) throw()
  9500. {
  9501. swapVariables (text, other.text);
  9502. }
  9503. String& String::operator= (const String& other) throw()
  9504. {
  9505. juce_wchar* const newText = other.text;
  9506. StringHolder::retain (newText);
  9507. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>&> (text).exchange (newText));
  9508. return *this;
  9509. }
  9510. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9511. String::String (const Preallocation& preallocationSize)
  9512. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9513. {
  9514. }
  9515. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9516. {
  9517. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9518. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9519. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9520. }
  9521. String::String (const char* const t)
  9522. {
  9523. if (t != 0 && *t != 0)
  9524. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9525. else
  9526. text = StringHolder::getEmpty();
  9527. }
  9528. String::String (const juce_wchar* const t)
  9529. {
  9530. if (t != 0 && *t != 0)
  9531. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9532. else
  9533. text = StringHolder::getEmpty();
  9534. }
  9535. String::String (const char* const t, const size_t maxChars)
  9536. {
  9537. int i;
  9538. for (i = 0; (size_t) i < maxChars; ++i)
  9539. if (t[i] == 0)
  9540. break;
  9541. if (i > 0)
  9542. text = StringHolder::createCopy (t, i);
  9543. else
  9544. text = StringHolder::getEmpty();
  9545. }
  9546. String::String (const juce_wchar* const t, const size_t maxChars)
  9547. {
  9548. int i;
  9549. for (i = 0; (size_t) i < maxChars; ++i)
  9550. if (t[i] == 0)
  9551. break;
  9552. if (i > 0)
  9553. text = StringHolder::createCopy (t, i);
  9554. else
  9555. text = StringHolder::getEmpty();
  9556. }
  9557. const String String::charToString (const juce_wchar character)
  9558. {
  9559. String result (Preallocation (1));
  9560. result.text[0] = character;
  9561. result.text[1] = 0;
  9562. return result;
  9563. }
  9564. namespace NumberToStringConverters
  9565. {
  9566. // pass in a pointer to the END of a buffer..
  9567. juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9568. {
  9569. *--t = 0;
  9570. int64 v = (n >= 0) ? n : -n;
  9571. do
  9572. {
  9573. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9574. v /= 10;
  9575. } while (v > 0);
  9576. if (n < 0)
  9577. *--t = '-';
  9578. return t;
  9579. }
  9580. juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9581. {
  9582. *--t = 0;
  9583. do
  9584. {
  9585. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9586. v /= 10;
  9587. } while (v > 0);
  9588. return t;
  9589. }
  9590. juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9591. {
  9592. if (n == (int) 0x80000000) // (would cause an overflow)
  9593. return int64ToString (t, n);
  9594. *--t = 0;
  9595. int v = abs (n);
  9596. do
  9597. {
  9598. *--t = (juce_wchar) ('0' + (v % 10));
  9599. v /= 10;
  9600. } while (v > 0);
  9601. if (n < 0)
  9602. *--t = '-';
  9603. return t;
  9604. }
  9605. juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9606. {
  9607. *--t = 0;
  9608. do
  9609. {
  9610. *--t = (juce_wchar) ('0' + (v % 10));
  9611. v /= 10;
  9612. } while (v > 0);
  9613. return t;
  9614. }
  9615. juce_wchar getDecimalPoint()
  9616. {
  9617. #if JUCE_VC7_OR_EARLIER
  9618. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9619. #else
  9620. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9621. #endif
  9622. return dp;
  9623. }
  9624. juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9625. {
  9626. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9627. {
  9628. juce_wchar* const end = buffer + numChars;
  9629. juce_wchar* t = end;
  9630. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9631. *--t = (juce_wchar) 0;
  9632. while (numDecPlaces >= 0 || v > 0)
  9633. {
  9634. if (numDecPlaces == 0)
  9635. *--t = getDecimalPoint();
  9636. *--t = (juce_wchar) ('0' + (v % 10));
  9637. v /= 10;
  9638. --numDecPlaces;
  9639. }
  9640. if (n < 0)
  9641. *--t = '-';
  9642. len = end - t - 1;
  9643. return t;
  9644. }
  9645. else
  9646. {
  9647. #if JUCE_WINDOWS
  9648. #if JUCE_VC7_OR_EARLIER || JUCE_MINGW
  9649. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9650. #else
  9651. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9652. #endif
  9653. #else
  9654. len = swprintf (buffer, numChars, L"%.9g", n);
  9655. #endif
  9656. return buffer;
  9657. }
  9658. }
  9659. }
  9660. String::String (const int number)
  9661. {
  9662. juce_wchar buffer [16];
  9663. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9664. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9665. createInternal (start, end - start - 1);
  9666. }
  9667. String::String (const unsigned int number)
  9668. {
  9669. juce_wchar buffer [16];
  9670. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9671. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9672. createInternal (start, end - start - 1);
  9673. }
  9674. String::String (const short number)
  9675. {
  9676. juce_wchar buffer [16];
  9677. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9678. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9679. createInternal (start, end - start - 1);
  9680. }
  9681. String::String (const unsigned short number)
  9682. {
  9683. juce_wchar buffer [16];
  9684. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9685. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9686. createInternal (start, end - start - 1);
  9687. }
  9688. String::String (const int64 number)
  9689. {
  9690. juce_wchar buffer [32];
  9691. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9692. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9693. createInternal (start, end - start - 1);
  9694. }
  9695. String::String (const uint64 number)
  9696. {
  9697. juce_wchar buffer [32];
  9698. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9699. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9700. createInternal (start, end - start - 1);
  9701. }
  9702. String::String (const float number, const int numberOfDecimalPlaces)
  9703. {
  9704. juce_wchar buffer [48];
  9705. size_t len;
  9706. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9707. createInternal (start, len);
  9708. }
  9709. String::String (const double number, const int numberOfDecimalPlaces)
  9710. {
  9711. juce_wchar buffer [48];
  9712. size_t len;
  9713. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9714. createInternal (start, len);
  9715. }
  9716. int String::length() const throw()
  9717. {
  9718. return CharacterFunctions::length (text);
  9719. }
  9720. int String::hashCode() const throw()
  9721. {
  9722. const juce_wchar* t = text;
  9723. int result = 0;
  9724. while (*t != (juce_wchar) 0)
  9725. result = 31 * result + *t++;
  9726. return result;
  9727. }
  9728. int64 String::hashCode64() const throw()
  9729. {
  9730. const juce_wchar* t = text;
  9731. int64 result = 0;
  9732. while (*t != (juce_wchar) 0)
  9733. result = 101 * result + *t++;
  9734. return result;
  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 char* string2) throw()
  9741. {
  9742. return string1.compare (string2) == 0;
  9743. }
  9744. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* 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. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9753. {
  9754. return string1.compare (string2) != 0;
  9755. }
  9756. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9757. {
  9758. return string1.compare (string2) != 0;
  9759. }
  9760. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9761. {
  9762. return string1.compare (string2) > 0;
  9763. }
  9764. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9765. {
  9766. return string1.compare (string2) < 0;
  9767. }
  9768. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9769. {
  9770. return string1.compare (string2) >= 0;
  9771. }
  9772. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9773. {
  9774. return string1.compare (string2) <= 0;
  9775. }
  9776. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9777. {
  9778. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9779. : isEmpty();
  9780. }
  9781. bool String::equalsIgnoreCase (const char* t) const throw()
  9782. {
  9783. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9784. : isEmpty();
  9785. }
  9786. bool String::equalsIgnoreCase (const String& other) const throw()
  9787. {
  9788. return text == other.text
  9789. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9790. }
  9791. int String::compare (const String& other) const throw()
  9792. {
  9793. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9794. }
  9795. int String::compare (const char* other) const throw()
  9796. {
  9797. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9798. }
  9799. int String::compare (const juce_wchar* other) const throw()
  9800. {
  9801. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9802. }
  9803. int String::compareIgnoreCase (const String& other) const throw()
  9804. {
  9805. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9806. }
  9807. int String::compareLexicographically (const String& other) const throw()
  9808. {
  9809. const juce_wchar* s1 = text;
  9810. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9811. ++s1;
  9812. const juce_wchar* s2 = other.text;
  9813. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9814. ++s2;
  9815. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9816. }
  9817. String& String::operator+= (const juce_wchar* const t)
  9818. {
  9819. if (t != 0)
  9820. appendInternal (t, CharacterFunctions::length (t));
  9821. return *this;
  9822. }
  9823. String& String::operator+= (const String& other)
  9824. {
  9825. if (isEmpty())
  9826. operator= (other);
  9827. else
  9828. appendInternal (other.text, other.length());
  9829. return *this;
  9830. }
  9831. String& String::operator+= (const char ch)
  9832. {
  9833. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9834. return operator+= (static_cast <const juce_wchar*> (asString));
  9835. }
  9836. String& String::operator+= (const juce_wchar ch)
  9837. {
  9838. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9839. return operator+= (static_cast <const juce_wchar*> (asString));
  9840. }
  9841. String& String::operator+= (const int number)
  9842. {
  9843. juce_wchar buffer [16];
  9844. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9845. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9846. appendInternal (start, (int) (end - start));
  9847. return *this;
  9848. }
  9849. String& String::operator+= (const unsigned int number)
  9850. {
  9851. juce_wchar buffer [16];
  9852. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9853. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9854. appendInternal (start, (int) (end - start));
  9855. return *this;
  9856. }
  9857. void String::append (const juce_wchar* const other, const int howMany)
  9858. {
  9859. if (howMany > 0)
  9860. {
  9861. int i;
  9862. for (i = 0; i < howMany; ++i)
  9863. if (other[i] == 0)
  9864. break;
  9865. appendInternal (other, i);
  9866. }
  9867. }
  9868. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9869. {
  9870. String s (string1);
  9871. return s += string2;
  9872. }
  9873. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9874. {
  9875. String s (string1);
  9876. return s += string2;
  9877. }
  9878. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9879. {
  9880. return String::charToString (string1) + string2;
  9881. }
  9882. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9883. {
  9884. return String::charToString (string1) + string2;
  9885. }
  9886. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9887. {
  9888. return string1 += string2;
  9889. }
  9890. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9891. {
  9892. return string1 += string2;
  9893. }
  9894. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9895. {
  9896. return string1 += string2;
  9897. }
  9898. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9899. {
  9900. return string1 += string2;
  9901. }
  9902. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9903. {
  9904. return string1 += string2;
  9905. }
  9906. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9907. {
  9908. return string1 += characterToAppend;
  9909. }
  9910. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9911. {
  9912. return string1 += characterToAppend;
  9913. }
  9914. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9915. {
  9916. return string1 += string2;
  9917. }
  9918. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9919. {
  9920. return string1 += string2;
  9921. }
  9922. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9923. {
  9924. return string1 += string2;
  9925. }
  9926. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9927. {
  9928. return string1 += (int) number;
  9929. }
  9930. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9931. {
  9932. return string1 += number;
  9933. }
  9934. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  9935. {
  9936. return string1 += number;
  9937. }
  9938. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9939. {
  9940. return string1 += (int) number;
  9941. }
  9942. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  9943. {
  9944. return string1 += (unsigned int) number;
  9945. }
  9946. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9947. {
  9948. return string1 += String (number);
  9949. }
  9950. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9951. {
  9952. return string1 += String (number);
  9953. }
  9954. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9955. {
  9956. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9957. // if lots of large, persistent strings were to be written to streams).
  9958. const int numBytes = text.getNumBytesAsUTF8();
  9959. HeapBlock<char> temp (numBytes + 1);
  9960. text.copyToUTF8 (temp, numBytes + 1);
  9961. stream.write (temp, numBytes);
  9962. return stream;
  9963. }
  9964. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  9965. {
  9966. return string1 += NewLine::getDefault();
  9967. }
  9968. int String::indexOfChar (const juce_wchar character) const throw()
  9969. {
  9970. const juce_wchar* t = text;
  9971. for (;;)
  9972. {
  9973. if (*t == character)
  9974. return (int) (t - text);
  9975. if (*t++ == 0)
  9976. return -1;
  9977. }
  9978. }
  9979. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9980. {
  9981. for (int i = length(); --i >= 0;)
  9982. if (text[i] == character)
  9983. return i;
  9984. return -1;
  9985. }
  9986. int String::indexOf (const String& t) const throw()
  9987. {
  9988. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9989. return r == 0 ? -1 : (int) (r - text);
  9990. }
  9991. int String::indexOfChar (const int startIndex,
  9992. const juce_wchar character) const throw()
  9993. {
  9994. if (startIndex > 0 && startIndex >= length())
  9995. return -1;
  9996. const juce_wchar* t = text + jmax (0, startIndex);
  9997. for (;;)
  9998. {
  9999. if (*t == character)
  10000. return (int) (t - text);
  10001. if (*t == 0)
  10002. return -1;
  10003. ++t;
  10004. }
  10005. }
  10006. int String::indexOfAnyOf (const String& charactersToLookFor,
  10007. const int startIndex,
  10008. const bool ignoreCase) const throw()
  10009. {
  10010. if (startIndex > 0 && startIndex >= length())
  10011. return -1;
  10012. const juce_wchar* t = text + jmax (0, startIndex);
  10013. while (*t != 0)
  10014. {
  10015. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10016. return (int) (t - text);
  10017. ++t;
  10018. }
  10019. return -1;
  10020. }
  10021. int String::indexOf (const int startIndex, const String& other) const throw()
  10022. {
  10023. if (startIndex > 0 && startIndex >= length())
  10024. return -1;
  10025. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10026. return found == 0 ? -1 : (int) (found - text);
  10027. }
  10028. int String::indexOfIgnoreCase (const String& other) const throw()
  10029. {
  10030. if (other.isNotEmpty())
  10031. {
  10032. const int len = other.length();
  10033. const int end = length() - len;
  10034. for (int i = 0; i <= end; ++i)
  10035. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10036. return i;
  10037. }
  10038. return -1;
  10039. }
  10040. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10041. {
  10042. if (other.isNotEmpty())
  10043. {
  10044. const int len = other.length();
  10045. const int end = length() - len;
  10046. for (int i = jmax (0, startIndex); i <= end; ++i)
  10047. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10048. return i;
  10049. }
  10050. return -1;
  10051. }
  10052. int String::lastIndexOf (const String& other) const throw()
  10053. {
  10054. if (other.isNotEmpty())
  10055. {
  10056. const int len = other.length();
  10057. int i = length() - len;
  10058. if (i >= 0)
  10059. {
  10060. const juce_wchar* n = text + i;
  10061. while (i >= 0)
  10062. {
  10063. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10064. return i;
  10065. --i;
  10066. }
  10067. }
  10068. }
  10069. return -1;
  10070. }
  10071. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10072. {
  10073. if (other.isNotEmpty())
  10074. {
  10075. const int len = other.length();
  10076. int i = length() - len;
  10077. if (i >= 0)
  10078. {
  10079. const juce_wchar* n = text + i;
  10080. while (i >= 0)
  10081. {
  10082. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10083. return i;
  10084. --i;
  10085. }
  10086. }
  10087. }
  10088. return -1;
  10089. }
  10090. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10091. {
  10092. for (int i = length(); --i >= 0;)
  10093. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10094. return i;
  10095. return -1;
  10096. }
  10097. bool String::contains (const String& other) const throw()
  10098. {
  10099. return indexOf (other) >= 0;
  10100. }
  10101. bool String::containsChar (const juce_wchar character) const throw()
  10102. {
  10103. const juce_wchar* t = text;
  10104. for (;;)
  10105. {
  10106. if (*t == 0)
  10107. return false;
  10108. if (*t == character)
  10109. return true;
  10110. ++t;
  10111. }
  10112. }
  10113. bool String::containsIgnoreCase (const String& t) const throw()
  10114. {
  10115. return indexOfIgnoreCase (t) >= 0;
  10116. }
  10117. int String::indexOfWholeWord (const String& word) const throw()
  10118. {
  10119. if (word.isNotEmpty())
  10120. {
  10121. const int wordLen = word.length();
  10122. const int end = length() - wordLen;
  10123. const juce_wchar* t = text;
  10124. for (int i = 0; i <= end; ++i)
  10125. {
  10126. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10127. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10128. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10129. {
  10130. return i;
  10131. }
  10132. ++t;
  10133. }
  10134. }
  10135. return -1;
  10136. }
  10137. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10138. {
  10139. if (word.isNotEmpty())
  10140. {
  10141. const int wordLen = word.length();
  10142. const int end = length() - wordLen;
  10143. const juce_wchar* t = text;
  10144. for (int i = 0; i <= end; ++i)
  10145. {
  10146. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10147. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10148. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10149. {
  10150. return i;
  10151. }
  10152. ++t;
  10153. }
  10154. }
  10155. return -1;
  10156. }
  10157. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10158. {
  10159. return indexOfWholeWord (wordToLookFor) >= 0;
  10160. }
  10161. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10162. {
  10163. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10164. }
  10165. namespace WildCardHelpers
  10166. {
  10167. int indexOfMatch (const juce_wchar* const wildcard,
  10168. const juce_wchar* const test,
  10169. const bool ignoreCase) throw()
  10170. {
  10171. int start = 0;
  10172. while (test [start] != 0)
  10173. {
  10174. int i = 0;
  10175. for (;;)
  10176. {
  10177. const juce_wchar wc = wildcard [i];
  10178. const juce_wchar c = test [i + start];
  10179. if (wc == c
  10180. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10181. || (wc == '?' && c != 0))
  10182. {
  10183. if (wc == 0)
  10184. return start;
  10185. ++i;
  10186. }
  10187. else
  10188. {
  10189. if (wc == '*' && (wildcard [i + 1] == 0
  10190. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10191. {
  10192. return start;
  10193. }
  10194. break;
  10195. }
  10196. }
  10197. ++start;
  10198. }
  10199. return -1;
  10200. }
  10201. }
  10202. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10203. {
  10204. int i = 0;
  10205. for (;;)
  10206. {
  10207. const juce_wchar wc = wildcard.text [i];
  10208. const juce_wchar c = text [i];
  10209. if (wc == c
  10210. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10211. || (wc == '?' && c != 0))
  10212. {
  10213. if (wc == 0)
  10214. return true;
  10215. ++i;
  10216. }
  10217. else
  10218. {
  10219. return wc == '*' && (wildcard [i + 1] == 0
  10220. || WildCardHelpers::indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10221. }
  10222. }
  10223. }
  10224. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10225. {
  10226. const int len = stringToRepeat.length();
  10227. String result (Preallocation (len * numberOfTimesToRepeat + 1));
  10228. juce_wchar* n = result.text;
  10229. *n = 0;
  10230. while (--numberOfTimesToRepeat >= 0)
  10231. {
  10232. StringHolder::copyChars (n, stringToRepeat.text, len);
  10233. n += len;
  10234. }
  10235. return result;
  10236. }
  10237. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10238. {
  10239. jassert (padCharacter != 0);
  10240. const int len = length();
  10241. if (len >= minimumLength || padCharacter == 0)
  10242. return *this;
  10243. String result (Preallocation (minimumLength + 1));
  10244. juce_wchar* n = result.text;
  10245. minimumLength -= len;
  10246. while (--minimumLength >= 0)
  10247. *n++ = padCharacter;
  10248. StringHolder::copyChars (n, text, len);
  10249. return result;
  10250. }
  10251. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10252. {
  10253. jassert (padCharacter != 0);
  10254. const int len = length();
  10255. if (len >= minimumLength || padCharacter == 0)
  10256. return *this;
  10257. String result (*this, (size_t) minimumLength);
  10258. juce_wchar* n = result.text + len;
  10259. minimumLength -= len;
  10260. while (--minimumLength >= 0)
  10261. *n++ = padCharacter;
  10262. *n = 0;
  10263. return result;
  10264. }
  10265. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10266. {
  10267. if (index < 0)
  10268. {
  10269. // a negative index to replace from?
  10270. jassertfalse;
  10271. index = 0;
  10272. }
  10273. if (numCharsToReplace < 0)
  10274. {
  10275. // replacing a negative number of characters?
  10276. numCharsToReplace = 0;
  10277. jassertfalse;
  10278. }
  10279. const int len = length();
  10280. if (index + numCharsToReplace > len)
  10281. {
  10282. if (index > len)
  10283. {
  10284. // replacing beyond the end of the string?
  10285. index = len;
  10286. jassertfalse;
  10287. }
  10288. numCharsToReplace = len - index;
  10289. }
  10290. const int newStringLen = stringToInsert.length();
  10291. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10292. if (newTotalLen <= 0)
  10293. return String::empty;
  10294. String result (Preallocation ((size_t) newTotalLen));
  10295. StringHolder::copyChars (result.text, text, index);
  10296. if (newStringLen > 0)
  10297. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10298. const int endStringLen = newTotalLen - (index + newStringLen);
  10299. if (endStringLen > 0)
  10300. StringHolder::copyChars (result.text + (index + newStringLen),
  10301. text + (index + numCharsToReplace),
  10302. endStringLen);
  10303. return result;
  10304. }
  10305. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10306. {
  10307. const int stringToReplaceLen = stringToReplace.length();
  10308. const int stringToInsertLen = stringToInsert.length();
  10309. int i = 0;
  10310. String result (*this);
  10311. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10312. : result.indexOf (i, stringToReplace))) >= 0)
  10313. {
  10314. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10315. i += stringToInsertLen;
  10316. }
  10317. return result;
  10318. }
  10319. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10320. {
  10321. const int index = indexOfChar (charToReplace);
  10322. if (index < 0)
  10323. return *this;
  10324. String result (*this, size_t());
  10325. juce_wchar* t = result.text + index;
  10326. while (*t != 0)
  10327. {
  10328. if (*t == charToReplace)
  10329. *t = charToInsert;
  10330. ++t;
  10331. }
  10332. return result;
  10333. }
  10334. const String String::replaceCharacters (const String& charactersToReplace,
  10335. const String& charactersToInsertInstead) const
  10336. {
  10337. String result (*this, size_t());
  10338. juce_wchar* t = result.text;
  10339. const int len2 = charactersToInsertInstead.length();
  10340. // the two strings passed in are supposed to be the same length!
  10341. jassert (len2 == charactersToReplace.length());
  10342. while (*t != 0)
  10343. {
  10344. const int index = charactersToReplace.indexOfChar (*t);
  10345. if (isPositiveAndBelow (index, len2))
  10346. *t = charactersToInsertInstead [index];
  10347. ++t;
  10348. }
  10349. return result;
  10350. }
  10351. bool String::startsWith (const String& other) const throw()
  10352. {
  10353. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10354. }
  10355. bool String::startsWithIgnoreCase (const String& other) const throw()
  10356. {
  10357. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10358. }
  10359. bool String::startsWithChar (const juce_wchar character) const throw()
  10360. {
  10361. jassert (character != 0); // strings can't contain a null character!
  10362. return text[0] == character;
  10363. }
  10364. bool String::endsWithChar (const juce_wchar character) const throw()
  10365. {
  10366. jassert (character != 0); // strings can't contain a null character!
  10367. return text[0] != 0
  10368. && text [length() - 1] == character;
  10369. }
  10370. bool String::endsWith (const String& other) const throw()
  10371. {
  10372. const int thisLen = length();
  10373. const int otherLen = other.length();
  10374. return thisLen >= otherLen
  10375. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10376. }
  10377. bool String::endsWithIgnoreCase (const String& other) const throw()
  10378. {
  10379. const int thisLen = length();
  10380. const int otherLen = other.length();
  10381. return thisLen >= otherLen
  10382. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10383. }
  10384. const String String::toUpperCase() const
  10385. {
  10386. String result (*this, size_t());
  10387. CharacterFunctions::toUpperCase (result.text);
  10388. return result;
  10389. }
  10390. const String String::toLowerCase() const
  10391. {
  10392. String result (*this, size_t());
  10393. CharacterFunctions::toLowerCase (result.text);
  10394. return result;
  10395. }
  10396. juce_wchar& String::operator[] (const int index)
  10397. {
  10398. jassert (isPositiveAndNotGreaterThan (index, length()));
  10399. text = StringHolder::makeUnique (text);
  10400. return text [index];
  10401. }
  10402. juce_wchar String::getLastCharacter() const throw()
  10403. {
  10404. return isEmpty() ? juce_wchar() : text [length() - 1];
  10405. }
  10406. const String String::substring (int start, int end) const
  10407. {
  10408. if (start < 0)
  10409. start = 0;
  10410. else if (end <= start)
  10411. return empty;
  10412. int len = 0;
  10413. while (len <= end && text [len] != 0)
  10414. ++len;
  10415. if (end >= len)
  10416. {
  10417. if (start == 0)
  10418. return *this;
  10419. end = len;
  10420. }
  10421. return String (text + start, end - start);
  10422. }
  10423. const String String::substring (const int start) const
  10424. {
  10425. if (start <= 0)
  10426. return *this;
  10427. const int len = length();
  10428. if (start >= len)
  10429. return empty;
  10430. return String (text + start, len - start);
  10431. }
  10432. const String String::dropLastCharacters (const int numberToDrop) const
  10433. {
  10434. return String (text, jmax (0, length() - numberToDrop));
  10435. }
  10436. const String String::getLastCharacters (const int numCharacters) const
  10437. {
  10438. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10439. }
  10440. const String String::fromFirstOccurrenceOf (const String& sub,
  10441. const bool includeSubString,
  10442. const bool ignoreCase) const
  10443. {
  10444. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10445. : indexOf (sub);
  10446. if (i < 0)
  10447. return empty;
  10448. return substring (includeSubString ? i : i + sub.length());
  10449. }
  10450. const String String::fromLastOccurrenceOf (const String& sub,
  10451. const bool includeSubString,
  10452. const bool ignoreCase) const
  10453. {
  10454. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10455. : lastIndexOf (sub);
  10456. if (i < 0)
  10457. return *this;
  10458. return substring (includeSubString ? i : i + sub.length());
  10459. }
  10460. const String String::upToFirstOccurrenceOf (const String& sub,
  10461. const bool includeSubString,
  10462. const bool ignoreCase) const
  10463. {
  10464. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10465. : indexOf (sub);
  10466. if (i < 0)
  10467. return *this;
  10468. return substring (0, includeSubString ? i + sub.length() : i);
  10469. }
  10470. const String String::upToLastOccurrenceOf (const String& sub,
  10471. const bool includeSubString,
  10472. const bool ignoreCase) const
  10473. {
  10474. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10475. : lastIndexOf (sub);
  10476. if (i < 0)
  10477. return *this;
  10478. return substring (0, includeSubString ? i + sub.length() : i);
  10479. }
  10480. bool String::isQuotedString() const
  10481. {
  10482. const String trimmed (trimStart());
  10483. return trimmed[0] == '"'
  10484. || trimmed[0] == '\'';
  10485. }
  10486. const String String::unquoted() const
  10487. {
  10488. String s (*this);
  10489. if (s.text[0] == '"' || s.text[0] == '\'')
  10490. s = s.substring (1);
  10491. const int lastCharIndex = s.length() - 1;
  10492. if (lastCharIndex >= 0
  10493. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10494. s [lastCharIndex] = 0;
  10495. return s;
  10496. }
  10497. const String String::quoted (const juce_wchar quoteCharacter) const
  10498. {
  10499. if (isEmpty())
  10500. return charToString (quoteCharacter) + quoteCharacter;
  10501. String t (*this);
  10502. if (! t.startsWithChar (quoteCharacter))
  10503. t = charToString (quoteCharacter) + t;
  10504. if (! t.endsWithChar (quoteCharacter))
  10505. t += quoteCharacter;
  10506. return t;
  10507. }
  10508. const String String::trim() const
  10509. {
  10510. if (isEmpty())
  10511. return empty;
  10512. int start = 0;
  10513. while (CharacterFunctions::isWhitespace (text [start]))
  10514. ++start;
  10515. const int len = length();
  10516. int end = len - 1;
  10517. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10518. --end;
  10519. ++end;
  10520. if (end <= start)
  10521. return empty;
  10522. else if (start > 0 || end < len)
  10523. return String (text + start, end - start);
  10524. return *this;
  10525. }
  10526. const String String::trimStart() const
  10527. {
  10528. if (isEmpty())
  10529. return empty;
  10530. const juce_wchar* t = text;
  10531. while (CharacterFunctions::isWhitespace (*t))
  10532. ++t;
  10533. if (t == text)
  10534. return *this;
  10535. return String (t);
  10536. }
  10537. const String String::trimEnd() const
  10538. {
  10539. if (isEmpty())
  10540. return empty;
  10541. const juce_wchar* endT = text + (length() - 1);
  10542. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10543. --endT;
  10544. return String (text, (int) (++endT - text));
  10545. }
  10546. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10547. {
  10548. const juce_wchar* t = text;
  10549. while (charactersToTrim.containsChar (*t))
  10550. ++t;
  10551. return t == text ? *this : String (t);
  10552. }
  10553. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10554. {
  10555. if (isEmpty())
  10556. return empty;
  10557. const int len = length();
  10558. const juce_wchar* endT = text + (len - 1);
  10559. int numToRemove = 0;
  10560. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10561. {
  10562. ++numToRemove;
  10563. --endT;
  10564. }
  10565. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10566. }
  10567. const String String::retainCharacters (const String& charactersToRetain) const
  10568. {
  10569. if (isEmpty())
  10570. return empty;
  10571. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10572. juce_wchar* dst = result.text;
  10573. const juce_wchar* src = text;
  10574. while (*src != 0)
  10575. {
  10576. if (charactersToRetain.containsChar (*src))
  10577. *dst++ = *src;
  10578. ++src;
  10579. }
  10580. *dst = 0;
  10581. return result;
  10582. }
  10583. const String String::removeCharacters (const String& charactersToRemove) const
  10584. {
  10585. if (isEmpty())
  10586. return empty;
  10587. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10588. juce_wchar* dst = result.text;
  10589. const juce_wchar* src = text;
  10590. while (*src != 0)
  10591. {
  10592. if (! charactersToRemove.containsChar (*src))
  10593. *dst++ = *src;
  10594. ++src;
  10595. }
  10596. *dst = 0;
  10597. return result;
  10598. }
  10599. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10600. {
  10601. int i = 0;
  10602. for (;;)
  10603. {
  10604. if (! permittedCharacters.containsChar (text[i]))
  10605. break;
  10606. ++i;
  10607. }
  10608. return substring (0, i);
  10609. }
  10610. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10611. {
  10612. const juce_wchar* const t = text;
  10613. int i = 0;
  10614. while (t[i] != 0)
  10615. {
  10616. if (charactersToStopAt.containsChar (t[i]))
  10617. return String (text, i);
  10618. ++i;
  10619. }
  10620. return empty;
  10621. }
  10622. bool String::containsOnly (const String& chars) const throw()
  10623. {
  10624. const juce_wchar* t = text;
  10625. while (*t != 0)
  10626. if (! chars.containsChar (*t++))
  10627. return false;
  10628. return true;
  10629. }
  10630. bool String::containsAnyOf (const String& chars) const throw()
  10631. {
  10632. const juce_wchar* t = text;
  10633. while (*t != 0)
  10634. if (chars.containsChar (*t++))
  10635. return true;
  10636. return false;
  10637. }
  10638. bool String::containsNonWhitespaceChars() const throw()
  10639. {
  10640. const juce_wchar* t = text;
  10641. while (*t != 0)
  10642. if (! CharacterFunctions::isWhitespace (*t++))
  10643. return true;
  10644. return false;
  10645. }
  10646. const String String::formatted (const juce_wchar* const pf, ... )
  10647. {
  10648. jassert (pf != 0);
  10649. va_list args;
  10650. va_start (args, pf);
  10651. size_t bufferSize = 256;
  10652. String result (Preallocation ((size_t) bufferSize));
  10653. result.text[0] = 0;
  10654. for (;;)
  10655. {
  10656. #if JUCE_LINUX && JUCE_64BIT
  10657. va_list tempArgs;
  10658. va_copy (tempArgs, args);
  10659. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10660. va_end (tempArgs);
  10661. #elif JUCE_WINDOWS
  10662. #if JUCE_MSVC
  10663. #pragma warning (push)
  10664. #pragma warning (disable: 4996)
  10665. #endif
  10666. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10667. #if JUCE_MSVC
  10668. #pragma warning (pop)
  10669. #endif
  10670. #else
  10671. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10672. #endif
  10673. if (num > 0)
  10674. return result;
  10675. bufferSize += 256;
  10676. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10677. break; // returns -1 because of an error rather than because it needs more space.
  10678. result.preallocateStorage (bufferSize);
  10679. }
  10680. return empty;
  10681. }
  10682. int String::getIntValue() const throw()
  10683. {
  10684. return CharacterFunctions::getIntValue (text);
  10685. }
  10686. int String::getTrailingIntValue() const throw()
  10687. {
  10688. int n = 0;
  10689. int mult = 1;
  10690. const juce_wchar* t = text + length();
  10691. while (--t >= text)
  10692. {
  10693. const juce_wchar c = *t;
  10694. if (! CharacterFunctions::isDigit (c))
  10695. {
  10696. if (c == '-')
  10697. n = -n;
  10698. break;
  10699. }
  10700. n += mult * (c - '0');
  10701. mult *= 10;
  10702. }
  10703. return n;
  10704. }
  10705. int64 String::getLargeIntValue() const throw()
  10706. {
  10707. return CharacterFunctions::getInt64Value (text);
  10708. }
  10709. float String::getFloatValue() const throw()
  10710. {
  10711. return (float) CharacterFunctions::getDoubleValue (text);
  10712. }
  10713. double String::getDoubleValue() const throw()
  10714. {
  10715. return CharacterFunctions::getDoubleValue (text);
  10716. }
  10717. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10718. const String String::toHexString (const int number)
  10719. {
  10720. juce_wchar buffer[32];
  10721. juce_wchar* const end = buffer + 32;
  10722. juce_wchar* t = end;
  10723. *--t = 0;
  10724. unsigned int v = (unsigned int) number;
  10725. do
  10726. {
  10727. *--t = hexDigits [v & 15];
  10728. v >>= 4;
  10729. } while (v != 0);
  10730. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10731. }
  10732. const String String::toHexString (const int64 number)
  10733. {
  10734. juce_wchar buffer[32];
  10735. juce_wchar* const end = buffer + 32;
  10736. juce_wchar* t = end;
  10737. *--t = 0;
  10738. uint64 v = (uint64) number;
  10739. do
  10740. {
  10741. *--t = hexDigits [(int) (v & 15)];
  10742. v >>= 4;
  10743. } while (v != 0);
  10744. return String (t, (int) (((char*) end) - (char*) t));
  10745. }
  10746. const String String::toHexString (const short number)
  10747. {
  10748. return toHexString ((int) (unsigned short) number);
  10749. }
  10750. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10751. {
  10752. if (size <= 0)
  10753. return empty;
  10754. int numChars = (size * 2) + 2;
  10755. if (groupSize > 0)
  10756. numChars += size / groupSize;
  10757. String s (Preallocation ((size_t) numChars));
  10758. juce_wchar* d = s.text;
  10759. for (int i = 0; i < size; ++i)
  10760. {
  10761. *d++ = hexDigits [(*data) >> 4];
  10762. *d++ = hexDigits [(*data) & 0xf];
  10763. ++data;
  10764. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10765. *d++ = ' ';
  10766. }
  10767. *d = 0;
  10768. return s;
  10769. }
  10770. int String::getHexValue32() const throw()
  10771. {
  10772. int result = 0;
  10773. const juce_wchar* c = text;
  10774. for (;;)
  10775. {
  10776. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10777. if (hexValue >= 0)
  10778. result = (result << 4) | hexValue;
  10779. else if (*c == 0)
  10780. break;
  10781. ++c;
  10782. }
  10783. return result;
  10784. }
  10785. int64 String::getHexValue64() const throw()
  10786. {
  10787. int64 result = 0;
  10788. const juce_wchar* c = text;
  10789. for (;;)
  10790. {
  10791. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10792. if (hexValue >= 0)
  10793. result = (result << 4) | hexValue;
  10794. else if (*c == 0)
  10795. break;
  10796. ++c;
  10797. }
  10798. return result;
  10799. }
  10800. const String String::createStringFromData (const void* const data_, const int size)
  10801. {
  10802. const char* const data = static_cast <const char*> (data_);
  10803. if (size <= 0 || data == 0)
  10804. {
  10805. return empty;
  10806. }
  10807. else if (size < 2)
  10808. {
  10809. return charToString (data[0]);
  10810. }
  10811. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10812. || (data[0] == (char)-1 && data[1] == (char)-2))
  10813. {
  10814. // assume it's 16-bit unicode
  10815. const bool bigEndian = (data[0] == (char)-2);
  10816. const int numChars = size / 2 - 1;
  10817. String result;
  10818. result.preallocateStorage (numChars + 2);
  10819. const uint16* const src = (const uint16*) (data + 2);
  10820. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10821. if (bigEndian)
  10822. {
  10823. for (int i = 0; i < numChars; ++i)
  10824. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10825. }
  10826. else
  10827. {
  10828. for (int i = 0; i < numChars; ++i)
  10829. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10830. }
  10831. dst [numChars] = 0;
  10832. return result;
  10833. }
  10834. else
  10835. {
  10836. return String::fromUTF8 (data, size);
  10837. }
  10838. }
  10839. const char* String::toUTF8() const
  10840. {
  10841. if (isEmpty())
  10842. {
  10843. return reinterpret_cast <const char*> (text);
  10844. }
  10845. else
  10846. {
  10847. const int currentLen = length() + 1;
  10848. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10849. String* const mutableThis = const_cast <String*> (this);
  10850. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10851. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10852. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10853. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10854. #endif
  10855. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10856. return otherCopy;
  10857. }
  10858. }
  10859. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10860. {
  10861. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10862. int num = 0, index = 0;
  10863. for (;;)
  10864. {
  10865. const uint32 c = (uint32) text [index++];
  10866. if (c >= 0x80)
  10867. {
  10868. int numExtraBytes = 1;
  10869. if (c >= 0x800)
  10870. {
  10871. ++numExtraBytes;
  10872. if (c >= 0x10000)
  10873. {
  10874. ++numExtraBytes;
  10875. if (c >= 0x200000)
  10876. {
  10877. ++numExtraBytes;
  10878. if (c >= 0x4000000)
  10879. ++numExtraBytes;
  10880. }
  10881. }
  10882. }
  10883. if (buffer != 0)
  10884. {
  10885. if (num + numExtraBytes >= maxBufferSizeBytes)
  10886. {
  10887. buffer [num++] = 0;
  10888. break;
  10889. }
  10890. else
  10891. {
  10892. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10893. while (--numExtraBytes >= 0)
  10894. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10895. }
  10896. }
  10897. else
  10898. {
  10899. num += numExtraBytes + 1;
  10900. }
  10901. }
  10902. else
  10903. {
  10904. if (buffer != 0)
  10905. {
  10906. if (num + 1 >= maxBufferSizeBytes)
  10907. {
  10908. buffer [num++] = 0;
  10909. break;
  10910. }
  10911. buffer [num] = (uint8) c;
  10912. }
  10913. ++num;
  10914. }
  10915. if (c == 0)
  10916. break;
  10917. }
  10918. return num;
  10919. }
  10920. int String::getNumBytesAsUTF8() const throw()
  10921. {
  10922. int num = 0;
  10923. const juce_wchar* t = text;
  10924. for (;;)
  10925. {
  10926. const uint32 c = (uint32) *t;
  10927. if (c >= 0x80)
  10928. {
  10929. ++num;
  10930. if (c >= 0x800)
  10931. {
  10932. ++num;
  10933. if (c >= 0x10000)
  10934. {
  10935. ++num;
  10936. if (c >= 0x200000)
  10937. {
  10938. ++num;
  10939. if (c >= 0x4000000)
  10940. ++num;
  10941. }
  10942. }
  10943. }
  10944. }
  10945. else if (c == 0)
  10946. break;
  10947. ++num;
  10948. ++t;
  10949. }
  10950. return num;
  10951. }
  10952. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10953. {
  10954. if (buffer == 0)
  10955. return empty;
  10956. if (bufferSizeBytes < 0)
  10957. bufferSizeBytes = std::numeric_limits<int>::max();
  10958. size_t numBytes;
  10959. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10960. if (buffer [numBytes] == 0)
  10961. break;
  10962. String result (Preallocation (numBytes + 1));
  10963. juce_wchar* dest = result.text;
  10964. size_t i = 0;
  10965. while (i < numBytes)
  10966. {
  10967. const char c = buffer [i++];
  10968. if (c < 0)
  10969. {
  10970. unsigned int mask = 0x7f;
  10971. int bit = 0x40;
  10972. int numExtraValues = 0;
  10973. while (bit != 0 && (c & bit) != 0)
  10974. {
  10975. bit >>= 1;
  10976. mask >>= 1;
  10977. ++numExtraValues;
  10978. }
  10979. int n = (mask & (unsigned char) c);
  10980. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10981. {
  10982. const char nextByte = buffer[i];
  10983. if ((nextByte & 0xc0) != 0x80)
  10984. break;
  10985. n <<= 6;
  10986. n |= (nextByte & 0x3f);
  10987. ++i;
  10988. }
  10989. *dest++ = (juce_wchar) n;
  10990. }
  10991. else
  10992. {
  10993. *dest++ = (juce_wchar) c;
  10994. }
  10995. }
  10996. *dest = 0;
  10997. return result;
  10998. }
  10999. const char* String::toCString() const
  11000. {
  11001. if (isEmpty())
  11002. {
  11003. return reinterpret_cast <const char*> (text);
  11004. }
  11005. else
  11006. {
  11007. const int len = length();
  11008. String* const mutableThis = const_cast <String*> (this);
  11009. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11010. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11011. CharacterFunctions::copy (otherCopy, text, len);
  11012. otherCopy [len] = 0;
  11013. return otherCopy;
  11014. }
  11015. }
  11016. #if JUCE_MSVC
  11017. #pragma warning (push)
  11018. #pragma warning (disable: 4514 4996)
  11019. #endif
  11020. int String::getNumBytesAsCString() const throw()
  11021. {
  11022. return (int) wcstombs (0, text, 0);
  11023. }
  11024. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11025. {
  11026. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11027. if (destBuffer != 0 && numBytes >= 0)
  11028. destBuffer [numBytes] = 0;
  11029. return numBytes;
  11030. }
  11031. #if JUCE_MSVC
  11032. #pragma warning (pop)
  11033. #endif
  11034. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11035. {
  11036. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11037. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11038. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11039. }
  11040. String::Concatenator::Concatenator (String& stringToAppendTo)
  11041. : result (stringToAppendTo),
  11042. nextIndex (stringToAppendTo.length())
  11043. {
  11044. }
  11045. String::Concatenator::~Concatenator()
  11046. {
  11047. }
  11048. void String::Concatenator::append (const String& s)
  11049. {
  11050. const int len = s.length();
  11051. if (len > 0)
  11052. {
  11053. result.preallocateStorage (nextIndex + len);
  11054. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11055. nextIndex += len;
  11056. }
  11057. }
  11058. #if JUCE_UNIT_TESTS
  11059. class StringTests : public UnitTest
  11060. {
  11061. public:
  11062. StringTests() : UnitTest ("String class") {}
  11063. void runTest()
  11064. {
  11065. {
  11066. beginTest ("Basics");
  11067. expect (String().length() == 0);
  11068. expect (String() == String::empty);
  11069. String s1, s2 ("abcd");
  11070. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11071. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11072. expect (s2.length() == 4);
  11073. s1 = "abcd";
  11074. expect (s2 == s1 && s1 == s2);
  11075. expect (s1 == "abcd" && s1 == L"abcd");
  11076. expect (String ("abcd") == String (L"abcd"));
  11077. expect (String ("abcdefg", 4) == L"abcd");
  11078. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11079. expect (String::charToString ('x') == "x");
  11080. expect (String::charToString (0) == String::empty);
  11081. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11082. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11083. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11084. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11085. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11086. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11087. expect (s1.indexOf (String::empty) == 0);
  11088. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11089. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11090. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11091. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11092. }
  11093. {
  11094. beginTest ("Operations");
  11095. String s ("012345678");
  11096. expect (s.hashCode() != 0);
  11097. expect (s.hashCode64() != 0);
  11098. expect (s.hashCode() != (s + s).hashCode());
  11099. expect (s.hashCode64() != (s + s).hashCode64());
  11100. expect (s.compare (String ("012345678")) == 0);
  11101. expect (s.compare (String ("012345679")) < 0);
  11102. expect (s.compare (String ("012345676")) > 0);
  11103. expect (s.substring (2, 3) == String::charToString (s[2]));
  11104. expect (s.substring (0, 1) == String::charToString (s[0]));
  11105. expect (s.getLastCharacter() == s [s.length() - 1]);
  11106. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11107. expect (s.substring (0, 3) == L"012");
  11108. expect (s.substring (0, 100) == s);
  11109. expect (s.substring (-1, 100) == s);
  11110. expect (s.substring (3) == "345678");
  11111. expect (s.indexOf (L"45") == 4);
  11112. expect (String ("444445").indexOf ("45") == 4);
  11113. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11114. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11115. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11116. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11117. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11118. expect (s.indexOfChar (L'4') == 4);
  11119. expect (s + s == "012345678012345678");
  11120. expect (s.startsWith (s));
  11121. expect (s.startsWith (s.substring (0, 4)));
  11122. expect (s.startsWith (s.dropLastCharacters (4)));
  11123. expect (s.endsWith (s.substring (5)));
  11124. expect (s.endsWith (s));
  11125. expect (s.contains (s.substring (3, 6)));
  11126. expect (s.contains (s.substring (3)));
  11127. expect (s.startsWithChar (s[0]));
  11128. expect (s.endsWithChar (s.getLastCharacter()));
  11129. expect (s [s.length()] == 0);
  11130. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11131. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11132. String s2 ("123");
  11133. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11134. s2 += "xyz";
  11135. expect (s2 == "1234567890xyz");
  11136. beginTest ("Numeric conversions");
  11137. expect (String::empty.getIntValue() == 0);
  11138. expect (String::empty.getDoubleValue() == 0.0);
  11139. expect (String::empty.getFloatValue() == 0.0f);
  11140. expect (s.getIntValue() == 12345678);
  11141. expect (s.getLargeIntValue() == (int64) 12345678);
  11142. expect (s.getDoubleValue() == 12345678.0);
  11143. expect (s.getFloatValue() == 12345678.0f);
  11144. expect (String (-1234).getIntValue() == -1234);
  11145. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11146. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11147. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11148. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11149. expect (s.getHexValue32() == 0x12345678);
  11150. expect (s.getHexValue64() == (int64) 0x12345678);
  11151. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11152. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11153. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11154. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11155. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11156. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11157. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11158. beginTest ("Subsections");
  11159. String s3;
  11160. s3 = "abcdeFGHIJ";
  11161. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11162. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11163. expect (s3.containsIgnoreCase (s3.substring (3)));
  11164. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11165. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11166. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11167. expect (s3.containsAnyOf (L"zzzFs"));
  11168. expect (s3.startsWith ("abcd"));
  11169. expect (s3.startsWithIgnoreCase (L"abCD"));
  11170. expect (s3.startsWith (String::empty));
  11171. expect (s3.startsWithChar ('a'));
  11172. expect (s3.endsWith (String ("HIJ")));
  11173. expect (s3.endsWithIgnoreCase (L"Hij"));
  11174. expect (s3.endsWith (String::empty));
  11175. expect (s3.endsWithChar (L'J'));
  11176. expect (s3.indexOf ("HIJ") == 7);
  11177. expect (s3.indexOf (L"HIJK") == -1);
  11178. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11179. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11180. String s4 (s3);
  11181. s4.append (String ("xyz123"), 3);
  11182. expect (s4 == s3 + "xyz");
  11183. expect (String (1234) < String (1235));
  11184. expect (String (1235) > String (1234));
  11185. expect (String (1234) >= String (1234));
  11186. expect (String (1234) <= String (1234));
  11187. expect (String (1235) >= String (1234));
  11188. expect (String (1234) <= String (1235));
  11189. String s5 ("word word2 word3");
  11190. expect (s5.containsWholeWord (String ("word2")));
  11191. expect (s5.indexOfWholeWord ("word2") == 5);
  11192. expect (s5.containsWholeWord (L"word"));
  11193. expect (s5.containsWholeWord ("word3"));
  11194. expect (s5.containsWholeWord (s5));
  11195. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11196. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11197. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11198. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11199. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11200. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11201. expect (s5.containsNonWhitespaceChars());
  11202. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11203. expect (s5.matchesWildcard (L"wor*", false));
  11204. expect (s5.matchesWildcard ("wOr*", true));
  11205. expect (s5.matchesWildcard (L"*word3", true));
  11206. expect (s5.matchesWildcard ("*word?", true));
  11207. expect (s5.matchesWildcard (L"Word*3", true));
  11208. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11209. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11210. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11211. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11212. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11213. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11214. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11215. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11216. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11217. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11218. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11219. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11220. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11221. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11222. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11223. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11224. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11225. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11226. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11227. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11228. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11229. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11230. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11231. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11232. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11233. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11234. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11235. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11236. expect (s5.replace ("Word", "", true) == " 2 3");
  11237. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11238. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11239. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11240. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11241. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11242. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11243. expect (s5.retainCharacters (String::empty).isEmpty());
  11244. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11245. expect (s5.removeCharacters (String::empty) == s5);
  11246. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11247. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11248. expect (! s5.isQuotedString());
  11249. expect (s5.quoted().isQuotedString());
  11250. expect (! s5.quoted().unquoted().isQuotedString());
  11251. expect (! String ("x'").isQuotedString());
  11252. expect (String ("'x").isQuotedString());
  11253. String s6 (" \t xyz \t\r\n");
  11254. expect (s6.trim() == String ("xyz"));
  11255. expect (s6.trim().trim() == "xyz");
  11256. expect (s5.trim() == s5);
  11257. expect (s6.trimStart().trimEnd() == s6.trim());
  11258. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11259. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11260. expect (s6.trimStart() != s6.trimEnd());
  11261. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11262. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11263. }
  11264. {
  11265. beginTest ("UTF8");
  11266. String s ("word word2 word3");
  11267. {
  11268. char buffer [100];
  11269. memset (buffer, 0xff, sizeof (buffer));
  11270. s.copyToUTF8 (buffer, 100);
  11271. expect (String::fromUTF8 (buffer, 100) == s);
  11272. juce_wchar bufferUnicode [100];
  11273. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11274. s.copyToUnicode (bufferUnicode, 100);
  11275. expect (String (bufferUnicode, 100) == s);
  11276. }
  11277. {
  11278. juce_wchar wideBuffer [50];
  11279. zerostruct (wideBuffer);
  11280. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11281. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11282. String wide (wideBuffer);
  11283. expect (wide == (const juce_wchar*) wideBuffer);
  11284. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11285. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11286. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11287. }
  11288. }
  11289. }
  11290. };
  11291. static StringTests stringUnitTests;
  11292. #endif
  11293. END_JUCE_NAMESPACE
  11294. /*** End of inlined file: juce_String.cpp ***/
  11295. /*** Start of inlined file: juce_StringArray.cpp ***/
  11296. BEGIN_JUCE_NAMESPACE
  11297. StringArray::StringArray() throw()
  11298. {
  11299. }
  11300. StringArray::StringArray (const StringArray& other)
  11301. : strings (other.strings)
  11302. {
  11303. }
  11304. StringArray::StringArray (const String& firstValue)
  11305. {
  11306. strings.add (firstValue);
  11307. }
  11308. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11309. const int numberOfStrings)
  11310. {
  11311. for (int i = 0; i < numberOfStrings; ++i)
  11312. strings.add (initialStrings [i]);
  11313. }
  11314. StringArray::StringArray (const char* const* const initialStrings,
  11315. const int numberOfStrings)
  11316. {
  11317. for (int i = 0; i < numberOfStrings; ++i)
  11318. strings.add (initialStrings [i]);
  11319. }
  11320. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11321. {
  11322. int i = 0;
  11323. while (initialStrings[i] != 0)
  11324. strings.add (initialStrings [i++]);
  11325. }
  11326. StringArray::StringArray (const char* const* const initialStrings)
  11327. {
  11328. int i = 0;
  11329. while (initialStrings[i] != 0)
  11330. strings.add (initialStrings [i++]);
  11331. }
  11332. StringArray& StringArray::operator= (const StringArray& other)
  11333. {
  11334. strings = other.strings;
  11335. return *this;
  11336. }
  11337. StringArray::~StringArray()
  11338. {
  11339. }
  11340. bool StringArray::operator== (const StringArray& other) const throw()
  11341. {
  11342. if (other.size() != size())
  11343. return false;
  11344. for (int i = size(); --i >= 0;)
  11345. if (other.strings.getReference(i) != strings.getReference(i))
  11346. return false;
  11347. return true;
  11348. }
  11349. bool StringArray::operator!= (const StringArray& other) const throw()
  11350. {
  11351. return ! operator== (other);
  11352. }
  11353. void StringArray::clear()
  11354. {
  11355. strings.clear();
  11356. }
  11357. const String& StringArray::operator[] (const int index) const throw()
  11358. {
  11359. if (isPositiveAndBelow (index, strings.size()))
  11360. return strings.getReference (index);
  11361. return String::empty;
  11362. }
  11363. String& StringArray::getReference (const int index) throw()
  11364. {
  11365. jassert (isPositiveAndBelow (index, strings.size()));
  11366. return strings.getReference (index);
  11367. }
  11368. void StringArray::add (const String& newString)
  11369. {
  11370. strings.add (newString);
  11371. }
  11372. void StringArray::insert (const int index, const String& newString)
  11373. {
  11374. strings.insert (index, newString);
  11375. }
  11376. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11377. {
  11378. if (! contains (newString, ignoreCase))
  11379. add (newString);
  11380. }
  11381. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11382. {
  11383. if (startIndex < 0)
  11384. {
  11385. jassertfalse;
  11386. startIndex = 0;
  11387. }
  11388. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11389. numElementsToAdd = otherArray.size() - startIndex;
  11390. while (--numElementsToAdd >= 0)
  11391. strings.add (otherArray.strings.getReference (startIndex++));
  11392. }
  11393. void StringArray::set (const int index, const String& newString)
  11394. {
  11395. strings.set (index, newString);
  11396. }
  11397. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11398. {
  11399. if (ignoreCase)
  11400. {
  11401. for (int i = size(); --i >= 0;)
  11402. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11403. return true;
  11404. }
  11405. else
  11406. {
  11407. for (int i = size(); --i >= 0;)
  11408. if (stringToLookFor == strings.getReference(i))
  11409. return true;
  11410. }
  11411. return false;
  11412. }
  11413. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11414. {
  11415. if (i < 0)
  11416. i = 0;
  11417. const int numElements = size();
  11418. if (ignoreCase)
  11419. {
  11420. while (i < numElements)
  11421. {
  11422. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11423. return i;
  11424. ++i;
  11425. }
  11426. }
  11427. else
  11428. {
  11429. while (i < numElements)
  11430. {
  11431. if (stringToLookFor == strings.getReference (i))
  11432. return i;
  11433. ++i;
  11434. }
  11435. }
  11436. return -1;
  11437. }
  11438. void StringArray::remove (const int index)
  11439. {
  11440. strings.remove (index);
  11441. }
  11442. void StringArray::removeString (const String& stringToRemove,
  11443. const bool ignoreCase)
  11444. {
  11445. if (ignoreCase)
  11446. {
  11447. for (int i = size(); --i >= 0;)
  11448. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11449. strings.remove (i);
  11450. }
  11451. else
  11452. {
  11453. for (int i = size(); --i >= 0;)
  11454. if (stringToRemove == strings.getReference (i))
  11455. strings.remove (i);
  11456. }
  11457. }
  11458. void StringArray::removeRange (int startIndex, int numberToRemove)
  11459. {
  11460. strings.removeRange (startIndex, numberToRemove);
  11461. }
  11462. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11463. {
  11464. if (removeWhitespaceStrings)
  11465. {
  11466. for (int i = size(); --i >= 0;)
  11467. if (! strings.getReference(i).containsNonWhitespaceChars())
  11468. strings.remove (i);
  11469. }
  11470. else
  11471. {
  11472. for (int i = size(); --i >= 0;)
  11473. if (strings.getReference(i).isEmpty())
  11474. strings.remove (i);
  11475. }
  11476. }
  11477. void StringArray::trim()
  11478. {
  11479. for (int i = size(); --i >= 0;)
  11480. {
  11481. String& s = strings.getReference(i);
  11482. s = s.trim();
  11483. }
  11484. }
  11485. class InternalStringArrayComparator_CaseSensitive
  11486. {
  11487. public:
  11488. static int compareElements (String& first, String& second) { return first.compare (second); }
  11489. };
  11490. class InternalStringArrayComparator_CaseInsensitive
  11491. {
  11492. public:
  11493. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11494. };
  11495. void StringArray::sort (const bool ignoreCase)
  11496. {
  11497. if (ignoreCase)
  11498. {
  11499. InternalStringArrayComparator_CaseInsensitive comp;
  11500. strings.sort (comp);
  11501. }
  11502. else
  11503. {
  11504. InternalStringArrayComparator_CaseSensitive comp;
  11505. strings.sort (comp);
  11506. }
  11507. }
  11508. void StringArray::move (const int currentIndex, int newIndex) throw()
  11509. {
  11510. strings.move (currentIndex, newIndex);
  11511. }
  11512. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11513. {
  11514. const int last = (numberToJoin < 0) ? size()
  11515. : jmin (size(), start + numberToJoin);
  11516. if (start < 0)
  11517. start = 0;
  11518. if (start >= last)
  11519. return String::empty;
  11520. if (start == last - 1)
  11521. return strings.getReference (start);
  11522. const int separatorLen = separator.length();
  11523. int charsNeeded = separatorLen * (last - start - 1);
  11524. for (int i = start; i < last; ++i)
  11525. charsNeeded += strings.getReference(i).length();
  11526. String result;
  11527. result.preallocateStorage (charsNeeded);
  11528. juce_wchar* dest = result;
  11529. while (start < last)
  11530. {
  11531. const String& s = strings.getReference (start);
  11532. const int len = s.length();
  11533. if (len > 0)
  11534. {
  11535. s.copyToUnicode (dest, len);
  11536. dest += len;
  11537. }
  11538. if (++start < last && separatorLen > 0)
  11539. {
  11540. separator.copyToUnicode (dest, separatorLen);
  11541. dest += separatorLen;
  11542. }
  11543. }
  11544. *dest = 0;
  11545. return result;
  11546. }
  11547. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11548. {
  11549. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11550. }
  11551. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11552. {
  11553. int num = 0;
  11554. if (text.isNotEmpty())
  11555. {
  11556. bool insideQuotes = false;
  11557. juce_wchar currentQuoteChar = 0;
  11558. int i = 0;
  11559. int tokenStart = 0;
  11560. for (;;)
  11561. {
  11562. const juce_wchar c = text[i];
  11563. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11564. if (! isBreak)
  11565. {
  11566. if (quoteCharacters.containsChar (c))
  11567. {
  11568. if (insideQuotes)
  11569. {
  11570. // only break out of quotes-mode if we find a matching quote to the
  11571. // one that we opened with..
  11572. if (currentQuoteChar == c)
  11573. insideQuotes = false;
  11574. }
  11575. else
  11576. {
  11577. insideQuotes = true;
  11578. currentQuoteChar = c;
  11579. }
  11580. }
  11581. }
  11582. else
  11583. {
  11584. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11585. ++num;
  11586. tokenStart = i + 1;
  11587. }
  11588. if (c == 0)
  11589. break;
  11590. ++i;
  11591. }
  11592. }
  11593. return num;
  11594. }
  11595. int StringArray::addLines (const String& sourceText)
  11596. {
  11597. int numLines = 0;
  11598. const juce_wchar* text = sourceText;
  11599. while (*text != 0)
  11600. {
  11601. const juce_wchar* const startOfLine = text;
  11602. while (*text != 0)
  11603. {
  11604. if (*text == '\r')
  11605. {
  11606. ++text;
  11607. if (*text == '\n')
  11608. ++text;
  11609. break;
  11610. }
  11611. if (*text == '\n')
  11612. {
  11613. ++text;
  11614. break;
  11615. }
  11616. ++text;
  11617. }
  11618. const juce_wchar* endOfLine = text;
  11619. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11620. --endOfLine;
  11621. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11622. --endOfLine;
  11623. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11624. ++numLines;
  11625. }
  11626. return numLines;
  11627. }
  11628. void StringArray::removeDuplicates (const bool ignoreCase)
  11629. {
  11630. for (int i = 0; i < size() - 1; ++i)
  11631. {
  11632. const String s (strings.getReference(i));
  11633. int nextIndex = i + 1;
  11634. for (;;)
  11635. {
  11636. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11637. if (nextIndex < 0)
  11638. break;
  11639. strings.remove (nextIndex);
  11640. }
  11641. }
  11642. }
  11643. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11644. const bool appendNumberToFirstInstance,
  11645. const juce_wchar* preNumberString,
  11646. const juce_wchar* postNumberString)
  11647. {
  11648. if (preNumberString == 0)
  11649. preNumberString = L" (";
  11650. if (postNumberString == 0)
  11651. postNumberString = L")";
  11652. for (int i = 0; i < size() - 1; ++i)
  11653. {
  11654. String& s = strings.getReference(i);
  11655. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11656. if (nextIndex >= 0)
  11657. {
  11658. const String original (s);
  11659. int number = 0;
  11660. if (appendNumberToFirstInstance)
  11661. s = original + preNumberString + String (++number) + postNumberString;
  11662. else
  11663. ++number;
  11664. while (nextIndex >= 0)
  11665. {
  11666. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11667. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11668. }
  11669. }
  11670. }
  11671. }
  11672. void StringArray::minimiseStorageOverheads()
  11673. {
  11674. strings.minimiseStorageOverheads();
  11675. }
  11676. END_JUCE_NAMESPACE
  11677. /*** End of inlined file: juce_StringArray.cpp ***/
  11678. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11679. BEGIN_JUCE_NAMESPACE
  11680. StringPairArray::StringPairArray (const bool ignoreCase_)
  11681. : ignoreCase (ignoreCase_)
  11682. {
  11683. }
  11684. StringPairArray::StringPairArray (const StringPairArray& other)
  11685. : keys (other.keys),
  11686. values (other.values),
  11687. ignoreCase (other.ignoreCase)
  11688. {
  11689. }
  11690. StringPairArray::~StringPairArray()
  11691. {
  11692. }
  11693. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11694. {
  11695. keys = other.keys;
  11696. values = other.values;
  11697. return *this;
  11698. }
  11699. bool StringPairArray::operator== (const StringPairArray& other) const
  11700. {
  11701. for (int i = keys.size(); --i >= 0;)
  11702. if (other [keys[i]] != values[i])
  11703. return false;
  11704. return true;
  11705. }
  11706. bool StringPairArray::operator!= (const StringPairArray& other) const
  11707. {
  11708. return ! operator== (other);
  11709. }
  11710. const String& StringPairArray::operator[] (const String& key) const
  11711. {
  11712. return values [keys.indexOf (key, ignoreCase)];
  11713. }
  11714. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11715. {
  11716. const int i = keys.indexOf (key, ignoreCase);
  11717. if (i >= 0)
  11718. return values[i];
  11719. return defaultReturnValue;
  11720. }
  11721. void StringPairArray::set (const String& key, const String& value)
  11722. {
  11723. const int i = keys.indexOf (key, ignoreCase);
  11724. if (i >= 0)
  11725. {
  11726. values.set (i, value);
  11727. }
  11728. else
  11729. {
  11730. keys.add (key);
  11731. values.add (value);
  11732. }
  11733. }
  11734. void StringPairArray::addArray (const StringPairArray& other)
  11735. {
  11736. for (int i = 0; i < other.size(); ++i)
  11737. set (other.keys[i], other.values[i]);
  11738. }
  11739. void StringPairArray::clear()
  11740. {
  11741. keys.clear();
  11742. values.clear();
  11743. }
  11744. void StringPairArray::remove (const String& key)
  11745. {
  11746. remove (keys.indexOf (key, ignoreCase));
  11747. }
  11748. void StringPairArray::remove (const int index)
  11749. {
  11750. keys.remove (index);
  11751. values.remove (index);
  11752. }
  11753. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11754. {
  11755. ignoreCase = shouldIgnoreCase;
  11756. }
  11757. const String StringPairArray::getDescription() const
  11758. {
  11759. String s;
  11760. for (int i = 0; i < keys.size(); ++i)
  11761. {
  11762. s << keys[i] << " = " << values[i];
  11763. if (i < keys.size())
  11764. s << ", ";
  11765. }
  11766. return s;
  11767. }
  11768. void StringPairArray::minimiseStorageOverheads()
  11769. {
  11770. keys.minimiseStorageOverheads();
  11771. values.minimiseStorageOverheads();
  11772. }
  11773. END_JUCE_NAMESPACE
  11774. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11775. /*** Start of inlined file: juce_StringPool.cpp ***/
  11776. BEGIN_JUCE_NAMESPACE
  11777. StringPool::StringPool() throw() {}
  11778. StringPool::~StringPool() {}
  11779. namespace StringPoolHelpers
  11780. {
  11781. template <class StringType>
  11782. const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11783. {
  11784. int start = 0;
  11785. int end = strings.size();
  11786. for (;;)
  11787. {
  11788. if (start >= end)
  11789. {
  11790. jassert (start <= end);
  11791. strings.insert (start, newString);
  11792. return strings.getReference (start);
  11793. }
  11794. else
  11795. {
  11796. const String& startString = strings.getReference (start);
  11797. if (startString == newString)
  11798. return startString;
  11799. const int halfway = (start + end) >> 1;
  11800. if (halfway == start)
  11801. {
  11802. if (startString.compare (newString) < 0)
  11803. ++start;
  11804. strings.insert (start, newString);
  11805. return strings.getReference (start);
  11806. }
  11807. const int comp = strings.getReference (halfway).compare (newString);
  11808. if (comp == 0)
  11809. return strings.getReference (halfway);
  11810. else if (comp < 0)
  11811. start = halfway;
  11812. else
  11813. end = halfway;
  11814. }
  11815. }
  11816. }
  11817. }
  11818. const juce_wchar* StringPool::getPooledString (const String& s)
  11819. {
  11820. if (s.isEmpty())
  11821. return String::empty;
  11822. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11823. }
  11824. const juce_wchar* StringPool::getPooledString (const char* const s)
  11825. {
  11826. if (s == 0 || *s == 0)
  11827. return String::empty;
  11828. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11829. }
  11830. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11831. {
  11832. if (s == 0 || *s == 0)
  11833. return String::empty;
  11834. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11835. }
  11836. int StringPool::size() const throw()
  11837. {
  11838. return strings.size();
  11839. }
  11840. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11841. {
  11842. return strings [index];
  11843. }
  11844. END_JUCE_NAMESPACE
  11845. /*** End of inlined file: juce_StringPool.cpp ***/
  11846. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11847. BEGIN_JUCE_NAMESPACE
  11848. XmlDocument::XmlDocument (const String& documentText)
  11849. : originalText (documentText),
  11850. ignoreEmptyTextElements (true)
  11851. {
  11852. }
  11853. XmlDocument::XmlDocument (const File& file)
  11854. : ignoreEmptyTextElements (true),
  11855. inputSource (new FileInputSource (file))
  11856. {
  11857. }
  11858. XmlDocument::~XmlDocument()
  11859. {
  11860. }
  11861. XmlElement* XmlDocument::parse (const File& file)
  11862. {
  11863. XmlDocument doc (file);
  11864. return doc.getDocumentElement();
  11865. }
  11866. XmlElement* XmlDocument::parse (const String& xmlData)
  11867. {
  11868. XmlDocument doc (xmlData);
  11869. return doc.getDocumentElement();
  11870. }
  11871. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11872. {
  11873. inputSource = newSource;
  11874. }
  11875. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11876. {
  11877. ignoreEmptyTextElements = shouldBeIgnored;
  11878. }
  11879. namespace XmlIdentifierChars
  11880. {
  11881. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11882. {
  11883. return CharacterFunctions::isLetterOrDigit (c)
  11884. || c == '_' || c == '-' || c == ':' || c == '.';
  11885. }
  11886. bool isIdentifierChar (const juce_wchar c) throw()
  11887. {
  11888. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11889. return (c < numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11890. : isIdentifierCharSlow (c);
  11891. }
  11892. /*static void generateIdentifierCharConstants()
  11893. {
  11894. uint32 n[8];
  11895. zerostruct (n);
  11896. for (int i = 0; i < 256; ++i)
  11897. if (isIdentifierCharSlow (i))
  11898. n[i >> 5] |= (1 << (i & 31));
  11899. String s;
  11900. for (int i = 0; i < 8; ++i)
  11901. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11902. DBG (s);
  11903. }*/
  11904. }
  11905. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11906. {
  11907. String textToParse (originalText);
  11908. if (textToParse.isEmpty() && inputSource != 0)
  11909. {
  11910. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11911. if (in != 0)
  11912. {
  11913. MemoryOutputStream data;
  11914. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11915. textToParse = data.toString();
  11916. if (! onlyReadOuterDocumentElement)
  11917. originalText = textToParse;
  11918. }
  11919. }
  11920. input = textToParse;
  11921. lastError = String::empty;
  11922. errorOccurred = false;
  11923. outOfData = false;
  11924. needToLoadDTD = true;
  11925. if (textToParse.isEmpty())
  11926. {
  11927. lastError = "not enough input";
  11928. }
  11929. else
  11930. {
  11931. skipHeader();
  11932. if (input != 0)
  11933. {
  11934. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11935. if (! errorOccurred)
  11936. return result.release();
  11937. }
  11938. else
  11939. {
  11940. lastError = "incorrect xml header";
  11941. }
  11942. }
  11943. return 0;
  11944. }
  11945. const String& XmlDocument::getLastParseError() const throw()
  11946. {
  11947. return lastError;
  11948. }
  11949. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11950. {
  11951. lastError = desc;
  11952. errorOccurred = ! carryOn;
  11953. }
  11954. const String XmlDocument::getFileContents (const String& filename) const
  11955. {
  11956. if (inputSource != 0)
  11957. {
  11958. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11959. if (in != 0)
  11960. return in->readEntireStreamAsString();
  11961. }
  11962. return String::empty;
  11963. }
  11964. juce_wchar XmlDocument::readNextChar() throw()
  11965. {
  11966. if (*input != 0)
  11967. return *input++;
  11968. outOfData = true;
  11969. return 0;
  11970. }
  11971. int XmlDocument::findNextTokenLength() throw()
  11972. {
  11973. int len = 0;
  11974. juce_wchar c = *input;
  11975. while (XmlIdentifierChars::isIdentifierChar (c))
  11976. c = input [++len];
  11977. return len;
  11978. }
  11979. void XmlDocument::skipHeader()
  11980. {
  11981. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11982. if (found != 0)
  11983. {
  11984. input = found;
  11985. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11986. if (input == 0)
  11987. return;
  11988. #if JUCE_DEBUG
  11989. const String header (found, input - found);
  11990. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11991. .fromFirstOccurrenceOf ("=", false, false)
  11992. .fromFirstOccurrenceOf ("\"", false, false)
  11993. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11994. /* If you load an XML document with a non-UTF encoding type, it may have been
  11995. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11996. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11997. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11998. read, use your own code to convert them to a unicode String, and pass that to the
  11999. XML parser.
  12000. */
  12001. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  12002. #endif
  12003. input += 2;
  12004. }
  12005. skipNextWhiteSpace();
  12006. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  12007. if (docType == 0)
  12008. return;
  12009. input = docType + 9;
  12010. int n = 1;
  12011. while (n > 0)
  12012. {
  12013. const juce_wchar c = readNextChar();
  12014. if (outOfData)
  12015. return;
  12016. if (c == '<')
  12017. ++n;
  12018. else if (c == '>')
  12019. --n;
  12020. }
  12021. docType += 9;
  12022. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  12023. }
  12024. void XmlDocument::skipNextWhiteSpace()
  12025. {
  12026. for (;;)
  12027. {
  12028. juce_wchar c = *input;
  12029. while (CharacterFunctions::isWhitespace (c))
  12030. c = *++input;
  12031. if (c == 0)
  12032. {
  12033. outOfData = true;
  12034. break;
  12035. }
  12036. else if (c == '<')
  12037. {
  12038. if (input[1] == '!'
  12039. && input[2] == '-'
  12040. && input[3] == '-')
  12041. {
  12042. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12043. if (closeComment == 0)
  12044. {
  12045. outOfData = true;
  12046. break;
  12047. }
  12048. input = closeComment + 3;
  12049. continue;
  12050. }
  12051. else if (input[1] == '?')
  12052. {
  12053. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12054. if (closeBracket == 0)
  12055. {
  12056. outOfData = true;
  12057. break;
  12058. }
  12059. input = closeBracket + 2;
  12060. continue;
  12061. }
  12062. }
  12063. break;
  12064. }
  12065. }
  12066. void XmlDocument::readQuotedString (String& result)
  12067. {
  12068. const juce_wchar quote = readNextChar();
  12069. while (! outOfData)
  12070. {
  12071. const juce_wchar c = readNextChar();
  12072. if (c == quote)
  12073. break;
  12074. if (c == '&')
  12075. {
  12076. --input;
  12077. readEntity (result);
  12078. }
  12079. else
  12080. {
  12081. --input;
  12082. const juce_wchar* const start = input;
  12083. for (;;)
  12084. {
  12085. const juce_wchar character = *input;
  12086. if (character == quote)
  12087. {
  12088. result.append (start, (int) (input - start));
  12089. ++input;
  12090. return;
  12091. }
  12092. else if (character == '&')
  12093. {
  12094. result.append (start, (int) (input - start));
  12095. break;
  12096. }
  12097. else if (character == 0)
  12098. {
  12099. outOfData = true;
  12100. setLastError ("unmatched quotes", false);
  12101. break;
  12102. }
  12103. ++input;
  12104. }
  12105. }
  12106. }
  12107. }
  12108. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12109. {
  12110. XmlElement* node = 0;
  12111. skipNextWhiteSpace();
  12112. if (outOfData)
  12113. return 0;
  12114. input = CharacterFunctions::find (input, JUCE_T("<"));
  12115. if (input != 0)
  12116. {
  12117. ++input;
  12118. int tagLen = findNextTokenLength();
  12119. if (tagLen == 0)
  12120. {
  12121. // no tag name - but allow for a gap after the '<' before giving an error
  12122. skipNextWhiteSpace();
  12123. tagLen = findNextTokenLength();
  12124. if (tagLen == 0)
  12125. {
  12126. setLastError ("tag name missing", false);
  12127. return node;
  12128. }
  12129. }
  12130. node = new XmlElement (String (input, tagLen));
  12131. input += tagLen;
  12132. LinkedListPointer<XmlElement::XmlAttributeNode>::Appender attributeAppender (node->attributes);
  12133. // look for attributes
  12134. for (;;)
  12135. {
  12136. skipNextWhiteSpace();
  12137. const juce_wchar c = *input;
  12138. // empty tag..
  12139. if (c == '/' && input[1] == '>')
  12140. {
  12141. input += 2;
  12142. break;
  12143. }
  12144. // parse the guts of the element..
  12145. if (c == '>')
  12146. {
  12147. ++input;
  12148. if (alsoParseSubElements)
  12149. readChildElements (node);
  12150. break;
  12151. }
  12152. // get an attribute..
  12153. if (XmlIdentifierChars::isIdentifierChar (c))
  12154. {
  12155. const int attNameLen = findNextTokenLength();
  12156. if (attNameLen > 0)
  12157. {
  12158. const juce_wchar* attNameStart = input;
  12159. input += attNameLen;
  12160. skipNextWhiteSpace();
  12161. if (readNextChar() == '=')
  12162. {
  12163. skipNextWhiteSpace();
  12164. const juce_wchar nextChar = *input;
  12165. if (nextChar == '"' || nextChar == '\'')
  12166. {
  12167. XmlElement::XmlAttributeNode* const newAtt
  12168. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12169. String::empty);
  12170. readQuotedString (newAtt->value);
  12171. attributeAppender.append (newAtt);
  12172. continue;
  12173. }
  12174. }
  12175. }
  12176. }
  12177. else
  12178. {
  12179. if (! outOfData)
  12180. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12181. }
  12182. break;
  12183. }
  12184. }
  12185. return node;
  12186. }
  12187. void XmlDocument::readChildElements (XmlElement* parent)
  12188. {
  12189. LinkedListPointer<XmlElement>::Appender childAppender (parent->firstChildElement);
  12190. for (;;)
  12191. {
  12192. const juce_wchar* const preWhitespaceInput = input;
  12193. skipNextWhiteSpace();
  12194. if (outOfData)
  12195. {
  12196. setLastError ("unmatched tags", false);
  12197. break;
  12198. }
  12199. if (*input == '<')
  12200. {
  12201. if (input[1] == '/')
  12202. {
  12203. // our close tag..
  12204. input = CharacterFunctions::find (input, JUCE_T(">"));
  12205. ++input;
  12206. break;
  12207. }
  12208. else if (input[1] == '!'
  12209. && input[2] == '['
  12210. && input[3] == 'C'
  12211. && input[4] == 'D'
  12212. && input[5] == 'A'
  12213. && input[6] == 'T'
  12214. && input[7] == 'A'
  12215. && input[8] == '[')
  12216. {
  12217. input += 9;
  12218. const juce_wchar* const inputStart = input;
  12219. int len = 0;
  12220. for (;;)
  12221. {
  12222. if (*input == 0)
  12223. {
  12224. setLastError ("unterminated CDATA section", false);
  12225. outOfData = true;
  12226. break;
  12227. }
  12228. else if (input[0] == ']'
  12229. && input[1] == ']'
  12230. && input[2] == '>')
  12231. {
  12232. input += 3;
  12233. break;
  12234. }
  12235. ++input;
  12236. ++len;
  12237. }
  12238. childAppender.append (XmlElement::createTextElement (String (inputStart, len)));
  12239. }
  12240. else
  12241. {
  12242. // this is some other element, so parse and add it..
  12243. XmlElement* const n = readNextElement (true);
  12244. if (n != 0)
  12245. childAppender.append (n);
  12246. else
  12247. return;
  12248. }
  12249. }
  12250. else // must be a character block
  12251. {
  12252. input = preWhitespaceInput; // roll back to include the leading whitespace
  12253. String textElementContent;
  12254. for (;;)
  12255. {
  12256. const juce_wchar c = *input;
  12257. if (c == '<')
  12258. break;
  12259. if (c == 0)
  12260. {
  12261. setLastError ("unmatched tags", false);
  12262. outOfData = true;
  12263. return;
  12264. }
  12265. if (c == '&')
  12266. {
  12267. String entity;
  12268. readEntity (entity);
  12269. if (entity.startsWithChar ('<') && entity [1] != 0)
  12270. {
  12271. const juce_wchar* const oldInput = input;
  12272. const bool oldOutOfData = outOfData;
  12273. input = entity;
  12274. outOfData = false;
  12275. for (;;)
  12276. {
  12277. XmlElement* const n = readNextElement (true);
  12278. if (n == 0)
  12279. break;
  12280. childAppender.append (n);
  12281. }
  12282. input = oldInput;
  12283. outOfData = oldOutOfData;
  12284. }
  12285. else
  12286. {
  12287. textElementContent += entity;
  12288. }
  12289. }
  12290. else
  12291. {
  12292. const juce_wchar* start = input;
  12293. int len = 0;
  12294. for (;;)
  12295. {
  12296. const juce_wchar nextChar = *input;
  12297. if (nextChar == '<' || nextChar == '&')
  12298. {
  12299. break;
  12300. }
  12301. else if (nextChar == 0)
  12302. {
  12303. setLastError ("unmatched tags", false);
  12304. outOfData = true;
  12305. return;
  12306. }
  12307. ++input;
  12308. ++len;
  12309. }
  12310. textElementContent.append (start, len);
  12311. }
  12312. }
  12313. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12314. {
  12315. childAppender.append (XmlElement::createTextElement (textElementContent));
  12316. }
  12317. }
  12318. }
  12319. }
  12320. void XmlDocument::readEntity (String& result)
  12321. {
  12322. // skip over the ampersand
  12323. ++input;
  12324. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12325. {
  12326. input += 4;
  12327. result += '&';
  12328. }
  12329. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12330. {
  12331. input += 5;
  12332. result += '"';
  12333. }
  12334. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12335. {
  12336. input += 5;
  12337. result += '\'';
  12338. }
  12339. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12340. {
  12341. input += 3;
  12342. result += '<';
  12343. }
  12344. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12345. {
  12346. input += 3;
  12347. result += '>';
  12348. }
  12349. else if (*input == '#')
  12350. {
  12351. int charCode = 0;
  12352. ++input;
  12353. if (*input == 'x' || *input == 'X')
  12354. {
  12355. ++input;
  12356. int numChars = 0;
  12357. while (input[0] != ';')
  12358. {
  12359. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12360. if (hexValue < 0 || ++numChars > 8)
  12361. {
  12362. setLastError ("illegal escape sequence", true);
  12363. break;
  12364. }
  12365. charCode = (charCode << 4) | hexValue;
  12366. ++input;
  12367. }
  12368. ++input;
  12369. }
  12370. else if (input[0] >= '0' && input[0] <= '9')
  12371. {
  12372. int numChars = 0;
  12373. while (input[0] != ';')
  12374. {
  12375. if (++numChars > 12)
  12376. {
  12377. setLastError ("illegal escape sequence", true);
  12378. break;
  12379. }
  12380. charCode = charCode * 10 + (input[0] - '0');
  12381. ++input;
  12382. }
  12383. ++input;
  12384. }
  12385. else
  12386. {
  12387. setLastError ("illegal escape sequence", true);
  12388. result += '&';
  12389. return;
  12390. }
  12391. result << (juce_wchar) charCode;
  12392. }
  12393. else
  12394. {
  12395. const juce_wchar* const entityNameStart = input;
  12396. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12397. if (closingSemiColon == 0)
  12398. {
  12399. outOfData = true;
  12400. result += '&';
  12401. }
  12402. else
  12403. {
  12404. input = closingSemiColon + 1;
  12405. result += expandExternalEntity (String (entityNameStart,
  12406. (int) (closingSemiColon - entityNameStart)));
  12407. }
  12408. }
  12409. }
  12410. const String XmlDocument::expandEntity (const String& ent)
  12411. {
  12412. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12413. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12414. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12415. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12416. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12417. if (ent[0] == '#')
  12418. {
  12419. if (ent[1] == 'x' || ent[1] == 'X')
  12420. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12421. if (ent[1] >= '0' && ent[1] <= '9')
  12422. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12423. setLastError ("illegal escape sequence", false);
  12424. return String::charToString ('&');
  12425. }
  12426. return expandExternalEntity (ent);
  12427. }
  12428. const String XmlDocument::expandExternalEntity (const String& entity)
  12429. {
  12430. if (needToLoadDTD)
  12431. {
  12432. if (dtdText.isNotEmpty())
  12433. {
  12434. dtdText = dtdText.trimCharactersAtEnd (">");
  12435. tokenisedDTD.addTokens (dtdText, true);
  12436. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12437. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12438. {
  12439. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12440. tokenisedDTD.clear();
  12441. tokenisedDTD.addTokens (getFileContents (fn), true);
  12442. }
  12443. else
  12444. {
  12445. tokenisedDTD.clear();
  12446. const int openBracket = dtdText.indexOfChar ('[');
  12447. if (openBracket > 0)
  12448. {
  12449. const int closeBracket = dtdText.lastIndexOfChar (']');
  12450. if (closeBracket > openBracket)
  12451. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12452. closeBracket), true);
  12453. }
  12454. }
  12455. for (int i = tokenisedDTD.size(); --i >= 0;)
  12456. {
  12457. if (tokenisedDTD[i].startsWithChar ('%')
  12458. && tokenisedDTD[i].endsWithChar (';'))
  12459. {
  12460. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12461. StringArray newToks;
  12462. newToks.addTokens (parsed, true);
  12463. tokenisedDTD.remove (i);
  12464. for (int j = newToks.size(); --j >= 0;)
  12465. tokenisedDTD.insert (i, newToks[j]);
  12466. }
  12467. }
  12468. }
  12469. needToLoadDTD = false;
  12470. }
  12471. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12472. {
  12473. if (tokenisedDTD[i] == entity)
  12474. {
  12475. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12476. {
  12477. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12478. // check for sub-entities..
  12479. int ampersand = ent.indexOfChar ('&');
  12480. while (ampersand >= 0)
  12481. {
  12482. const int semiColon = ent.indexOf (i + 1, ";");
  12483. if (semiColon < 0)
  12484. {
  12485. setLastError ("entity without terminating semi-colon", false);
  12486. break;
  12487. }
  12488. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12489. ent = ent.substring (0, ampersand)
  12490. + resolved
  12491. + ent.substring (semiColon + 1);
  12492. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12493. }
  12494. return ent;
  12495. }
  12496. }
  12497. }
  12498. setLastError ("unknown entity", true);
  12499. return entity;
  12500. }
  12501. const String XmlDocument::getParameterEntity (const String& entity)
  12502. {
  12503. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12504. {
  12505. if (tokenisedDTD[i] == entity
  12506. && tokenisedDTD [i - 1] == "%"
  12507. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12508. {
  12509. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12510. if (ent.equalsIgnoreCase ("system"))
  12511. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12512. else
  12513. return ent.trim().unquoted();
  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. {
  12526. }
  12527. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12528. : name (name_),
  12529. value (value_)
  12530. {
  12531. #if JUCE_DEBUG
  12532. // this checks whether the attribute name string contains any illegal characters..
  12533. for (const juce_wchar* t = name; *t != 0; ++t)
  12534. jassert (CharacterFunctions::isLetterOrDigit (*t) || *t == '_' || *t == '-' || *t == ':');
  12535. #endif
  12536. }
  12537. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12538. {
  12539. return name.equalsIgnoreCase (nameToMatch);
  12540. }
  12541. XmlElement::XmlElement (const String& tagName_) throw()
  12542. : tagName (tagName_)
  12543. {
  12544. // the tag name mustn't be empty, or it'll look like a text element!
  12545. jassert (tagName_.containsNonWhitespaceChars())
  12546. // The tag can't contain spaces or other characters that would create invalid XML!
  12547. jassert (! tagName_.containsAnyOf (" <>/&"));
  12548. }
  12549. XmlElement::XmlElement (int /*dummy*/) throw()
  12550. {
  12551. }
  12552. XmlElement::XmlElement (const XmlElement& other)
  12553. : tagName (other.tagName)
  12554. {
  12555. copyChildrenAndAttributesFrom (other);
  12556. }
  12557. XmlElement& XmlElement::operator= (const XmlElement& other)
  12558. {
  12559. if (this != &other)
  12560. {
  12561. removeAllAttributes();
  12562. deleteAllChildElements();
  12563. tagName = other.tagName;
  12564. copyChildrenAndAttributesFrom (other);
  12565. }
  12566. return *this;
  12567. }
  12568. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12569. {
  12570. jassert (firstChildElement.get() == 0);
  12571. firstChildElement.addCopyOfList (other.firstChildElement);
  12572. jassert (attributes.get() == 0);
  12573. attributes.addCopyOfList (other.attributes);
  12574. }
  12575. XmlElement::~XmlElement() throw()
  12576. {
  12577. firstChildElement.deleteAll();
  12578. attributes.deleteAll();
  12579. }
  12580. namespace XmlOutputFunctions
  12581. {
  12582. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12583. {
  12584. if ((character >= 'a' && character <= 'z')
  12585. || (character >= 'A' && character <= 'Z')
  12586. || (character >= '0' && character <= '9'))
  12587. return true;
  12588. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12589. do
  12590. {
  12591. if (((juce_wchar) (uint8) *t) == character)
  12592. return true;
  12593. }
  12594. while (*++t != 0);
  12595. return false;
  12596. }
  12597. void generateLegalCharConstants()
  12598. {
  12599. uint8 n[32];
  12600. zerostruct (n);
  12601. for (int i = 0; i < 256; ++i)
  12602. if (isLegalXmlCharSlow (i))
  12603. n[i >> 3] |= (1 << (i & 7));
  12604. String s;
  12605. for (int i = 0; i < 32; ++i)
  12606. s << (int) n[i] << ", ";
  12607. DBG (s);
  12608. }*/
  12609. bool isLegalXmlChar (const uint32 c) throw()
  12610. {
  12611. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12612. return c < sizeof (legalChars) * 8
  12613. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12614. }
  12615. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12616. {
  12617. const juce_wchar* t = text;
  12618. for (;;)
  12619. {
  12620. const juce_wchar character = *t++;
  12621. if (character == 0)
  12622. break;
  12623. if (isLegalXmlChar ((uint32) character))
  12624. {
  12625. outputStream << (char) character;
  12626. }
  12627. else
  12628. {
  12629. switch (character)
  12630. {
  12631. case '&': outputStream << "&amp;"; break;
  12632. case '"': outputStream << "&quot;"; break;
  12633. case '>': outputStream << "&gt;"; break;
  12634. case '<': outputStream << "&lt;"; break;
  12635. case '\n':
  12636. case '\r':
  12637. if (! changeNewLines)
  12638. {
  12639. outputStream << (char) character;
  12640. break;
  12641. }
  12642. // Note: deliberate fall-through here!
  12643. default:
  12644. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12645. break;
  12646. }
  12647. }
  12648. }
  12649. }
  12650. void writeSpaces (OutputStream& out, int numSpaces)
  12651. {
  12652. if (numSpaces > 0)
  12653. {
  12654. const char blanks[] = " ";
  12655. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12656. while (numSpaces > blankSize)
  12657. {
  12658. out.write (blanks, blankSize);
  12659. numSpaces -= blankSize;
  12660. }
  12661. out.write (blanks, numSpaces);
  12662. }
  12663. }
  12664. }
  12665. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12666. const int indentationLevel,
  12667. const int lineWrapLength) const
  12668. {
  12669. using namespace XmlOutputFunctions;
  12670. writeSpaces (outputStream, indentationLevel);
  12671. if (! isTextElement())
  12672. {
  12673. outputStream.writeByte ('<');
  12674. outputStream << tagName;
  12675. {
  12676. const int attIndent = indentationLevel + tagName.length() + 1;
  12677. int lineLen = 0;
  12678. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12679. {
  12680. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12681. {
  12682. outputStream << newLine;
  12683. writeSpaces (outputStream, attIndent);
  12684. lineLen = 0;
  12685. }
  12686. const int64 startPos = outputStream.getPosition();
  12687. outputStream.writeByte (' ');
  12688. outputStream << att->name;
  12689. outputStream.write ("=\"", 2);
  12690. escapeIllegalXmlChars (outputStream, att->value, true);
  12691. outputStream.writeByte ('"');
  12692. lineLen += (int) (outputStream.getPosition() - startPos);
  12693. }
  12694. }
  12695. if (firstChildElement != 0)
  12696. {
  12697. outputStream.writeByte ('>');
  12698. XmlElement* child = firstChildElement;
  12699. bool lastWasTextNode = false;
  12700. while (child != 0)
  12701. {
  12702. if (child->isTextElement())
  12703. {
  12704. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12705. lastWasTextNode = true;
  12706. }
  12707. else
  12708. {
  12709. if (indentationLevel >= 0 && ! lastWasTextNode)
  12710. outputStream << newLine;
  12711. child->writeElementAsText (outputStream,
  12712. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12713. lastWasTextNode = false;
  12714. }
  12715. child = child->getNextElement();
  12716. }
  12717. if (indentationLevel >= 0 && ! lastWasTextNode)
  12718. {
  12719. outputStream << newLine;
  12720. writeSpaces (outputStream, indentationLevel);
  12721. }
  12722. outputStream.write ("</", 2);
  12723. outputStream << tagName;
  12724. outputStream.writeByte ('>');
  12725. }
  12726. else
  12727. {
  12728. outputStream.write ("/>", 2);
  12729. }
  12730. }
  12731. else
  12732. {
  12733. escapeIllegalXmlChars (outputStream, getText(), false);
  12734. }
  12735. }
  12736. const String XmlElement::createDocument (const String& dtdToUse,
  12737. const bool allOnOneLine,
  12738. const bool includeXmlHeader,
  12739. const String& encodingType,
  12740. const int lineWrapLength) const
  12741. {
  12742. MemoryOutputStream mem (2048);
  12743. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12744. return mem.toUTF8();
  12745. }
  12746. void XmlElement::writeToStream (OutputStream& output,
  12747. const String& dtdToUse,
  12748. const bool allOnOneLine,
  12749. const bool includeXmlHeader,
  12750. const String& encodingType,
  12751. const int lineWrapLength) const
  12752. {
  12753. using namespace XmlOutputFunctions;
  12754. if (includeXmlHeader)
  12755. {
  12756. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12757. if (allOnOneLine)
  12758. output.writeByte (' ');
  12759. else
  12760. output << newLine << newLine;
  12761. }
  12762. if (dtdToUse.isNotEmpty())
  12763. {
  12764. output << dtdToUse;
  12765. if (allOnOneLine)
  12766. output.writeByte (' ');
  12767. else
  12768. output << newLine;
  12769. }
  12770. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12771. if (! allOnOneLine)
  12772. output << newLine;
  12773. }
  12774. bool XmlElement::writeToFile (const File& file,
  12775. const String& dtdToUse,
  12776. const String& encodingType,
  12777. const int lineWrapLength) const
  12778. {
  12779. if (file.hasWriteAccess())
  12780. {
  12781. TemporaryFile tempFile (file);
  12782. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12783. if (out != 0)
  12784. {
  12785. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12786. out = 0;
  12787. return tempFile.overwriteTargetFileWithTemporary();
  12788. }
  12789. }
  12790. return false;
  12791. }
  12792. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12793. {
  12794. #if JUCE_DEBUG
  12795. // if debugging, check that the case is actually the same, because
  12796. // valid xml is case-sensitive, and although this lets it pass, it's
  12797. // better not to..
  12798. if (tagName.equalsIgnoreCase (tagNameWanted))
  12799. {
  12800. jassert (tagName == tagNameWanted);
  12801. return true;
  12802. }
  12803. else
  12804. {
  12805. return false;
  12806. }
  12807. #else
  12808. return tagName.equalsIgnoreCase (tagNameWanted);
  12809. #endif
  12810. }
  12811. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12812. {
  12813. XmlElement* e = nextListItem;
  12814. while (e != 0 && ! e->hasTagName (requiredTagName))
  12815. e = e->nextListItem;
  12816. return e;
  12817. }
  12818. int XmlElement::getNumAttributes() const throw()
  12819. {
  12820. return attributes.size();
  12821. }
  12822. const String& XmlElement::getAttributeName (const int index) const throw()
  12823. {
  12824. const XmlAttributeNode* const att = attributes [index];
  12825. return att != 0 ? att->name : String::empty;
  12826. }
  12827. const String& XmlElement::getAttributeValue (const int index) const throw()
  12828. {
  12829. const XmlAttributeNode* const att = attributes [index];
  12830. return att != 0 ? att->value : String::empty;
  12831. }
  12832. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12833. {
  12834. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12835. if (att->hasName (attributeName))
  12836. return true;
  12837. return false;
  12838. }
  12839. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12840. {
  12841. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12842. if (att->hasName (attributeName))
  12843. return att->value;
  12844. return String::empty;
  12845. }
  12846. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12847. {
  12848. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12849. if (att->hasName (attributeName))
  12850. return att->value;
  12851. return defaultReturnValue;
  12852. }
  12853. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12854. {
  12855. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12856. if (att->hasName (attributeName))
  12857. return att->value.getIntValue();
  12858. return defaultReturnValue;
  12859. }
  12860. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12861. {
  12862. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12863. if (att->hasName (attributeName))
  12864. return att->value.getDoubleValue();
  12865. return defaultReturnValue;
  12866. }
  12867. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12868. {
  12869. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12870. {
  12871. if (att->hasName (attributeName))
  12872. {
  12873. juce_wchar firstChar = att->value[0];
  12874. if (CharacterFunctions::isWhitespace (firstChar))
  12875. firstChar = att->value.trimStart() [0];
  12876. return firstChar == '1'
  12877. || firstChar == 't'
  12878. || firstChar == 'y'
  12879. || firstChar == 'T'
  12880. || firstChar == 'Y';
  12881. }
  12882. }
  12883. return defaultReturnValue;
  12884. }
  12885. bool XmlElement::compareAttribute (const String& attributeName,
  12886. const String& stringToCompareAgainst,
  12887. const bool ignoreCase) const throw()
  12888. {
  12889. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12890. if (att->hasName (attributeName))
  12891. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12892. : att->value == stringToCompareAgainst;
  12893. return false;
  12894. }
  12895. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12896. {
  12897. if (attributes == 0)
  12898. {
  12899. attributes = new XmlAttributeNode (attributeName, value);
  12900. }
  12901. else
  12902. {
  12903. XmlAttributeNode* att = attributes;
  12904. for (;;)
  12905. {
  12906. if (att->hasName (attributeName))
  12907. {
  12908. att->value = value;
  12909. break;
  12910. }
  12911. else if (att->nextListItem == 0)
  12912. {
  12913. att->nextListItem = new XmlAttributeNode (attributeName, value);
  12914. break;
  12915. }
  12916. att = att->nextListItem;
  12917. }
  12918. }
  12919. }
  12920. void XmlElement::setAttribute (const String& attributeName, const int number)
  12921. {
  12922. setAttribute (attributeName, String (number));
  12923. }
  12924. void XmlElement::setAttribute (const String& attributeName, const double number)
  12925. {
  12926. setAttribute (attributeName, String (number));
  12927. }
  12928. void XmlElement::removeAttribute (const String& attributeName) throw()
  12929. {
  12930. LinkedListPointer<XmlAttributeNode>* att = &attributes;
  12931. while (att->get() != 0)
  12932. {
  12933. if (att->get()->hasName (attributeName))
  12934. {
  12935. delete att->removeNext();
  12936. break;
  12937. }
  12938. att = &(att->get()->nextListItem);
  12939. }
  12940. }
  12941. void XmlElement::removeAllAttributes() throw()
  12942. {
  12943. attributes.deleteAll();
  12944. }
  12945. int XmlElement::getNumChildElements() const throw()
  12946. {
  12947. return firstChildElement.size();
  12948. }
  12949. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12950. {
  12951. return firstChildElement [index].get();
  12952. }
  12953. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12954. {
  12955. XmlElement* child = firstChildElement;
  12956. while (child != 0)
  12957. {
  12958. if (child->hasTagName (childName))
  12959. break;
  12960. child = child->nextListItem;
  12961. }
  12962. return child;
  12963. }
  12964. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12965. {
  12966. if (newNode != 0)
  12967. firstChildElement.append (newNode);
  12968. }
  12969. void XmlElement::insertChildElement (XmlElement* const newNode,
  12970. int indexToInsertAt) throw()
  12971. {
  12972. if (newNode != 0)
  12973. {
  12974. removeChildElement (newNode, false);
  12975. firstChildElement.insertAtIndex (indexToInsertAt, newNode);
  12976. }
  12977. }
  12978. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12979. {
  12980. XmlElement* const newElement = new XmlElement (childTagName);
  12981. addChildElement (newElement);
  12982. return newElement;
  12983. }
  12984. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12985. XmlElement* const newNode) throw()
  12986. {
  12987. if (newNode != 0)
  12988. {
  12989. LinkedListPointer<XmlElement>* const p = firstChildElement.findPointerTo (currentChildElement);
  12990. if (p != 0)
  12991. {
  12992. if (currentChildElement != newNode)
  12993. delete p->replaceNext (newNode);
  12994. return true;
  12995. }
  12996. }
  12997. return false;
  12998. }
  12999. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13000. const bool shouldDeleteTheChild) throw()
  13001. {
  13002. if (childToRemove != 0)
  13003. {
  13004. firstChildElement.remove (childToRemove);
  13005. if (shouldDeleteTheChild)
  13006. delete childToRemove;
  13007. }
  13008. }
  13009. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13010. const bool ignoreOrderOfAttributes) const throw()
  13011. {
  13012. if (this != other)
  13013. {
  13014. if (other == 0 || tagName != other->tagName)
  13015. return false;
  13016. if (ignoreOrderOfAttributes)
  13017. {
  13018. int totalAtts = 0;
  13019. const XmlAttributeNode* att = attributes;
  13020. while (att != 0)
  13021. {
  13022. if (! other->compareAttribute (att->name, att->value))
  13023. return false;
  13024. att = att->nextListItem;
  13025. ++totalAtts;
  13026. }
  13027. if (totalAtts != other->getNumAttributes())
  13028. return false;
  13029. }
  13030. else
  13031. {
  13032. const XmlAttributeNode* thisAtt = attributes;
  13033. const XmlAttributeNode* otherAtt = other->attributes;
  13034. for (;;)
  13035. {
  13036. if (thisAtt == 0 || otherAtt == 0)
  13037. {
  13038. if (thisAtt == otherAtt) // both 0, so it's a match
  13039. break;
  13040. return false;
  13041. }
  13042. if (thisAtt->name != otherAtt->name
  13043. || thisAtt->value != otherAtt->value)
  13044. {
  13045. return false;
  13046. }
  13047. thisAtt = thisAtt->nextListItem;
  13048. otherAtt = otherAtt->nextListItem;
  13049. }
  13050. }
  13051. const XmlElement* thisChild = firstChildElement;
  13052. const XmlElement* otherChild = other->firstChildElement;
  13053. for (;;)
  13054. {
  13055. if (thisChild == 0 || otherChild == 0)
  13056. {
  13057. if (thisChild == otherChild) // both 0, so it's a match
  13058. break;
  13059. return false;
  13060. }
  13061. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13062. return false;
  13063. thisChild = thisChild->nextListItem;
  13064. otherChild = otherChild->nextListItem;
  13065. }
  13066. }
  13067. return true;
  13068. }
  13069. void XmlElement::deleteAllChildElements() throw()
  13070. {
  13071. firstChildElement.deleteAll();
  13072. }
  13073. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13074. {
  13075. XmlElement* child = firstChildElement;
  13076. while (child != 0)
  13077. {
  13078. XmlElement* const nextChild = child->nextListItem;
  13079. if (child->hasTagName (name))
  13080. removeChildElement (child, true);
  13081. child = nextChild;
  13082. }
  13083. }
  13084. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13085. {
  13086. return firstChildElement.contains (possibleChild);
  13087. }
  13088. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13089. {
  13090. if (this == elementToLookFor || elementToLookFor == 0)
  13091. return 0;
  13092. XmlElement* child = firstChildElement;
  13093. while (child != 0)
  13094. {
  13095. if (elementToLookFor == child)
  13096. return this;
  13097. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13098. if (found != 0)
  13099. return found;
  13100. child = child->nextListItem;
  13101. }
  13102. return 0;
  13103. }
  13104. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13105. {
  13106. firstChildElement.copyToArray (elems);
  13107. }
  13108. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13109. {
  13110. XmlElement* e = firstChildElement = elems[0];
  13111. for (int i = 1; i < num; ++i)
  13112. {
  13113. e->nextListItem = elems[i];
  13114. e = e->nextListItem;
  13115. }
  13116. e->nextListItem = 0;
  13117. }
  13118. bool XmlElement::isTextElement() const throw()
  13119. {
  13120. return tagName.isEmpty();
  13121. }
  13122. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13123. const String& XmlElement::getText() const throw()
  13124. {
  13125. jassert (isTextElement()); // you're trying to get the text from an element that
  13126. // isn't actually a text element.. If this contains text sub-nodes, you
  13127. // probably want to use getAllSubText instead.
  13128. return getStringAttribute (juce_xmltextContentAttributeName);
  13129. }
  13130. void XmlElement::setText (const String& newText)
  13131. {
  13132. if (isTextElement())
  13133. setAttribute (juce_xmltextContentAttributeName, newText);
  13134. else
  13135. jassertfalse; // you can only change the text in a text element, not a normal one.
  13136. }
  13137. const String XmlElement::getAllSubText() const
  13138. {
  13139. if (isTextElement())
  13140. return getText();
  13141. String result;
  13142. String::Concatenator concatenator (result);
  13143. const XmlElement* child = firstChildElement;
  13144. while (child != 0)
  13145. {
  13146. concatenator.append (child->getAllSubText());
  13147. child = child->nextListItem;
  13148. }
  13149. return result;
  13150. }
  13151. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13152. const String& defaultReturnValue) const
  13153. {
  13154. const XmlElement* const child = getChildByName (childTagName);
  13155. if (child != 0)
  13156. return child->getAllSubText();
  13157. return defaultReturnValue;
  13158. }
  13159. XmlElement* XmlElement::createTextElement (const String& text)
  13160. {
  13161. XmlElement* const e = new XmlElement ((int) 0);
  13162. e->setAttribute (juce_xmltextContentAttributeName, text);
  13163. return e;
  13164. }
  13165. void XmlElement::addTextElement (const String& text)
  13166. {
  13167. addChildElement (createTextElement (text));
  13168. }
  13169. void XmlElement::deleteAllTextElements() throw()
  13170. {
  13171. XmlElement* child = firstChildElement;
  13172. while (child != 0)
  13173. {
  13174. XmlElement* const next = child->nextListItem;
  13175. if (child->isTextElement())
  13176. removeChildElement (child, true);
  13177. child = next;
  13178. }
  13179. }
  13180. END_JUCE_NAMESPACE
  13181. /*** End of inlined file: juce_XmlElement.cpp ***/
  13182. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13183. BEGIN_JUCE_NAMESPACE
  13184. ReadWriteLock::ReadWriteLock() throw()
  13185. : numWaitingWriters (0),
  13186. numWriters (0),
  13187. writerThreadId (0)
  13188. {
  13189. }
  13190. ReadWriteLock::~ReadWriteLock() throw()
  13191. {
  13192. jassert (readerThreads.size() == 0);
  13193. jassert (numWriters == 0);
  13194. }
  13195. void ReadWriteLock::enterRead() const throw()
  13196. {
  13197. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13198. const ScopedLock sl (accessLock);
  13199. for (;;)
  13200. {
  13201. jassert (readerThreads.size() % 2 == 0);
  13202. int i;
  13203. for (i = 0; i < readerThreads.size(); i += 2)
  13204. if (readerThreads.getUnchecked(i) == threadId)
  13205. break;
  13206. if (i < readerThreads.size()
  13207. || numWriters + numWaitingWriters == 0
  13208. || (threadId == writerThreadId && numWriters > 0))
  13209. {
  13210. if (i < readerThreads.size())
  13211. {
  13212. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13213. }
  13214. else
  13215. {
  13216. readerThreads.add (threadId);
  13217. readerThreads.add ((Thread::ThreadID) 1);
  13218. }
  13219. return;
  13220. }
  13221. const ScopedUnlock ul (accessLock);
  13222. waitEvent.wait (100);
  13223. }
  13224. }
  13225. void ReadWriteLock::exitRead() const throw()
  13226. {
  13227. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13228. const ScopedLock sl (accessLock);
  13229. for (int i = 0; i < readerThreads.size(); i += 2)
  13230. {
  13231. if (readerThreads.getUnchecked(i) == threadId)
  13232. {
  13233. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13234. if (newCount == 0)
  13235. {
  13236. readerThreads.removeRange (i, 2);
  13237. waitEvent.signal();
  13238. }
  13239. else
  13240. {
  13241. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13242. }
  13243. return;
  13244. }
  13245. }
  13246. jassertfalse; // unlocking a lock that wasn't locked..
  13247. }
  13248. void ReadWriteLock::enterWrite() const throw()
  13249. {
  13250. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13251. const ScopedLock sl (accessLock);
  13252. for (;;)
  13253. {
  13254. if (readerThreads.size() + numWriters == 0
  13255. || threadId == writerThreadId
  13256. || (readerThreads.size() == 2
  13257. && readerThreads.getUnchecked(0) == threadId))
  13258. {
  13259. writerThreadId = threadId;
  13260. ++numWriters;
  13261. break;
  13262. }
  13263. ++numWaitingWriters;
  13264. accessLock.exit();
  13265. waitEvent.wait (100);
  13266. accessLock.enter();
  13267. --numWaitingWriters;
  13268. }
  13269. }
  13270. bool ReadWriteLock::tryEnterWrite() const throw()
  13271. {
  13272. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13273. const ScopedLock sl (accessLock);
  13274. if (readerThreads.size() + numWriters == 0
  13275. || threadId == writerThreadId
  13276. || (readerThreads.size() == 2
  13277. && readerThreads.getUnchecked(0) == threadId))
  13278. {
  13279. writerThreadId = threadId;
  13280. ++numWriters;
  13281. return true;
  13282. }
  13283. return false;
  13284. }
  13285. void ReadWriteLock::exitWrite() const throw()
  13286. {
  13287. const ScopedLock sl (accessLock);
  13288. // check this thread actually had the lock..
  13289. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13290. if (--numWriters == 0)
  13291. {
  13292. writerThreadId = 0;
  13293. waitEvent.signal();
  13294. }
  13295. }
  13296. END_JUCE_NAMESPACE
  13297. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13298. /*** Start of inlined file: juce_Thread.cpp ***/
  13299. BEGIN_JUCE_NAMESPACE
  13300. class RunningThreadsList
  13301. {
  13302. public:
  13303. RunningThreadsList()
  13304. {
  13305. }
  13306. void add (Thread* const thread)
  13307. {
  13308. const ScopedLock sl (lock);
  13309. jassert (! threads.contains (thread));
  13310. threads.add (thread);
  13311. }
  13312. void remove (Thread* const thread)
  13313. {
  13314. const ScopedLock sl (lock);
  13315. jassert (threads.contains (thread));
  13316. threads.removeValue (thread);
  13317. }
  13318. int size() const throw()
  13319. {
  13320. return threads.size();
  13321. }
  13322. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13323. {
  13324. const ScopedLock sl (lock);
  13325. for (int i = threads.size(); --i >= 0;)
  13326. {
  13327. Thread* const t = threads.getUnchecked(i);
  13328. if (t->getThreadId() == targetID)
  13329. return t;
  13330. }
  13331. return 0;
  13332. }
  13333. void stopAll (const int timeOutMilliseconds)
  13334. {
  13335. signalAllThreadsToStop();
  13336. for (;;)
  13337. {
  13338. Thread* firstThread = getFirstThread();
  13339. if (firstThread != 0)
  13340. firstThread->stopThread (timeOutMilliseconds);
  13341. else
  13342. break;
  13343. }
  13344. }
  13345. static RunningThreadsList& getInstance()
  13346. {
  13347. static RunningThreadsList runningThreads;
  13348. return runningThreads;
  13349. }
  13350. private:
  13351. Array<Thread*> threads;
  13352. CriticalSection lock;
  13353. void signalAllThreadsToStop()
  13354. {
  13355. const ScopedLock sl (lock);
  13356. for (int i = threads.size(); --i >= 0;)
  13357. threads.getUnchecked(i)->signalThreadShouldExit();
  13358. }
  13359. Thread* getFirstThread() const
  13360. {
  13361. const ScopedLock sl (lock);
  13362. return threads.getFirst();
  13363. }
  13364. };
  13365. void Thread::threadEntryPoint()
  13366. {
  13367. RunningThreadsList::getInstance().add (this);
  13368. JUCE_TRY
  13369. {
  13370. if (threadName_.isNotEmpty())
  13371. setCurrentThreadName (threadName_);
  13372. if (startSuspensionEvent_.wait (10000))
  13373. {
  13374. jassert (getCurrentThreadId() == threadId_);
  13375. if (affinityMask_ != 0)
  13376. setCurrentThreadAffinityMask (affinityMask_);
  13377. run();
  13378. }
  13379. }
  13380. JUCE_CATCH_ALL_ASSERT
  13381. RunningThreadsList::getInstance().remove (this);
  13382. closeThreadHandle();
  13383. }
  13384. // used to wrap the incoming call from the platform-specific code
  13385. void JUCE_API juce_threadEntryPoint (void* userData)
  13386. {
  13387. static_cast <Thread*> (userData)->threadEntryPoint();
  13388. }
  13389. Thread::Thread (const String& threadName)
  13390. : threadName_ (threadName),
  13391. threadHandle_ (0),
  13392. threadId_ (0),
  13393. threadPriority_ (5),
  13394. affinityMask_ (0),
  13395. threadShouldExit_ (false)
  13396. {
  13397. }
  13398. Thread::~Thread()
  13399. {
  13400. /* If your thread class's destructor has been called without first stopping the thread, that
  13401. means that this partially destructed object is still performing some work - and that's
  13402. probably a Bad Thing!
  13403. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13404. your subclass's destructor.
  13405. */
  13406. jassert (! isThreadRunning());
  13407. stopThread (100);
  13408. }
  13409. void Thread::startThread()
  13410. {
  13411. const ScopedLock sl (startStopLock);
  13412. threadShouldExit_ = false;
  13413. if (threadHandle_ == 0)
  13414. {
  13415. launchThread();
  13416. setThreadPriority (threadHandle_, threadPriority_);
  13417. startSuspensionEvent_.signal();
  13418. }
  13419. }
  13420. void Thread::startThread (const int priority)
  13421. {
  13422. const ScopedLock sl (startStopLock);
  13423. if (threadHandle_ == 0)
  13424. {
  13425. threadPriority_ = priority;
  13426. startThread();
  13427. }
  13428. else
  13429. {
  13430. setPriority (priority);
  13431. }
  13432. }
  13433. bool Thread::isThreadRunning() const
  13434. {
  13435. return threadHandle_ != 0;
  13436. }
  13437. void Thread::signalThreadShouldExit()
  13438. {
  13439. threadShouldExit_ = true;
  13440. }
  13441. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13442. {
  13443. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13444. jassert (getThreadId() != getCurrentThreadId());
  13445. const int sleepMsPerIteration = 5;
  13446. int count = timeOutMilliseconds / sleepMsPerIteration;
  13447. while (isThreadRunning())
  13448. {
  13449. if (timeOutMilliseconds > 0 && --count < 0)
  13450. return false;
  13451. sleep (sleepMsPerIteration);
  13452. }
  13453. return true;
  13454. }
  13455. void Thread::stopThread (const int timeOutMilliseconds)
  13456. {
  13457. // agh! You can't stop the thread that's calling this method! How on earth
  13458. // would that work??
  13459. jassert (getCurrentThreadId() != getThreadId());
  13460. const ScopedLock sl (startStopLock);
  13461. if (isThreadRunning())
  13462. {
  13463. signalThreadShouldExit();
  13464. notify();
  13465. if (timeOutMilliseconds != 0)
  13466. waitForThreadToExit (timeOutMilliseconds);
  13467. if (isThreadRunning())
  13468. {
  13469. // very bad karma if this point is reached, as there are bound to be
  13470. // locks and events left in silly states when a thread is killed by force..
  13471. jassertfalse;
  13472. Logger::writeToLog ("!! killing thread by force !!");
  13473. killThread();
  13474. RunningThreadsList::getInstance().remove (this);
  13475. threadHandle_ = 0;
  13476. threadId_ = 0;
  13477. }
  13478. }
  13479. }
  13480. bool Thread::setPriority (const int priority)
  13481. {
  13482. const ScopedLock sl (startStopLock);
  13483. if (setThreadPriority (threadHandle_, priority))
  13484. {
  13485. threadPriority_ = priority;
  13486. return true;
  13487. }
  13488. return false;
  13489. }
  13490. bool Thread::setCurrentThreadPriority (const int priority)
  13491. {
  13492. return setThreadPriority (0, priority);
  13493. }
  13494. void Thread::setAffinityMask (const uint32 affinityMask)
  13495. {
  13496. affinityMask_ = affinityMask;
  13497. }
  13498. bool Thread::wait (const int timeOutMilliseconds) const
  13499. {
  13500. return defaultEvent_.wait (timeOutMilliseconds);
  13501. }
  13502. void Thread::notify() const
  13503. {
  13504. defaultEvent_.signal();
  13505. }
  13506. int Thread::getNumRunningThreads()
  13507. {
  13508. return RunningThreadsList::getInstance().size();
  13509. }
  13510. Thread* Thread::getCurrentThread()
  13511. {
  13512. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13513. }
  13514. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13515. {
  13516. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13517. }
  13518. END_JUCE_NAMESPACE
  13519. /*** End of inlined file: juce_Thread.cpp ***/
  13520. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13521. BEGIN_JUCE_NAMESPACE
  13522. ThreadPoolJob::ThreadPoolJob (const String& name)
  13523. : jobName (name),
  13524. pool (0),
  13525. shouldStop (false),
  13526. isActive (false),
  13527. shouldBeDeleted (false)
  13528. {
  13529. }
  13530. ThreadPoolJob::~ThreadPoolJob()
  13531. {
  13532. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13533. // to remove it first!
  13534. jassert (pool == 0 || ! pool->contains (this));
  13535. }
  13536. const String ThreadPoolJob::getJobName() const
  13537. {
  13538. return jobName;
  13539. }
  13540. void ThreadPoolJob::setJobName (const String& newName)
  13541. {
  13542. jobName = newName;
  13543. }
  13544. void ThreadPoolJob::signalJobShouldExit()
  13545. {
  13546. shouldStop = true;
  13547. }
  13548. class ThreadPool::ThreadPoolThread : public Thread
  13549. {
  13550. public:
  13551. ThreadPoolThread (ThreadPool& pool_)
  13552. : Thread ("Pool"),
  13553. pool (pool_),
  13554. busy (false)
  13555. {
  13556. }
  13557. void run()
  13558. {
  13559. while (! threadShouldExit())
  13560. {
  13561. if (! pool.runNextJob())
  13562. wait (500);
  13563. }
  13564. }
  13565. private:
  13566. ThreadPool& pool;
  13567. bool volatile busy;
  13568. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13569. };
  13570. ThreadPool::ThreadPool (const int numThreads,
  13571. const bool startThreadsOnlyWhenNeeded,
  13572. const int stopThreadsWhenNotUsedTimeoutMs)
  13573. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13574. priority (5)
  13575. {
  13576. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13577. for (int i = jmax (1, numThreads); --i >= 0;)
  13578. threads.add (new ThreadPoolThread (*this));
  13579. if (! startThreadsOnlyWhenNeeded)
  13580. for (int i = threads.size(); --i >= 0;)
  13581. threads.getUnchecked(i)->startThread (priority);
  13582. }
  13583. ThreadPool::~ThreadPool()
  13584. {
  13585. removeAllJobs (true, 4000);
  13586. int i;
  13587. for (i = threads.size(); --i >= 0;)
  13588. threads.getUnchecked(i)->signalThreadShouldExit();
  13589. for (i = threads.size(); --i >= 0;)
  13590. threads.getUnchecked(i)->stopThread (500);
  13591. }
  13592. void ThreadPool::addJob (ThreadPoolJob* const job)
  13593. {
  13594. jassert (job != 0);
  13595. jassert (job->pool == 0);
  13596. if (job->pool == 0)
  13597. {
  13598. job->pool = this;
  13599. job->shouldStop = false;
  13600. job->isActive = false;
  13601. {
  13602. const ScopedLock sl (lock);
  13603. jobs.add (job);
  13604. int numRunning = 0;
  13605. for (int i = threads.size(); --i >= 0;)
  13606. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13607. ++numRunning;
  13608. if (numRunning < threads.size())
  13609. {
  13610. bool startedOne = false;
  13611. int n = 1000;
  13612. while (--n >= 0 && ! startedOne)
  13613. {
  13614. for (int i = threads.size(); --i >= 0;)
  13615. {
  13616. if (! threads.getUnchecked(i)->isThreadRunning())
  13617. {
  13618. threads.getUnchecked(i)->startThread (priority);
  13619. startedOne = true;
  13620. break;
  13621. }
  13622. }
  13623. if (! startedOne)
  13624. Thread::sleep (2);
  13625. }
  13626. }
  13627. }
  13628. for (int i = threads.size(); --i >= 0;)
  13629. threads.getUnchecked(i)->notify();
  13630. }
  13631. }
  13632. int ThreadPool::getNumJobs() const
  13633. {
  13634. return jobs.size();
  13635. }
  13636. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13637. {
  13638. const ScopedLock sl (lock);
  13639. return jobs [index];
  13640. }
  13641. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13642. {
  13643. const ScopedLock sl (lock);
  13644. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13645. }
  13646. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13647. {
  13648. const ScopedLock sl (lock);
  13649. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13650. }
  13651. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13652. const int timeOutMs) const
  13653. {
  13654. if (job != 0)
  13655. {
  13656. const uint32 start = Time::getMillisecondCounter();
  13657. while (contains (job))
  13658. {
  13659. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13660. return false;
  13661. jobFinishedSignal.wait (2);
  13662. }
  13663. }
  13664. return true;
  13665. }
  13666. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13667. const bool interruptIfRunning,
  13668. const int timeOutMs)
  13669. {
  13670. bool dontWait = true;
  13671. if (job != 0)
  13672. {
  13673. const ScopedLock sl (lock);
  13674. if (jobs.contains (job))
  13675. {
  13676. if (job->isActive)
  13677. {
  13678. if (interruptIfRunning)
  13679. job->signalJobShouldExit();
  13680. dontWait = false;
  13681. }
  13682. else
  13683. {
  13684. jobs.removeValue (job);
  13685. job->pool = 0;
  13686. }
  13687. }
  13688. }
  13689. return dontWait || waitForJobToFinish (job, timeOutMs);
  13690. }
  13691. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13692. const int timeOutMs,
  13693. const bool deleteInactiveJobs,
  13694. ThreadPool::JobSelector* selectedJobsToRemove)
  13695. {
  13696. Array <ThreadPoolJob*> jobsToWaitFor;
  13697. {
  13698. const ScopedLock sl (lock);
  13699. for (int i = jobs.size(); --i >= 0;)
  13700. {
  13701. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13702. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13703. {
  13704. if (job->isActive)
  13705. {
  13706. jobsToWaitFor.add (job);
  13707. if (interruptRunningJobs)
  13708. job->signalJobShouldExit();
  13709. }
  13710. else
  13711. {
  13712. jobs.remove (i);
  13713. if (deleteInactiveJobs)
  13714. delete job;
  13715. else
  13716. job->pool = 0;
  13717. }
  13718. }
  13719. }
  13720. }
  13721. const uint32 start = Time::getMillisecondCounter();
  13722. for (;;)
  13723. {
  13724. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13725. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13726. jobsToWaitFor.remove (i);
  13727. if (jobsToWaitFor.size() == 0)
  13728. break;
  13729. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13730. return false;
  13731. jobFinishedSignal.wait (20);
  13732. }
  13733. return true;
  13734. }
  13735. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13736. {
  13737. StringArray s;
  13738. const ScopedLock sl (lock);
  13739. for (int i = 0; i < jobs.size(); ++i)
  13740. {
  13741. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13742. if (job->isActive || ! onlyReturnActiveJobs)
  13743. s.add (job->getJobName());
  13744. }
  13745. return s;
  13746. }
  13747. bool ThreadPool::setThreadPriorities (const int newPriority)
  13748. {
  13749. bool ok = true;
  13750. if (priority != newPriority)
  13751. {
  13752. priority = newPriority;
  13753. for (int i = threads.size(); --i >= 0;)
  13754. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13755. ok = false;
  13756. }
  13757. return ok;
  13758. }
  13759. bool ThreadPool::runNextJob()
  13760. {
  13761. ThreadPoolJob* job = 0;
  13762. {
  13763. const ScopedLock sl (lock);
  13764. for (int i = 0; i < jobs.size(); ++i)
  13765. {
  13766. job = jobs[i];
  13767. if (job != 0 && ! (job->isActive || job->shouldStop))
  13768. break;
  13769. job = 0;
  13770. }
  13771. if (job != 0)
  13772. job->isActive = true;
  13773. }
  13774. if (job != 0)
  13775. {
  13776. JUCE_TRY
  13777. {
  13778. ThreadPoolJob::JobStatus result = job->runJob();
  13779. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13780. const ScopedLock sl (lock);
  13781. if (jobs.contains (job))
  13782. {
  13783. job->isActive = false;
  13784. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13785. {
  13786. job->pool = 0;
  13787. job->shouldStop = true;
  13788. jobs.removeValue (job);
  13789. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13790. delete job;
  13791. jobFinishedSignal.signal();
  13792. }
  13793. else
  13794. {
  13795. // move the job to the end of the queue if it wants another go
  13796. jobs.move (jobs.indexOf (job), -1);
  13797. }
  13798. }
  13799. }
  13800. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13801. catch (...)
  13802. {
  13803. const ScopedLock sl (lock);
  13804. jobs.removeValue (job);
  13805. }
  13806. #endif
  13807. }
  13808. else
  13809. {
  13810. if (threadStopTimeout > 0
  13811. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13812. {
  13813. const ScopedLock sl (lock);
  13814. if (jobs.size() == 0)
  13815. for (int i = threads.size(); --i >= 0;)
  13816. threads.getUnchecked(i)->signalThreadShouldExit();
  13817. }
  13818. else
  13819. {
  13820. return false;
  13821. }
  13822. }
  13823. return true;
  13824. }
  13825. END_JUCE_NAMESPACE
  13826. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13827. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13828. BEGIN_JUCE_NAMESPACE
  13829. TimeSliceThread::TimeSliceThread (const String& threadName)
  13830. : Thread (threadName),
  13831. index (0),
  13832. clientBeingCalled (0),
  13833. clientsChanged (false)
  13834. {
  13835. }
  13836. TimeSliceThread::~TimeSliceThread()
  13837. {
  13838. stopThread (2000);
  13839. }
  13840. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  13841. {
  13842. const ScopedLock sl (listLock);
  13843. clients.addIfNotAlreadyThere (client);
  13844. clientsChanged = true;
  13845. notify();
  13846. }
  13847. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13848. {
  13849. const ScopedLock sl1 (listLock);
  13850. clientsChanged = true;
  13851. // if there's a chance we're in the middle of calling this client, we need to
  13852. // also lock the outer lock..
  13853. if (clientBeingCalled == client)
  13854. {
  13855. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13856. const ScopedLock sl2 (callbackLock);
  13857. const ScopedLock sl3 (listLock);
  13858. clients.removeValue (client);
  13859. }
  13860. else
  13861. {
  13862. clients.removeValue (client);
  13863. }
  13864. }
  13865. int TimeSliceThread::getNumClients() const
  13866. {
  13867. return clients.size();
  13868. }
  13869. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13870. {
  13871. const ScopedLock sl (listLock);
  13872. return clients [i];
  13873. }
  13874. void TimeSliceThread::run()
  13875. {
  13876. int numCallsSinceBusy = 0;
  13877. while (! threadShouldExit())
  13878. {
  13879. int timeToWait = 500;
  13880. {
  13881. const ScopedLock sl (callbackLock);
  13882. {
  13883. const ScopedLock sl2 (listLock);
  13884. if (clients.size() > 0)
  13885. {
  13886. index = (index + 1) % clients.size();
  13887. clientBeingCalled = clients [index];
  13888. }
  13889. else
  13890. {
  13891. index = 0;
  13892. clientBeingCalled = 0;
  13893. }
  13894. if (clientsChanged)
  13895. {
  13896. clientsChanged = false;
  13897. numCallsSinceBusy = 0;
  13898. }
  13899. }
  13900. if (clientBeingCalled != 0)
  13901. {
  13902. if (clientBeingCalled->useTimeSlice())
  13903. numCallsSinceBusy = 0;
  13904. else
  13905. ++numCallsSinceBusy;
  13906. if (numCallsSinceBusy >= clients.size())
  13907. timeToWait = 500;
  13908. else if (index == 0)
  13909. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  13910. else
  13911. timeToWait = 0;
  13912. }
  13913. }
  13914. if (timeToWait > 0)
  13915. wait (timeToWait);
  13916. }
  13917. }
  13918. END_JUCE_NAMESPACE
  13919. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13920. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  13921. BEGIN_JUCE_NAMESPACE
  13922. DeletedAtShutdown::DeletedAtShutdown()
  13923. {
  13924. const ScopedLock sl (getLock());
  13925. getObjects().add (this);
  13926. }
  13927. DeletedAtShutdown::~DeletedAtShutdown()
  13928. {
  13929. const ScopedLock sl (getLock());
  13930. getObjects().removeValue (this);
  13931. }
  13932. void DeletedAtShutdown::deleteAll()
  13933. {
  13934. // make a local copy of the array, so it can't get into a loop if something
  13935. // creates another DeletedAtShutdown object during its destructor.
  13936. Array <DeletedAtShutdown*> localCopy;
  13937. {
  13938. const ScopedLock sl (getLock());
  13939. localCopy = getObjects();
  13940. }
  13941. for (int i = localCopy.size(); --i >= 0;)
  13942. {
  13943. JUCE_TRY
  13944. {
  13945. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  13946. // double-check that it's not already been deleted during another object's destructor.
  13947. {
  13948. const ScopedLock sl (getLock());
  13949. if (! getObjects().contains (deletee))
  13950. deletee = 0;
  13951. }
  13952. delete deletee;
  13953. }
  13954. JUCE_CATCH_EXCEPTION
  13955. }
  13956. // if no objects got re-created during shutdown, this should have been emptied by their
  13957. // destructors
  13958. jassert (getObjects().size() == 0);
  13959. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  13960. }
  13961. CriticalSection& DeletedAtShutdown::getLock()
  13962. {
  13963. static CriticalSection lock;
  13964. return lock;
  13965. }
  13966. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  13967. {
  13968. static Array <DeletedAtShutdown*> objects;
  13969. return objects;
  13970. }
  13971. END_JUCE_NAMESPACE
  13972. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  13973. /*** Start of inlined file: juce_UnitTest.cpp ***/
  13974. BEGIN_JUCE_NAMESPACE
  13975. UnitTest::UnitTest (const String& name_)
  13976. : name (name_), runner (0)
  13977. {
  13978. getAllTests().add (this);
  13979. }
  13980. UnitTest::~UnitTest()
  13981. {
  13982. getAllTests().removeValue (this);
  13983. }
  13984. Array<UnitTest*>& UnitTest::getAllTests()
  13985. {
  13986. static Array<UnitTest*> tests;
  13987. return tests;
  13988. }
  13989. void UnitTest::initialise() {}
  13990. void UnitTest::shutdown() {}
  13991. void UnitTest::performTest (UnitTestRunner* const runner_)
  13992. {
  13993. jassert (runner_ != 0);
  13994. runner = runner_;
  13995. initialise();
  13996. runTest();
  13997. shutdown();
  13998. }
  13999. void UnitTest::logMessage (const String& message)
  14000. {
  14001. runner->logMessage (message);
  14002. }
  14003. void UnitTest::beginTest (const String& testName)
  14004. {
  14005. runner->beginNewTest (this, testName);
  14006. }
  14007. void UnitTest::expect (const bool result, const String& failureMessage)
  14008. {
  14009. if (result)
  14010. runner->addPass();
  14011. else
  14012. runner->addFail (failureMessage);
  14013. }
  14014. UnitTestRunner::UnitTestRunner()
  14015. : currentTest (0), assertOnFailure (false)
  14016. {
  14017. }
  14018. UnitTestRunner::~UnitTestRunner()
  14019. {
  14020. }
  14021. int UnitTestRunner::getNumResults() const throw()
  14022. {
  14023. return results.size();
  14024. }
  14025. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14026. {
  14027. return results [index];
  14028. }
  14029. void UnitTestRunner::resultsUpdated()
  14030. {
  14031. }
  14032. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14033. {
  14034. results.clear();
  14035. assertOnFailure = assertOnFailure_;
  14036. resultsUpdated();
  14037. for (int i = 0; i < tests.size(); ++i)
  14038. {
  14039. try
  14040. {
  14041. tests.getUnchecked(i)->performTest (this);
  14042. }
  14043. catch (...)
  14044. {
  14045. addFail ("An unhandled exception was thrown!");
  14046. }
  14047. }
  14048. endTest();
  14049. }
  14050. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14051. {
  14052. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14053. }
  14054. void UnitTestRunner::logMessage (const String& message)
  14055. {
  14056. Logger::writeToLog (message);
  14057. }
  14058. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14059. {
  14060. endTest();
  14061. currentTest = test;
  14062. TestResult* const r = new TestResult();
  14063. r->unitTestName = test->getName();
  14064. r->subcategoryName = subCategory;
  14065. r->passes = 0;
  14066. r->failures = 0;
  14067. results.add (r);
  14068. logMessage ("-----------------------------------------------------------------");
  14069. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14070. resultsUpdated();
  14071. }
  14072. void UnitTestRunner::endTest()
  14073. {
  14074. if (results.size() > 0)
  14075. {
  14076. TestResult* const r = results.getLast();
  14077. if (r->failures > 0)
  14078. {
  14079. String m ("FAILED!!");
  14080. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14081. << " failed, out of a total of " << (r->passes + r->failures);
  14082. logMessage (String::empty);
  14083. logMessage (m);
  14084. logMessage (String::empty);
  14085. }
  14086. else
  14087. {
  14088. logMessage ("All tests completed successfully");
  14089. }
  14090. }
  14091. }
  14092. void UnitTestRunner::addPass()
  14093. {
  14094. {
  14095. const ScopedLock sl (results.getLock());
  14096. TestResult* const r = results.getLast();
  14097. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14098. r->passes++;
  14099. String message ("Test ");
  14100. message << (r->failures + r->passes) << " passed";
  14101. logMessage (message);
  14102. }
  14103. resultsUpdated();
  14104. }
  14105. void UnitTestRunner::addFail (const String& failureMessage)
  14106. {
  14107. {
  14108. const ScopedLock sl (results.getLock());
  14109. TestResult* const r = results.getLast();
  14110. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14111. r->failures++;
  14112. String message ("!!! Test ");
  14113. message << (r->failures + r->passes) << " failed";
  14114. if (failureMessage.isNotEmpty())
  14115. message << ": " << failureMessage;
  14116. r->messages.add (message);
  14117. logMessage (message);
  14118. }
  14119. resultsUpdated();
  14120. if (assertOnFailure) { jassertfalse }
  14121. }
  14122. END_JUCE_NAMESPACE
  14123. /*** End of inlined file: juce_UnitTest.cpp ***/
  14124. #endif
  14125. #if JUCE_BUILD_MISC
  14126. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14127. BEGIN_JUCE_NAMESPACE
  14128. class ValueTree::SetPropertyAction : public UndoableAction
  14129. {
  14130. public:
  14131. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14132. const var& newValue_, const var& oldValue_,
  14133. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14134. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14135. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14136. {
  14137. }
  14138. bool perform()
  14139. {
  14140. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14141. if (isDeletingProperty)
  14142. target->removeProperty (name, 0);
  14143. else
  14144. target->setProperty (name, newValue, 0);
  14145. return true;
  14146. }
  14147. bool undo()
  14148. {
  14149. if (isAddingNewProperty)
  14150. target->removeProperty (name, 0);
  14151. else
  14152. target->setProperty (name, oldValue, 0);
  14153. return true;
  14154. }
  14155. int getSizeInUnits()
  14156. {
  14157. return (int) sizeof (*this); //xxx should be more accurate
  14158. }
  14159. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14160. {
  14161. if (! (isAddingNewProperty || isDeletingProperty))
  14162. {
  14163. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14164. if (next != 0 && next->target == target && next->name == name
  14165. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14166. {
  14167. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14168. }
  14169. }
  14170. return 0;
  14171. }
  14172. private:
  14173. const SharedObjectPtr target;
  14174. const Identifier name;
  14175. const var newValue;
  14176. var oldValue;
  14177. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14178. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  14179. };
  14180. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14181. {
  14182. public:
  14183. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14184. const SharedObjectPtr& newChild_)
  14185. : target (target_),
  14186. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14187. childIndex (childIndex_),
  14188. isDeleting (newChild_ == 0)
  14189. {
  14190. jassert (child != 0);
  14191. }
  14192. bool perform()
  14193. {
  14194. if (isDeleting)
  14195. target->removeChild (childIndex, 0);
  14196. else
  14197. target->addChild (child, childIndex, 0);
  14198. return true;
  14199. }
  14200. bool undo()
  14201. {
  14202. if (isDeleting)
  14203. {
  14204. target->addChild (child, childIndex, 0);
  14205. }
  14206. else
  14207. {
  14208. // If you hit this, it seems that your object's state is getting confused - probably
  14209. // because you've interleaved some undoable and non-undoable operations?
  14210. jassert (childIndex < target->children.size());
  14211. target->removeChild (childIndex, 0);
  14212. }
  14213. return true;
  14214. }
  14215. int getSizeInUnits()
  14216. {
  14217. return (int) sizeof (*this); //xxx should be more accurate
  14218. }
  14219. private:
  14220. const SharedObjectPtr target, child;
  14221. const int childIndex;
  14222. const bool isDeleting;
  14223. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  14224. };
  14225. class ValueTree::MoveChildAction : public UndoableAction
  14226. {
  14227. public:
  14228. MoveChildAction (const SharedObjectPtr& parent_,
  14229. const int startIndex_, const int endIndex_)
  14230. : parent (parent_),
  14231. startIndex (startIndex_),
  14232. endIndex (endIndex_)
  14233. {
  14234. }
  14235. bool perform()
  14236. {
  14237. parent->moveChild (startIndex, endIndex, 0);
  14238. return true;
  14239. }
  14240. bool undo()
  14241. {
  14242. parent->moveChild (endIndex, startIndex, 0);
  14243. return true;
  14244. }
  14245. int getSizeInUnits()
  14246. {
  14247. return (int) sizeof (*this); //xxx should be more accurate
  14248. }
  14249. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14250. {
  14251. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14252. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14253. return new MoveChildAction (parent, startIndex, next->endIndex);
  14254. return 0;
  14255. }
  14256. private:
  14257. const SharedObjectPtr parent;
  14258. const int startIndex, endIndex;
  14259. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  14260. };
  14261. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14262. : type (type_), parent (0)
  14263. {
  14264. }
  14265. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14266. : type (other.type), properties (other.properties), parent (0)
  14267. {
  14268. for (int i = 0; i < other.children.size(); ++i)
  14269. {
  14270. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14271. child->parent = this;
  14272. children.add (child);
  14273. }
  14274. }
  14275. ValueTree::SharedObject::~SharedObject()
  14276. {
  14277. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14278. for (int i = children.size(); --i >= 0;)
  14279. {
  14280. const SharedObjectPtr c (children.getUnchecked(i));
  14281. c->parent = 0;
  14282. children.remove (i);
  14283. c->sendParentChangeMessage();
  14284. }
  14285. }
  14286. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14287. {
  14288. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14289. {
  14290. ValueTree* const v = valueTreesWithListeners[i];
  14291. if (v != 0)
  14292. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14293. }
  14294. }
  14295. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14296. {
  14297. ValueTree tree (this);
  14298. ValueTree::SharedObject* t = this;
  14299. while (t != 0)
  14300. {
  14301. t->sendPropertyChangeMessage (tree, property);
  14302. t = t->parent;
  14303. }
  14304. }
  14305. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14306. {
  14307. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14308. {
  14309. ValueTree* const v = valueTreesWithListeners[i];
  14310. if (v != 0)
  14311. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14312. }
  14313. }
  14314. void ValueTree::SharedObject::sendChildChangeMessage()
  14315. {
  14316. ValueTree tree (this);
  14317. ValueTree::SharedObject* t = this;
  14318. while (t != 0)
  14319. {
  14320. t->sendChildChangeMessage (tree);
  14321. t = t->parent;
  14322. }
  14323. }
  14324. void ValueTree::SharedObject::sendParentChangeMessage()
  14325. {
  14326. ValueTree tree (this);
  14327. int i;
  14328. for (i = children.size(); --i >= 0;)
  14329. {
  14330. SharedObject* const t = children[i];
  14331. if (t != 0)
  14332. t->sendParentChangeMessage();
  14333. }
  14334. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14335. {
  14336. ValueTree* const v = valueTreesWithListeners[i];
  14337. if (v != 0)
  14338. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14339. }
  14340. }
  14341. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14342. {
  14343. return properties [name];
  14344. }
  14345. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14346. {
  14347. return properties.getWithDefault (name, defaultReturnValue);
  14348. }
  14349. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14350. {
  14351. if (undoManager == 0)
  14352. {
  14353. if (properties.set (name, newValue))
  14354. sendPropertyChangeMessage (name);
  14355. }
  14356. else
  14357. {
  14358. var* const existingValue = properties.getVarPointer (name);
  14359. if (existingValue != 0)
  14360. {
  14361. if (*existingValue != newValue)
  14362. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14363. }
  14364. else
  14365. {
  14366. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14367. }
  14368. }
  14369. }
  14370. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14371. {
  14372. return properties.contains (name);
  14373. }
  14374. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14375. {
  14376. if (undoManager == 0)
  14377. {
  14378. if (properties.remove (name))
  14379. sendPropertyChangeMessage (name);
  14380. }
  14381. else
  14382. {
  14383. if (properties.contains (name))
  14384. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14385. }
  14386. }
  14387. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14388. {
  14389. if (undoManager == 0)
  14390. {
  14391. while (properties.size() > 0)
  14392. {
  14393. const Identifier name (properties.getName (properties.size() - 1));
  14394. properties.remove (name);
  14395. sendPropertyChangeMessage (name);
  14396. }
  14397. }
  14398. else
  14399. {
  14400. for (int i = properties.size(); --i >= 0;)
  14401. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14402. }
  14403. }
  14404. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14405. {
  14406. for (int i = 0; i < children.size(); ++i)
  14407. if (children.getUnchecked(i)->type == typeToMatch)
  14408. return ValueTree (children.getUnchecked(i).getObject());
  14409. return ValueTree::invalid;
  14410. }
  14411. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14412. {
  14413. for (int i = 0; i < children.size(); ++i)
  14414. if (children.getUnchecked(i)->type == typeToMatch)
  14415. return ValueTree (children.getUnchecked(i).getObject());
  14416. SharedObject* const newObject = new SharedObject (typeToMatch);
  14417. addChild (newObject, -1, undoManager);
  14418. return ValueTree (newObject);
  14419. }
  14420. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14421. {
  14422. for (int i = 0; i < children.size(); ++i)
  14423. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14424. return ValueTree (children.getUnchecked(i).getObject());
  14425. return ValueTree::invalid;
  14426. }
  14427. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14428. {
  14429. const SharedObject* p = parent;
  14430. while (p != 0)
  14431. {
  14432. if (p == possibleParent)
  14433. return true;
  14434. p = p->parent;
  14435. }
  14436. return false;
  14437. }
  14438. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14439. {
  14440. return children.indexOf (child.object);
  14441. }
  14442. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14443. {
  14444. if (child != 0 && child->parent != this)
  14445. {
  14446. if (child != this && ! isAChildOf (child))
  14447. {
  14448. // You should always make sure that a child is removed from its previous parent before
  14449. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14450. // undomanager should be used when removing it from its current parent..
  14451. jassert (child->parent == 0);
  14452. if (child->parent != 0)
  14453. {
  14454. jassert (child->parent->children.indexOf (child) >= 0);
  14455. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14456. }
  14457. if (undoManager == 0)
  14458. {
  14459. children.insert (index, child);
  14460. child->parent = this;
  14461. sendChildChangeMessage();
  14462. child->sendParentChangeMessage();
  14463. }
  14464. else
  14465. {
  14466. if (index < 0)
  14467. index = children.size();
  14468. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14469. }
  14470. }
  14471. else
  14472. {
  14473. // You're attempting to create a recursive loop! A node
  14474. // can't be a child of one of its own children!
  14475. jassertfalse;
  14476. }
  14477. }
  14478. }
  14479. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14480. {
  14481. const SharedObjectPtr child (children [childIndex]);
  14482. if (child != 0)
  14483. {
  14484. if (undoManager == 0)
  14485. {
  14486. children.remove (childIndex);
  14487. child->parent = 0;
  14488. sendChildChangeMessage();
  14489. child->sendParentChangeMessage();
  14490. }
  14491. else
  14492. {
  14493. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14494. }
  14495. }
  14496. }
  14497. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14498. {
  14499. while (children.size() > 0)
  14500. removeChild (children.size() - 1, undoManager);
  14501. }
  14502. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14503. {
  14504. // The source index must be a valid index!
  14505. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14506. if (currentIndex != newIndex
  14507. && isPositiveAndBelow (currentIndex, children.size()))
  14508. {
  14509. if (undoManager == 0)
  14510. {
  14511. children.move (currentIndex, newIndex);
  14512. sendChildChangeMessage();
  14513. }
  14514. else
  14515. {
  14516. if (! isPositiveAndBelow (newIndex, children.size()))
  14517. newIndex = children.size() - 1;
  14518. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14519. }
  14520. }
  14521. }
  14522. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14523. {
  14524. jassert (newOrder.size() == children.size());
  14525. if (undoManager == 0)
  14526. {
  14527. children = newOrder;
  14528. sendChildChangeMessage();
  14529. }
  14530. else
  14531. {
  14532. for (int i = 0; i < children.size(); ++i)
  14533. {
  14534. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14535. {
  14536. jassert (children.contains (newOrder.getUnchecked(i)));
  14537. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14538. }
  14539. }
  14540. }
  14541. }
  14542. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14543. {
  14544. if (type != other.type
  14545. || properties.size() != other.properties.size()
  14546. || children.size() != other.children.size()
  14547. || properties != other.properties)
  14548. return false;
  14549. for (int i = 0; i < children.size(); ++i)
  14550. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14551. return false;
  14552. return true;
  14553. }
  14554. ValueTree::ValueTree() throw()
  14555. : object (0)
  14556. {
  14557. }
  14558. const ValueTree ValueTree::invalid;
  14559. ValueTree::ValueTree (const Identifier& type_)
  14560. : object (new ValueTree::SharedObject (type_))
  14561. {
  14562. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14563. }
  14564. ValueTree::ValueTree (SharedObject* const object_)
  14565. : object (object_)
  14566. {
  14567. }
  14568. ValueTree::ValueTree (const ValueTree& other)
  14569. : object (other.object)
  14570. {
  14571. }
  14572. ValueTree& ValueTree::operator= (const ValueTree& other)
  14573. {
  14574. if (listeners.size() > 0)
  14575. {
  14576. if (object != 0)
  14577. object->valueTreesWithListeners.removeValue (this);
  14578. if (other.object != 0)
  14579. other.object->valueTreesWithListeners.add (this);
  14580. }
  14581. object = other.object;
  14582. return *this;
  14583. }
  14584. ValueTree::~ValueTree()
  14585. {
  14586. if (listeners.size() > 0 && object != 0)
  14587. object->valueTreesWithListeners.removeValue (this);
  14588. }
  14589. bool ValueTree::operator== (const ValueTree& other) const throw()
  14590. {
  14591. return object == other.object;
  14592. }
  14593. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14594. {
  14595. return object != other.object;
  14596. }
  14597. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14598. {
  14599. return object == other.object
  14600. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14601. }
  14602. ValueTree ValueTree::createCopy() const
  14603. {
  14604. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14605. }
  14606. bool ValueTree::hasType (const Identifier& typeName) const
  14607. {
  14608. return object != 0 && object->type == typeName;
  14609. }
  14610. const Identifier ValueTree::getType() const
  14611. {
  14612. return object != 0 ? object->type : Identifier();
  14613. }
  14614. ValueTree ValueTree::getParent() const
  14615. {
  14616. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14617. }
  14618. ValueTree ValueTree::getSibling (const int delta) const
  14619. {
  14620. if (object == 0 || object->parent == 0)
  14621. return invalid;
  14622. const int index = object->parent->indexOf (*this) + delta;
  14623. return ValueTree (object->parent->children [index].getObject());
  14624. }
  14625. const var& ValueTree::operator[] (const Identifier& name) const
  14626. {
  14627. return object == 0 ? var::null : object->getProperty (name);
  14628. }
  14629. const var& ValueTree::getProperty (const Identifier& name) const
  14630. {
  14631. return object == 0 ? var::null : object->getProperty (name);
  14632. }
  14633. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14634. {
  14635. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14636. }
  14637. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14638. {
  14639. jassert (name.toString().isNotEmpty());
  14640. if (object != 0 && name.toString().isNotEmpty())
  14641. object->setProperty (name, newValue, undoManager);
  14642. }
  14643. bool ValueTree::hasProperty (const Identifier& name) const
  14644. {
  14645. return object != 0 && object->hasProperty (name);
  14646. }
  14647. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14648. {
  14649. if (object != 0)
  14650. object->removeProperty (name, undoManager);
  14651. }
  14652. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14653. {
  14654. if (object != 0)
  14655. object->removeAllProperties (undoManager);
  14656. }
  14657. int ValueTree::getNumProperties() const
  14658. {
  14659. return object == 0 ? 0 : object->properties.size();
  14660. }
  14661. const Identifier ValueTree::getPropertyName (const int index) const
  14662. {
  14663. return object == 0 ? Identifier()
  14664. : object->properties.getName (index);
  14665. }
  14666. class ValueTreePropertyValueSource : public Value::ValueSource,
  14667. public ValueTree::Listener
  14668. {
  14669. public:
  14670. ValueTreePropertyValueSource (const ValueTree& tree_,
  14671. const Identifier& property_,
  14672. UndoManager* const undoManager_)
  14673. : tree (tree_),
  14674. property (property_),
  14675. undoManager (undoManager_)
  14676. {
  14677. tree.addListener (this);
  14678. }
  14679. ~ValueTreePropertyValueSource()
  14680. {
  14681. tree.removeListener (this);
  14682. }
  14683. const var getValue() const
  14684. {
  14685. return tree [property];
  14686. }
  14687. void setValue (const var& newValue)
  14688. {
  14689. tree.setProperty (property, newValue, undoManager);
  14690. }
  14691. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14692. {
  14693. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14694. sendChangeMessage (false);
  14695. }
  14696. void valueTreeChildrenChanged (ValueTree&) {}
  14697. void valueTreeParentChanged (ValueTree&) {}
  14698. private:
  14699. ValueTree tree;
  14700. const Identifier property;
  14701. UndoManager* const undoManager;
  14702. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14703. };
  14704. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14705. {
  14706. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14707. }
  14708. int ValueTree::getNumChildren() const
  14709. {
  14710. return object == 0 ? 0 : object->children.size();
  14711. }
  14712. ValueTree ValueTree::getChild (int index) const
  14713. {
  14714. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14715. }
  14716. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14717. {
  14718. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14719. }
  14720. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14721. {
  14722. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14723. }
  14724. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14725. {
  14726. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14727. }
  14728. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14729. {
  14730. return object != 0 && object->isAChildOf (possibleParent.object);
  14731. }
  14732. int ValueTree::indexOf (const ValueTree& child) const
  14733. {
  14734. return object != 0 ? object->indexOf (child) : -1;
  14735. }
  14736. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14737. {
  14738. if (object != 0)
  14739. object->addChild (child.object, index, undoManager);
  14740. }
  14741. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14742. {
  14743. if (object != 0)
  14744. object->removeChild (childIndex, undoManager);
  14745. }
  14746. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14747. {
  14748. if (object != 0)
  14749. object->removeChild (object->children.indexOf (child.object), undoManager);
  14750. }
  14751. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14752. {
  14753. if (object != 0)
  14754. object->removeAllChildren (undoManager);
  14755. }
  14756. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14757. {
  14758. if (object != 0)
  14759. object->moveChild (currentIndex, newIndex, undoManager);
  14760. }
  14761. void ValueTree::addListener (Listener* listener)
  14762. {
  14763. if (listener != 0)
  14764. {
  14765. if (listeners.size() == 0 && object != 0)
  14766. object->valueTreesWithListeners.add (this);
  14767. listeners.add (listener);
  14768. }
  14769. }
  14770. void ValueTree::removeListener (Listener* listener)
  14771. {
  14772. listeners.remove (listener);
  14773. if (listeners.size() == 0 && object != 0)
  14774. object->valueTreesWithListeners.removeValue (this);
  14775. }
  14776. XmlElement* ValueTree::SharedObject::createXml() const
  14777. {
  14778. XmlElement* const xml = new XmlElement (type.toString());
  14779. properties.copyToXmlAttributes (*xml);
  14780. for (int i = 0; i < children.size(); ++i)
  14781. xml->addChildElement (children.getUnchecked(i)->createXml());
  14782. return xml;
  14783. }
  14784. XmlElement* ValueTree::createXml() const
  14785. {
  14786. return object != 0 ? object->createXml() : 0;
  14787. }
  14788. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14789. {
  14790. ValueTree v (xml.getTagName());
  14791. v.object->properties.setFromXmlAttributes (xml);
  14792. forEachXmlChildElement (xml, e)
  14793. v.addChild (fromXml (*e), -1, 0);
  14794. return v;
  14795. }
  14796. void ValueTree::writeToStream (OutputStream& output)
  14797. {
  14798. output.writeString (getType().toString());
  14799. const int numProps = getNumProperties();
  14800. output.writeCompressedInt (numProps);
  14801. int i;
  14802. for (i = 0; i < numProps; ++i)
  14803. {
  14804. const Identifier name (getPropertyName(i));
  14805. output.writeString (name.toString());
  14806. getProperty(name).writeToStream (output);
  14807. }
  14808. const int numChildren = getNumChildren();
  14809. output.writeCompressedInt (numChildren);
  14810. for (i = 0; i < numChildren; ++i)
  14811. getChild (i).writeToStream (output);
  14812. }
  14813. ValueTree ValueTree::readFromStream (InputStream& input)
  14814. {
  14815. const String type (input.readString());
  14816. if (type.isEmpty())
  14817. return ValueTree::invalid;
  14818. ValueTree v (type);
  14819. const int numProps = input.readCompressedInt();
  14820. if (numProps < 0)
  14821. {
  14822. jassertfalse; // trying to read corrupted data!
  14823. return v;
  14824. }
  14825. int i;
  14826. for (i = 0; i < numProps; ++i)
  14827. {
  14828. const String name (input.readString());
  14829. jassert (name.isNotEmpty());
  14830. const var value (var::readFromStream (input));
  14831. v.object->properties.set (name, value);
  14832. }
  14833. const int numChildren = input.readCompressedInt();
  14834. for (i = 0; i < numChildren; ++i)
  14835. {
  14836. ValueTree child (readFromStream (input));
  14837. v.object->children.add (child.object);
  14838. child.object->parent = v.object;
  14839. }
  14840. return v;
  14841. }
  14842. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14843. {
  14844. MemoryInputStream in (data, numBytes, false);
  14845. return readFromStream (in);
  14846. }
  14847. END_JUCE_NAMESPACE
  14848. /*** End of inlined file: juce_ValueTree.cpp ***/
  14849. /*** Start of inlined file: juce_Value.cpp ***/
  14850. BEGIN_JUCE_NAMESPACE
  14851. Value::ValueSource::ValueSource()
  14852. {
  14853. }
  14854. Value::ValueSource::~ValueSource()
  14855. {
  14856. }
  14857. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14858. {
  14859. if (synchronous)
  14860. {
  14861. for (int i = valuesWithListeners.size(); --i >= 0;)
  14862. {
  14863. Value* const v = valuesWithListeners[i];
  14864. if (v != 0)
  14865. v->callListeners();
  14866. }
  14867. }
  14868. else
  14869. {
  14870. triggerAsyncUpdate();
  14871. }
  14872. }
  14873. void Value::ValueSource::handleAsyncUpdate()
  14874. {
  14875. sendChangeMessage (true);
  14876. }
  14877. class SimpleValueSource : public Value::ValueSource
  14878. {
  14879. public:
  14880. SimpleValueSource()
  14881. {
  14882. }
  14883. SimpleValueSource (const var& initialValue)
  14884. : value (initialValue)
  14885. {
  14886. }
  14887. ~SimpleValueSource()
  14888. {
  14889. }
  14890. const var getValue() const
  14891. {
  14892. return value;
  14893. }
  14894. void setValue (const var& newValue)
  14895. {
  14896. if (newValue != value)
  14897. {
  14898. value = newValue;
  14899. sendChangeMessage (false);
  14900. }
  14901. }
  14902. private:
  14903. var value;
  14904. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  14905. };
  14906. Value::Value()
  14907. : value (new SimpleValueSource())
  14908. {
  14909. }
  14910. Value::Value (ValueSource* const value_)
  14911. : value (value_)
  14912. {
  14913. jassert (value_ != 0);
  14914. }
  14915. Value::Value (const var& initialValue)
  14916. : value (new SimpleValueSource (initialValue))
  14917. {
  14918. }
  14919. Value::Value (const Value& other)
  14920. : value (other.value)
  14921. {
  14922. }
  14923. Value& Value::operator= (const Value& other)
  14924. {
  14925. value = other.value;
  14926. return *this;
  14927. }
  14928. Value::~Value()
  14929. {
  14930. if (listeners.size() > 0)
  14931. value->valuesWithListeners.removeValue (this);
  14932. }
  14933. const var Value::getValue() const
  14934. {
  14935. return value->getValue();
  14936. }
  14937. Value::operator const var() const
  14938. {
  14939. return getValue();
  14940. }
  14941. void Value::setValue (const var& newValue)
  14942. {
  14943. value->setValue (newValue);
  14944. }
  14945. const String Value::toString() const
  14946. {
  14947. return value->getValue().toString();
  14948. }
  14949. Value& Value::operator= (const var& newValue)
  14950. {
  14951. value->setValue (newValue);
  14952. return *this;
  14953. }
  14954. void Value::referTo (const Value& valueToReferTo)
  14955. {
  14956. if (valueToReferTo.value != value)
  14957. {
  14958. if (listeners.size() > 0)
  14959. {
  14960. value->valuesWithListeners.removeValue (this);
  14961. valueToReferTo.value->valuesWithListeners.add (this);
  14962. }
  14963. value = valueToReferTo.value;
  14964. callListeners();
  14965. }
  14966. }
  14967. bool Value::refersToSameSourceAs (const Value& other) const
  14968. {
  14969. return value == other.value;
  14970. }
  14971. bool Value::operator== (const Value& other) const
  14972. {
  14973. return value == other.value || value->getValue() == other.getValue();
  14974. }
  14975. bool Value::operator!= (const Value& other) const
  14976. {
  14977. return value != other.value && value->getValue() != other.getValue();
  14978. }
  14979. void Value::addListener (ValueListener* const listener)
  14980. {
  14981. if (listener != 0)
  14982. {
  14983. if (listeners.size() == 0)
  14984. value->valuesWithListeners.add (this);
  14985. listeners.add (listener);
  14986. }
  14987. }
  14988. void Value::removeListener (ValueListener* const listener)
  14989. {
  14990. listeners.remove (listener);
  14991. if (listeners.size() == 0)
  14992. value->valuesWithListeners.removeValue (this);
  14993. }
  14994. void Value::callListeners()
  14995. {
  14996. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14997. listeners.call (&ValueListener::valueChanged, v);
  14998. }
  14999. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15000. {
  15001. return stream << value.toString();
  15002. }
  15003. END_JUCE_NAMESPACE
  15004. /*** End of inlined file: juce_Value.cpp ***/
  15005. /*** Start of inlined file: juce_Application.cpp ***/
  15006. BEGIN_JUCE_NAMESPACE
  15007. #if JUCE_MAC
  15008. extern void juce_initialiseMacMainMenu();
  15009. #endif
  15010. JUCEApplication::JUCEApplication()
  15011. : appReturnValue (0),
  15012. stillInitialising (true)
  15013. {
  15014. jassert (isStandaloneApp() && appInstance == 0);
  15015. appInstance = this;
  15016. }
  15017. JUCEApplication::~JUCEApplication()
  15018. {
  15019. if (appLock != 0)
  15020. {
  15021. appLock->exit();
  15022. appLock = 0;
  15023. }
  15024. jassert (appInstance == this);
  15025. appInstance = 0;
  15026. }
  15027. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15028. JUCEApplication* JUCEApplication::appInstance = 0;
  15029. bool JUCEApplication::moreThanOneInstanceAllowed()
  15030. {
  15031. return true;
  15032. }
  15033. void JUCEApplication::anotherInstanceStarted (const String&)
  15034. {
  15035. }
  15036. void JUCEApplication::systemRequestedQuit()
  15037. {
  15038. quit();
  15039. }
  15040. void JUCEApplication::quit()
  15041. {
  15042. MessageManager::getInstance()->stopDispatchLoop();
  15043. }
  15044. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15045. {
  15046. appReturnValue = newReturnValue;
  15047. }
  15048. void JUCEApplication::actionListenerCallback (const String& message)
  15049. {
  15050. if (message.startsWith (getApplicationName() + "/"))
  15051. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15052. }
  15053. void JUCEApplication::unhandledException (const std::exception*,
  15054. const String&,
  15055. const int)
  15056. {
  15057. jassertfalse;
  15058. }
  15059. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15060. const char* const sourceFile,
  15061. const int lineNumber)
  15062. {
  15063. if (appInstance != 0)
  15064. appInstance->unhandledException (e, sourceFile, lineNumber);
  15065. }
  15066. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15067. {
  15068. return 0;
  15069. }
  15070. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15071. {
  15072. commands.add (StandardApplicationCommandIDs::quit);
  15073. }
  15074. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15075. {
  15076. if (commandID == StandardApplicationCommandIDs::quit)
  15077. {
  15078. result.setInfo (TRANS("Quit"),
  15079. TRANS("Quits the application"),
  15080. "Application",
  15081. 0);
  15082. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15083. }
  15084. }
  15085. bool JUCEApplication::perform (const InvocationInfo& info)
  15086. {
  15087. if (info.commandID == StandardApplicationCommandIDs::quit)
  15088. {
  15089. systemRequestedQuit();
  15090. return true;
  15091. }
  15092. return false;
  15093. }
  15094. bool JUCEApplication::initialiseApp (const String& commandLine)
  15095. {
  15096. commandLineParameters = commandLine.trim();
  15097. #if ! JUCE_IOS
  15098. jassert (appLock == 0); // initialiseApp must only be called once!
  15099. if (! moreThanOneInstanceAllowed())
  15100. {
  15101. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15102. if (! appLock->enter(0))
  15103. {
  15104. appLock = 0;
  15105. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15106. DBG ("Another instance is running - quitting...");
  15107. return false;
  15108. }
  15109. }
  15110. #endif
  15111. // let the app do its setting-up..
  15112. initialise (commandLineParameters);
  15113. #if JUCE_MAC
  15114. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15115. #endif
  15116. // register for broadcast new app messages
  15117. MessageManager::getInstance()->registerBroadcastListener (this);
  15118. stillInitialising = false;
  15119. return true;
  15120. }
  15121. int JUCEApplication::shutdownApp()
  15122. {
  15123. jassert (appInstance == this);
  15124. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15125. JUCE_TRY
  15126. {
  15127. // give the app a chance to clean up..
  15128. shutdown();
  15129. }
  15130. JUCE_CATCH_EXCEPTION
  15131. return getApplicationReturnValue();
  15132. }
  15133. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15134. void JUCEApplication::appWillTerminateByForce()
  15135. {
  15136. {
  15137. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15138. if (app != 0)
  15139. app->shutdownApp();
  15140. }
  15141. shutdownJuce_GUI();
  15142. }
  15143. int JUCEApplication::main (const String& commandLine)
  15144. {
  15145. ScopedJuceInitialiser_GUI libraryInitialiser;
  15146. jassert (createInstance != 0);
  15147. int returnCode = 0;
  15148. {
  15149. const ScopedPointer<JUCEApplication> app (createInstance());
  15150. if (! app->initialiseApp (commandLine))
  15151. return 0;
  15152. JUCE_TRY
  15153. {
  15154. // loop until a quit message is received..
  15155. MessageManager::getInstance()->runDispatchLoop();
  15156. }
  15157. JUCE_CATCH_EXCEPTION
  15158. returnCode = app->shutdownApp();
  15159. }
  15160. return returnCode;
  15161. }
  15162. #if JUCE_IOS
  15163. extern int juce_iOSMain (int argc, const char* argv[]);
  15164. #endif
  15165. #if ! JUCE_WINDOWS
  15166. extern const char* juce_Argv0;
  15167. #endif
  15168. int JUCEApplication::main (int argc, const char* argv[])
  15169. {
  15170. JUCE_AUTORELEASEPOOL
  15171. #if ! JUCE_WINDOWS
  15172. jassert (createInstance != 0);
  15173. juce_Argv0 = argv[0];
  15174. #endif
  15175. #if JUCE_IOS
  15176. return juce_iOSMain (argc, argv);
  15177. #else
  15178. String cmd;
  15179. for (int i = 1; i < argc; ++i)
  15180. cmd << argv[i] << ' ';
  15181. return JUCEApplication::main (cmd);
  15182. #endif
  15183. }
  15184. END_JUCE_NAMESPACE
  15185. /*** End of inlined file: juce_Application.cpp ***/
  15186. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15187. BEGIN_JUCE_NAMESPACE
  15188. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15189. : commandID (commandID_),
  15190. flags (0)
  15191. {
  15192. }
  15193. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15194. const String& description_,
  15195. const String& categoryName_,
  15196. const int flags_) throw()
  15197. {
  15198. shortName = shortName_;
  15199. description = description_;
  15200. categoryName = categoryName_;
  15201. flags = flags_;
  15202. }
  15203. void ApplicationCommandInfo::setActive (const bool b) throw()
  15204. {
  15205. if (b)
  15206. flags &= ~isDisabled;
  15207. else
  15208. flags |= isDisabled;
  15209. }
  15210. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15211. {
  15212. if (b)
  15213. flags |= isTicked;
  15214. else
  15215. flags &= ~isTicked;
  15216. }
  15217. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15218. {
  15219. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15220. }
  15221. END_JUCE_NAMESPACE
  15222. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15223. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15224. BEGIN_JUCE_NAMESPACE
  15225. ApplicationCommandManager::ApplicationCommandManager()
  15226. : firstTarget (0)
  15227. {
  15228. keyMappings = new KeyPressMappingSet (this);
  15229. Desktop::getInstance().addFocusChangeListener (this);
  15230. }
  15231. ApplicationCommandManager::~ApplicationCommandManager()
  15232. {
  15233. Desktop::getInstance().removeFocusChangeListener (this);
  15234. keyMappings = 0;
  15235. }
  15236. void ApplicationCommandManager::clearCommands()
  15237. {
  15238. commands.clear();
  15239. keyMappings->clearAllKeyPresses();
  15240. triggerAsyncUpdate();
  15241. }
  15242. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15243. {
  15244. // zero isn't a valid command ID!
  15245. jassert (newCommand.commandID != 0);
  15246. // the name isn't optional!
  15247. jassert (newCommand.shortName.isNotEmpty());
  15248. if (getCommandForID (newCommand.commandID) == 0)
  15249. {
  15250. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15251. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15252. commands.add (newInfo);
  15253. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15254. triggerAsyncUpdate();
  15255. }
  15256. else
  15257. {
  15258. // trying to re-register the same command with different parameters?
  15259. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15260. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15261. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15262. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15263. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15264. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15265. }
  15266. }
  15267. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15268. {
  15269. if (target != 0)
  15270. {
  15271. Array <CommandID> commandIDs;
  15272. target->getAllCommands (commandIDs);
  15273. for (int i = 0; i < commandIDs.size(); ++i)
  15274. {
  15275. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15276. target->getCommandInfo (info.commandID, info);
  15277. registerCommand (info);
  15278. }
  15279. }
  15280. }
  15281. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15282. {
  15283. for (int i = commands.size(); --i >= 0;)
  15284. {
  15285. if (commands.getUnchecked (i)->commandID == commandID)
  15286. {
  15287. commands.remove (i);
  15288. triggerAsyncUpdate();
  15289. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15290. for (int j = keys.size(); --j >= 0;)
  15291. keyMappings->removeKeyPress (keys.getReference (j));
  15292. }
  15293. }
  15294. }
  15295. void ApplicationCommandManager::commandStatusChanged()
  15296. {
  15297. triggerAsyncUpdate();
  15298. }
  15299. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15300. {
  15301. for (int i = commands.size(); --i >= 0;)
  15302. if (commands.getUnchecked(i)->commandID == commandID)
  15303. return commands.getUnchecked(i);
  15304. return 0;
  15305. }
  15306. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15307. {
  15308. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15309. return (ci != 0) ? ci->shortName : String::empty;
  15310. }
  15311. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15312. {
  15313. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15314. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15315. : String::empty;
  15316. }
  15317. const StringArray ApplicationCommandManager::getCommandCategories() const
  15318. {
  15319. StringArray s;
  15320. for (int i = 0; i < commands.size(); ++i)
  15321. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15322. return s;
  15323. }
  15324. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15325. {
  15326. Array <CommandID> results;
  15327. for (int i = 0; i < commands.size(); ++i)
  15328. if (commands.getUnchecked(i)->categoryName == categoryName)
  15329. results.add (commands.getUnchecked(i)->commandID);
  15330. return results;
  15331. }
  15332. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15333. {
  15334. ApplicationCommandTarget::InvocationInfo info (commandID);
  15335. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15336. return invoke (info, asynchronously);
  15337. }
  15338. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15339. {
  15340. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15341. // manager first..
  15342. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15343. ApplicationCommandInfo commandInfo (0);
  15344. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15345. if (target == 0)
  15346. return false;
  15347. ApplicationCommandTarget::InvocationInfo info (info_);
  15348. info.commandFlags = commandInfo.flags;
  15349. sendListenerInvokeCallback (info);
  15350. const bool ok = target->invoke (info, asynchronously);
  15351. commandStatusChanged();
  15352. return ok;
  15353. }
  15354. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15355. {
  15356. return firstTarget != 0 ? firstTarget
  15357. : findDefaultComponentTarget();
  15358. }
  15359. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15360. {
  15361. firstTarget = newTarget;
  15362. }
  15363. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15364. ApplicationCommandInfo& upToDateInfo)
  15365. {
  15366. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15367. if (target == 0)
  15368. target = JUCEApplication::getInstance();
  15369. if (target != 0)
  15370. target = target->getTargetForCommand (commandID);
  15371. if (target != 0)
  15372. target->getCommandInfo (commandID, upToDateInfo);
  15373. return target;
  15374. }
  15375. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15376. {
  15377. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15378. if (target == 0 && c != 0)
  15379. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15380. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15381. return target;
  15382. }
  15383. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15384. {
  15385. Component* c = Component::getCurrentlyFocusedComponent();
  15386. if (c == 0)
  15387. {
  15388. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15389. if (activeWindow != 0)
  15390. {
  15391. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15392. if (c == 0)
  15393. c = activeWindow;
  15394. }
  15395. }
  15396. if (c == 0 && Process::isForegroundProcess())
  15397. {
  15398. // getting a bit desperate now - try all desktop comps..
  15399. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15400. {
  15401. ApplicationCommandTarget* const target
  15402. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15403. ->getPeer()->getLastFocusedSubcomponent());
  15404. if (target != 0)
  15405. return target;
  15406. }
  15407. }
  15408. if (c != 0)
  15409. {
  15410. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15411. // if we're focused on a ResizableWindow, chances are that it's the content
  15412. // component that really should get the event. And if not, the event will
  15413. // still be passed up to the top level window anyway, so let's send it to the
  15414. // content comp.
  15415. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15416. c = resizableWindow->getContentComponent();
  15417. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15418. if (target != 0)
  15419. return target;
  15420. }
  15421. return JUCEApplication::getInstance();
  15422. }
  15423. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15424. {
  15425. listeners.add (listener);
  15426. }
  15427. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15428. {
  15429. listeners.remove (listener);
  15430. }
  15431. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15432. {
  15433. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15434. }
  15435. void ApplicationCommandManager::handleAsyncUpdate()
  15436. {
  15437. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15438. }
  15439. void ApplicationCommandManager::globalFocusChanged (Component*)
  15440. {
  15441. commandStatusChanged();
  15442. }
  15443. END_JUCE_NAMESPACE
  15444. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15445. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15446. BEGIN_JUCE_NAMESPACE
  15447. ApplicationCommandTarget::ApplicationCommandTarget()
  15448. {
  15449. }
  15450. ApplicationCommandTarget::~ApplicationCommandTarget()
  15451. {
  15452. messageInvoker = 0;
  15453. }
  15454. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15455. {
  15456. if (isCommandActive (info.commandID))
  15457. {
  15458. if (async)
  15459. {
  15460. if (messageInvoker == 0)
  15461. messageInvoker = new CommandTargetMessageInvoker (this);
  15462. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15463. return true;
  15464. }
  15465. else
  15466. {
  15467. const bool success = perform (info);
  15468. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15469. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15470. // returns the command's info.
  15471. return success;
  15472. }
  15473. }
  15474. return false;
  15475. }
  15476. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15477. {
  15478. Component* c = dynamic_cast <Component*> (this);
  15479. if (c != 0)
  15480. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15481. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15482. return 0;
  15483. }
  15484. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15485. {
  15486. ApplicationCommandTarget* target = this;
  15487. int depth = 0;
  15488. while (target != 0)
  15489. {
  15490. Array <CommandID> commandIDs;
  15491. target->getAllCommands (commandIDs);
  15492. if (commandIDs.contains (commandID))
  15493. return target;
  15494. target = target->getNextCommandTarget();
  15495. ++depth;
  15496. jassert (depth < 100); // could be a recursive command chain??
  15497. jassert (target != this); // definitely a recursive command chain!
  15498. if (depth > 100 || target == this)
  15499. break;
  15500. }
  15501. if (target == 0)
  15502. {
  15503. target = JUCEApplication::getInstance();
  15504. if (target != 0)
  15505. {
  15506. Array <CommandID> commandIDs;
  15507. target->getAllCommands (commandIDs);
  15508. if (commandIDs.contains (commandID))
  15509. return target;
  15510. }
  15511. }
  15512. return 0;
  15513. }
  15514. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15515. {
  15516. ApplicationCommandInfo info (commandID);
  15517. info.flags = ApplicationCommandInfo::isDisabled;
  15518. getCommandInfo (commandID, info);
  15519. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15520. }
  15521. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15522. {
  15523. ApplicationCommandTarget* target = this;
  15524. int depth = 0;
  15525. while (target != 0)
  15526. {
  15527. if (target->tryToInvoke (info, async))
  15528. return true;
  15529. target = target->getNextCommandTarget();
  15530. ++depth;
  15531. jassert (depth < 100); // could be a recursive command chain??
  15532. jassert (target != this); // definitely a recursive command chain!
  15533. if (depth > 100 || target == this)
  15534. break;
  15535. }
  15536. if (target == 0)
  15537. {
  15538. target = JUCEApplication::getInstance();
  15539. if (target != 0)
  15540. return target->tryToInvoke (info, async);
  15541. }
  15542. return false;
  15543. }
  15544. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15545. {
  15546. ApplicationCommandTarget::InvocationInfo info (commandID);
  15547. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15548. return invoke (info, asynchronously);
  15549. }
  15550. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15551. : commandID (commandID_),
  15552. commandFlags (0),
  15553. invocationMethod (direct),
  15554. originatingComponent (0),
  15555. isKeyDown (false),
  15556. millisecsSinceKeyPressed (0)
  15557. {
  15558. }
  15559. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15560. : owner (owner_)
  15561. {
  15562. }
  15563. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15564. {
  15565. }
  15566. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15567. {
  15568. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15569. owner->tryToInvoke (*info, false);
  15570. }
  15571. END_JUCE_NAMESPACE
  15572. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15573. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15574. BEGIN_JUCE_NAMESPACE
  15575. juce_ImplementSingleton (ApplicationProperties)
  15576. ApplicationProperties::ApplicationProperties()
  15577. : msBeforeSaving (3000),
  15578. options (PropertiesFile::storeAsBinary),
  15579. commonSettingsAreReadOnly (0),
  15580. processLock (0)
  15581. {
  15582. }
  15583. ApplicationProperties::~ApplicationProperties()
  15584. {
  15585. closeFiles();
  15586. clearSingletonInstance();
  15587. }
  15588. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15589. const String& fileNameSuffix,
  15590. const String& folderName_,
  15591. const int millisecondsBeforeSaving,
  15592. const int propertiesFileOptions,
  15593. InterProcessLock* processLock_)
  15594. {
  15595. appName = applicationName;
  15596. fileSuffix = fileNameSuffix;
  15597. folderName = folderName_;
  15598. msBeforeSaving = millisecondsBeforeSaving;
  15599. options = propertiesFileOptions;
  15600. processLock = processLock_;
  15601. }
  15602. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15603. const bool testCommonSettings,
  15604. const bool showWarningDialogOnFailure)
  15605. {
  15606. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15607. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15608. if (! (userOk && commonOk))
  15609. {
  15610. if (showWarningDialogOnFailure)
  15611. {
  15612. String filenames;
  15613. if (userProps != 0 && ! userOk)
  15614. filenames << '\n' << userProps->getFile().getFullPathName();
  15615. if (commonProps != 0 && ! commonOk)
  15616. filenames << '\n' << commonProps->getFile().getFullPathName();
  15617. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15618. appName + TRANS(" - Unable to save settings"),
  15619. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15620. + appName + TRANS(" needs to be able to write to the following files:\n")
  15621. + filenames
  15622. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15623. }
  15624. return false;
  15625. }
  15626. return true;
  15627. }
  15628. void ApplicationProperties::openFiles()
  15629. {
  15630. // You need to call setStorageParameters() before trying to get hold of the
  15631. // properties!
  15632. jassert (appName.isNotEmpty());
  15633. if (appName.isNotEmpty())
  15634. {
  15635. if (userProps == 0)
  15636. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15637. false, msBeforeSaving, options, processLock);
  15638. if (commonProps == 0)
  15639. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15640. true, msBeforeSaving, options, processLock);
  15641. userProps->setFallbackPropertySet (commonProps);
  15642. }
  15643. }
  15644. PropertiesFile* ApplicationProperties::getUserSettings()
  15645. {
  15646. if (userProps == 0)
  15647. openFiles();
  15648. return userProps;
  15649. }
  15650. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15651. {
  15652. if (commonProps == 0)
  15653. openFiles();
  15654. if (returnUserPropsIfReadOnly)
  15655. {
  15656. if (commonSettingsAreReadOnly == 0)
  15657. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15658. if (commonSettingsAreReadOnly > 0)
  15659. return userProps;
  15660. }
  15661. return commonProps;
  15662. }
  15663. bool ApplicationProperties::saveIfNeeded()
  15664. {
  15665. return (userProps == 0 || userProps->saveIfNeeded())
  15666. && (commonProps == 0 || commonProps->saveIfNeeded());
  15667. }
  15668. void ApplicationProperties::closeFiles()
  15669. {
  15670. userProps = 0;
  15671. commonProps = 0;
  15672. }
  15673. END_JUCE_NAMESPACE
  15674. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15675. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15676. BEGIN_JUCE_NAMESPACE
  15677. namespace PropertyFileConstants
  15678. {
  15679. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15680. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15681. static const char* const fileTag = "PROPERTIES";
  15682. static const char* const valueTag = "VALUE";
  15683. static const char* const nameAttribute = "name";
  15684. static const char* const valueAttribute = "val";
  15685. }
  15686. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15687. const int options_, InterProcessLock* const processLock_)
  15688. : PropertySet (ignoreCaseOfKeyNames),
  15689. file (f),
  15690. timerInterval (millisecondsBeforeSaving),
  15691. options (options_),
  15692. loadedOk (false),
  15693. needsWriting (false),
  15694. processLock (processLock_)
  15695. {
  15696. // You need to correctly specify just one storage format for the file
  15697. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15698. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15699. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15700. ProcessScopedLock pl (createProcessLock());
  15701. if (pl != 0 && ! pl->isLocked())
  15702. return; // locking failure..
  15703. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15704. if (fileStream != 0)
  15705. {
  15706. int magicNumber = fileStream->readInt();
  15707. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15708. {
  15709. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15710. magicNumber = PropertyFileConstants::magicNumber;
  15711. }
  15712. if (magicNumber == PropertyFileConstants::magicNumber)
  15713. {
  15714. loadedOk = true;
  15715. BufferedInputStream in (fileStream.release(), 2048, true);
  15716. int numValues = in.readInt();
  15717. while (--numValues >= 0 && ! in.isExhausted())
  15718. {
  15719. const String key (in.readString());
  15720. const String value (in.readString());
  15721. jassert (key.isNotEmpty());
  15722. if (key.isNotEmpty())
  15723. getAllProperties().set (key, value);
  15724. }
  15725. }
  15726. else
  15727. {
  15728. // Not a binary props file - let's see if it's XML..
  15729. fileStream = 0;
  15730. XmlDocument parser (f);
  15731. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15732. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15733. {
  15734. doc = parser.getDocumentElement();
  15735. if (doc != 0)
  15736. {
  15737. loadedOk = true;
  15738. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15739. {
  15740. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15741. if (name.isNotEmpty())
  15742. {
  15743. getAllProperties().set (name,
  15744. e->getFirstChildElement() != 0
  15745. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15746. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15747. }
  15748. }
  15749. }
  15750. else
  15751. {
  15752. // must be a pretty broken XML file we're trying to parse here,
  15753. // or a sign that this object needs an InterProcessLock,
  15754. // or just a failure reading the file. This last reason is why
  15755. // we don't jassertfalse here.
  15756. }
  15757. }
  15758. }
  15759. }
  15760. else
  15761. {
  15762. loadedOk = ! f.exists();
  15763. }
  15764. }
  15765. PropertiesFile::~PropertiesFile()
  15766. {
  15767. if (! saveIfNeeded())
  15768. jassertfalse;
  15769. }
  15770. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15771. {
  15772. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15773. }
  15774. bool PropertiesFile::saveIfNeeded()
  15775. {
  15776. const ScopedLock sl (getLock());
  15777. return (! needsWriting) || save();
  15778. }
  15779. bool PropertiesFile::needsToBeSaved() const
  15780. {
  15781. const ScopedLock sl (getLock());
  15782. return needsWriting;
  15783. }
  15784. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15785. {
  15786. const ScopedLock sl (getLock());
  15787. needsWriting = needsToBeSaved_;
  15788. }
  15789. bool PropertiesFile::save()
  15790. {
  15791. const ScopedLock sl (getLock());
  15792. stopTimer();
  15793. if (file == File::nonexistent
  15794. || file.isDirectory()
  15795. || ! file.getParentDirectory().createDirectory())
  15796. return false;
  15797. if ((options & storeAsXML) != 0)
  15798. {
  15799. XmlElement doc (PropertyFileConstants::fileTag);
  15800. for (int i = 0; i < getAllProperties().size(); ++i)
  15801. {
  15802. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15803. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15804. // if the value seems to contain xml, store it as such..
  15805. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  15806. if (childElement != 0)
  15807. e->addChildElement (childElement);
  15808. else
  15809. e->setAttribute (PropertyFileConstants::valueAttribute,
  15810. getAllProperties().getAllValues() [i]);
  15811. }
  15812. ProcessScopedLock pl (createProcessLock());
  15813. if (pl != 0 && ! pl->isLocked())
  15814. return false; // locking failure..
  15815. if (doc.writeToFile (file, String::empty))
  15816. {
  15817. needsWriting = false;
  15818. return true;
  15819. }
  15820. }
  15821. else
  15822. {
  15823. ProcessScopedLock pl (createProcessLock());
  15824. if (pl != 0 && ! pl->isLocked())
  15825. return false; // locking failure..
  15826. TemporaryFile tempFile (file);
  15827. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15828. if (out != 0)
  15829. {
  15830. if ((options & storeAsCompressedBinary) != 0)
  15831. {
  15832. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15833. out->flush();
  15834. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15835. }
  15836. else
  15837. {
  15838. // have you set up the storage option flags correctly?
  15839. jassert ((options & storeAsBinary) != 0);
  15840. out->writeInt (PropertyFileConstants::magicNumber);
  15841. }
  15842. const int numProperties = getAllProperties().size();
  15843. out->writeInt (numProperties);
  15844. for (int i = 0; i < numProperties; ++i)
  15845. {
  15846. out->writeString (getAllProperties().getAllKeys() [i]);
  15847. out->writeString (getAllProperties().getAllValues() [i]);
  15848. }
  15849. out = 0;
  15850. if (tempFile.overwriteTargetFileWithTemporary())
  15851. {
  15852. needsWriting = false;
  15853. return true;
  15854. }
  15855. }
  15856. }
  15857. return false;
  15858. }
  15859. void PropertiesFile::timerCallback()
  15860. {
  15861. saveIfNeeded();
  15862. }
  15863. void PropertiesFile::propertyChanged()
  15864. {
  15865. sendChangeMessage();
  15866. needsWriting = true;
  15867. if (timerInterval > 0)
  15868. startTimer (timerInterval);
  15869. else if (timerInterval == 0)
  15870. saveIfNeeded();
  15871. }
  15872. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15873. const String& fileNameSuffix,
  15874. const String& folderName,
  15875. const bool commonToAllUsers)
  15876. {
  15877. // mustn't have illegal characters in this name..
  15878. jassert (applicationName == File::createLegalFileName (applicationName));
  15879. #if JUCE_MAC || JUCE_IOS
  15880. File dir (commonToAllUsers ? "/Library/Preferences"
  15881. : "~/Library/Preferences");
  15882. if (folderName.isNotEmpty())
  15883. dir = dir.getChildFile (folderName);
  15884. #endif
  15885. #ifdef JUCE_LINUX
  15886. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15887. + (folderName.isNotEmpty() ? folderName
  15888. : ("." + applicationName)));
  15889. #endif
  15890. #if JUCE_WINDOWS
  15891. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15892. : File::userApplicationDataDirectory));
  15893. if (dir == File::nonexistent)
  15894. return File::nonexistent;
  15895. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15896. : applicationName);
  15897. #endif
  15898. return dir.getChildFile (applicationName)
  15899. .withFileExtension (fileNameSuffix);
  15900. }
  15901. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15902. const String& fileNameSuffix,
  15903. const String& folderName,
  15904. const bool commonToAllUsers,
  15905. const int millisecondsBeforeSaving,
  15906. const int propertiesFileOptions,
  15907. InterProcessLock* processLock_)
  15908. {
  15909. const File file (getDefaultAppSettingsFile (applicationName,
  15910. fileNameSuffix,
  15911. folderName,
  15912. commonToAllUsers));
  15913. jassert (file != File::nonexistent);
  15914. if (file == File::nonexistent)
  15915. return 0;
  15916. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15917. }
  15918. END_JUCE_NAMESPACE
  15919. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15920. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15921. BEGIN_JUCE_NAMESPACE
  15922. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15923. const String& fileWildcard_,
  15924. const String& openFileDialogTitle_,
  15925. const String& saveFileDialogTitle_)
  15926. : changedSinceSave (false),
  15927. fileExtension (fileExtension_),
  15928. fileWildcard (fileWildcard_),
  15929. openFileDialogTitle (openFileDialogTitle_),
  15930. saveFileDialogTitle (saveFileDialogTitle_)
  15931. {
  15932. }
  15933. FileBasedDocument::~FileBasedDocument()
  15934. {
  15935. }
  15936. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15937. {
  15938. if (changedSinceSave != hasChanged)
  15939. {
  15940. changedSinceSave = hasChanged;
  15941. sendChangeMessage();
  15942. }
  15943. }
  15944. void FileBasedDocument::changed()
  15945. {
  15946. changedSinceSave = true;
  15947. sendChangeMessage();
  15948. }
  15949. void FileBasedDocument::setFile (const File& newFile)
  15950. {
  15951. if (documentFile != newFile)
  15952. {
  15953. documentFile = newFile;
  15954. changed();
  15955. }
  15956. }
  15957. bool FileBasedDocument::loadFrom (const File& newFile,
  15958. const bool showMessageOnFailure)
  15959. {
  15960. MouseCursor::showWaitCursor();
  15961. const File oldFile (documentFile);
  15962. documentFile = newFile;
  15963. String error;
  15964. if (newFile.existsAsFile())
  15965. {
  15966. error = loadDocument (newFile);
  15967. if (error.isEmpty())
  15968. {
  15969. setChangedFlag (false);
  15970. MouseCursor::hideWaitCursor();
  15971. setLastDocumentOpened (newFile);
  15972. return true;
  15973. }
  15974. }
  15975. else
  15976. {
  15977. error = "The file doesn't exist";
  15978. }
  15979. documentFile = oldFile;
  15980. MouseCursor::hideWaitCursor();
  15981. if (showMessageOnFailure)
  15982. {
  15983. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15984. TRANS("Failed to open file..."),
  15985. TRANS("There was an error while trying to load the file:\n\n")
  15986. + newFile.getFullPathName()
  15987. + "\n\n"
  15988. + error);
  15989. }
  15990. return false;
  15991. }
  15992. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15993. {
  15994. FileChooser fc (openFileDialogTitle,
  15995. getLastDocumentOpened(),
  15996. fileWildcard);
  15997. if (fc.browseForFileToOpen())
  15998. return loadFrom (fc.getResult(), showMessageOnFailure);
  15999. return false;
  16000. }
  16001. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16002. const bool showMessageOnFailure)
  16003. {
  16004. return saveAs (documentFile,
  16005. false,
  16006. askUserForFileIfNotSpecified,
  16007. showMessageOnFailure);
  16008. }
  16009. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16010. const bool warnAboutOverwritingExistingFiles,
  16011. const bool askUserForFileIfNotSpecified,
  16012. const bool showMessageOnFailure)
  16013. {
  16014. if (newFile == File::nonexistent)
  16015. {
  16016. if (askUserForFileIfNotSpecified)
  16017. {
  16018. return saveAsInteractive (true);
  16019. }
  16020. else
  16021. {
  16022. // can't save to an unspecified file
  16023. jassertfalse;
  16024. return failedToWriteToFile;
  16025. }
  16026. }
  16027. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16028. {
  16029. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16030. TRANS("File already exists"),
  16031. TRANS("There's already a file called:\n\n")
  16032. + newFile.getFullPathName()
  16033. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16034. TRANS("overwrite"),
  16035. TRANS("cancel")))
  16036. {
  16037. return userCancelledSave;
  16038. }
  16039. }
  16040. MouseCursor::showWaitCursor();
  16041. const File oldFile (documentFile);
  16042. documentFile = newFile;
  16043. String error (saveDocument (newFile));
  16044. if (error.isEmpty())
  16045. {
  16046. setChangedFlag (false);
  16047. MouseCursor::hideWaitCursor();
  16048. return savedOk;
  16049. }
  16050. documentFile = oldFile;
  16051. MouseCursor::hideWaitCursor();
  16052. if (showMessageOnFailure)
  16053. {
  16054. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16055. TRANS("Error writing to file..."),
  16056. TRANS("An error occurred while trying to save \"")
  16057. + getDocumentTitle()
  16058. + TRANS("\" to the file:\n\n")
  16059. + newFile.getFullPathName()
  16060. + "\n\n"
  16061. + error);
  16062. }
  16063. return failedToWriteToFile;
  16064. }
  16065. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16066. {
  16067. if (! hasChangedSinceSaved())
  16068. return savedOk;
  16069. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16070. TRANS("Closing document..."),
  16071. TRANS("Do you want to save the changes to \"")
  16072. + getDocumentTitle() + "\"?",
  16073. TRANS("save"),
  16074. TRANS("discard changes"),
  16075. TRANS("cancel"));
  16076. if (r == 1)
  16077. {
  16078. // save changes
  16079. return save (true, true);
  16080. }
  16081. else if (r == 2)
  16082. {
  16083. // discard changes
  16084. return savedOk;
  16085. }
  16086. return userCancelledSave;
  16087. }
  16088. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16089. {
  16090. File f;
  16091. if (documentFile.existsAsFile())
  16092. f = documentFile;
  16093. else
  16094. f = getLastDocumentOpened();
  16095. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16096. if (legalFilename.isEmpty())
  16097. legalFilename = "unnamed";
  16098. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16099. f = f.getSiblingFile (legalFilename);
  16100. else
  16101. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16102. f = f.withFileExtension (fileExtension)
  16103. .getNonexistentSibling (true);
  16104. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16105. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16106. {
  16107. File chosen (fc.getResult());
  16108. if (chosen.getFileExtension().isEmpty())
  16109. {
  16110. chosen = chosen.withFileExtension (fileExtension);
  16111. if (chosen.exists())
  16112. {
  16113. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16114. TRANS("File already exists"),
  16115. TRANS("There's already a file called:")
  16116. + "\n\n" + chosen.getFullPathName()
  16117. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16118. TRANS("overwrite"),
  16119. TRANS("cancel")))
  16120. {
  16121. return userCancelledSave;
  16122. }
  16123. }
  16124. }
  16125. setLastDocumentOpened (chosen);
  16126. return saveAs (chosen, false, false, true);
  16127. }
  16128. return userCancelledSave;
  16129. }
  16130. END_JUCE_NAMESPACE
  16131. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16132. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16133. BEGIN_JUCE_NAMESPACE
  16134. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16135. : maxNumberOfItems (10)
  16136. {
  16137. }
  16138. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16139. {
  16140. }
  16141. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16142. {
  16143. maxNumberOfItems = jmax (1, newMaxNumber);
  16144. while (getNumFiles() > maxNumberOfItems)
  16145. files.remove (getNumFiles() - 1);
  16146. }
  16147. int RecentlyOpenedFilesList::getNumFiles() const
  16148. {
  16149. return files.size();
  16150. }
  16151. const File RecentlyOpenedFilesList::getFile (const int index) const
  16152. {
  16153. return File (files [index]);
  16154. }
  16155. void RecentlyOpenedFilesList::clear()
  16156. {
  16157. files.clear();
  16158. }
  16159. void RecentlyOpenedFilesList::addFile (const File& file)
  16160. {
  16161. const String path (file.getFullPathName());
  16162. files.removeString (path, true);
  16163. files.insert (0, path);
  16164. setMaxNumberOfItems (maxNumberOfItems);
  16165. }
  16166. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16167. {
  16168. for (int i = getNumFiles(); --i >= 0;)
  16169. if (! getFile(i).exists())
  16170. files.remove (i);
  16171. }
  16172. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16173. const int baseItemId,
  16174. const bool showFullPaths,
  16175. const bool dontAddNonExistentFiles,
  16176. const File** filesToAvoid)
  16177. {
  16178. int num = 0;
  16179. for (int i = 0; i < getNumFiles(); ++i)
  16180. {
  16181. const File f (getFile(i));
  16182. if ((! dontAddNonExistentFiles) || f.exists())
  16183. {
  16184. bool needsAvoiding = false;
  16185. if (filesToAvoid != 0)
  16186. {
  16187. const File** avoid = filesToAvoid;
  16188. while (*avoid != 0)
  16189. {
  16190. if (f == **avoid)
  16191. {
  16192. needsAvoiding = true;
  16193. break;
  16194. }
  16195. ++avoid;
  16196. }
  16197. }
  16198. if (! needsAvoiding)
  16199. {
  16200. menuToAddTo.addItem (baseItemId + i,
  16201. showFullPaths ? f.getFullPathName()
  16202. : f.getFileName());
  16203. ++num;
  16204. }
  16205. }
  16206. }
  16207. return num;
  16208. }
  16209. const String RecentlyOpenedFilesList::toString() const
  16210. {
  16211. return files.joinIntoString ("\n");
  16212. }
  16213. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16214. {
  16215. clear();
  16216. files.addLines (stringifiedVersion);
  16217. setMaxNumberOfItems (maxNumberOfItems);
  16218. }
  16219. END_JUCE_NAMESPACE
  16220. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16221. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16222. BEGIN_JUCE_NAMESPACE
  16223. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16224. const int minimumTransactions)
  16225. : totalUnitsStored (0),
  16226. nextIndex (0),
  16227. newTransaction (true),
  16228. reentrancyCheck (false)
  16229. {
  16230. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16231. minimumTransactions);
  16232. }
  16233. UndoManager::~UndoManager()
  16234. {
  16235. clearUndoHistory();
  16236. }
  16237. void UndoManager::clearUndoHistory()
  16238. {
  16239. transactions.clear();
  16240. transactionNames.clear();
  16241. totalUnitsStored = 0;
  16242. nextIndex = 0;
  16243. sendChangeMessage();
  16244. }
  16245. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16246. {
  16247. return totalUnitsStored;
  16248. }
  16249. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16250. const int minimumTransactions)
  16251. {
  16252. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16253. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16254. }
  16255. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16256. {
  16257. if (command_ != 0)
  16258. {
  16259. ScopedPointer<UndoableAction> command (command_);
  16260. if (actionName.isNotEmpty())
  16261. currentTransactionName = actionName;
  16262. if (reentrancyCheck)
  16263. {
  16264. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16265. // undo() methods, or else these actions won't actually get done.
  16266. return false;
  16267. }
  16268. else if (command->perform())
  16269. {
  16270. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16271. if (commandSet != 0 && ! newTransaction)
  16272. {
  16273. UndoableAction* lastAction = commandSet->getLast();
  16274. if (lastAction != 0)
  16275. {
  16276. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16277. if (coalescedAction != 0)
  16278. {
  16279. command = coalescedAction;
  16280. totalUnitsStored -= lastAction->getSizeInUnits();
  16281. commandSet->removeLast();
  16282. }
  16283. }
  16284. }
  16285. else
  16286. {
  16287. commandSet = new OwnedArray<UndoableAction>();
  16288. transactions.insert (nextIndex, commandSet);
  16289. transactionNames.insert (nextIndex, currentTransactionName);
  16290. ++nextIndex;
  16291. }
  16292. totalUnitsStored += command->getSizeInUnits();
  16293. commandSet->add (command.release());
  16294. newTransaction = false;
  16295. while (nextIndex < transactions.size())
  16296. {
  16297. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16298. for (int i = lastSet->size(); --i >= 0;)
  16299. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16300. transactions.removeLast();
  16301. transactionNames.remove (transactionNames.size() - 1);
  16302. }
  16303. while (nextIndex > 0
  16304. && totalUnitsStored > maxNumUnitsToKeep
  16305. && transactions.size() > minimumTransactionsToKeep)
  16306. {
  16307. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16308. for (int i = firstSet->size(); --i >= 0;)
  16309. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16310. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16311. transactions.remove (0);
  16312. transactionNames.remove (0);
  16313. --nextIndex;
  16314. }
  16315. sendChangeMessage();
  16316. return true;
  16317. }
  16318. }
  16319. return false;
  16320. }
  16321. void UndoManager::beginNewTransaction (const String& actionName)
  16322. {
  16323. newTransaction = true;
  16324. currentTransactionName = actionName;
  16325. }
  16326. void UndoManager::setCurrentTransactionName (const String& newName)
  16327. {
  16328. currentTransactionName = newName;
  16329. }
  16330. bool UndoManager::canUndo() const
  16331. {
  16332. return nextIndex > 0;
  16333. }
  16334. bool UndoManager::canRedo() const
  16335. {
  16336. return nextIndex < transactions.size();
  16337. }
  16338. const String UndoManager::getUndoDescription() const
  16339. {
  16340. return transactionNames [nextIndex - 1];
  16341. }
  16342. const String UndoManager::getRedoDescription() const
  16343. {
  16344. return transactionNames [nextIndex];
  16345. }
  16346. bool UndoManager::undo()
  16347. {
  16348. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16349. if (commandSet == 0)
  16350. return false;
  16351. bool failed = false;
  16352. {
  16353. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16354. for (int i = commandSet->size(); --i >= 0;)
  16355. {
  16356. if (! commandSet->getUnchecked(i)->undo())
  16357. {
  16358. jassertfalse;
  16359. failed = true;
  16360. break;
  16361. }
  16362. }
  16363. }
  16364. if (failed)
  16365. clearUndoHistory();
  16366. else
  16367. --nextIndex;
  16368. beginNewTransaction();
  16369. sendChangeMessage();
  16370. return true;
  16371. }
  16372. bool UndoManager::redo()
  16373. {
  16374. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16375. if (commandSet == 0)
  16376. return false;
  16377. bool failed = false;
  16378. {
  16379. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16380. for (int i = 0; i < commandSet->size(); ++i)
  16381. {
  16382. if (! commandSet->getUnchecked(i)->perform())
  16383. {
  16384. jassertfalse;
  16385. failed = true;
  16386. break;
  16387. }
  16388. }
  16389. }
  16390. if (failed)
  16391. clearUndoHistory();
  16392. else
  16393. ++nextIndex;
  16394. beginNewTransaction();
  16395. sendChangeMessage();
  16396. return true;
  16397. }
  16398. bool UndoManager::undoCurrentTransactionOnly()
  16399. {
  16400. return newTransaction ? false : undo();
  16401. }
  16402. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16403. {
  16404. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16405. if (commandSet != 0 && ! newTransaction)
  16406. {
  16407. for (int i = 0; i < commandSet->size(); ++i)
  16408. actionsFound.add (commandSet->getUnchecked(i));
  16409. }
  16410. }
  16411. int UndoManager::getNumActionsInCurrentTransaction() const
  16412. {
  16413. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16414. if (commandSet != 0 && ! newTransaction)
  16415. return commandSet->size();
  16416. return 0;
  16417. }
  16418. END_JUCE_NAMESPACE
  16419. /*** End of inlined file: juce_UndoManager.cpp ***/
  16420. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16421. BEGIN_JUCE_NAMESPACE
  16422. static const char* const aiffFormatName = "AIFF file";
  16423. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16424. class AiffAudioFormatReader : public AudioFormatReader
  16425. {
  16426. public:
  16427. int bytesPerFrame;
  16428. int64 dataChunkStart;
  16429. bool littleEndian;
  16430. AiffAudioFormatReader (InputStream* in)
  16431. : AudioFormatReader (in, TRANS (aiffFormatName))
  16432. {
  16433. if (input->readInt() == chunkName ("FORM"))
  16434. {
  16435. const int len = input->readIntBigEndian();
  16436. const int64 end = input->getPosition() + len;
  16437. const int nextType = input->readInt();
  16438. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16439. {
  16440. bool hasGotVer = false;
  16441. bool hasGotData = false;
  16442. bool hasGotType = false;
  16443. while (input->getPosition() < end)
  16444. {
  16445. const int type = input->readInt();
  16446. const uint32 length = (uint32) input->readIntBigEndian();
  16447. const int64 chunkEnd = input->getPosition() + length;
  16448. if (type == chunkName ("FVER"))
  16449. {
  16450. hasGotVer = true;
  16451. const int ver = input->readIntBigEndian();
  16452. if (ver != 0 && ver != (int) 0xa2805140)
  16453. break;
  16454. }
  16455. else if (type == chunkName ("COMM"))
  16456. {
  16457. hasGotType = true;
  16458. numChannels = (unsigned int) input->readShortBigEndian();
  16459. lengthInSamples = input->readIntBigEndian();
  16460. bitsPerSample = input->readShortBigEndian();
  16461. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16462. unsigned char sampleRateBytes[10];
  16463. input->read (sampleRateBytes, 10);
  16464. const int byte0 = sampleRateBytes[0];
  16465. if ((byte0 & 0x80) != 0
  16466. || byte0 <= 0x3F || byte0 > 0x40
  16467. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16468. break;
  16469. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16470. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16471. sampleRate = (int) sampRate;
  16472. if (length <= 18)
  16473. {
  16474. // some types don't have a chunk large enough to include a compression
  16475. // type, so assume it's just big-endian pcm
  16476. littleEndian = false;
  16477. }
  16478. else
  16479. {
  16480. const int compType = input->readInt();
  16481. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16482. {
  16483. littleEndian = false;
  16484. }
  16485. else if (compType == chunkName ("sowt"))
  16486. {
  16487. littleEndian = true;
  16488. }
  16489. else
  16490. {
  16491. sampleRate = 0;
  16492. break;
  16493. }
  16494. }
  16495. }
  16496. else if (type == chunkName ("SSND"))
  16497. {
  16498. hasGotData = true;
  16499. const int offset = input->readIntBigEndian();
  16500. dataChunkStart = input->getPosition() + 4 + offset;
  16501. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16502. }
  16503. else if ((hasGotVer && hasGotData && hasGotType)
  16504. || chunkEnd < input->getPosition()
  16505. || input->isExhausted())
  16506. {
  16507. break;
  16508. }
  16509. input->setPosition (chunkEnd);
  16510. }
  16511. }
  16512. }
  16513. }
  16514. ~AiffAudioFormatReader()
  16515. {
  16516. }
  16517. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16518. int64 startSampleInFile, int numSamples)
  16519. {
  16520. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16521. if (samplesAvailable < numSamples)
  16522. {
  16523. for (int i = numDestChannels; --i >= 0;)
  16524. if (destSamples[i] != 0)
  16525. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16526. numSamples = (int) samplesAvailable;
  16527. }
  16528. if (numSamples <= 0)
  16529. return true;
  16530. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16531. while (numSamples > 0)
  16532. {
  16533. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16534. char tempBuffer [tempBufSize];
  16535. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16536. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16537. if (bytesRead < numThisTime * bytesPerFrame)
  16538. {
  16539. jassert (bytesRead >= 0);
  16540. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16541. }
  16542. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16543. if (littleEndian)
  16544. {
  16545. switch (bitsPerSample)
  16546. {
  16547. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16548. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16549. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16550. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16551. default: jassertfalse; break;
  16552. }
  16553. }
  16554. else
  16555. {
  16556. switch (bitsPerSample)
  16557. {
  16558. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16559. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16560. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16561. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16562. default: jassertfalse; break;
  16563. }
  16564. }
  16565. startOffsetInDestBuffer += numThisTime;
  16566. numSamples -= numThisTime;
  16567. }
  16568. return true;
  16569. }
  16570. private:
  16571. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16572. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16573. };
  16574. class AiffAudioFormatWriter : public AudioFormatWriter
  16575. {
  16576. public:
  16577. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16578. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16579. lengthInSamples (0),
  16580. bytesWritten (0),
  16581. writeFailed (false)
  16582. {
  16583. headerPosition = out->getPosition();
  16584. writeHeader();
  16585. }
  16586. ~AiffAudioFormatWriter()
  16587. {
  16588. if ((bytesWritten & 1) != 0)
  16589. output->writeByte (0);
  16590. writeHeader();
  16591. }
  16592. bool write (const int** data, int numSamples)
  16593. {
  16594. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16595. if (writeFailed)
  16596. return false;
  16597. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16598. tempBlock.ensureSize (bytes, false);
  16599. switch (bitsPerSample)
  16600. {
  16601. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16602. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16603. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16604. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16605. default: jassertfalse; break;
  16606. }
  16607. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16608. || ! output->write (tempBlock.getData(), bytes))
  16609. {
  16610. // failed to write to disk, so let's try writing the header.
  16611. // If it's just run out of disk space, then if it does manage
  16612. // to write the header, we'll still have a useable file..
  16613. writeHeader();
  16614. writeFailed = true;
  16615. return false;
  16616. }
  16617. else
  16618. {
  16619. bytesWritten += bytes;
  16620. lengthInSamples += numSamples;
  16621. return true;
  16622. }
  16623. }
  16624. private:
  16625. MemoryBlock tempBlock;
  16626. uint32 lengthInSamples, bytesWritten;
  16627. int64 headerPosition;
  16628. bool writeFailed;
  16629. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16630. void writeHeader()
  16631. {
  16632. const bool couldSeekOk = output->setPosition (headerPosition);
  16633. (void) couldSeekOk;
  16634. // if this fails, you've given it an output stream that can't seek! It needs
  16635. // to be able to seek back to write the header
  16636. jassert (couldSeekOk);
  16637. const int headerLen = 54;
  16638. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16639. audioBytes += (audioBytes & 1);
  16640. output->writeInt (chunkName ("FORM"));
  16641. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16642. output->writeInt (chunkName ("AIFF"));
  16643. output->writeInt (chunkName ("COMM"));
  16644. output->writeIntBigEndian (18);
  16645. output->writeShortBigEndian ((short) numChannels);
  16646. output->writeIntBigEndian (lengthInSamples);
  16647. output->writeShortBigEndian ((short) bitsPerSample);
  16648. uint8 sampleRateBytes[10];
  16649. zeromem (sampleRateBytes, 10);
  16650. if (sampleRate <= 1)
  16651. {
  16652. sampleRateBytes[0] = 0x3f;
  16653. sampleRateBytes[1] = 0xff;
  16654. sampleRateBytes[2] = 0x80;
  16655. }
  16656. else
  16657. {
  16658. int mask = 0x40000000;
  16659. sampleRateBytes[0] = 0x40;
  16660. if (sampleRate >= mask)
  16661. {
  16662. jassertfalse;
  16663. sampleRateBytes[1] = 0x1d;
  16664. }
  16665. else
  16666. {
  16667. int n = (int) sampleRate;
  16668. int i;
  16669. for (i = 0; i <= 32 ; ++i)
  16670. {
  16671. if ((n & mask) != 0)
  16672. break;
  16673. mask >>= 1;
  16674. }
  16675. n = n << (i + 1);
  16676. sampleRateBytes[1] = (uint8) (29 - i);
  16677. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16678. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16679. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16680. sampleRateBytes[5] = (uint8) (n & 0xff);
  16681. }
  16682. }
  16683. output->write (sampleRateBytes, 10);
  16684. output->writeInt (chunkName ("SSND"));
  16685. output->writeIntBigEndian (audioBytes + 8);
  16686. output->writeInt (0);
  16687. output->writeInt (0);
  16688. jassert (output->getPosition() == headerLen);
  16689. }
  16690. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16691. };
  16692. AiffAudioFormat::AiffAudioFormat()
  16693. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16694. {
  16695. }
  16696. AiffAudioFormat::~AiffAudioFormat()
  16697. {
  16698. }
  16699. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16700. {
  16701. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16702. return Array <int> (rates);
  16703. }
  16704. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16705. {
  16706. const int depths[] = { 8, 16, 24, 0 };
  16707. return Array <int> (depths);
  16708. }
  16709. bool AiffAudioFormat::canDoStereo() { return true; }
  16710. bool AiffAudioFormat::canDoMono() { return true; }
  16711. #if JUCE_MAC
  16712. bool AiffAudioFormat::canHandleFile (const File& f)
  16713. {
  16714. if (AudioFormat::canHandleFile (f))
  16715. return true;
  16716. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16717. return type == 'AIFF' || type == 'AIFC'
  16718. || type == 'aiff' || type == 'aifc';
  16719. }
  16720. #endif
  16721. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16722. {
  16723. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16724. if (w->sampleRate != 0)
  16725. return w.release();
  16726. if (! deleteStreamIfOpeningFails)
  16727. w->input = 0;
  16728. return 0;
  16729. }
  16730. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16731. double sampleRate,
  16732. unsigned int numberOfChannels,
  16733. int bitsPerSample,
  16734. const StringPairArray& /*metadataValues*/,
  16735. int /*qualityOptionIndex*/)
  16736. {
  16737. if (getPossibleBitDepths().contains (bitsPerSample))
  16738. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16739. return 0;
  16740. }
  16741. END_JUCE_NAMESPACE
  16742. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16743. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16744. BEGIN_JUCE_NAMESPACE
  16745. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16746. : formatName (name),
  16747. fileExtensions (extensions)
  16748. {
  16749. }
  16750. AudioFormat::~AudioFormat()
  16751. {
  16752. }
  16753. bool AudioFormat::canHandleFile (const File& f)
  16754. {
  16755. for (int i = 0; i < fileExtensions.size(); ++i)
  16756. if (f.hasFileExtension (fileExtensions[i]))
  16757. return true;
  16758. return false;
  16759. }
  16760. const String& AudioFormat::getFormatName() const { return formatName; }
  16761. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16762. bool AudioFormat::isCompressed() { return false; }
  16763. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16764. END_JUCE_NAMESPACE
  16765. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16766. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16767. BEGIN_JUCE_NAMESPACE
  16768. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16769. const String& formatName_)
  16770. : sampleRate (0),
  16771. bitsPerSample (0),
  16772. lengthInSamples (0),
  16773. numChannels (0),
  16774. usesFloatingPointData (false),
  16775. input (in),
  16776. formatName (formatName_)
  16777. {
  16778. }
  16779. AudioFormatReader::~AudioFormatReader()
  16780. {
  16781. delete input;
  16782. }
  16783. bool AudioFormatReader::read (int* const* destSamples,
  16784. int numDestChannels,
  16785. int64 startSampleInSource,
  16786. int numSamplesToRead,
  16787. const bool fillLeftoverChannelsWithCopies)
  16788. {
  16789. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16790. int startOffsetInDestBuffer = 0;
  16791. if (startSampleInSource < 0)
  16792. {
  16793. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16794. for (int i = numDestChannels; --i >= 0;)
  16795. if (destSamples[i] != 0)
  16796. zeromem (destSamples[i], sizeof (int) * silence);
  16797. startOffsetInDestBuffer += silence;
  16798. numSamplesToRead -= silence;
  16799. startSampleInSource = 0;
  16800. }
  16801. if (numSamplesToRead <= 0)
  16802. return true;
  16803. if (! readSamples (const_cast<int**> (destSamples),
  16804. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16805. startSampleInSource, numSamplesToRead))
  16806. return false;
  16807. if (numDestChannels > (int) numChannels)
  16808. {
  16809. if (fillLeftoverChannelsWithCopies)
  16810. {
  16811. int* lastFullChannel = destSamples[0];
  16812. for (int i = (int) numChannels; --i > 0;)
  16813. {
  16814. if (destSamples[i] != 0)
  16815. {
  16816. lastFullChannel = destSamples[i];
  16817. break;
  16818. }
  16819. }
  16820. if (lastFullChannel != 0)
  16821. for (int i = numChannels; i < numDestChannels; ++i)
  16822. if (destSamples[i] != 0)
  16823. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16824. }
  16825. else
  16826. {
  16827. for (int i = numChannels; i < numDestChannels; ++i)
  16828. if (destSamples[i] != 0)
  16829. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16830. }
  16831. }
  16832. return true;
  16833. }
  16834. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16835. int64 numSamples,
  16836. float& lowestLeft, float& highestLeft,
  16837. float& lowestRight, float& highestRight)
  16838. {
  16839. if (numSamples <= 0)
  16840. {
  16841. lowestLeft = 0;
  16842. lowestRight = 0;
  16843. highestLeft = 0;
  16844. highestRight = 0;
  16845. return;
  16846. }
  16847. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16848. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16849. int* tempBuffer[3];
  16850. tempBuffer[0] = tempSpace.getData();
  16851. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16852. tempBuffer[2] = 0;
  16853. if (usesFloatingPointData)
  16854. {
  16855. float lmin = 1.0e6f;
  16856. float lmax = -lmin;
  16857. float rmin = lmin;
  16858. float rmax = lmax;
  16859. while (numSamples > 0)
  16860. {
  16861. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16862. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  16863. numSamples -= numToDo;
  16864. startSampleInFile += numToDo;
  16865. float bufMin, bufMax;
  16866. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  16867. lmin = jmin (lmin, bufMin);
  16868. lmax = jmax (lmax, bufMax);
  16869. if (numChannels > 1)
  16870. {
  16871. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  16872. rmin = jmin (rmin, bufMin);
  16873. rmax = jmax (rmax, bufMax);
  16874. }
  16875. }
  16876. if (numChannels <= 1)
  16877. {
  16878. rmax = lmax;
  16879. rmin = lmin;
  16880. }
  16881. lowestLeft = lmin;
  16882. highestLeft = lmax;
  16883. lowestRight = rmin;
  16884. highestRight = rmax;
  16885. }
  16886. else
  16887. {
  16888. int lmax = std::numeric_limits<int>::min();
  16889. int lmin = std::numeric_limits<int>::max();
  16890. int rmax = std::numeric_limits<int>::min();
  16891. int rmin = std::numeric_limits<int>::max();
  16892. while (numSamples > 0)
  16893. {
  16894. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16895. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  16896. break;
  16897. numSamples -= numToDo;
  16898. startSampleInFile += numToDo;
  16899. for (int j = numChannels; --j >= 0;)
  16900. {
  16901. int bufMin, bufMax;
  16902. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  16903. if (j == 0)
  16904. {
  16905. lmax = jmax (lmax, bufMax);
  16906. lmin = jmin (lmin, bufMin);
  16907. }
  16908. else
  16909. {
  16910. rmax = jmax (rmax, bufMax);
  16911. rmin = jmin (rmin, bufMin);
  16912. }
  16913. }
  16914. }
  16915. if (numChannels <= 1)
  16916. {
  16917. rmax = lmax;
  16918. rmin = lmin;
  16919. }
  16920. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16921. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16922. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16923. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16924. }
  16925. }
  16926. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16927. int64 numSamplesToSearch,
  16928. const double magnitudeRangeMinimum,
  16929. const double magnitudeRangeMaximum,
  16930. const int minimumConsecutiveSamples)
  16931. {
  16932. if (numSamplesToSearch == 0)
  16933. return -1;
  16934. const int bufferSize = 4096;
  16935. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16936. int* tempBuffer[3];
  16937. tempBuffer[0] = tempSpace.getData();
  16938. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16939. tempBuffer[2] = 0;
  16940. int consecutive = 0;
  16941. int64 firstMatchPos = -1;
  16942. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16943. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16944. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16945. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16946. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16947. while (numSamplesToSearch != 0)
  16948. {
  16949. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16950. int64 bufferStart = startSample;
  16951. if (numSamplesToSearch < 0)
  16952. bufferStart -= numThisTime;
  16953. if (bufferStart >= (int) lengthInSamples)
  16954. break;
  16955. read (tempBuffer, 2, bufferStart, numThisTime, false);
  16956. int num = numThisTime;
  16957. while (--num >= 0)
  16958. {
  16959. if (numSamplesToSearch < 0)
  16960. --startSample;
  16961. bool matches = false;
  16962. const int index = (int) (startSample - bufferStart);
  16963. if (usesFloatingPointData)
  16964. {
  16965. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16966. if (sample1 >= magnitudeRangeMinimum
  16967. && sample1 <= magnitudeRangeMaximum)
  16968. {
  16969. matches = true;
  16970. }
  16971. else if (numChannels > 1)
  16972. {
  16973. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16974. matches = (sample2 >= magnitudeRangeMinimum
  16975. && sample2 <= magnitudeRangeMaximum);
  16976. }
  16977. }
  16978. else
  16979. {
  16980. const int sample1 = abs (tempBuffer[0] [index]);
  16981. if (sample1 >= intMagnitudeRangeMinimum
  16982. && sample1 <= intMagnitudeRangeMaximum)
  16983. {
  16984. matches = true;
  16985. }
  16986. else if (numChannels > 1)
  16987. {
  16988. const int sample2 = abs (tempBuffer[1][index]);
  16989. matches = (sample2 >= intMagnitudeRangeMinimum
  16990. && sample2 <= intMagnitudeRangeMaximum);
  16991. }
  16992. }
  16993. if (matches)
  16994. {
  16995. if (firstMatchPos < 0)
  16996. firstMatchPos = startSample;
  16997. if (++consecutive >= minimumConsecutiveSamples)
  16998. {
  16999. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17000. return -1;
  17001. return firstMatchPos;
  17002. }
  17003. }
  17004. else
  17005. {
  17006. consecutive = 0;
  17007. firstMatchPos = -1;
  17008. }
  17009. if (numSamplesToSearch > 0)
  17010. ++startSample;
  17011. }
  17012. if (numSamplesToSearch > 0)
  17013. numSamplesToSearch -= numThisTime;
  17014. else
  17015. numSamplesToSearch += numThisTime;
  17016. }
  17017. return -1;
  17018. }
  17019. END_JUCE_NAMESPACE
  17020. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17021. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17022. BEGIN_JUCE_NAMESPACE
  17023. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17024. const String& formatName_,
  17025. const double rate,
  17026. const unsigned int numChannels_,
  17027. const unsigned int bitsPerSample_)
  17028. : sampleRate (rate),
  17029. numChannels (numChannels_),
  17030. bitsPerSample (bitsPerSample_),
  17031. usesFloatingPointData (false),
  17032. output (out),
  17033. formatName (formatName_)
  17034. {
  17035. }
  17036. AudioFormatWriter::~AudioFormatWriter()
  17037. {
  17038. delete output;
  17039. }
  17040. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17041. int64 startSample,
  17042. int64 numSamplesToRead)
  17043. {
  17044. const int bufferSize = 16384;
  17045. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17046. int* buffers [128];
  17047. zerostruct (buffers);
  17048. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17049. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17050. if (numSamplesToRead < 0)
  17051. numSamplesToRead = reader.lengthInSamples;
  17052. while (numSamplesToRead > 0)
  17053. {
  17054. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17055. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17056. return false;
  17057. if (reader.usesFloatingPointData != isFloatingPoint())
  17058. {
  17059. int** bufferChan = buffers;
  17060. while (*bufferChan != 0)
  17061. {
  17062. int* b = *bufferChan++;
  17063. if (isFloatingPoint())
  17064. {
  17065. // int -> float
  17066. const double factor = 1.0 / std::numeric_limits<int>::max();
  17067. for (int i = 0; i < numToDo; ++i)
  17068. ((float*) b)[i] = (float) (factor * b[i]);
  17069. }
  17070. else
  17071. {
  17072. // float -> int
  17073. for (int i = 0; i < numToDo; ++i)
  17074. {
  17075. const double samp = *(const float*) b;
  17076. if (samp <= -1.0)
  17077. *b++ = std::numeric_limits<int>::min();
  17078. else if (samp >= 1.0)
  17079. *b++ = std::numeric_limits<int>::max();
  17080. else
  17081. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17082. }
  17083. }
  17084. }
  17085. }
  17086. if (! write (const_cast<const int**> (buffers), numToDo))
  17087. return false;
  17088. numSamplesToRead -= numToDo;
  17089. startSample += numToDo;
  17090. }
  17091. return true;
  17092. }
  17093. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17094. {
  17095. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17096. while (numSamplesToRead > 0)
  17097. {
  17098. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17099. AudioSourceChannelInfo info;
  17100. info.buffer = &tempBuffer;
  17101. info.startSample = 0;
  17102. info.numSamples = numToDo;
  17103. info.clearActiveBufferRegion();
  17104. source.getNextAudioBlock (info);
  17105. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17106. return false;
  17107. numSamplesToRead -= numToDo;
  17108. }
  17109. return true;
  17110. }
  17111. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17112. {
  17113. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17114. if (numSamples <= 0)
  17115. return true;
  17116. HeapBlock<int> tempBuffer;
  17117. HeapBlock<int*> chans (numChannels + 1);
  17118. chans [numChannels] = 0;
  17119. if (isFloatingPoint())
  17120. {
  17121. for (int i = numChannels; --i >= 0;)
  17122. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17123. }
  17124. else
  17125. {
  17126. tempBuffer.malloc (numSamples * numChannels);
  17127. for (unsigned int i = 0; i < numChannels; ++i)
  17128. {
  17129. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17130. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17131. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17132. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17133. destData.convertSamples (sourceData, numSamples);
  17134. }
  17135. }
  17136. return write ((const int**) chans.getData(), numSamples);
  17137. }
  17138. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17139. public AbstractFifo
  17140. {
  17141. public:
  17142. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize_)
  17143. : AbstractFifo (bufferSize_),
  17144. buffer (numChannels, bufferSize_),
  17145. timeSliceThread (timeSliceThread_),
  17146. writer (writer_),
  17147. thumbnailToUpdate (0),
  17148. samplesWritten (0),
  17149. isRunning (true)
  17150. {
  17151. timeSliceThread.addTimeSliceClient (this);
  17152. }
  17153. ~Buffer()
  17154. {
  17155. isRunning = false;
  17156. timeSliceThread.removeTimeSliceClient (this);
  17157. while (useTimeSlice())
  17158. {}
  17159. }
  17160. bool write (const float** data, int numSamples)
  17161. {
  17162. if (numSamples <= 0 || ! isRunning)
  17163. return true;
  17164. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17165. int start1, size1, start2, size2;
  17166. prepareToWrite (numSamples, start1, size1, start2, size2);
  17167. if (size1 + size2 < numSamples)
  17168. return false;
  17169. for (int i = buffer.getNumChannels(); --i >= 0;)
  17170. {
  17171. buffer.copyFrom (i, start1, data[i], size1);
  17172. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17173. }
  17174. finishedWrite (size1 + size2);
  17175. timeSliceThread.notify();
  17176. return true;
  17177. }
  17178. bool useTimeSlice()
  17179. {
  17180. const int numToDo = getTotalSize() / 4;
  17181. int start1, size1, start2, size2;
  17182. prepareToRead (numToDo, start1, size1, start2, size2);
  17183. if (size1 <= 0)
  17184. return false;
  17185. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17186. const ScopedLock sl (thumbnailLock);
  17187. if (thumbnailToUpdate != 0)
  17188. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  17189. samplesWritten += size1;
  17190. if (size2 > 0)
  17191. {
  17192. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17193. if (thumbnailToUpdate != 0)
  17194. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  17195. samplesWritten += size2;
  17196. }
  17197. finishedRead (size1 + size2);
  17198. return true;
  17199. }
  17200. void setThumbnail (AudioThumbnail* thumb)
  17201. {
  17202. if (thumb != 0)
  17203. thumb->reset (buffer.getNumChannels(), writer->getSampleRate(), 0);
  17204. const ScopedLock sl (thumbnailLock);
  17205. thumbnailToUpdate = thumb;
  17206. samplesWritten = 0;
  17207. }
  17208. private:
  17209. AudioSampleBuffer buffer;
  17210. TimeSliceThread& timeSliceThread;
  17211. ScopedPointer<AudioFormatWriter> writer;
  17212. CriticalSection thumbnailLock;
  17213. AudioThumbnail* thumbnailToUpdate;
  17214. int64 samplesWritten;
  17215. volatile bool isRunning;
  17216. JUCE_DECLARE_NON_COPYABLE (Buffer);
  17217. };
  17218. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17219. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17220. {
  17221. }
  17222. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17223. {
  17224. }
  17225. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17226. {
  17227. return buffer->write (data, numSamples);
  17228. }
  17229. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  17230. {
  17231. buffer->setThumbnail (thumb);
  17232. }
  17233. END_JUCE_NAMESPACE
  17234. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17235. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17236. BEGIN_JUCE_NAMESPACE
  17237. AudioFormatManager::AudioFormatManager()
  17238. : defaultFormatIndex (0)
  17239. {
  17240. }
  17241. AudioFormatManager::~AudioFormatManager()
  17242. {
  17243. }
  17244. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  17245. {
  17246. jassert (newFormat != 0);
  17247. if (newFormat != 0)
  17248. {
  17249. #if JUCE_DEBUG
  17250. for (int i = getNumKnownFormats(); --i >= 0;)
  17251. {
  17252. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17253. {
  17254. jassertfalse; // trying to add the same format twice!
  17255. }
  17256. }
  17257. #endif
  17258. if (makeThisTheDefaultFormat)
  17259. defaultFormatIndex = getNumKnownFormats();
  17260. knownFormats.add (newFormat);
  17261. }
  17262. }
  17263. void AudioFormatManager::registerBasicFormats()
  17264. {
  17265. #if JUCE_MAC
  17266. registerFormat (new AiffAudioFormat(), true);
  17267. registerFormat (new WavAudioFormat(), false);
  17268. #else
  17269. registerFormat (new WavAudioFormat(), true);
  17270. registerFormat (new AiffAudioFormat(), false);
  17271. #endif
  17272. #if JUCE_USE_FLAC
  17273. registerFormat (new FlacAudioFormat(), false);
  17274. #endif
  17275. #if JUCE_USE_OGGVORBIS
  17276. registerFormat (new OggVorbisAudioFormat(), false);
  17277. #endif
  17278. }
  17279. void AudioFormatManager::clearFormats()
  17280. {
  17281. knownFormats.clear();
  17282. defaultFormatIndex = 0;
  17283. }
  17284. int AudioFormatManager::getNumKnownFormats() const
  17285. {
  17286. return knownFormats.size();
  17287. }
  17288. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17289. {
  17290. return knownFormats [index];
  17291. }
  17292. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17293. {
  17294. return getKnownFormat (defaultFormatIndex);
  17295. }
  17296. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17297. {
  17298. String e (fileExtension);
  17299. if (! e.startsWithChar ('.'))
  17300. e = "." + e;
  17301. for (int i = 0; i < getNumKnownFormats(); ++i)
  17302. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17303. return getKnownFormat(i);
  17304. return 0;
  17305. }
  17306. const String AudioFormatManager::getWildcardForAllFormats() const
  17307. {
  17308. StringArray allExtensions;
  17309. int i;
  17310. for (i = 0; i < getNumKnownFormats(); ++i)
  17311. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17312. allExtensions.trim();
  17313. allExtensions.removeEmptyStrings();
  17314. String s;
  17315. for (i = 0; i < allExtensions.size(); ++i)
  17316. {
  17317. s << '*';
  17318. if (! allExtensions[i].startsWithChar ('.'))
  17319. s << '.';
  17320. s << allExtensions[i];
  17321. if (i < allExtensions.size() - 1)
  17322. s << ';';
  17323. }
  17324. return s;
  17325. }
  17326. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17327. {
  17328. // you need to actually register some formats before the manager can
  17329. // use them to open a file!
  17330. jassert (getNumKnownFormats() > 0);
  17331. for (int i = 0; i < getNumKnownFormats(); ++i)
  17332. {
  17333. AudioFormat* const af = getKnownFormat(i);
  17334. if (af->canHandleFile (file))
  17335. {
  17336. InputStream* const in = file.createInputStream();
  17337. if (in != 0)
  17338. {
  17339. AudioFormatReader* const r = af->createReaderFor (in, true);
  17340. if (r != 0)
  17341. return r;
  17342. }
  17343. }
  17344. }
  17345. return 0;
  17346. }
  17347. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17348. {
  17349. // you need to actually register some formats before the manager can
  17350. // use them to open a file!
  17351. jassert (getNumKnownFormats() > 0);
  17352. ScopedPointer <InputStream> in (audioFileStream);
  17353. if (in != 0)
  17354. {
  17355. const int64 originalStreamPos = in->getPosition();
  17356. for (int i = 0; i < getNumKnownFormats(); ++i)
  17357. {
  17358. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17359. if (r != 0)
  17360. {
  17361. in.release();
  17362. return r;
  17363. }
  17364. in->setPosition (originalStreamPos);
  17365. // the stream that is passed-in must be capable of being repositioned so
  17366. // that all the formats can have a go at opening it.
  17367. jassert (in->getPosition() == originalStreamPos);
  17368. }
  17369. }
  17370. return 0;
  17371. }
  17372. END_JUCE_NAMESPACE
  17373. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17374. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17375. BEGIN_JUCE_NAMESPACE
  17376. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17377. const int64 startSample_,
  17378. const int64 length_,
  17379. const bool deleteSourceWhenDeleted_)
  17380. : AudioFormatReader (0, source_->getFormatName()),
  17381. source (source_),
  17382. startSample (startSample_),
  17383. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17384. {
  17385. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17386. sampleRate = source->sampleRate;
  17387. bitsPerSample = source->bitsPerSample;
  17388. lengthInSamples = length;
  17389. numChannels = source->numChannels;
  17390. usesFloatingPointData = source->usesFloatingPointData;
  17391. }
  17392. AudioSubsectionReader::~AudioSubsectionReader()
  17393. {
  17394. if (deleteSourceWhenDeleted)
  17395. delete source;
  17396. }
  17397. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17398. int64 startSampleInFile, int numSamples)
  17399. {
  17400. if (startSampleInFile + numSamples > length)
  17401. {
  17402. for (int i = numDestChannels; --i >= 0;)
  17403. if (destSamples[i] != 0)
  17404. zeromem (destSamples[i], sizeof (int) * numSamples);
  17405. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17406. if (numSamples <= 0)
  17407. return true;
  17408. }
  17409. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17410. startSampleInFile + startSample, numSamples);
  17411. }
  17412. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17413. int64 numSamples,
  17414. float& lowestLeft,
  17415. float& highestLeft,
  17416. float& lowestRight,
  17417. float& highestRight)
  17418. {
  17419. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17420. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17421. source->readMaxLevels (startSampleInFile + startSample,
  17422. numSamples,
  17423. lowestLeft,
  17424. highestLeft,
  17425. lowestRight,
  17426. highestRight);
  17427. }
  17428. END_JUCE_NAMESPACE
  17429. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17430. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17431. BEGIN_JUCE_NAMESPACE
  17432. struct AudioThumbnail::MinMaxValue
  17433. {
  17434. char minValue;
  17435. char maxValue;
  17436. MinMaxValue() : minValue (0), maxValue (0)
  17437. {
  17438. }
  17439. inline void set (const char newMin, const char newMax) throw()
  17440. {
  17441. minValue = newMin;
  17442. maxValue = newMax;
  17443. }
  17444. inline void setFloat (const float newMin, const float newMax) throw()
  17445. {
  17446. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17447. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17448. if (maxValue == minValue)
  17449. maxValue = (char) jmin (127, maxValue + 1);
  17450. }
  17451. inline bool isNonZero() const throw()
  17452. {
  17453. return maxValue > minValue;
  17454. }
  17455. inline int getPeak() const throw()
  17456. {
  17457. return jmax (std::abs ((int) minValue),
  17458. std::abs ((int) maxValue));
  17459. }
  17460. inline void read (InputStream& input)
  17461. {
  17462. minValue = input.readByte();
  17463. maxValue = input.readByte();
  17464. }
  17465. inline void write (OutputStream& output)
  17466. {
  17467. output.writeByte (minValue);
  17468. output.writeByte (maxValue);
  17469. }
  17470. };
  17471. class AudioThumbnail::LevelDataSource : public TimeSliceClient,
  17472. public Timer
  17473. {
  17474. public:
  17475. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17476. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17477. hashCode (hash), owner (owner_), reader (newReader)
  17478. {
  17479. }
  17480. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17481. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17482. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17483. {
  17484. }
  17485. ~LevelDataSource()
  17486. {
  17487. owner.cache.removeTimeSliceClient (this);
  17488. }
  17489. enum { timeBeforeDeletingReader = 2000 };
  17490. void initialise (int64 numSamplesFinished_)
  17491. {
  17492. const ScopedLock sl (readerLock);
  17493. numSamplesFinished = numSamplesFinished_;
  17494. createReader();
  17495. if (reader != 0)
  17496. {
  17497. lengthInSamples = reader->lengthInSamples;
  17498. numChannels = reader->numChannels;
  17499. sampleRate = reader->sampleRate;
  17500. if (lengthInSamples <= 0)
  17501. reader = 0;
  17502. else if (! isFullyLoaded())
  17503. owner.cache.addTimeSliceClient (this);
  17504. }
  17505. }
  17506. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17507. {
  17508. const ScopedLock sl (readerLock);
  17509. createReader();
  17510. if (reader != 0)
  17511. {
  17512. float l[4] = { 0 };
  17513. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17514. levels.clearQuick();
  17515. levels.addArray ((const float*) l, 4);
  17516. }
  17517. }
  17518. void releaseResources()
  17519. {
  17520. const ScopedLock sl (readerLock);
  17521. reader = 0;
  17522. }
  17523. bool useTimeSlice()
  17524. {
  17525. if (isFullyLoaded())
  17526. {
  17527. if (reader != 0 && source != 0)
  17528. startTimer (timeBeforeDeletingReader);
  17529. owner.cache.removeTimeSliceClient (this);
  17530. return false;
  17531. }
  17532. stopTimer();
  17533. bool justFinished = false;
  17534. {
  17535. const ScopedLock sl (readerLock);
  17536. createReader();
  17537. if (reader != 0)
  17538. {
  17539. if (! readNextBlock())
  17540. return true;
  17541. justFinished = true;
  17542. }
  17543. }
  17544. if (justFinished)
  17545. owner.cache.storeThumb (owner, hashCode);
  17546. return false;
  17547. }
  17548. void timerCallback()
  17549. {
  17550. stopTimer();
  17551. releaseResources();
  17552. }
  17553. bool isFullyLoaded() const throw()
  17554. {
  17555. return numSamplesFinished >= lengthInSamples;
  17556. }
  17557. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17558. {
  17559. return (int) (originalSample / owner.samplesPerThumbSample);
  17560. }
  17561. int64 lengthInSamples, numSamplesFinished;
  17562. double sampleRate;
  17563. int numChannels;
  17564. int64 hashCode;
  17565. private:
  17566. AudioThumbnail& owner;
  17567. ScopedPointer <InputSource> source;
  17568. ScopedPointer <AudioFormatReader> reader;
  17569. CriticalSection readerLock;
  17570. void createReader()
  17571. {
  17572. if (reader == 0 && source != 0)
  17573. {
  17574. InputStream* audioFileStream = source->createInputStream();
  17575. if (audioFileStream != 0)
  17576. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17577. }
  17578. }
  17579. bool readNextBlock()
  17580. {
  17581. jassert (reader != 0);
  17582. if (! isFullyLoaded())
  17583. {
  17584. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17585. if (numToDo > 0)
  17586. {
  17587. int64 startSample = numSamplesFinished;
  17588. const int firstThumbIndex = sampleToThumbSample (startSample);
  17589. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17590. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17591. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17592. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17593. for (int i = 0; i < numThumbSamps; ++i)
  17594. {
  17595. float lowestLeft, highestLeft, lowestRight, highestRight;
  17596. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17597. lowestLeft, highestLeft, lowestRight, highestRight);
  17598. levels[0][i].setFloat (lowestLeft, highestLeft);
  17599. levels[1][i].setFloat (lowestRight, highestRight);
  17600. }
  17601. {
  17602. const ScopedUnlock su (readerLock);
  17603. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17604. }
  17605. numSamplesFinished += numToDo;
  17606. }
  17607. }
  17608. return isFullyLoaded();
  17609. }
  17610. };
  17611. class AudioThumbnail::ThumbData
  17612. {
  17613. public:
  17614. ThumbData (const int numThumbSamples)
  17615. : peakLevel (-1)
  17616. {
  17617. ensureSize (numThumbSamples);
  17618. }
  17619. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17620. {
  17621. jassert (thumbSampleIndex < data.size());
  17622. return data.getRawDataPointer() + thumbSampleIndex;
  17623. }
  17624. int getSize() const throw()
  17625. {
  17626. return data.size();
  17627. }
  17628. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17629. {
  17630. if (startSample >= 0)
  17631. {
  17632. endSample = jmin (endSample, data.size() - 1);
  17633. char mx = -128;
  17634. char mn = 127;
  17635. while (startSample <= endSample)
  17636. {
  17637. const MinMaxValue& v = data.getReference (startSample);
  17638. if (v.minValue < mn) mn = v.minValue;
  17639. if (v.maxValue > mx) mx = v.maxValue;
  17640. ++startSample;
  17641. }
  17642. if (mn <= mx)
  17643. {
  17644. result.set (mn, mx);
  17645. return;
  17646. }
  17647. }
  17648. result.set (1, 0);
  17649. }
  17650. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17651. {
  17652. resetPeak();
  17653. if (startIndex + numValues > data.size())
  17654. ensureSize (startIndex + numValues);
  17655. MinMaxValue* const dest = getData (startIndex);
  17656. for (int i = 0; i < numValues; ++i)
  17657. dest[i] = source[i];
  17658. }
  17659. void resetPeak()
  17660. {
  17661. peakLevel = -1;
  17662. }
  17663. int getPeak()
  17664. {
  17665. if (peakLevel < 0)
  17666. {
  17667. for (int i = 0; i < data.size(); ++i)
  17668. {
  17669. const int peak = data[i].getPeak();
  17670. if (peak > peakLevel)
  17671. peakLevel = peak;
  17672. }
  17673. }
  17674. return peakLevel;
  17675. }
  17676. private:
  17677. Array <MinMaxValue> data;
  17678. int peakLevel;
  17679. void ensureSize (const int thumbSamples)
  17680. {
  17681. const int extraNeeded = thumbSamples - data.size();
  17682. if (extraNeeded > 0)
  17683. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17684. }
  17685. };
  17686. class AudioThumbnail::CachedWindow
  17687. {
  17688. public:
  17689. CachedWindow()
  17690. : cachedStart (0), cachedTimePerPixel (0),
  17691. numChannelsCached (0), numSamplesCached (0),
  17692. cacheNeedsRefilling (true)
  17693. {
  17694. }
  17695. void invalidate()
  17696. {
  17697. cacheNeedsRefilling = true;
  17698. }
  17699. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17700. const double startTime, const double endTime,
  17701. const int channelNum, const float verticalZoomFactor,
  17702. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17703. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17704. {
  17705. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17706. numChannels, samplesPerThumbSample, levelData, channels);
  17707. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17708. {
  17709. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17710. if (! clip.isEmpty())
  17711. {
  17712. const float topY = (float) area.getY();
  17713. const float bottomY = (float) area.getBottom();
  17714. const float midY = (topY + bottomY) * 0.5f;
  17715. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17716. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17717. int x = clip.getX();
  17718. for (int w = clip.getWidth(); --w >= 0;)
  17719. {
  17720. if (cacheData->isNonZero())
  17721. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17722. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17723. ++x;
  17724. ++cacheData;
  17725. }
  17726. }
  17727. }
  17728. }
  17729. private:
  17730. Array <MinMaxValue> data;
  17731. double cachedStart, cachedTimePerPixel;
  17732. int numChannelsCached, numSamplesCached;
  17733. bool cacheNeedsRefilling;
  17734. void refillCache (const int numSamples, double startTime, const double endTime,
  17735. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17736. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17737. {
  17738. const double timePerPixel = (endTime - startTime) / numSamples;
  17739. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17740. {
  17741. invalidate();
  17742. return;
  17743. }
  17744. if (numSamples == numSamplesCached
  17745. && numChannelsCached == numChannels
  17746. && startTime == cachedStart
  17747. && timePerPixel == cachedTimePerPixel
  17748. && ! cacheNeedsRefilling)
  17749. {
  17750. return;
  17751. }
  17752. numSamplesCached = numSamples;
  17753. numChannelsCached = numChannels;
  17754. cachedStart = startTime;
  17755. cachedTimePerPixel = timePerPixel;
  17756. cacheNeedsRefilling = false;
  17757. ensureSize (numSamples);
  17758. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17759. {
  17760. int sample = roundToInt (startTime * sampleRate);
  17761. Array<float> levels;
  17762. int i;
  17763. for (i = 0; i < numSamples; ++i)
  17764. {
  17765. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17766. if (sample >= 0)
  17767. {
  17768. if (sample >= levelData->lengthInSamples)
  17769. break;
  17770. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17771. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17772. for (int chan = 0; chan < numChans; ++chan)
  17773. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17774. levels.getUnchecked (chan * 2 + 1));
  17775. }
  17776. startTime += timePerPixel;
  17777. sample = nextSample;
  17778. }
  17779. numSamplesCached = i;
  17780. }
  17781. else
  17782. {
  17783. jassert (channels.size() == numChannelsCached);
  17784. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17785. {
  17786. ThumbData* channelData = channels.getUnchecked (channelNum);
  17787. MinMaxValue* cacheData = getData (channelNum, 0);
  17788. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17789. startTime = cachedStart;
  17790. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17791. for (int i = numSamples; --i >= 0;)
  17792. {
  17793. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17794. channelData->getMinMax (sample, nextSample, *cacheData);
  17795. ++cacheData;
  17796. startTime += timePerPixel;
  17797. sample = nextSample;
  17798. }
  17799. }
  17800. }
  17801. }
  17802. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17803. {
  17804. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17805. return data.getRawDataPointer() + channelNum * numSamplesCached
  17806. + cacheIndex;
  17807. }
  17808. void ensureSize (const int numSamples)
  17809. {
  17810. const int itemsRequired = numSamples * numChannelsCached;
  17811. if (data.size() < itemsRequired)
  17812. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  17813. }
  17814. };
  17815. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  17816. AudioFormatManager& formatManagerToUse_,
  17817. AudioThumbnailCache& cacheToUse)
  17818. : formatManagerToUse (formatManagerToUse_),
  17819. cache (cacheToUse),
  17820. window (new CachedWindow()),
  17821. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  17822. totalSamples (0),
  17823. numChannels (0),
  17824. sampleRate (0)
  17825. {
  17826. }
  17827. AudioThumbnail::~AudioThumbnail()
  17828. {
  17829. clear();
  17830. }
  17831. void AudioThumbnail::clear()
  17832. {
  17833. source = 0;
  17834. const ScopedLock sl (lock);
  17835. window->invalidate();
  17836. channels.clear();
  17837. totalSamples = numSamplesFinished = 0;
  17838. numChannels = 0;
  17839. sampleRate = 0;
  17840. sendChangeMessage();
  17841. }
  17842. void AudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  17843. {
  17844. clear();
  17845. numChannels = newNumChannels;
  17846. sampleRate = newSampleRate;
  17847. totalSamples = totalSamplesInSource;
  17848. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  17849. }
  17850. void AudioThumbnail::createChannels (const int length)
  17851. {
  17852. while (channels.size() < numChannels)
  17853. channels.add (new ThumbData (length));
  17854. }
  17855. void AudioThumbnail::loadFrom (InputStream& input)
  17856. {
  17857. clear();
  17858. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  17859. return;
  17860. samplesPerThumbSample = input.readInt();
  17861. totalSamples = input.readInt64(); // Total number of source samples.
  17862. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  17863. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  17864. numChannels = input.readInt(); // Number of audio channels.
  17865. sampleRate = input.readInt(); // Source sample rate.
  17866. input.skipNextBytes (16); // reserved area
  17867. createChannels (numThumbnailSamples);
  17868. for (int i = 0; i < numThumbnailSamples; ++i)
  17869. for (int chan = 0; chan < numChannels; ++chan)
  17870. channels.getUnchecked(chan)->getData(i)->read (input);
  17871. }
  17872. void AudioThumbnail::saveTo (OutputStream& output) const
  17873. {
  17874. const ScopedLock sl (lock);
  17875. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  17876. output.write ("jatm", 4);
  17877. output.writeInt (samplesPerThumbSample);
  17878. output.writeInt64 (totalSamples);
  17879. output.writeInt64 (numSamplesFinished);
  17880. output.writeInt (numThumbnailSamples);
  17881. output.writeInt (numChannels);
  17882. output.writeInt ((int) sampleRate);
  17883. output.writeInt64 (0);
  17884. output.writeInt64 (0);
  17885. for (int i = 0; i < numThumbnailSamples; ++i)
  17886. for (int chan = 0; chan < numChannels; ++chan)
  17887. channels.getUnchecked(chan)->getData(i)->write (output);
  17888. }
  17889. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  17890. {
  17891. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  17892. numSamplesFinished = 0;
  17893. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  17894. {
  17895. source = newSource; // (make sure this isn't done before loadThumb is called)
  17896. source->lengthInSamples = totalSamples;
  17897. source->sampleRate = sampleRate;
  17898. source->numChannels = numChannels;
  17899. source->numSamplesFinished = numSamplesFinished;
  17900. }
  17901. else
  17902. {
  17903. source = newSource; // (make sure this isn't done before loadThumb is called)
  17904. const ScopedLock sl (lock);
  17905. source->initialise (numSamplesFinished);
  17906. totalSamples = source->lengthInSamples;
  17907. sampleRate = source->sampleRate;
  17908. numChannels = source->numChannels;
  17909. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  17910. }
  17911. return sampleRate > 0 && totalSamples > 0;
  17912. }
  17913. bool AudioThumbnail::setSource (InputSource* const newSource)
  17914. {
  17915. clear();
  17916. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  17917. }
  17918. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  17919. {
  17920. clear();
  17921. if (newReader != 0)
  17922. setDataSource (new LevelDataSource (*this, newReader, hash));
  17923. }
  17924. int64 AudioThumbnail::getHashCode() const
  17925. {
  17926. return source == 0 ? 0 : source->hashCode;
  17927. }
  17928. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  17929. int startOffsetInBuffer, int numSamples)
  17930. {
  17931. jassert (startSample >= 0);
  17932. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  17933. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  17934. const int numToDo = lastThumbIndex - firstThumbIndex;
  17935. if (numToDo > 0)
  17936. {
  17937. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  17938. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  17939. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  17940. for (int chan = 0; chan < numChans; ++chan)
  17941. {
  17942. const float* const sourceData = incoming.getSampleData (chan, startOffsetInBuffer);
  17943. MinMaxValue* const dest = thumbData + numToDo * chan;
  17944. thumbChannels [chan] = dest;
  17945. for (int i = 0; i < numToDo; ++i)
  17946. {
  17947. float low, high;
  17948. const int start = i * samplesPerThumbSample;
  17949. findMinAndMax (sourceData + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  17950. dest[i].setFloat (low, high);
  17951. }
  17952. }
  17953. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  17954. }
  17955. }
  17956. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  17957. {
  17958. const ScopedLock sl (lock);
  17959. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  17960. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  17961. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  17962. totalSamples = jmax (numSamplesFinished, totalSamples);
  17963. window->invalidate();
  17964. sendChangeMessage();
  17965. }
  17966. int AudioThumbnail::getNumChannels() const throw()
  17967. {
  17968. return numChannels;
  17969. }
  17970. double AudioThumbnail::getTotalLength() const throw()
  17971. {
  17972. return totalSamples / sampleRate;
  17973. }
  17974. bool AudioThumbnail::isFullyLoaded() const throw()
  17975. {
  17976. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  17977. }
  17978. int64 AudioThumbnail::getNumSamplesFinished() const throw()
  17979. {
  17980. return numSamplesFinished;
  17981. }
  17982. float AudioThumbnail::getApproximatePeak() const
  17983. {
  17984. int peak = 0;
  17985. for (int i = channels.size(); --i >= 0;)
  17986. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  17987. return jlimit (0, 127, peak) / 127.0f;
  17988. }
  17989. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  17990. double endTime, int channelNum, float verticalZoomFactor)
  17991. {
  17992. const ScopedLock sl (lock);
  17993. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  17994. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  17995. }
  17996. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  17997. double endTimeSeconds, float verticalZoomFactor)
  17998. {
  17999. for (int i = 0; i < numChannels; ++i)
  18000. {
  18001. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  18002. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  18003. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  18004. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  18005. }
  18006. }
  18007. END_JUCE_NAMESPACE
  18008. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18009. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18010. BEGIN_JUCE_NAMESPACE
  18011. struct ThumbnailCacheEntry
  18012. {
  18013. int64 hash;
  18014. uint32 lastUsed;
  18015. MemoryBlock data;
  18016. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  18017. };
  18018. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18019. : TimeSliceThread ("thumb cache"),
  18020. maxNumThumbsToStore (maxNumThumbsToStore_)
  18021. {
  18022. startThread (2);
  18023. }
  18024. AudioThumbnailCache::~AudioThumbnailCache()
  18025. {
  18026. }
  18027. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  18028. {
  18029. for (int i = thumbs.size(); --i >= 0;)
  18030. if (thumbs.getUnchecked(i)->hash == hash)
  18031. return thumbs.getUnchecked(i);
  18032. return 0;
  18033. }
  18034. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18035. {
  18036. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  18037. if (te != 0)
  18038. {
  18039. te->lastUsed = Time::getMillisecondCounter();
  18040. MemoryInputStream in (te->data, false);
  18041. thumb.loadFrom (in);
  18042. return true;
  18043. }
  18044. return false;
  18045. }
  18046. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18047. const int64 hashCode)
  18048. {
  18049. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  18050. if (te == 0)
  18051. {
  18052. te = new ThumbnailCacheEntry();
  18053. te->hash = hashCode;
  18054. if (thumbs.size() < maxNumThumbsToStore)
  18055. {
  18056. thumbs.add (te);
  18057. }
  18058. else
  18059. {
  18060. int oldest = 0;
  18061. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  18062. for (int i = thumbs.size(); --i >= 0;)
  18063. {
  18064. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  18065. {
  18066. oldest = i;
  18067. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  18068. }
  18069. }
  18070. thumbs.set (oldest, te);
  18071. }
  18072. }
  18073. te->lastUsed = Time::getMillisecondCounter();
  18074. MemoryOutputStream out (te->data, false);
  18075. thumb.saveTo (out);
  18076. }
  18077. void AudioThumbnailCache::clear()
  18078. {
  18079. thumbs.clear();
  18080. }
  18081. END_JUCE_NAMESPACE
  18082. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18083. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18084. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18085. #if ! JUCE_WINDOWS
  18086. #include <QuickTime/Movies.h>
  18087. #include <QuickTime/QTML.h>
  18088. #include <QuickTime/QuickTimeComponents.h>
  18089. #include <QuickTime/MediaHandlers.h>
  18090. #include <QuickTime/ImageCodec.h>
  18091. #else
  18092. #if JUCE_MSVC
  18093. #pragma warning (push)
  18094. #pragma warning (disable : 4100)
  18095. #endif
  18096. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18097. add its header directory to your include path.
  18098. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18099. flag in juce_Config.h
  18100. */
  18101. #include <Movies.h>
  18102. #include <QTML.h>
  18103. #include <QuickTimeComponents.h>
  18104. #include <MediaHandlers.h>
  18105. #include <ImageCodec.h>
  18106. #if JUCE_MSVC
  18107. #pragma warning (pop)
  18108. #endif
  18109. #endif
  18110. BEGIN_JUCE_NAMESPACE
  18111. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18112. static const char* const quickTimeFormatName = "QuickTime file";
  18113. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18114. class QTAudioReader : public AudioFormatReader
  18115. {
  18116. public:
  18117. QTAudioReader (InputStream* const input_, const int trackNum_)
  18118. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18119. ok (false),
  18120. movie (0),
  18121. trackNum (trackNum_),
  18122. lastSampleRead (0),
  18123. lastThreadId (0),
  18124. extractor (0),
  18125. dataHandle (0)
  18126. {
  18127. JUCE_AUTORELEASEPOOL
  18128. bufferList.calloc (256, 1);
  18129. #if JUCE_WINDOWS
  18130. if (InitializeQTML (0) != noErr)
  18131. return;
  18132. #endif
  18133. if (EnterMovies() != noErr)
  18134. return;
  18135. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18136. if (! opened)
  18137. return;
  18138. {
  18139. const int numTracks = GetMovieTrackCount (movie);
  18140. int trackCount = 0;
  18141. for (int i = 1; i <= numTracks; ++i)
  18142. {
  18143. track = GetMovieIndTrack (movie, i);
  18144. media = GetTrackMedia (track);
  18145. OSType mediaType;
  18146. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18147. if (mediaType == SoundMediaType
  18148. && trackCount++ == trackNum_)
  18149. {
  18150. ok = true;
  18151. break;
  18152. }
  18153. }
  18154. }
  18155. if (! ok)
  18156. return;
  18157. ok = false;
  18158. lengthInSamples = GetMediaDecodeDuration (media);
  18159. usesFloatingPointData = false;
  18160. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18161. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18162. / GetMediaTimeScale (media);
  18163. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18164. unsigned long output_layout_size;
  18165. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18166. kQTPropertyClass_MovieAudioExtraction_Audio,
  18167. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18168. 0, &output_layout_size, 0);
  18169. if (err != noErr)
  18170. return;
  18171. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18172. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18173. err = MovieAudioExtractionGetProperty (extractor,
  18174. kQTPropertyClass_MovieAudioExtraction_Audio,
  18175. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18176. output_layout_size, qt_audio_channel_layout, 0);
  18177. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18178. err = MovieAudioExtractionSetProperty (extractor,
  18179. kQTPropertyClass_MovieAudioExtraction_Audio,
  18180. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18181. output_layout_size,
  18182. qt_audio_channel_layout);
  18183. err = MovieAudioExtractionGetProperty (extractor,
  18184. kQTPropertyClass_MovieAudioExtraction_Audio,
  18185. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18186. sizeof (inputStreamDesc),
  18187. &inputStreamDesc, 0);
  18188. if (err != noErr)
  18189. return;
  18190. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18191. | kAudioFormatFlagIsPacked
  18192. | kAudioFormatFlagsNativeEndian;
  18193. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18194. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18195. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18196. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18197. err = MovieAudioExtractionSetProperty (extractor,
  18198. kQTPropertyClass_MovieAudioExtraction_Audio,
  18199. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18200. sizeof (inputStreamDesc),
  18201. &inputStreamDesc);
  18202. if (err != noErr)
  18203. return;
  18204. Boolean allChannelsDiscrete = false;
  18205. err = MovieAudioExtractionSetProperty (extractor,
  18206. kQTPropertyClass_MovieAudioExtraction_Movie,
  18207. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18208. sizeof (allChannelsDiscrete),
  18209. &allChannelsDiscrete);
  18210. if (err != noErr)
  18211. return;
  18212. bufferList->mNumberBuffers = 1;
  18213. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18214. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18215. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18216. bufferList->mBuffers[0].mData = dataBuffer;
  18217. sampleRate = inputStreamDesc.mSampleRate;
  18218. bitsPerSample = 16;
  18219. numChannels = inputStreamDesc.mChannelsPerFrame;
  18220. detachThread();
  18221. ok = true;
  18222. }
  18223. ~QTAudioReader()
  18224. {
  18225. JUCE_AUTORELEASEPOOL
  18226. checkThreadIsAttached();
  18227. if (dataHandle != 0)
  18228. DisposeHandle (dataHandle);
  18229. if (extractor != 0)
  18230. {
  18231. MovieAudioExtractionEnd (extractor);
  18232. extractor = 0;
  18233. }
  18234. DisposeMovie (movie);
  18235. #if JUCE_MAC
  18236. ExitMoviesOnThread ();
  18237. #endif
  18238. }
  18239. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18240. int64 startSampleInFile, int numSamples)
  18241. {
  18242. JUCE_AUTORELEASEPOOL
  18243. checkThreadIsAttached();
  18244. bool ok = true;
  18245. while (numSamples > 0)
  18246. {
  18247. if (lastSampleRead != startSampleInFile)
  18248. {
  18249. TimeRecord time;
  18250. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18251. time.base = 0;
  18252. time.value.hi = 0;
  18253. time.value.lo = (UInt32) startSampleInFile;
  18254. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18255. kQTPropertyClass_MovieAudioExtraction_Movie,
  18256. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18257. sizeof (time), &time);
  18258. if (err != noErr)
  18259. {
  18260. ok = false;
  18261. break;
  18262. }
  18263. }
  18264. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18265. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18266. UInt32 outFlags = 0;
  18267. UInt32 actualNumFrames = framesToDo;
  18268. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18269. if (err != noErr)
  18270. {
  18271. ok = false;
  18272. break;
  18273. }
  18274. lastSampleRead = startSampleInFile + actualNumFrames;
  18275. const int samplesReceived = actualNumFrames;
  18276. for (int j = numDestChannels; --j >= 0;)
  18277. {
  18278. if (destSamples[j] != 0)
  18279. {
  18280. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18281. for (int i = 0; i < samplesReceived; ++i)
  18282. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18283. }
  18284. }
  18285. startOffsetInDestBuffer += samplesReceived;
  18286. startSampleInFile += samplesReceived;
  18287. numSamples -= samplesReceived;
  18288. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18289. {
  18290. for (int j = numDestChannels; --j >= 0;)
  18291. if (destSamples[j] != 0)
  18292. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18293. break;
  18294. }
  18295. }
  18296. detachThread();
  18297. return ok;
  18298. }
  18299. bool ok;
  18300. private:
  18301. Movie movie;
  18302. Media media;
  18303. Track track;
  18304. const int trackNum;
  18305. double trackUnitsPerFrame;
  18306. int samplesPerFrame;
  18307. int64 lastSampleRead;
  18308. Thread::ThreadID lastThreadId;
  18309. MovieAudioExtractionRef extractor;
  18310. AudioStreamBasicDescription inputStreamDesc;
  18311. HeapBlock <AudioBufferList> bufferList;
  18312. HeapBlock <char> dataBuffer;
  18313. Handle dataHandle;
  18314. void checkThreadIsAttached()
  18315. {
  18316. #if JUCE_MAC
  18317. if (Thread::getCurrentThreadId() != lastThreadId)
  18318. EnterMoviesOnThread (0);
  18319. AttachMovieToCurrentThread (movie);
  18320. #endif
  18321. }
  18322. void detachThread()
  18323. {
  18324. #if JUCE_MAC
  18325. DetachMovieFromCurrentThread (movie);
  18326. #endif
  18327. }
  18328. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18329. };
  18330. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18331. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18332. {
  18333. }
  18334. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18335. {
  18336. }
  18337. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18338. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18339. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18340. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18341. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18342. const bool deleteStreamIfOpeningFails)
  18343. {
  18344. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18345. if (r->ok)
  18346. return r.release();
  18347. if (! deleteStreamIfOpeningFails)
  18348. r->input = 0;
  18349. return 0;
  18350. }
  18351. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18352. double /*sampleRateToUse*/,
  18353. unsigned int /*numberOfChannels*/,
  18354. int /*bitsPerSample*/,
  18355. const StringPairArray& /*metadataValues*/,
  18356. int /*qualityOptionIndex*/)
  18357. {
  18358. jassertfalse; // not yet implemented!
  18359. return 0;
  18360. }
  18361. END_JUCE_NAMESPACE
  18362. #endif
  18363. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18364. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18365. BEGIN_JUCE_NAMESPACE
  18366. static const char* const wavFormatName = "WAV file";
  18367. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18368. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18369. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18370. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18371. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18372. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18373. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18374. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18375. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18376. const String& originator,
  18377. const String& originatorRef,
  18378. const Time& date,
  18379. const int64 timeReferenceSamples,
  18380. const String& codingHistory)
  18381. {
  18382. StringPairArray m;
  18383. m.set (bwavDescription, description);
  18384. m.set (bwavOriginator, originator);
  18385. m.set (bwavOriginatorRef, originatorRef);
  18386. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18387. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18388. m.set (bwavTimeReference, String (timeReferenceSamples));
  18389. m.set (bwavCodingHistory, codingHistory);
  18390. return m;
  18391. }
  18392. #if JUCE_MSVC
  18393. #pragma pack (push, 1)
  18394. #define PACKED
  18395. #elif JUCE_GCC
  18396. #define PACKED __attribute__((packed))
  18397. #else
  18398. #define PACKED
  18399. #endif
  18400. struct BWAVChunk
  18401. {
  18402. char description [256];
  18403. char originator [32];
  18404. char originatorRef [32];
  18405. char originationDate [10];
  18406. char originationTime [8];
  18407. uint32 timeRefLow;
  18408. uint32 timeRefHigh;
  18409. uint16 version;
  18410. uint8 umid[64];
  18411. uint8 reserved[190];
  18412. char codingHistory[1];
  18413. void copyTo (StringPairArray& values) const
  18414. {
  18415. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18416. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18417. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18418. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18419. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18420. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18421. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18422. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18423. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18424. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18425. }
  18426. static MemoryBlock createFrom (const StringPairArray& values)
  18427. {
  18428. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18429. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18430. data.fillWith (0);
  18431. BWAVChunk* b = (BWAVChunk*) data.getData();
  18432. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18433. // as they get called in the right order..
  18434. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18435. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18436. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18437. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18438. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18439. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18440. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18441. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18442. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18443. if (b->description[0] != 0
  18444. || b->originator[0] != 0
  18445. || b->originationDate[0] != 0
  18446. || b->originationTime[0] != 0
  18447. || b->codingHistory[0] != 0
  18448. || time != 0)
  18449. {
  18450. return data;
  18451. }
  18452. return MemoryBlock();
  18453. }
  18454. } PACKED;
  18455. struct SMPLChunk
  18456. {
  18457. struct SampleLoop
  18458. {
  18459. uint32 identifier;
  18460. uint32 type;
  18461. uint32 start;
  18462. uint32 end;
  18463. uint32 fraction;
  18464. uint32 playCount;
  18465. } PACKED;
  18466. uint32 manufacturer;
  18467. uint32 product;
  18468. uint32 samplePeriod;
  18469. uint32 midiUnityNote;
  18470. uint32 midiPitchFraction;
  18471. uint32 smpteFormat;
  18472. uint32 smpteOffset;
  18473. uint32 numSampleLoops;
  18474. uint32 samplerData;
  18475. SampleLoop loops[1];
  18476. void copyTo (StringPairArray& values, const int totalSize) const
  18477. {
  18478. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18479. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18480. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18481. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18482. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18483. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18484. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18485. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18486. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18487. for (uint32 i = 0; i < numSampleLoops; ++i)
  18488. {
  18489. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18490. break;
  18491. const String prefix ("Loop" + String(i));
  18492. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18493. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18494. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18495. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18496. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18497. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18498. }
  18499. }
  18500. static MemoryBlock createFrom (const StringPairArray& values)
  18501. {
  18502. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18503. if (numLoops <= 0)
  18504. return MemoryBlock();
  18505. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18506. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18507. data.fillWith (0);
  18508. SMPLChunk* s = (SMPLChunk*) data.getData();
  18509. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18510. // as they get called in the right order..
  18511. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18512. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18513. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18514. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18515. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18516. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18517. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18518. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18519. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18520. for (int i = 0; i < numLoops; ++i)
  18521. {
  18522. const String prefix ("Loop" + String(i));
  18523. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18524. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18525. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18526. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18527. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18528. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18529. }
  18530. return data;
  18531. }
  18532. } PACKED;
  18533. struct ExtensibleWavSubFormat
  18534. {
  18535. uint32 data1;
  18536. uint16 data2;
  18537. uint16 data3;
  18538. uint8 data4[8];
  18539. } PACKED;
  18540. #if JUCE_MSVC
  18541. #pragma pack (pop)
  18542. #endif
  18543. #undef PACKED
  18544. class WavAudioFormatReader : public AudioFormatReader
  18545. {
  18546. public:
  18547. WavAudioFormatReader (InputStream* const in)
  18548. : AudioFormatReader (in, TRANS (wavFormatName)),
  18549. bwavChunkStart (0),
  18550. bwavSize (0),
  18551. dataLength (0)
  18552. {
  18553. if (input->readInt() == chunkName ("RIFF"))
  18554. {
  18555. const uint32 len = (uint32) input->readInt();
  18556. const int64 end = input->getPosition() + len;
  18557. bool hasGotType = false;
  18558. bool hasGotData = false;
  18559. if (input->readInt() == chunkName ("WAVE"))
  18560. {
  18561. while (input->getPosition() < end
  18562. && ! input->isExhausted())
  18563. {
  18564. const int chunkType = input->readInt();
  18565. uint32 length = (uint32) input->readInt();
  18566. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18567. if (chunkType == chunkName ("fmt "))
  18568. {
  18569. // read the format chunk
  18570. const unsigned short format = input->readShort();
  18571. const short numChans = input->readShort();
  18572. sampleRate = input->readInt();
  18573. const int bytesPerSec = input->readInt();
  18574. numChannels = numChans;
  18575. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18576. bitsPerSample = 8 * bytesPerFrame / numChans;
  18577. if (format == 3)
  18578. {
  18579. usesFloatingPointData = true;
  18580. }
  18581. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18582. {
  18583. if (length < 40) // too short
  18584. {
  18585. bytesPerFrame = 0;
  18586. }
  18587. else
  18588. {
  18589. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18590. ExtensibleWavSubFormat subFormat;
  18591. subFormat.data1 = input->readInt();
  18592. subFormat.data2 = input->readShort();
  18593. subFormat.data3 = input->readShort();
  18594. input->read (subFormat.data4, sizeof (subFormat.data4));
  18595. const ExtensibleWavSubFormat pcmFormat
  18596. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18597. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18598. {
  18599. const ExtensibleWavSubFormat ambisonicFormat
  18600. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18601. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18602. bytesPerFrame = 0;
  18603. }
  18604. }
  18605. }
  18606. else if (format != 1)
  18607. {
  18608. bytesPerFrame = 0;
  18609. }
  18610. hasGotType = true;
  18611. }
  18612. else if (chunkType == chunkName ("data"))
  18613. {
  18614. // get the data chunk's position
  18615. dataLength = length;
  18616. dataChunkStart = input->getPosition();
  18617. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18618. hasGotData = true;
  18619. }
  18620. else if (chunkType == chunkName ("bext"))
  18621. {
  18622. bwavChunkStart = input->getPosition();
  18623. bwavSize = length;
  18624. // Broadcast-wav extension chunk..
  18625. HeapBlock <BWAVChunk> bwav;
  18626. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18627. input->read (bwav, length);
  18628. bwav->copyTo (metadataValues);
  18629. }
  18630. else if (chunkType == chunkName ("smpl"))
  18631. {
  18632. HeapBlock <SMPLChunk> smpl;
  18633. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18634. input->read (smpl, length);
  18635. smpl->copyTo (metadataValues, length);
  18636. }
  18637. else if (chunkEnd <= input->getPosition())
  18638. {
  18639. break;
  18640. }
  18641. input->setPosition (chunkEnd);
  18642. }
  18643. }
  18644. }
  18645. }
  18646. ~WavAudioFormatReader()
  18647. {
  18648. }
  18649. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18650. int64 startSampleInFile, int numSamples)
  18651. {
  18652. jassert (destSamples != 0);
  18653. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18654. if (samplesAvailable < numSamples)
  18655. {
  18656. for (int i = numDestChannels; --i >= 0;)
  18657. if (destSamples[i] != 0)
  18658. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18659. numSamples = (int) samplesAvailable;
  18660. }
  18661. if (numSamples <= 0)
  18662. return true;
  18663. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18664. while (numSamples > 0)
  18665. {
  18666. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18667. char tempBuffer [tempBufSize];
  18668. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18669. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18670. if (bytesRead < numThisTime * bytesPerFrame)
  18671. {
  18672. jassert (bytesRead >= 0);
  18673. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18674. }
  18675. switch (bitsPerSample)
  18676. {
  18677. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18678. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18679. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18680. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18681. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18682. default: jassertfalse; break;
  18683. }
  18684. startOffsetInDestBuffer += numThisTime;
  18685. numSamples -= numThisTime;
  18686. }
  18687. return true;
  18688. }
  18689. int64 bwavChunkStart, bwavSize;
  18690. private:
  18691. ScopedPointer<AudioData::Converter> converter;
  18692. int bytesPerFrame;
  18693. int64 dataChunkStart, dataLength;
  18694. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18695. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18696. };
  18697. class WavAudioFormatWriter : public AudioFormatWriter
  18698. {
  18699. public:
  18700. WavAudioFormatWriter (OutputStream* const out,
  18701. const double sampleRate_,
  18702. const unsigned int numChannels_,
  18703. const int bits,
  18704. const StringPairArray& metadataValues)
  18705. : AudioFormatWriter (out,
  18706. TRANS (wavFormatName),
  18707. sampleRate_,
  18708. numChannels_,
  18709. bits),
  18710. lengthInSamples (0),
  18711. bytesWritten (0),
  18712. writeFailed (false)
  18713. {
  18714. if (metadataValues.size() > 0)
  18715. {
  18716. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18717. smplChunk = SMPLChunk::createFrom (metadataValues);
  18718. }
  18719. headerPosition = out->getPosition();
  18720. writeHeader();
  18721. }
  18722. ~WavAudioFormatWriter()
  18723. {
  18724. writeHeader();
  18725. }
  18726. bool write (const int** data, int numSamples)
  18727. {
  18728. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18729. if (writeFailed)
  18730. return false;
  18731. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18732. tempBlock.ensureSize (bytes, false);
  18733. switch (bitsPerSample)
  18734. {
  18735. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18736. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18737. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18738. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18739. default: jassertfalse; break;
  18740. }
  18741. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18742. || ! output->write (tempBlock.getData(), bytes))
  18743. {
  18744. // failed to write to disk, so let's try writing the header.
  18745. // If it's just run out of disk space, then if it does manage
  18746. // to write the header, we'll still have a useable file..
  18747. writeHeader();
  18748. writeFailed = true;
  18749. return false;
  18750. }
  18751. else
  18752. {
  18753. bytesWritten += bytes;
  18754. lengthInSamples += numSamples;
  18755. return true;
  18756. }
  18757. }
  18758. private:
  18759. ScopedPointer<AudioData::Converter> converter;
  18760. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18761. uint32 lengthInSamples, bytesWritten;
  18762. int64 headerPosition;
  18763. bool writeFailed;
  18764. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18765. void writeHeader()
  18766. {
  18767. const bool seekedOk = output->setPosition (headerPosition);
  18768. (void) seekedOk;
  18769. // if this fails, you've given it an output stream that can't seek! It needs
  18770. // to be able to seek back to write the header
  18771. jassert (seekedOk);
  18772. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18773. output->writeInt (chunkName ("RIFF"));
  18774. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18775. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18776. output->writeInt (chunkName ("WAVE"));
  18777. output->writeInt (chunkName ("fmt "));
  18778. output->writeInt (16);
  18779. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18780. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18781. output->writeShort ((short) numChannels);
  18782. output->writeInt ((int) sampleRate);
  18783. output->writeInt (bytesPerFrame * (int) sampleRate);
  18784. output->writeShort ((short) bytesPerFrame);
  18785. output->writeShort ((short) bitsPerSample);
  18786. if (bwavChunk.getSize() > 0)
  18787. {
  18788. output->writeInt (chunkName ("bext"));
  18789. output->writeInt ((int) bwavChunk.getSize());
  18790. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18791. }
  18792. if (smplChunk.getSize() > 0)
  18793. {
  18794. output->writeInt (chunkName ("smpl"));
  18795. output->writeInt ((int) smplChunk.getSize());
  18796. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18797. }
  18798. output->writeInt (chunkName ("data"));
  18799. output->writeInt (lengthInSamples * bytesPerFrame);
  18800. usesFloatingPointData = (bitsPerSample == 32);
  18801. }
  18802. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18803. };
  18804. WavAudioFormat::WavAudioFormat()
  18805. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18806. {
  18807. }
  18808. WavAudioFormat::~WavAudioFormat()
  18809. {
  18810. }
  18811. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18812. {
  18813. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18814. return Array <int> (rates);
  18815. }
  18816. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18817. {
  18818. const int depths[] = { 8, 16, 24, 32, 0 };
  18819. return Array <int> (depths);
  18820. }
  18821. bool WavAudioFormat::canDoStereo() { return true; }
  18822. bool WavAudioFormat::canDoMono() { return true; }
  18823. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18824. const bool deleteStreamIfOpeningFails)
  18825. {
  18826. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18827. if (r->sampleRate != 0)
  18828. return r.release();
  18829. if (! deleteStreamIfOpeningFails)
  18830. r->input = 0;
  18831. return 0;
  18832. }
  18833. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18834. double sampleRate,
  18835. unsigned int numChannels,
  18836. int bitsPerSample,
  18837. const StringPairArray& metadataValues,
  18838. int /*qualityOptionIndex*/)
  18839. {
  18840. if (getPossibleBitDepths().contains (bitsPerSample))
  18841. {
  18842. return new WavAudioFormatWriter (out,
  18843. sampleRate,
  18844. numChannels,
  18845. bitsPerSample,
  18846. metadataValues);
  18847. }
  18848. return 0;
  18849. }
  18850. namespace
  18851. {
  18852. bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18853. {
  18854. TemporaryFile tempFile (file);
  18855. WavAudioFormat wav;
  18856. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18857. if (reader != 0)
  18858. {
  18859. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18860. if (outStream != 0)
  18861. {
  18862. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18863. reader->numChannels, reader->bitsPerSample,
  18864. metadata, 0));
  18865. if (writer != 0)
  18866. {
  18867. outStream.release();
  18868. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18869. writer = 0;
  18870. reader = 0;
  18871. return ok && tempFile.overwriteTargetFileWithTemporary();
  18872. }
  18873. }
  18874. }
  18875. return false;
  18876. }
  18877. }
  18878. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18879. {
  18880. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18881. if (reader != 0)
  18882. {
  18883. const int64 bwavPos = reader->bwavChunkStart;
  18884. const int64 bwavSize = reader->bwavSize;
  18885. reader = 0;
  18886. if (bwavSize > 0)
  18887. {
  18888. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18889. if (chunk.getSize() <= (size_t) bwavSize)
  18890. {
  18891. // the new one will fit in the space available, so write it directly..
  18892. const int64 oldSize = wavFile.getSize();
  18893. {
  18894. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18895. out->setPosition (bwavPos);
  18896. out->write (chunk.getData(), (int) chunk.getSize());
  18897. out->setPosition (oldSize);
  18898. }
  18899. jassert (wavFile.getSize() == oldSize);
  18900. return true;
  18901. }
  18902. }
  18903. }
  18904. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18905. }
  18906. END_JUCE_NAMESPACE
  18907. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18908. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18909. #if JUCE_USE_CDREADER
  18910. BEGIN_JUCE_NAMESPACE
  18911. int AudioCDReader::getNumTracks() const
  18912. {
  18913. return trackStartSamples.size() - 1;
  18914. }
  18915. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18916. {
  18917. return trackStartSamples [trackNum];
  18918. }
  18919. const Array<int>& AudioCDReader::getTrackOffsets() const
  18920. {
  18921. return trackStartSamples;
  18922. }
  18923. int AudioCDReader::getCDDBId()
  18924. {
  18925. int checksum = 0;
  18926. const int numTracks = getNumTracks();
  18927. for (int i = 0; i < numTracks; ++i)
  18928. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18929. checksum += offset % 10;
  18930. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18931. // CCLLLLTT: checksum, length, tracks
  18932. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18933. }
  18934. END_JUCE_NAMESPACE
  18935. #endif
  18936. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18937. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18938. BEGIN_JUCE_NAMESPACE
  18939. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18940. const bool deleteReaderWhenThisIsDeleted)
  18941. : reader (reader_),
  18942. deleteReader (deleteReaderWhenThisIsDeleted),
  18943. nextPlayPos (0),
  18944. looping (false)
  18945. {
  18946. jassert (reader != 0);
  18947. }
  18948. AudioFormatReaderSource::~AudioFormatReaderSource()
  18949. {
  18950. releaseResources();
  18951. if (deleteReader)
  18952. delete reader;
  18953. }
  18954. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18955. {
  18956. nextPlayPos = newPosition;
  18957. }
  18958. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18959. {
  18960. looping = shouldLoop;
  18961. }
  18962. int AudioFormatReaderSource::getNextReadPosition() const
  18963. {
  18964. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18965. : nextPlayPos;
  18966. }
  18967. int AudioFormatReaderSource::getTotalLength() const
  18968. {
  18969. return (int) reader->lengthInSamples;
  18970. }
  18971. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18972. double /*sampleRate*/)
  18973. {
  18974. }
  18975. void AudioFormatReaderSource::releaseResources()
  18976. {
  18977. }
  18978. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18979. {
  18980. if (info.numSamples > 0)
  18981. {
  18982. const int start = nextPlayPos;
  18983. if (looping)
  18984. {
  18985. const int newStart = start % (int) reader->lengthInSamples;
  18986. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18987. if (newEnd > newStart)
  18988. {
  18989. info.buffer->readFromAudioReader (reader,
  18990. info.startSample,
  18991. newEnd - newStart,
  18992. newStart,
  18993. true, true);
  18994. }
  18995. else
  18996. {
  18997. const int endSamps = (int) reader->lengthInSamples - newStart;
  18998. info.buffer->readFromAudioReader (reader,
  18999. info.startSample,
  19000. endSamps,
  19001. newStart,
  19002. true, true);
  19003. info.buffer->readFromAudioReader (reader,
  19004. info.startSample + endSamps,
  19005. newEnd,
  19006. 0,
  19007. true, true);
  19008. }
  19009. nextPlayPos = newEnd;
  19010. }
  19011. else
  19012. {
  19013. info.buffer->readFromAudioReader (reader,
  19014. info.startSample,
  19015. info.numSamples,
  19016. start,
  19017. true, true);
  19018. nextPlayPos += info.numSamples;
  19019. }
  19020. }
  19021. }
  19022. END_JUCE_NAMESPACE
  19023. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19024. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19025. BEGIN_JUCE_NAMESPACE
  19026. AudioSourcePlayer::AudioSourcePlayer()
  19027. : source (0),
  19028. sampleRate (0),
  19029. bufferSize (0),
  19030. tempBuffer (2, 8),
  19031. lastGain (1.0f),
  19032. gain (1.0f)
  19033. {
  19034. }
  19035. AudioSourcePlayer::~AudioSourcePlayer()
  19036. {
  19037. setSource (0);
  19038. }
  19039. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19040. {
  19041. if (source != newSource)
  19042. {
  19043. AudioSource* const oldSource = source;
  19044. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19045. newSource->prepareToPlay (bufferSize, sampleRate);
  19046. {
  19047. const ScopedLock sl (readLock);
  19048. source = newSource;
  19049. }
  19050. if (oldSource != 0)
  19051. oldSource->releaseResources();
  19052. }
  19053. }
  19054. void AudioSourcePlayer::setGain (const float newGain) throw()
  19055. {
  19056. gain = newGain;
  19057. }
  19058. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19059. int totalNumInputChannels,
  19060. float** outputChannelData,
  19061. int totalNumOutputChannels,
  19062. int numSamples)
  19063. {
  19064. // these should have been prepared by audioDeviceAboutToStart()...
  19065. jassert (sampleRate > 0 && bufferSize > 0);
  19066. const ScopedLock sl (readLock);
  19067. if (source != 0)
  19068. {
  19069. AudioSourceChannelInfo info;
  19070. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19071. // messy stuff needed to compact the channels down into an array
  19072. // of non-zero pointers..
  19073. for (i = 0; i < totalNumInputChannels; ++i)
  19074. {
  19075. if (inputChannelData[i] != 0)
  19076. {
  19077. inputChans [numInputs++] = inputChannelData[i];
  19078. if (numInputs >= numElementsInArray (inputChans))
  19079. break;
  19080. }
  19081. }
  19082. for (i = 0; i < totalNumOutputChannels; ++i)
  19083. {
  19084. if (outputChannelData[i] != 0)
  19085. {
  19086. outputChans [numOutputs++] = outputChannelData[i];
  19087. if (numOutputs >= numElementsInArray (outputChans))
  19088. break;
  19089. }
  19090. }
  19091. if (numInputs > numOutputs)
  19092. {
  19093. // if there aren't enough output channels for the number of
  19094. // inputs, we need to create some temporary extra ones (can't
  19095. // use the input data in case it gets written to)
  19096. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19097. false, false, true);
  19098. for (i = 0; i < numOutputs; ++i)
  19099. {
  19100. channels[numActiveChans] = outputChans[i];
  19101. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19102. ++numActiveChans;
  19103. }
  19104. for (i = numOutputs; i < numInputs; ++i)
  19105. {
  19106. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19107. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19108. ++numActiveChans;
  19109. }
  19110. }
  19111. else
  19112. {
  19113. for (i = 0; i < numInputs; ++i)
  19114. {
  19115. channels[numActiveChans] = outputChans[i];
  19116. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19117. ++numActiveChans;
  19118. }
  19119. for (i = numInputs; i < numOutputs; ++i)
  19120. {
  19121. channels[numActiveChans] = outputChans[i];
  19122. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19123. ++numActiveChans;
  19124. }
  19125. }
  19126. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19127. info.buffer = &buffer;
  19128. info.startSample = 0;
  19129. info.numSamples = numSamples;
  19130. source->getNextAudioBlock (info);
  19131. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19132. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19133. lastGain = gain;
  19134. }
  19135. else
  19136. {
  19137. for (int i = 0; i < totalNumOutputChannels; ++i)
  19138. if (outputChannelData[i] != 0)
  19139. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19140. }
  19141. }
  19142. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19143. {
  19144. sampleRate = device->getCurrentSampleRate();
  19145. bufferSize = device->getCurrentBufferSizeSamples();
  19146. zeromem (channels, sizeof (channels));
  19147. if (source != 0)
  19148. source->prepareToPlay (bufferSize, sampleRate);
  19149. }
  19150. void AudioSourcePlayer::audioDeviceStopped()
  19151. {
  19152. if (source != 0)
  19153. source->releaseResources();
  19154. sampleRate = 0.0;
  19155. bufferSize = 0;
  19156. tempBuffer.setSize (2, 8);
  19157. }
  19158. END_JUCE_NAMESPACE
  19159. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19160. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19161. BEGIN_JUCE_NAMESPACE
  19162. AudioTransportSource::AudioTransportSource()
  19163. : source (0),
  19164. resamplerSource (0),
  19165. bufferingSource (0),
  19166. positionableSource (0),
  19167. masterSource (0),
  19168. gain (1.0f),
  19169. lastGain (1.0f),
  19170. playing (false),
  19171. stopped (true),
  19172. sampleRate (44100.0),
  19173. sourceSampleRate (0.0),
  19174. blockSize (128),
  19175. readAheadBufferSize (0),
  19176. isPrepared (false),
  19177. inputStreamEOF (false)
  19178. {
  19179. }
  19180. AudioTransportSource::~AudioTransportSource()
  19181. {
  19182. setSource (0);
  19183. releaseResources();
  19184. }
  19185. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19186. int readAheadBufferSize_,
  19187. double sourceSampleRateToCorrectFor)
  19188. {
  19189. if (source == newSource)
  19190. {
  19191. if (source == 0)
  19192. return;
  19193. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19194. }
  19195. readAheadBufferSize = readAheadBufferSize_;
  19196. sourceSampleRate = sourceSampleRateToCorrectFor;
  19197. ResamplingAudioSource* newResamplerSource = 0;
  19198. BufferingAudioSource* newBufferingSource = 0;
  19199. PositionableAudioSource* newPositionableSource = 0;
  19200. AudioSource* newMasterSource = 0;
  19201. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19202. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19203. AudioSource* oldMasterSource = masterSource;
  19204. if (newSource != 0)
  19205. {
  19206. newPositionableSource = newSource;
  19207. if (readAheadBufferSize_ > 0)
  19208. newPositionableSource = newBufferingSource
  19209. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19210. newPositionableSource->setNextReadPosition (0);
  19211. if (sourceSampleRateToCorrectFor != 0)
  19212. newMasterSource = newResamplerSource
  19213. = new ResamplingAudioSource (newPositionableSource, false);
  19214. else
  19215. newMasterSource = newPositionableSource;
  19216. if (isPrepared)
  19217. {
  19218. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19219. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19220. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19221. }
  19222. }
  19223. {
  19224. const ScopedLock sl (callbackLock);
  19225. source = newSource;
  19226. resamplerSource = newResamplerSource;
  19227. bufferingSource = newBufferingSource;
  19228. masterSource = newMasterSource;
  19229. positionableSource = newPositionableSource;
  19230. playing = false;
  19231. }
  19232. if (oldMasterSource != 0)
  19233. oldMasterSource->releaseResources();
  19234. }
  19235. void AudioTransportSource::start()
  19236. {
  19237. if ((! playing) && masterSource != 0)
  19238. {
  19239. {
  19240. const ScopedLock sl (callbackLock);
  19241. playing = true;
  19242. stopped = false;
  19243. inputStreamEOF = false;
  19244. }
  19245. sendChangeMessage();
  19246. }
  19247. }
  19248. void AudioTransportSource::stop()
  19249. {
  19250. if (playing)
  19251. {
  19252. {
  19253. const ScopedLock sl (callbackLock);
  19254. playing = false;
  19255. }
  19256. int n = 500;
  19257. while (--n >= 0 && ! stopped)
  19258. Thread::sleep (2);
  19259. sendChangeMessage();
  19260. }
  19261. }
  19262. void AudioTransportSource::setPosition (double newPosition)
  19263. {
  19264. if (sampleRate > 0.0)
  19265. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19266. }
  19267. double AudioTransportSource::getCurrentPosition() const
  19268. {
  19269. if (sampleRate > 0.0)
  19270. return getNextReadPosition() / sampleRate;
  19271. else
  19272. return 0.0;
  19273. }
  19274. double AudioTransportSource::getLengthInSeconds() const
  19275. {
  19276. return getTotalLength() / sampleRate;
  19277. }
  19278. void AudioTransportSource::setNextReadPosition (int newPosition)
  19279. {
  19280. if (positionableSource != 0)
  19281. {
  19282. if (sampleRate > 0 && sourceSampleRate > 0)
  19283. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19284. positionableSource->setNextReadPosition (newPosition);
  19285. }
  19286. }
  19287. int AudioTransportSource::getNextReadPosition() const
  19288. {
  19289. if (positionableSource != 0)
  19290. {
  19291. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19292. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19293. }
  19294. return 0;
  19295. }
  19296. int AudioTransportSource::getTotalLength() const
  19297. {
  19298. const ScopedLock sl (callbackLock);
  19299. if (positionableSource != 0)
  19300. {
  19301. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19302. return roundToInt (positionableSource->getTotalLength() * ratio);
  19303. }
  19304. return 0;
  19305. }
  19306. bool AudioTransportSource::isLooping() const
  19307. {
  19308. const ScopedLock sl (callbackLock);
  19309. return positionableSource != 0
  19310. && positionableSource->isLooping();
  19311. }
  19312. void AudioTransportSource::setGain (const float newGain) throw()
  19313. {
  19314. gain = newGain;
  19315. }
  19316. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19317. double sampleRate_)
  19318. {
  19319. const ScopedLock sl (callbackLock);
  19320. sampleRate = sampleRate_;
  19321. blockSize = samplesPerBlockExpected;
  19322. if (masterSource != 0)
  19323. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19324. if (resamplerSource != 0 && sourceSampleRate != 0)
  19325. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19326. isPrepared = true;
  19327. }
  19328. void AudioTransportSource::releaseResources()
  19329. {
  19330. const ScopedLock sl (callbackLock);
  19331. if (masterSource != 0)
  19332. masterSource->releaseResources();
  19333. isPrepared = false;
  19334. }
  19335. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19336. {
  19337. const ScopedLock sl (callbackLock);
  19338. inputStreamEOF = false;
  19339. if (masterSource != 0 && ! stopped)
  19340. {
  19341. masterSource->getNextAudioBlock (info);
  19342. if (! playing)
  19343. {
  19344. // just stopped playing, so fade out the last block..
  19345. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19346. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19347. if (info.numSamples > 256)
  19348. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19349. }
  19350. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19351. && ! positionableSource->isLooping())
  19352. {
  19353. playing = false;
  19354. inputStreamEOF = true;
  19355. sendChangeMessage();
  19356. }
  19357. stopped = ! playing;
  19358. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19359. {
  19360. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19361. lastGain, gain);
  19362. }
  19363. }
  19364. else
  19365. {
  19366. info.clearActiveBufferRegion();
  19367. stopped = true;
  19368. }
  19369. lastGain = gain;
  19370. }
  19371. END_JUCE_NAMESPACE
  19372. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19373. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19374. BEGIN_JUCE_NAMESPACE
  19375. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19376. public Thread,
  19377. private Timer
  19378. {
  19379. public:
  19380. SharedBufferingAudioSourceThread()
  19381. : Thread ("Audio Buffer")
  19382. {
  19383. }
  19384. ~SharedBufferingAudioSourceThread()
  19385. {
  19386. stopThread (10000);
  19387. clearSingletonInstance();
  19388. }
  19389. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19390. void addSource (BufferingAudioSource* source)
  19391. {
  19392. const ScopedLock sl (lock);
  19393. if (! sources.contains (source))
  19394. {
  19395. sources.add (source);
  19396. startThread();
  19397. stopTimer();
  19398. }
  19399. notify();
  19400. }
  19401. void removeSource (BufferingAudioSource* source)
  19402. {
  19403. const ScopedLock sl (lock);
  19404. sources.removeValue (source);
  19405. if (sources.size() == 0)
  19406. startTimer (5000);
  19407. }
  19408. private:
  19409. Array <BufferingAudioSource*> sources;
  19410. CriticalSection lock;
  19411. void run()
  19412. {
  19413. while (! threadShouldExit())
  19414. {
  19415. bool busy = false;
  19416. for (int i = sources.size(); --i >= 0;)
  19417. {
  19418. if (threadShouldExit())
  19419. return;
  19420. const ScopedLock sl (lock);
  19421. BufferingAudioSource* const b = sources[i];
  19422. if (b != 0 && b->readNextBufferChunk())
  19423. busy = true;
  19424. }
  19425. if (! busy)
  19426. wait (500);
  19427. }
  19428. }
  19429. void timerCallback()
  19430. {
  19431. stopTimer();
  19432. if (sources.size() == 0)
  19433. deleteInstance();
  19434. }
  19435. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19436. };
  19437. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19438. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19439. const bool deleteSourceWhenDeleted_,
  19440. int numberOfSamplesToBuffer_)
  19441. : source (source_),
  19442. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19443. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19444. buffer (2, 0),
  19445. bufferValidStart (0),
  19446. bufferValidEnd (0),
  19447. nextPlayPos (0),
  19448. wasSourceLooping (false)
  19449. {
  19450. jassert (source_ != 0);
  19451. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19452. // not using a larger buffer..
  19453. }
  19454. BufferingAudioSource::~BufferingAudioSource()
  19455. {
  19456. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19457. if (thread != 0)
  19458. thread->removeSource (this);
  19459. if (deleteSourceWhenDeleted)
  19460. delete source;
  19461. }
  19462. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19463. {
  19464. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19465. sampleRate = sampleRate_;
  19466. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19467. buffer.clear();
  19468. bufferValidStart = 0;
  19469. bufferValidEnd = 0;
  19470. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19471. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19472. buffer.getNumSamples() / 2))
  19473. {
  19474. SharedBufferingAudioSourceThread::getInstance()->notify();
  19475. Thread::sleep (5);
  19476. }
  19477. }
  19478. void BufferingAudioSource::releaseResources()
  19479. {
  19480. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19481. if (thread != 0)
  19482. thread->removeSource (this);
  19483. buffer.setSize (2, 0);
  19484. source->releaseResources();
  19485. }
  19486. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19487. {
  19488. const ScopedLock sl (bufferStartPosLock);
  19489. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19490. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19491. if (validStart == validEnd)
  19492. {
  19493. // total cache miss
  19494. info.clearActiveBufferRegion();
  19495. }
  19496. else
  19497. {
  19498. if (validStart > 0)
  19499. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19500. if (validEnd < info.numSamples)
  19501. info.buffer->clear (info.startSample + validEnd,
  19502. info.numSamples - validEnd); // partial cache miss at end
  19503. if (validStart < validEnd)
  19504. {
  19505. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19506. {
  19507. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19508. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19509. if (startBufferIndex < endBufferIndex)
  19510. {
  19511. info.buffer->copyFrom (chan, info.startSample + validStart,
  19512. buffer,
  19513. chan, startBufferIndex,
  19514. validEnd - validStart);
  19515. }
  19516. else
  19517. {
  19518. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19519. info.buffer->copyFrom (chan, info.startSample + validStart,
  19520. buffer,
  19521. chan, startBufferIndex,
  19522. initialSize);
  19523. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19524. buffer,
  19525. chan, 0,
  19526. (validEnd - validStart) - initialSize);
  19527. }
  19528. }
  19529. }
  19530. nextPlayPos += info.numSamples;
  19531. if (source->isLooping() && nextPlayPos > 0)
  19532. nextPlayPos %= source->getTotalLength();
  19533. }
  19534. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19535. if (thread != 0)
  19536. thread->notify();
  19537. }
  19538. int BufferingAudioSource::getNextReadPosition() const
  19539. {
  19540. return (source->isLooping() && nextPlayPos > 0)
  19541. ? nextPlayPos % source->getTotalLength()
  19542. : nextPlayPos;
  19543. }
  19544. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19545. {
  19546. const ScopedLock sl (bufferStartPosLock);
  19547. nextPlayPos = newPosition;
  19548. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19549. if (thread != 0)
  19550. thread->notify();
  19551. }
  19552. bool BufferingAudioSource::readNextBufferChunk()
  19553. {
  19554. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19555. {
  19556. const ScopedLock sl (bufferStartPosLock);
  19557. if (wasSourceLooping != isLooping())
  19558. {
  19559. wasSourceLooping = isLooping();
  19560. bufferValidStart = 0;
  19561. bufferValidEnd = 0;
  19562. }
  19563. newBVS = jmax (0, nextPlayPos);
  19564. newBVE = newBVS + buffer.getNumSamples() - 4;
  19565. sectionToReadStart = 0;
  19566. sectionToReadEnd = 0;
  19567. const int maxChunkSize = 2048;
  19568. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19569. {
  19570. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19571. sectionToReadStart = newBVS;
  19572. sectionToReadEnd = newBVE;
  19573. bufferValidStart = 0;
  19574. bufferValidEnd = 0;
  19575. }
  19576. else if (abs (newBVS - bufferValidStart) > 512
  19577. || abs (newBVE - bufferValidEnd) > 512)
  19578. {
  19579. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19580. sectionToReadStart = bufferValidEnd;
  19581. sectionToReadEnd = newBVE;
  19582. bufferValidStart = newBVS;
  19583. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19584. }
  19585. }
  19586. if (sectionToReadStart != sectionToReadEnd)
  19587. {
  19588. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19589. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19590. if (bufferIndexStart < bufferIndexEnd)
  19591. {
  19592. readBufferSection (sectionToReadStart,
  19593. sectionToReadEnd - sectionToReadStart,
  19594. bufferIndexStart);
  19595. }
  19596. else
  19597. {
  19598. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19599. readBufferSection (sectionToReadStart,
  19600. initialSize,
  19601. bufferIndexStart);
  19602. readBufferSection (sectionToReadStart + initialSize,
  19603. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19604. 0);
  19605. }
  19606. const ScopedLock sl2 (bufferStartPosLock);
  19607. bufferValidStart = newBVS;
  19608. bufferValidEnd = newBVE;
  19609. return true;
  19610. }
  19611. else
  19612. {
  19613. return false;
  19614. }
  19615. }
  19616. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19617. {
  19618. if (source->getNextReadPosition() != start)
  19619. source->setNextReadPosition (start);
  19620. AudioSourceChannelInfo info;
  19621. info.buffer = &buffer;
  19622. info.startSample = bufferOffset;
  19623. info.numSamples = length;
  19624. source->getNextAudioBlock (info);
  19625. }
  19626. END_JUCE_NAMESPACE
  19627. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19628. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19629. BEGIN_JUCE_NAMESPACE
  19630. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19631. const bool deleteSourceWhenDeleted_)
  19632. : requiredNumberOfChannels (2),
  19633. source (source_),
  19634. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19635. buffer (2, 16)
  19636. {
  19637. remappedInfo.buffer = &buffer;
  19638. remappedInfo.startSample = 0;
  19639. }
  19640. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19641. {
  19642. if (deleteSourceWhenDeleted)
  19643. delete source;
  19644. }
  19645. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19646. {
  19647. const ScopedLock sl (lock);
  19648. requiredNumberOfChannels = requiredNumberOfChannels_;
  19649. }
  19650. void ChannelRemappingAudioSource::clearAllMappings()
  19651. {
  19652. const ScopedLock sl (lock);
  19653. remappedInputs.clear();
  19654. remappedOutputs.clear();
  19655. }
  19656. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19657. {
  19658. const ScopedLock sl (lock);
  19659. while (remappedInputs.size() < destIndex)
  19660. remappedInputs.add (-1);
  19661. remappedInputs.set (destIndex, sourceIndex);
  19662. }
  19663. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19664. {
  19665. const ScopedLock sl (lock);
  19666. while (remappedOutputs.size() < sourceIndex)
  19667. remappedOutputs.add (-1);
  19668. remappedOutputs.set (sourceIndex, destIndex);
  19669. }
  19670. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19671. {
  19672. const ScopedLock sl (lock);
  19673. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19674. return remappedInputs.getUnchecked (inputChannelIndex);
  19675. return -1;
  19676. }
  19677. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19678. {
  19679. const ScopedLock sl (lock);
  19680. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19681. return remappedOutputs .getUnchecked (outputChannelIndex);
  19682. return -1;
  19683. }
  19684. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19685. {
  19686. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19687. }
  19688. void ChannelRemappingAudioSource::releaseResources()
  19689. {
  19690. source->releaseResources();
  19691. }
  19692. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19693. {
  19694. const ScopedLock sl (lock);
  19695. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19696. const int numChans = bufferToFill.buffer->getNumChannels();
  19697. int i;
  19698. for (i = 0; i < buffer.getNumChannels(); ++i)
  19699. {
  19700. const int remappedChan = getRemappedInputChannel (i);
  19701. if (remappedChan >= 0 && remappedChan < numChans)
  19702. {
  19703. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19704. remappedChan,
  19705. bufferToFill.startSample,
  19706. bufferToFill.numSamples);
  19707. }
  19708. else
  19709. {
  19710. buffer.clear (i, 0, bufferToFill.numSamples);
  19711. }
  19712. }
  19713. remappedInfo.numSamples = bufferToFill.numSamples;
  19714. source->getNextAudioBlock (remappedInfo);
  19715. bufferToFill.clearActiveBufferRegion();
  19716. for (i = 0; i < requiredNumberOfChannels; ++i)
  19717. {
  19718. const int remappedChan = getRemappedOutputChannel (i);
  19719. if (remappedChan >= 0 && remappedChan < numChans)
  19720. {
  19721. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19722. buffer, i, 0, bufferToFill.numSamples);
  19723. }
  19724. }
  19725. }
  19726. XmlElement* ChannelRemappingAudioSource::createXml() const
  19727. {
  19728. XmlElement* e = new XmlElement ("MAPPINGS");
  19729. String ins, outs;
  19730. int i;
  19731. const ScopedLock sl (lock);
  19732. for (i = 0; i < remappedInputs.size(); ++i)
  19733. ins << remappedInputs.getUnchecked(i) << ' ';
  19734. for (i = 0; i < remappedOutputs.size(); ++i)
  19735. outs << remappedOutputs.getUnchecked(i) << ' ';
  19736. e->setAttribute ("inputs", ins.trimEnd());
  19737. e->setAttribute ("outputs", outs.trimEnd());
  19738. return e;
  19739. }
  19740. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19741. {
  19742. if (e.hasTagName ("MAPPINGS"))
  19743. {
  19744. const ScopedLock sl (lock);
  19745. clearAllMappings();
  19746. StringArray ins, outs;
  19747. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19748. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19749. int i;
  19750. for (i = 0; i < ins.size(); ++i)
  19751. remappedInputs.add (ins[i].getIntValue());
  19752. for (i = 0; i < outs.size(); ++i)
  19753. remappedOutputs.add (outs[i].getIntValue());
  19754. }
  19755. }
  19756. END_JUCE_NAMESPACE
  19757. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19758. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19759. BEGIN_JUCE_NAMESPACE
  19760. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19761. const bool deleteInputWhenDeleted_)
  19762. : input (inputSource),
  19763. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19764. {
  19765. jassert (inputSource != 0);
  19766. for (int i = 2; --i >= 0;)
  19767. iirFilters.add (new IIRFilter());
  19768. }
  19769. IIRFilterAudioSource::~IIRFilterAudioSource()
  19770. {
  19771. if (deleteInputWhenDeleted)
  19772. delete input;
  19773. }
  19774. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19775. {
  19776. for (int i = iirFilters.size(); --i >= 0;)
  19777. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19778. }
  19779. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19780. {
  19781. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19782. for (int i = iirFilters.size(); --i >= 0;)
  19783. iirFilters.getUnchecked(i)->reset();
  19784. }
  19785. void IIRFilterAudioSource::releaseResources()
  19786. {
  19787. input->releaseResources();
  19788. }
  19789. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19790. {
  19791. input->getNextAudioBlock (bufferToFill);
  19792. const int numChannels = bufferToFill.buffer->getNumChannels();
  19793. while (numChannels > iirFilters.size())
  19794. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19795. for (int i = 0; i < numChannels; ++i)
  19796. iirFilters.getUnchecked(i)
  19797. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19798. bufferToFill.numSamples);
  19799. }
  19800. END_JUCE_NAMESPACE
  19801. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19802. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19803. BEGIN_JUCE_NAMESPACE
  19804. MixerAudioSource::MixerAudioSource()
  19805. : tempBuffer (2, 0),
  19806. currentSampleRate (0.0),
  19807. bufferSizeExpected (0)
  19808. {
  19809. }
  19810. MixerAudioSource::~MixerAudioSource()
  19811. {
  19812. removeAllInputs();
  19813. }
  19814. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19815. {
  19816. if (input != 0 && ! inputs.contains (input))
  19817. {
  19818. double localRate;
  19819. int localBufferSize;
  19820. {
  19821. const ScopedLock sl (lock);
  19822. localRate = currentSampleRate;
  19823. localBufferSize = bufferSizeExpected;
  19824. }
  19825. if (localRate != 0.0)
  19826. input->prepareToPlay (localBufferSize, localRate);
  19827. const ScopedLock sl (lock);
  19828. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19829. inputs.add (input);
  19830. }
  19831. }
  19832. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19833. {
  19834. if (input != 0)
  19835. {
  19836. int index;
  19837. {
  19838. const ScopedLock sl (lock);
  19839. index = inputs.indexOf (input);
  19840. if (index >= 0)
  19841. {
  19842. inputsToDelete.shiftBits (index, 1);
  19843. inputs.remove (index);
  19844. }
  19845. }
  19846. if (index >= 0)
  19847. {
  19848. input->releaseResources();
  19849. if (deleteInput)
  19850. delete input;
  19851. }
  19852. }
  19853. }
  19854. void MixerAudioSource::removeAllInputs()
  19855. {
  19856. OwnedArray<AudioSource> toDelete;
  19857. {
  19858. const ScopedLock sl (lock);
  19859. for (int i = inputs.size(); --i >= 0;)
  19860. if (inputsToDelete[i])
  19861. toDelete.add (inputs.getUnchecked(i));
  19862. }
  19863. }
  19864. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19865. {
  19866. tempBuffer.setSize (2, samplesPerBlockExpected);
  19867. const ScopedLock sl (lock);
  19868. currentSampleRate = sampleRate;
  19869. bufferSizeExpected = samplesPerBlockExpected;
  19870. for (int i = inputs.size(); --i >= 0;)
  19871. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19872. }
  19873. void MixerAudioSource::releaseResources()
  19874. {
  19875. const ScopedLock sl (lock);
  19876. for (int i = inputs.size(); --i >= 0;)
  19877. inputs.getUnchecked(i)->releaseResources();
  19878. tempBuffer.setSize (2, 0);
  19879. currentSampleRate = 0;
  19880. bufferSizeExpected = 0;
  19881. }
  19882. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19883. {
  19884. const ScopedLock sl (lock);
  19885. if (inputs.size() > 0)
  19886. {
  19887. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19888. if (inputs.size() > 1)
  19889. {
  19890. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19891. info.buffer->getNumSamples());
  19892. AudioSourceChannelInfo info2;
  19893. info2.buffer = &tempBuffer;
  19894. info2.numSamples = info.numSamples;
  19895. info2.startSample = 0;
  19896. for (int i = 1; i < inputs.size(); ++i)
  19897. {
  19898. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19899. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19900. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19901. }
  19902. }
  19903. }
  19904. else
  19905. {
  19906. info.clearActiveBufferRegion();
  19907. }
  19908. }
  19909. END_JUCE_NAMESPACE
  19910. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19911. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19912. BEGIN_JUCE_NAMESPACE
  19913. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19914. const bool deleteInputWhenDeleted_,
  19915. const int numChannels_)
  19916. : input (inputSource),
  19917. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19918. ratio (1.0),
  19919. lastRatio (1.0),
  19920. buffer (numChannels_, 0),
  19921. sampsInBuffer (0),
  19922. numChannels (numChannels_)
  19923. {
  19924. jassert (input != 0);
  19925. }
  19926. ResamplingAudioSource::~ResamplingAudioSource()
  19927. {
  19928. if (deleteInputWhenDeleted)
  19929. delete input;
  19930. }
  19931. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19932. {
  19933. jassert (samplesInPerOutputSample > 0);
  19934. const ScopedLock sl (ratioLock);
  19935. ratio = jmax (0.0, samplesInPerOutputSample);
  19936. }
  19937. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19938. double sampleRate)
  19939. {
  19940. const ScopedLock sl (ratioLock);
  19941. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19942. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19943. buffer.clear();
  19944. sampsInBuffer = 0;
  19945. bufferPos = 0;
  19946. subSampleOffset = 0.0;
  19947. filterStates.calloc (numChannels);
  19948. srcBuffers.calloc (numChannels);
  19949. destBuffers.calloc (numChannels);
  19950. createLowPass (ratio);
  19951. resetFilters();
  19952. }
  19953. void ResamplingAudioSource::releaseResources()
  19954. {
  19955. input->releaseResources();
  19956. buffer.setSize (numChannels, 0);
  19957. }
  19958. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19959. {
  19960. double localRatio;
  19961. {
  19962. const ScopedLock sl (ratioLock);
  19963. localRatio = ratio;
  19964. }
  19965. if (lastRatio != localRatio)
  19966. {
  19967. createLowPass (localRatio);
  19968. lastRatio = localRatio;
  19969. }
  19970. const int sampsNeeded = roundToInt (info.numSamples * localRatio) + 2;
  19971. int bufferSize = buffer.getNumSamples();
  19972. if (bufferSize < sampsNeeded + 8)
  19973. {
  19974. bufferPos %= bufferSize;
  19975. bufferSize = sampsNeeded + 32;
  19976. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19977. }
  19978. bufferPos %= bufferSize;
  19979. int endOfBufferPos = bufferPos + sampsInBuffer;
  19980. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19981. while (sampsNeeded > sampsInBuffer)
  19982. {
  19983. endOfBufferPos %= bufferSize;
  19984. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19985. bufferSize - endOfBufferPos);
  19986. AudioSourceChannelInfo readInfo;
  19987. readInfo.buffer = &buffer;
  19988. readInfo.numSamples = numToDo;
  19989. readInfo.startSample = endOfBufferPos;
  19990. input->getNextAudioBlock (readInfo);
  19991. if (localRatio > 1.0001)
  19992. {
  19993. // for down-sampling, pre-apply the filter..
  19994. for (int i = channelsToProcess; --i >= 0;)
  19995. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19996. }
  19997. sampsInBuffer += numToDo;
  19998. endOfBufferPos += numToDo;
  19999. }
  20000. for (int channel = 0; channel < channelsToProcess; ++channel)
  20001. {
  20002. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20003. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20004. }
  20005. int nextPos = (bufferPos + 1) % bufferSize;
  20006. for (int m = info.numSamples; --m >= 0;)
  20007. {
  20008. const float alpha = (float) subSampleOffset;
  20009. const float invAlpha = 1.0f - alpha;
  20010. for (int channel = 0; channel < channelsToProcess; ++channel)
  20011. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20012. subSampleOffset += localRatio;
  20013. jassert (sampsInBuffer > 0);
  20014. while (subSampleOffset >= 1.0)
  20015. {
  20016. if (++bufferPos >= bufferSize)
  20017. bufferPos = 0;
  20018. --sampsInBuffer;
  20019. nextPos = (bufferPos + 1) % bufferSize;
  20020. subSampleOffset -= 1.0;
  20021. }
  20022. }
  20023. if (localRatio < 0.9999)
  20024. {
  20025. // for up-sampling, apply the filter after transposing..
  20026. for (int i = channelsToProcess; --i >= 0;)
  20027. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20028. }
  20029. else if (localRatio <= 1.0001)
  20030. {
  20031. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20032. for (int i = channelsToProcess; --i >= 0;)
  20033. {
  20034. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20035. FilterState& fs = filterStates[i];
  20036. if (info.numSamples > 1)
  20037. {
  20038. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20039. }
  20040. else
  20041. {
  20042. fs.y2 = fs.y1;
  20043. fs.x2 = fs.x1;
  20044. }
  20045. fs.y1 = fs.x1 = *endOfBuffer;
  20046. }
  20047. }
  20048. jassert (sampsInBuffer >= 0);
  20049. }
  20050. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20051. {
  20052. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20053. : 0.5 * frequencyRatio;
  20054. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  20055. const double nSquared = n * n;
  20056. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20057. setFilterCoefficients (c1,
  20058. c1 * 2.0f,
  20059. c1,
  20060. 1.0,
  20061. c1 * 2.0 * (1.0 - nSquared),
  20062. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20063. }
  20064. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20065. {
  20066. const double a = 1.0 / c4;
  20067. c1 *= a;
  20068. c2 *= a;
  20069. c3 *= a;
  20070. c5 *= a;
  20071. c6 *= a;
  20072. coefficients[0] = c1;
  20073. coefficients[1] = c2;
  20074. coefficients[2] = c3;
  20075. coefficients[3] = c4;
  20076. coefficients[4] = c5;
  20077. coefficients[5] = c6;
  20078. }
  20079. void ResamplingAudioSource::resetFilters()
  20080. {
  20081. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20082. }
  20083. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20084. {
  20085. while (--num >= 0)
  20086. {
  20087. const double in = *samples;
  20088. double out = coefficients[0] * in
  20089. + coefficients[1] * fs.x1
  20090. + coefficients[2] * fs.x2
  20091. - coefficients[4] * fs.y1
  20092. - coefficients[5] * fs.y2;
  20093. #if JUCE_INTEL
  20094. if (! (out < -1.0e-8 || out > 1.0e-8))
  20095. out = 0;
  20096. #endif
  20097. fs.x2 = fs.x1;
  20098. fs.x1 = in;
  20099. fs.y2 = fs.y1;
  20100. fs.y1 = out;
  20101. *samples++ = (float) out;
  20102. }
  20103. }
  20104. END_JUCE_NAMESPACE
  20105. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20106. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20107. BEGIN_JUCE_NAMESPACE
  20108. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20109. : frequency (1000.0),
  20110. sampleRate (44100.0),
  20111. currentPhase (0.0),
  20112. phasePerSample (0.0),
  20113. amplitude (0.5f)
  20114. {
  20115. }
  20116. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20117. {
  20118. }
  20119. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20120. {
  20121. amplitude = newAmplitude;
  20122. }
  20123. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20124. {
  20125. frequency = newFrequencyHz;
  20126. phasePerSample = 0.0;
  20127. }
  20128. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20129. double sampleRate_)
  20130. {
  20131. currentPhase = 0.0;
  20132. phasePerSample = 0.0;
  20133. sampleRate = sampleRate_;
  20134. }
  20135. void ToneGeneratorAudioSource::releaseResources()
  20136. {
  20137. }
  20138. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20139. {
  20140. if (phasePerSample == 0.0)
  20141. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20142. for (int i = 0; i < info.numSamples; ++i)
  20143. {
  20144. const float sample = amplitude * (float) std::sin (currentPhase);
  20145. currentPhase += phasePerSample;
  20146. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20147. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20148. }
  20149. }
  20150. END_JUCE_NAMESPACE
  20151. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20152. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20153. BEGIN_JUCE_NAMESPACE
  20154. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20155. : sampleRate (0),
  20156. bufferSize (0),
  20157. useDefaultInputChannels (true),
  20158. useDefaultOutputChannels (true)
  20159. {
  20160. }
  20161. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20162. {
  20163. return outputDeviceName == other.outputDeviceName
  20164. && inputDeviceName == other.inputDeviceName
  20165. && sampleRate == other.sampleRate
  20166. && bufferSize == other.bufferSize
  20167. && inputChannels == other.inputChannels
  20168. && useDefaultInputChannels == other.useDefaultInputChannels
  20169. && outputChannels == other.outputChannels
  20170. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20171. }
  20172. AudioDeviceManager::AudioDeviceManager()
  20173. : currentAudioDevice (0),
  20174. numInputChansNeeded (0),
  20175. numOutputChansNeeded (2),
  20176. listNeedsScanning (true),
  20177. useInputNames (false),
  20178. inputLevelMeasurementEnabledCount (0),
  20179. inputLevel (0),
  20180. tempBuffer (2, 2),
  20181. defaultMidiOutput (0),
  20182. cpuUsageMs (0),
  20183. timeToCpuScale (0)
  20184. {
  20185. callbackHandler.owner = this;
  20186. }
  20187. AudioDeviceManager::~AudioDeviceManager()
  20188. {
  20189. currentAudioDevice = 0;
  20190. defaultMidiOutput = 0;
  20191. }
  20192. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20193. {
  20194. if (availableDeviceTypes.size() == 0)
  20195. {
  20196. createAudioDeviceTypes (availableDeviceTypes);
  20197. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20198. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20199. if (availableDeviceTypes.size() > 0)
  20200. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20201. }
  20202. }
  20203. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20204. {
  20205. scanDevicesIfNeeded();
  20206. return availableDeviceTypes;
  20207. }
  20208. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20209. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20210. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20211. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20212. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20213. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20214. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20215. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20216. {
  20217. (void) list; // (to avoid 'unused param' warnings)
  20218. #if JUCE_WINDOWS
  20219. #if JUCE_WASAPI
  20220. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20221. list.add (juce_createAudioIODeviceType_WASAPI());
  20222. #endif
  20223. #if JUCE_DIRECTSOUND
  20224. list.add (juce_createAudioIODeviceType_DirectSound());
  20225. #endif
  20226. #if JUCE_ASIO
  20227. list.add (juce_createAudioIODeviceType_ASIO());
  20228. #endif
  20229. #endif
  20230. #if JUCE_MAC
  20231. list.add (juce_createAudioIODeviceType_CoreAudio());
  20232. #endif
  20233. #if JUCE_IOS
  20234. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20235. #endif
  20236. #if JUCE_LINUX && JUCE_ALSA
  20237. list.add (juce_createAudioIODeviceType_ALSA());
  20238. #endif
  20239. #if JUCE_LINUX && JUCE_JACK
  20240. list.add (juce_createAudioIODeviceType_JACK());
  20241. #endif
  20242. }
  20243. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20244. const int numOutputChannelsNeeded,
  20245. const XmlElement* const e,
  20246. const bool selectDefaultDeviceOnFailure,
  20247. const String& preferredDefaultDeviceName,
  20248. const AudioDeviceSetup* preferredSetupOptions)
  20249. {
  20250. scanDevicesIfNeeded();
  20251. numInputChansNeeded = numInputChannelsNeeded;
  20252. numOutputChansNeeded = numOutputChannelsNeeded;
  20253. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20254. {
  20255. lastExplicitSettings = new XmlElement (*e);
  20256. String error;
  20257. AudioDeviceSetup setup;
  20258. if (preferredSetupOptions != 0)
  20259. setup = *preferredSetupOptions;
  20260. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20261. {
  20262. setup.inputDeviceName = setup.outputDeviceName
  20263. = e->getStringAttribute ("audioDeviceName");
  20264. }
  20265. else
  20266. {
  20267. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20268. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20269. }
  20270. currentDeviceType = e->getStringAttribute ("deviceType");
  20271. if (currentDeviceType.isEmpty())
  20272. {
  20273. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20274. if (type != 0)
  20275. currentDeviceType = type->getTypeName();
  20276. else if (availableDeviceTypes.size() > 0)
  20277. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20278. }
  20279. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20280. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20281. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20282. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20283. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20284. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20285. error = setAudioDeviceSetup (setup, true);
  20286. midiInsFromXml.clear();
  20287. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20288. midiInsFromXml.add (c->getStringAttribute ("name"));
  20289. const StringArray allMidiIns (MidiInput::getDevices());
  20290. for (int i = allMidiIns.size(); --i >= 0;)
  20291. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20292. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20293. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20294. false, preferredDefaultDeviceName);
  20295. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20296. return error;
  20297. }
  20298. else
  20299. {
  20300. AudioDeviceSetup setup;
  20301. if (preferredSetupOptions != 0)
  20302. {
  20303. setup = *preferredSetupOptions;
  20304. }
  20305. else if (preferredDefaultDeviceName.isNotEmpty())
  20306. {
  20307. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20308. {
  20309. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20310. StringArray outs (type->getDeviceNames (false));
  20311. int i;
  20312. for (i = 0; i < outs.size(); ++i)
  20313. {
  20314. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20315. {
  20316. setup.outputDeviceName = outs[i];
  20317. break;
  20318. }
  20319. }
  20320. StringArray ins (type->getDeviceNames (true));
  20321. for (i = 0; i < ins.size(); ++i)
  20322. {
  20323. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20324. {
  20325. setup.inputDeviceName = ins[i];
  20326. break;
  20327. }
  20328. }
  20329. }
  20330. }
  20331. insertDefaultDeviceNames (setup);
  20332. return setAudioDeviceSetup (setup, false);
  20333. }
  20334. }
  20335. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20336. {
  20337. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20338. if (type != 0)
  20339. {
  20340. if (setup.outputDeviceName.isEmpty())
  20341. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20342. if (setup.inputDeviceName.isEmpty())
  20343. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20344. }
  20345. }
  20346. XmlElement* AudioDeviceManager::createStateXml() const
  20347. {
  20348. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20349. }
  20350. void AudioDeviceManager::scanDevicesIfNeeded()
  20351. {
  20352. if (listNeedsScanning)
  20353. {
  20354. listNeedsScanning = false;
  20355. createDeviceTypesIfNeeded();
  20356. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20357. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20358. }
  20359. }
  20360. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20361. {
  20362. scanDevicesIfNeeded();
  20363. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20364. {
  20365. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20366. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20367. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20368. {
  20369. return type;
  20370. }
  20371. }
  20372. return 0;
  20373. }
  20374. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20375. {
  20376. setup = currentSetup;
  20377. }
  20378. void AudioDeviceManager::deleteCurrentDevice()
  20379. {
  20380. currentAudioDevice = 0;
  20381. currentSetup.inputDeviceName = String::empty;
  20382. currentSetup.outputDeviceName = String::empty;
  20383. }
  20384. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20385. const bool treatAsChosenDevice)
  20386. {
  20387. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20388. {
  20389. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20390. && currentDeviceType != type)
  20391. {
  20392. currentDeviceType = type;
  20393. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20394. insertDefaultDeviceNames (s);
  20395. setAudioDeviceSetup (s, treatAsChosenDevice);
  20396. sendChangeMessage();
  20397. break;
  20398. }
  20399. }
  20400. }
  20401. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20402. {
  20403. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20404. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20405. return availableDeviceTypes[i];
  20406. return availableDeviceTypes[0];
  20407. }
  20408. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20409. const bool treatAsChosenDevice)
  20410. {
  20411. jassert (&newSetup != &currentSetup); // this will have no effect
  20412. if (newSetup == currentSetup && currentAudioDevice != 0)
  20413. return String::empty;
  20414. if (! (newSetup == currentSetup))
  20415. sendChangeMessage();
  20416. stopDevice();
  20417. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20418. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20419. String error;
  20420. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20421. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20422. {
  20423. deleteCurrentDevice();
  20424. if (treatAsChosenDevice)
  20425. updateXml();
  20426. return String::empty;
  20427. }
  20428. if (currentSetup.inputDeviceName != newInputDeviceName
  20429. || currentSetup.outputDeviceName != newOutputDeviceName
  20430. || currentAudioDevice == 0)
  20431. {
  20432. deleteCurrentDevice();
  20433. scanDevicesIfNeeded();
  20434. if (newOutputDeviceName.isNotEmpty()
  20435. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20436. {
  20437. return "No such device: " + newOutputDeviceName;
  20438. }
  20439. if (newInputDeviceName.isNotEmpty()
  20440. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20441. {
  20442. return "No such device: " + newInputDeviceName;
  20443. }
  20444. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20445. if (currentAudioDevice == 0)
  20446. 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!";
  20447. else
  20448. error = currentAudioDevice->getLastError();
  20449. if (error.isNotEmpty())
  20450. {
  20451. deleteCurrentDevice();
  20452. return error;
  20453. }
  20454. if (newSetup.useDefaultInputChannels)
  20455. {
  20456. inputChannels.clear();
  20457. inputChannels.setRange (0, numInputChansNeeded, true);
  20458. }
  20459. if (newSetup.useDefaultOutputChannels)
  20460. {
  20461. outputChannels.clear();
  20462. outputChannels.setRange (0, numOutputChansNeeded, true);
  20463. }
  20464. if (newInputDeviceName.isEmpty())
  20465. inputChannels.clear();
  20466. if (newOutputDeviceName.isEmpty())
  20467. outputChannels.clear();
  20468. }
  20469. if (! newSetup.useDefaultInputChannels)
  20470. inputChannels = newSetup.inputChannels;
  20471. if (! newSetup.useDefaultOutputChannels)
  20472. outputChannels = newSetup.outputChannels;
  20473. currentSetup = newSetup;
  20474. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20475. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20476. error = currentAudioDevice->open (inputChannels,
  20477. outputChannels,
  20478. currentSetup.sampleRate,
  20479. currentSetup.bufferSize);
  20480. if (error.isEmpty())
  20481. {
  20482. currentDeviceType = currentAudioDevice->getTypeName();
  20483. currentAudioDevice->start (&callbackHandler);
  20484. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20485. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20486. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20487. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20488. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20489. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20490. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20491. if (treatAsChosenDevice)
  20492. updateXml();
  20493. }
  20494. else
  20495. {
  20496. deleteCurrentDevice();
  20497. }
  20498. return error;
  20499. }
  20500. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20501. {
  20502. jassert (currentAudioDevice != 0);
  20503. if (rate > 0)
  20504. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20505. if (currentAudioDevice->getSampleRate (i) == rate)
  20506. return rate;
  20507. double lowestAbove44 = 0.0;
  20508. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20509. {
  20510. const double sr = currentAudioDevice->getSampleRate (i);
  20511. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20512. lowestAbove44 = sr;
  20513. }
  20514. if (lowestAbove44 > 0.0)
  20515. return lowestAbove44;
  20516. return currentAudioDevice->getSampleRate (0);
  20517. }
  20518. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20519. {
  20520. jassert (currentAudioDevice != 0);
  20521. if (bufferSize > 0)
  20522. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20523. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20524. return bufferSize;
  20525. return currentAudioDevice->getDefaultBufferSize();
  20526. }
  20527. void AudioDeviceManager::stopDevice()
  20528. {
  20529. if (currentAudioDevice != 0)
  20530. currentAudioDevice->stop();
  20531. testSound = 0;
  20532. }
  20533. void AudioDeviceManager::closeAudioDevice()
  20534. {
  20535. stopDevice();
  20536. currentAudioDevice = 0;
  20537. }
  20538. void AudioDeviceManager::restartLastAudioDevice()
  20539. {
  20540. if (currentAudioDevice == 0)
  20541. {
  20542. if (currentSetup.inputDeviceName.isEmpty()
  20543. && currentSetup.outputDeviceName.isEmpty())
  20544. {
  20545. // This method will only reload the last device that was running
  20546. // before closeAudioDevice() was called - you need to actually open
  20547. // one first, with setAudioDevice().
  20548. jassertfalse;
  20549. return;
  20550. }
  20551. AudioDeviceSetup s (currentSetup);
  20552. setAudioDeviceSetup (s, false);
  20553. }
  20554. }
  20555. void AudioDeviceManager::updateXml()
  20556. {
  20557. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20558. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20559. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20560. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20561. if (currentAudioDevice != 0)
  20562. {
  20563. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20564. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20565. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20566. if (! currentSetup.useDefaultInputChannels)
  20567. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20568. if (! currentSetup.useDefaultOutputChannels)
  20569. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20570. }
  20571. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20572. {
  20573. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20574. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20575. }
  20576. if (midiInsFromXml.size() > 0)
  20577. {
  20578. // Add any midi devices that have been enabled before, but which aren't currently
  20579. // open because the device has been disconnected.
  20580. const StringArray availableMidiDevices (MidiInput::getDevices());
  20581. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20582. {
  20583. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20584. {
  20585. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20586. m->setAttribute ("name", midiInsFromXml[i]);
  20587. }
  20588. }
  20589. }
  20590. if (defaultMidiOutputName.isNotEmpty())
  20591. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20592. }
  20593. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20594. {
  20595. {
  20596. const ScopedLock sl (audioCallbackLock);
  20597. if (callbacks.contains (newCallback))
  20598. return;
  20599. }
  20600. if (currentAudioDevice != 0 && newCallback != 0)
  20601. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20602. const ScopedLock sl (audioCallbackLock);
  20603. callbacks.add (newCallback);
  20604. }
  20605. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  20606. {
  20607. if (callbackToRemove != 0)
  20608. {
  20609. bool needsDeinitialising = currentAudioDevice != 0;
  20610. {
  20611. const ScopedLock sl (audioCallbackLock);
  20612. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  20613. callbacks.removeValue (callbackToRemove);
  20614. }
  20615. if (needsDeinitialising)
  20616. callbackToRemove->audioDeviceStopped();
  20617. }
  20618. }
  20619. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20620. int numInputChannels,
  20621. float** outputChannelData,
  20622. int numOutputChannels,
  20623. int numSamples)
  20624. {
  20625. const ScopedLock sl (audioCallbackLock);
  20626. if (inputLevelMeasurementEnabledCount > 0)
  20627. {
  20628. for (int j = 0; j < numSamples; ++j)
  20629. {
  20630. float s = 0;
  20631. for (int i = 0; i < numInputChannels; ++i)
  20632. s += std::abs (inputChannelData[i][j]);
  20633. s /= numInputChannels;
  20634. const double decayFactor = 0.99992;
  20635. if (s > inputLevel)
  20636. inputLevel = s;
  20637. else if (inputLevel > 0.001f)
  20638. inputLevel *= decayFactor;
  20639. else
  20640. inputLevel = 0;
  20641. }
  20642. }
  20643. if (callbacks.size() > 0)
  20644. {
  20645. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20646. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20647. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20648. outputChannelData, numOutputChannels, numSamples);
  20649. float** const tempChans = tempBuffer.getArrayOfChannels();
  20650. for (int i = callbacks.size(); --i > 0;)
  20651. {
  20652. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20653. tempChans, numOutputChannels, numSamples);
  20654. for (int chan = 0; chan < numOutputChannels; ++chan)
  20655. {
  20656. const float* const src = tempChans [chan];
  20657. float* const dst = outputChannelData [chan];
  20658. if (src != 0 && dst != 0)
  20659. for (int j = 0; j < numSamples; ++j)
  20660. dst[j] += src[j];
  20661. }
  20662. }
  20663. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20664. const double filterAmount = 0.2;
  20665. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20666. }
  20667. else
  20668. {
  20669. for (int i = 0; i < numOutputChannels; ++i)
  20670. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20671. }
  20672. if (testSound != 0)
  20673. {
  20674. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20675. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20676. for (int i = 0; i < numOutputChannels; ++i)
  20677. for (int j = 0; j < numSamps; ++j)
  20678. outputChannelData [i][j] += src[j];
  20679. testSoundPosition += numSamps;
  20680. if (testSoundPosition >= testSound->getNumSamples())
  20681. testSound = 0;
  20682. }
  20683. }
  20684. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20685. {
  20686. cpuUsageMs = 0;
  20687. const double sampleRate = device->getCurrentSampleRate();
  20688. const int blockSize = device->getCurrentBufferSizeSamples();
  20689. if (sampleRate > 0.0 && blockSize > 0)
  20690. {
  20691. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20692. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20693. }
  20694. {
  20695. const ScopedLock sl (audioCallbackLock);
  20696. for (int i = callbacks.size(); --i >= 0;)
  20697. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20698. }
  20699. sendChangeMessage();
  20700. }
  20701. void AudioDeviceManager::audioDeviceStoppedInt()
  20702. {
  20703. cpuUsageMs = 0;
  20704. timeToCpuScale = 0;
  20705. sendChangeMessage();
  20706. const ScopedLock sl (audioCallbackLock);
  20707. for (int i = callbacks.size(); --i >= 0;)
  20708. callbacks.getUnchecked(i)->audioDeviceStopped();
  20709. }
  20710. double AudioDeviceManager::getCpuUsage() const
  20711. {
  20712. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20713. }
  20714. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20715. const bool enabled)
  20716. {
  20717. if (enabled != isMidiInputEnabled (name))
  20718. {
  20719. if (enabled)
  20720. {
  20721. const int index = MidiInput::getDevices().indexOf (name);
  20722. if (index >= 0)
  20723. {
  20724. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20725. if (min != 0)
  20726. {
  20727. enabledMidiInputs.add (min);
  20728. min->start();
  20729. }
  20730. }
  20731. }
  20732. else
  20733. {
  20734. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20735. if (enabledMidiInputs[i]->getName() == name)
  20736. enabledMidiInputs.remove (i);
  20737. }
  20738. updateXml();
  20739. sendChangeMessage();
  20740. }
  20741. }
  20742. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20743. {
  20744. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20745. if (enabledMidiInputs[i]->getName() == name)
  20746. return true;
  20747. return false;
  20748. }
  20749. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20750. MidiInputCallback* callbackToAdd)
  20751. {
  20752. removeMidiInputCallback (name, callbackToAdd);
  20753. if (name.isEmpty())
  20754. {
  20755. midiCallbacks.add (callbackToAdd);
  20756. midiCallbackDevices.add (0);
  20757. }
  20758. else
  20759. {
  20760. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20761. {
  20762. if (enabledMidiInputs[i]->getName() == name)
  20763. {
  20764. const ScopedLock sl (midiCallbackLock);
  20765. midiCallbacks.add (callbackToAdd);
  20766. midiCallbackDevices.add (enabledMidiInputs[i]);
  20767. break;
  20768. }
  20769. }
  20770. }
  20771. }
  20772. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* /*callback*/)
  20773. {
  20774. const ScopedLock sl (midiCallbackLock);
  20775. for (int i = midiCallbacks.size(); --i >= 0;)
  20776. {
  20777. String devName;
  20778. if (midiCallbackDevices.getUnchecked(i) != 0)
  20779. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20780. if (devName == name)
  20781. {
  20782. midiCallbacks.remove (i);
  20783. midiCallbackDevices.remove (i);
  20784. }
  20785. }
  20786. }
  20787. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20788. const MidiMessage& message)
  20789. {
  20790. if (! message.isActiveSense())
  20791. {
  20792. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20793. const ScopedLock sl (midiCallbackLock);
  20794. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20795. {
  20796. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20797. if (md == source || (md == 0 && isDefaultSource))
  20798. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20799. }
  20800. }
  20801. }
  20802. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20803. {
  20804. if (defaultMidiOutputName != deviceName)
  20805. {
  20806. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20807. {
  20808. const ScopedLock sl (audioCallbackLock);
  20809. oldCallbacks = callbacks;
  20810. callbacks.clear();
  20811. }
  20812. if (currentAudioDevice != 0)
  20813. for (int i = oldCallbacks.size(); --i >= 0;)
  20814. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20815. defaultMidiOutput = 0;
  20816. defaultMidiOutputName = deviceName;
  20817. if (deviceName.isNotEmpty())
  20818. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20819. if (currentAudioDevice != 0)
  20820. for (int i = oldCallbacks.size(); --i >= 0;)
  20821. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20822. {
  20823. const ScopedLock sl (audioCallbackLock);
  20824. callbacks = oldCallbacks;
  20825. }
  20826. updateXml();
  20827. sendChangeMessage();
  20828. }
  20829. }
  20830. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20831. int numInputChannels,
  20832. float** outputChannelData,
  20833. int numOutputChannels,
  20834. int numSamples)
  20835. {
  20836. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20837. }
  20838. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20839. {
  20840. owner->audioDeviceAboutToStartInt (device);
  20841. }
  20842. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20843. {
  20844. owner->audioDeviceStoppedInt();
  20845. }
  20846. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20847. {
  20848. owner->handleIncomingMidiMessageInt (source, message);
  20849. }
  20850. void AudioDeviceManager::playTestSound()
  20851. {
  20852. { // cunningly nested to swap, unlock and delete in that order.
  20853. ScopedPointer <AudioSampleBuffer> oldSound;
  20854. {
  20855. const ScopedLock sl (audioCallbackLock);
  20856. oldSound = testSound;
  20857. }
  20858. }
  20859. testSoundPosition = 0;
  20860. if (currentAudioDevice != 0)
  20861. {
  20862. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20863. const int soundLength = (int) sampleRate;
  20864. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20865. float* samples = newSound->getSampleData (0);
  20866. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20867. const float amplitude = 0.5f;
  20868. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20869. for (int i = 0; i < soundLength; ++i)
  20870. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20871. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20872. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20873. const ScopedLock sl (audioCallbackLock);
  20874. testSound = newSound;
  20875. }
  20876. }
  20877. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20878. {
  20879. const ScopedLock sl (audioCallbackLock);
  20880. if (enableMeasurement)
  20881. ++inputLevelMeasurementEnabledCount;
  20882. else
  20883. --inputLevelMeasurementEnabledCount;
  20884. inputLevel = 0;
  20885. }
  20886. double AudioDeviceManager::getCurrentInputLevel() const
  20887. {
  20888. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20889. return inputLevel;
  20890. }
  20891. END_JUCE_NAMESPACE
  20892. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20893. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20894. BEGIN_JUCE_NAMESPACE
  20895. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20896. : name (deviceName),
  20897. typeName (typeName_)
  20898. {
  20899. }
  20900. AudioIODevice::~AudioIODevice()
  20901. {
  20902. }
  20903. bool AudioIODevice::hasControlPanel() const
  20904. {
  20905. return false;
  20906. }
  20907. bool AudioIODevice::showControlPanel()
  20908. {
  20909. jassertfalse; // this should only be called for devices which return true from
  20910. // their hasControlPanel() method.
  20911. return false;
  20912. }
  20913. END_JUCE_NAMESPACE
  20914. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20915. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20916. BEGIN_JUCE_NAMESPACE
  20917. AudioIODeviceType::AudioIODeviceType (const String& name)
  20918. : typeName (name)
  20919. {
  20920. }
  20921. AudioIODeviceType::~AudioIODeviceType()
  20922. {
  20923. }
  20924. END_JUCE_NAMESPACE
  20925. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20926. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20927. BEGIN_JUCE_NAMESPACE
  20928. MidiOutput::MidiOutput()
  20929. : Thread ("midi out"),
  20930. internal (0),
  20931. firstMessage (0)
  20932. {
  20933. }
  20934. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20935. const double sampleNumber)
  20936. : message (data, len, sampleNumber)
  20937. {
  20938. }
  20939. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20940. const double millisecondCounterToStartAt,
  20941. double samplesPerSecondForBuffer)
  20942. {
  20943. // You've got to call startBackgroundThread() for this to actually work..
  20944. jassert (isThreadRunning());
  20945. // this needs to be a value in the future - RTFM for this method!
  20946. jassert (millisecondCounterToStartAt > 0);
  20947. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20948. MidiBuffer::Iterator i (buffer);
  20949. const uint8* data;
  20950. int len, time;
  20951. while (i.getNextEvent (data, len, time))
  20952. {
  20953. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20954. PendingMessage* const m
  20955. = new PendingMessage (data, len, eventTime);
  20956. const ScopedLock sl (lock);
  20957. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20958. {
  20959. m->next = firstMessage;
  20960. firstMessage = m;
  20961. }
  20962. else
  20963. {
  20964. PendingMessage* mm = firstMessage;
  20965. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20966. mm = mm->next;
  20967. m->next = mm->next;
  20968. mm->next = m;
  20969. }
  20970. }
  20971. notify();
  20972. }
  20973. void MidiOutput::clearAllPendingMessages()
  20974. {
  20975. const ScopedLock sl (lock);
  20976. while (firstMessage != 0)
  20977. {
  20978. PendingMessage* const m = firstMessage;
  20979. firstMessage = firstMessage->next;
  20980. delete m;
  20981. }
  20982. }
  20983. void MidiOutput::startBackgroundThread()
  20984. {
  20985. startThread (9);
  20986. }
  20987. void MidiOutput::stopBackgroundThread()
  20988. {
  20989. stopThread (5000);
  20990. }
  20991. void MidiOutput::run()
  20992. {
  20993. while (! threadShouldExit())
  20994. {
  20995. uint32 now = Time::getMillisecondCounter();
  20996. uint32 eventTime = 0;
  20997. uint32 timeToWait = 500;
  20998. PendingMessage* message;
  20999. {
  21000. const ScopedLock sl (lock);
  21001. message = firstMessage;
  21002. if (message != 0)
  21003. {
  21004. eventTime = roundToInt (message->message.getTimeStamp());
  21005. if (eventTime > now + 20)
  21006. {
  21007. timeToWait = eventTime - (now + 20);
  21008. message = 0;
  21009. }
  21010. else
  21011. {
  21012. firstMessage = message->next;
  21013. }
  21014. }
  21015. }
  21016. if (message != 0)
  21017. {
  21018. if (eventTime > now)
  21019. {
  21020. Time::waitForMillisecondCounter (eventTime);
  21021. if (threadShouldExit())
  21022. break;
  21023. }
  21024. if (eventTime > now - 200)
  21025. sendMessageNow (message->message);
  21026. delete message;
  21027. }
  21028. else
  21029. {
  21030. jassert (timeToWait < 1000 * 30);
  21031. wait (timeToWait);
  21032. }
  21033. }
  21034. clearAllPendingMessages();
  21035. }
  21036. END_JUCE_NAMESPACE
  21037. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21038. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21039. BEGIN_JUCE_NAMESPACE
  21040. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21041. {
  21042. const double maxVal = (double) 0x7fff;
  21043. char* intData = static_cast <char*> (dest);
  21044. if (dest != (void*) source || destBytesPerSample <= 4)
  21045. {
  21046. for (int i = 0; i < numSamples; ++i)
  21047. {
  21048. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21049. intData += destBytesPerSample;
  21050. }
  21051. }
  21052. else
  21053. {
  21054. intData += destBytesPerSample * numSamples;
  21055. for (int i = numSamples; --i >= 0;)
  21056. {
  21057. intData -= destBytesPerSample;
  21058. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21059. }
  21060. }
  21061. }
  21062. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21063. {
  21064. const double maxVal = (double) 0x7fff;
  21065. char* intData = static_cast <char*> (dest);
  21066. if (dest != (void*) source || destBytesPerSample <= 4)
  21067. {
  21068. for (int i = 0; i < numSamples; ++i)
  21069. {
  21070. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21071. intData += destBytesPerSample;
  21072. }
  21073. }
  21074. else
  21075. {
  21076. intData += destBytesPerSample * numSamples;
  21077. for (int i = numSamples; --i >= 0;)
  21078. {
  21079. intData -= destBytesPerSample;
  21080. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21081. }
  21082. }
  21083. }
  21084. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21085. {
  21086. const double maxVal = (double) 0x7fffff;
  21087. char* intData = static_cast <char*> (dest);
  21088. if (dest != (void*) source || destBytesPerSample <= 4)
  21089. {
  21090. for (int i = 0; i < numSamples; ++i)
  21091. {
  21092. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21093. intData += destBytesPerSample;
  21094. }
  21095. }
  21096. else
  21097. {
  21098. intData += destBytesPerSample * numSamples;
  21099. for (int i = numSamples; --i >= 0;)
  21100. {
  21101. intData -= destBytesPerSample;
  21102. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21103. }
  21104. }
  21105. }
  21106. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21107. {
  21108. const double maxVal = (double) 0x7fffff;
  21109. char* intData = static_cast <char*> (dest);
  21110. if (dest != (void*) source || destBytesPerSample <= 4)
  21111. {
  21112. for (int i = 0; i < numSamples; ++i)
  21113. {
  21114. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21115. intData += destBytesPerSample;
  21116. }
  21117. }
  21118. else
  21119. {
  21120. intData += destBytesPerSample * numSamples;
  21121. for (int i = numSamples; --i >= 0;)
  21122. {
  21123. intData -= destBytesPerSample;
  21124. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21125. }
  21126. }
  21127. }
  21128. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21129. {
  21130. const double maxVal = (double) 0x7fffffff;
  21131. char* intData = static_cast <char*> (dest);
  21132. if (dest != (void*) source || destBytesPerSample <= 4)
  21133. {
  21134. for (int i = 0; i < numSamples; ++i)
  21135. {
  21136. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21137. intData += destBytesPerSample;
  21138. }
  21139. }
  21140. else
  21141. {
  21142. intData += destBytesPerSample * numSamples;
  21143. for (int i = numSamples; --i >= 0;)
  21144. {
  21145. intData -= destBytesPerSample;
  21146. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21147. }
  21148. }
  21149. }
  21150. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21151. {
  21152. const double maxVal = (double) 0x7fffffff;
  21153. char* intData = static_cast <char*> (dest);
  21154. if (dest != (void*) source || destBytesPerSample <= 4)
  21155. {
  21156. for (int i = 0; i < numSamples; ++i)
  21157. {
  21158. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21159. intData += destBytesPerSample;
  21160. }
  21161. }
  21162. else
  21163. {
  21164. intData += destBytesPerSample * numSamples;
  21165. for (int i = numSamples; --i >= 0;)
  21166. {
  21167. intData -= destBytesPerSample;
  21168. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21169. }
  21170. }
  21171. }
  21172. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21173. {
  21174. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21175. char* d = static_cast <char*> (dest);
  21176. for (int i = 0; i < numSamples; ++i)
  21177. {
  21178. *(float*) d = source[i];
  21179. #if JUCE_BIG_ENDIAN
  21180. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21181. #endif
  21182. d += destBytesPerSample;
  21183. }
  21184. }
  21185. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21186. {
  21187. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21188. char* d = static_cast <char*> (dest);
  21189. for (int i = 0; i < numSamples; ++i)
  21190. {
  21191. *(float*) d = source[i];
  21192. #if JUCE_LITTLE_ENDIAN
  21193. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21194. #endif
  21195. d += destBytesPerSample;
  21196. }
  21197. }
  21198. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21199. {
  21200. const float scale = 1.0f / 0x7fff;
  21201. const char* intData = static_cast <const char*> (source);
  21202. if (source != (void*) dest || srcBytesPerSample >= 4)
  21203. {
  21204. for (int i = 0; i < numSamples; ++i)
  21205. {
  21206. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21207. intData += srcBytesPerSample;
  21208. }
  21209. }
  21210. else
  21211. {
  21212. intData += srcBytesPerSample * numSamples;
  21213. for (int i = numSamples; --i >= 0;)
  21214. {
  21215. intData -= srcBytesPerSample;
  21216. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21217. }
  21218. }
  21219. }
  21220. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21221. {
  21222. const float scale = 1.0f / 0x7fff;
  21223. const char* intData = static_cast <const char*> (source);
  21224. if (source != (void*) dest || srcBytesPerSample >= 4)
  21225. {
  21226. for (int i = 0; i < numSamples; ++i)
  21227. {
  21228. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21229. intData += srcBytesPerSample;
  21230. }
  21231. }
  21232. else
  21233. {
  21234. intData += srcBytesPerSample * numSamples;
  21235. for (int i = numSamples; --i >= 0;)
  21236. {
  21237. intData -= srcBytesPerSample;
  21238. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21239. }
  21240. }
  21241. }
  21242. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21243. {
  21244. const float scale = 1.0f / 0x7fffff;
  21245. const char* intData = static_cast <const char*> (source);
  21246. if (source != (void*) dest || srcBytesPerSample >= 4)
  21247. {
  21248. for (int i = 0; i < numSamples; ++i)
  21249. {
  21250. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21251. intData += srcBytesPerSample;
  21252. }
  21253. }
  21254. else
  21255. {
  21256. intData += srcBytesPerSample * numSamples;
  21257. for (int i = numSamples; --i >= 0;)
  21258. {
  21259. intData -= srcBytesPerSample;
  21260. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21261. }
  21262. }
  21263. }
  21264. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21265. {
  21266. const float scale = 1.0f / 0x7fffff;
  21267. const char* intData = static_cast <const char*> (source);
  21268. if (source != (void*) dest || srcBytesPerSample >= 4)
  21269. {
  21270. for (int i = 0; i < numSamples; ++i)
  21271. {
  21272. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21273. intData += srcBytesPerSample;
  21274. }
  21275. }
  21276. else
  21277. {
  21278. intData += srcBytesPerSample * numSamples;
  21279. for (int i = numSamples; --i >= 0;)
  21280. {
  21281. intData -= srcBytesPerSample;
  21282. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21283. }
  21284. }
  21285. }
  21286. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21287. {
  21288. const float scale = 1.0f / 0x7fffffff;
  21289. const char* intData = static_cast <const char*> (source);
  21290. if (source != (void*) dest || srcBytesPerSample >= 4)
  21291. {
  21292. for (int i = 0; i < numSamples; ++i)
  21293. {
  21294. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21295. intData += srcBytesPerSample;
  21296. }
  21297. }
  21298. else
  21299. {
  21300. intData += srcBytesPerSample * numSamples;
  21301. for (int i = numSamples; --i >= 0;)
  21302. {
  21303. intData -= srcBytesPerSample;
  21304. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21305. }
  21306. }
  21307. }
  21308. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21309. {
  21310. const float scale = 1.0f / 0x7fffffff;
  21311. const char* intData = static_cast <const char*> (source);
  21312. if (source != (void*) dest || srcBytesPerSample >= 4)
  21313. {
  21314. for (int i = 0; i < numSamples; ++i)
  21315. {
  21316. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21317. intData += srcBytesPerSample;
  21318. }
  21319. }
  21320. else
  21321. {
  21322. intData += srcBytesPerSample * numSamples;
  21323. for (int i = numSamples; --i >= 0;)
  21324. {
  21325. intData -= srcBytesPerSample;
  21326. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21327. }
  21328. }
  21329. }
  21330. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21331. {
  21332. const char* s = static_cast <const char*> (source);
  21333. for (int i = 0; i < numSamples; ++i)
  21334. {
  21335. dest[i] = *(float*)s;
  21336. #if JUCE_BIG_ENDIAN
  21337. uint32* const d = (uint32*) (dest + i);
  21338. *d = ByteOrder::swap (*d);
  21339. #endif
  21340. s += srcBytesPerSample;
  21341. }
  21342. }
  21343. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21344. {
  21345. const char* s = static_cast <const char*> (source);
  21346. for (int i = 0; i < numSamples; ++i)
  21347. {
  21348. dest[i] = *(float*)s;
  21349. #if JUCE_LITTLE_ENDIAN
  21350. uint32* const d = (uint32*) (dest + i);
  21351. *d = ByteOrder::swap (*d);
  21352. #endif
  21353. s += srcBytesPerSample;
  21354. }
  21355. }
  21356. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21357. const float* const source,
  21358. void* const dest,
  21359. const int numSamples)
  21360. {
  21361. switch (destFormat)
  21362. {
  21363. case int16LE:
  21364. convertFloatToInt16LE (source, dest, numSamples);
  21365. break;
  21366. case int16BE:
  21367. convertFloatToInt16BE (source, dest, numSamples);
  21368. break;
  21369. case int24LE:
  21370. convertFloatToInt24LE (source, dest, numSamples);
  21371. break;
  21372. case int24BE:
  21373. convertFloatToInt24BE (source, dest, numSamples);
  21374. break;
  21375. case int32LE:
  21376. convertFloatToInt32LE (source, dest, numSamples);
  21377. break;
  21378. case int32BE:
  21379. convertFloatToInt32BE (source, dest, numSamples);
  21380. break;
  21381. case float32LE:
  21382. convertFloatToFloat32LE (source, dest, numSamples);
  21383. break;
  21384. case float32BE:
  21385. convertFloatToFloat32BE (source, dest, numSamples);
  21386. break;
  21387. default:
  21388. jassertfalse;
  21389. break;
  21390. }
  21391. }
  21392. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21393. const void* const source,
  21394. float* const dest,
  21395. const int numSamples)
  21396. {
  21397. switch (sourceFormat)
  21398. {
  21399. case int16LE:
  21400. convertInt16LEToFloat (source, dest, numSamples);
  21401. break;
  21402. case int16BE:
  21403. convertInt16BEToFloat (source, dest, numSamples);
  21404. break;
  21405. case int24LE:
  21406. convertInt24LEToFloat (source, dest, numSamples);
  21407. break;
  21408. case int24BE:
  21409. convertInt24BEToFloat (source, dest, numSamples);
  21410. break;
  21411. case int32LE:
  21412. convertInt32LEToFloat (source, dest, numSamples);
  21413. break;
  21414. case int32BE:
  21415. convertInt32BEToFloat (source, dest, numSamples);
  21416. break;
  21417. case float32LE:
  21418. convertFloat32LEToFloat (source, dest, numSamples);
  21419. break;
  21420. case float32BE:
  21421. convertFloat32BEToFloat (source, dest, numSamples);
  21422. break;
  21423. default:
  21424. jassertfalse;
  21425. break;
  21426. }
  21427. }
  21428. void AudioDataConverters::interleaveSamples (const float** const source,
  21429. float* const dest,
  21430. const int numSamples,
  21431. const int numChannels)
  21432. {
  21433. for (int chan = 0; chan < numChannels; ++chan)
  21434. {
  21435. int i = chan;
  21436. const float* src = source [chan];
  21437. for (int j = 0; j < numSamples; ++j)
  21438. {
  21439. dest [i] = src [j];
  21440. i += numChannels;
  21441. }
  21442. }
  21443. }
  21444. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21445. float** const dest,
  21446. const int numSamples,
  21447. const int numChannels)
  21448. {
  21449. for (int chan = 0; chan < numChannels; ++chan)
  21450. {
  21451. int i = chan;
  21452. float* dst = dest [chan];
  21453. for (int j = 0; j < numSamples; ++j)
  21454. {
  21455. dst [j] = source [i];
  21456. i += numChannels;
  21457. }
  21458. }
  21459. }
  21460. #if JUCE_UNIT_TESTS
  21461. class AudioConversionTests : public UnitTest
  21462. {
  21463. public:
  21464. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21465. template <class F1, class E1, class F2, class E2>
  21466. struct Test5
  21467. {
  21468. static void test (UnitTest& unitTest)
  21469. {
  21470. test (unitTest, false);
  21471. test (unitTest, true);
  21472. }
  21473. static void test (UnitTest& unitTest, bool inPlace)
  21474. {
  21475. const int numSamples = 2048;
  21476. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21477. {
  21478. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21479. bool clippingFailed = false;
  21480. for (int i = 0; i < numSamples / 2; ++i)
  21481. {
  21482. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21483. if (! d.isFloatingPoint())
  21484. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21485. ++d;
  21486. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21487. ++d;
  21488. }
  21489. unitTest.expect (! clippingFailed);
  21490. }
  21491. // convert data from the source to dest format..
  21492. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21493. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21494. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21495. // ..and back again..
  21496. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21497. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21498. if (! inPlace)
  21499. zerostruct (reversed);
  21500. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21501. {
  21502. int biggestDiff = 0;
  21503. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21504. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21505. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21506. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21507. for (int i = 0; i < numSamples; ++i)
  21508. {
  21509. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21510. ++d1;
  21511. ++d2;
  21512. }
  21513. unitTest.expect (biggestDiff <= errorMargin);
  21514. }
  21515. }
  21516. };
  21517. template <class F1, class E1, class FormatType>
  21518. struct Test3
  21519. {
  21520. static void test (UnitTest& unitTest)
  21521. {
  21522. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21523. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21524. }
  21525. };
  21526. template <class FormatType, class Endianness>
  21527. struct Test2
  21528. {
  21529. static void test (UnitTest& unitTest)
  21530. {
  21531. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21532. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21533. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21534. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21535. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21536. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21537. }
  21538. };
  21539. template <class FormatType>
  21540. struct Test1
  21541. {
  21542. static void test (UnitTest& unitTest)
  21543. {
  21544. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21545. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21546. }
  21547. };
  21548. void runTest()
  21549. {
  21550. beginTest ("Round-trip conversion");
  21551. Test1 <AudioData::Int8>::test (*this);
  21552. Test1 <AudioData::Int16>::test (*this);
  21553. Test1 <AudioData::Int24>::test (*this);
  21554. Test1 <AudioData::Int32>::test (*this);
  21555. Test1 <AudioData::Float32>::test (*this);
  21556. }
  21557. };
  21558. static AudioConversionTests audioConversionUnitTests;
  21559. #endif
  21560. END_JUCE_NAMESPACE
  21561. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21562. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21563. BEGIN_JUCE_NAMESPACE
  21564. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21565. const int numSamples) throw()
  21566. : numChannels (numChannels_),
  21567. size (numSamples)
  21568. {
  21569. jassert (numSamples >= 0);
  21570. jassert (numChannels_ > 0);
  21571. allocateData();
  21572. }
  21573. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21574. : numChannels (other.numChannels),
  21575. size (other.size)
  21576. {
  21577. allocateData();
  21578. const size_t numBytes = size * sizeof (float);
  21579. for (int i = 0; i < numChannels; ++i)
  21580. memcpy (channels[i], other.channels[i], numBytes);
  21581. }
  21582. void AudioSampleBuffer::allocateData()
  21583. {
  21584. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21585. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21586. allocatedData.malloc (allocatedBytes);
  21587. channels = reinterpret_cast <float**> (allocatedData.getData());
  21588. float* chan = (float*) (allocatedData + channelListSize);
  21589. for (int i = 0; i < numChannels; ++i)
  21590. {
  21591. channels[i] = chan;
  21592. chan += size;
  21593. }
  21594. channels [numChannels] = 0;
  21595. }
  21596. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21597. const int numChannels_,
  21598. const int numSamples) throw()
  21599. : numChannels (numChannels_),
  21600. size (numSamples),
  21601. allocatedBytes (0)
  21602. {
  21603. jassert (numChannels_ > 0);
  21604. allocateChannels (dataToReferTo);
  21605. }
  21606. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21607. const int newNumChannels,
  21608. const int newNumSamples) throw()
  21609. {
  21610. jassert (newNumChannels > 0);
  21611. allocatedBytes = 0;
  21612. allocatedData.free();
  21613. numChannels = newNumChannels;
  21614. size = newNumSamples;
  21615. allocateChannels (dataToReferTo);
  21616. }
  21617. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21618. {
  21619. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21620. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21621. {
  21622. channels = static_cast <float**> (preallocatedChannelSpace);
  21623. }
  21624. else
  21625. {
  21626. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21627. channels = reinterpret_cast <float**> (allocatedData.getData());
  21628. }
  21629. for (int i = 0; i < numChannels; ++i)
  21630. {
  21631. // you have to pass in the same number of valid pointers as numChannels
  21632. jassert (dataToReferTo[i] != 0);
  21633. channels[i] = dataToReferTo[i];
  21634. }
  21635. channels [numChannels] = 0;
  21636. }
  21637. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21638. {
  21639. if (this != &other)
  21640. {
  21641. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21642. const size_t numBytes = size * sizeof (float);
  21643. for (int i = 0; i < numChannels; ++i)
  21644. memcpy (channels[i], other.channels[i], numBytes);
  21645. }
  21646. return *this;
  21647. }
  21648. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21649. {
  21650. }
  21651. void AudioSampleBuffer::setSize (const int newNumChannels,
  21652. const int newNumSamples,
  21653. const bool keepExistingContent,
  21654. const bool clearExtraSpace,
  21655. const bool avoidReallocating) throw()
  21656. {
  21657. jassert (newNumChannels > 0);
  21658. if (newNumSamples != size || newNumChannels != numChannels)
  21659. {
  21660. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21661. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21662. if (keepExistingContent)
  21663. {
  21664. HeapBlock <char> newData;
  21665. newData.allocate (newTotalBytes, clearExtraSpace);
  21666. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21667. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21668. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21669. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21670. for (int i = 0; i < numChansToCopy; ++i)
  21671. {
  21672. memcpy (newChan, channels[i], numBytesToCopy);
  21673. newChannels[i] = newChan;
  21674. newChan += newNumSamples;
  21675. }
  21676. allocatedData.swapWith (newData);
  21677. allocatedBytes = (int) newTotalBytes;
  21678. channels = newChannels;
  21679. }
  21680. else
  21681. {
  21682. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21683. {
  21684. if (clearExtraSpace)
  21685. zeromem (allocatedData, newTotalBytes);
  21686. }
  21687. else
  21688. {
  21689. allocatedBytes = newTotalBytes;
  21690. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21691. channels = reinterpret_cast <float**> (allocatedData.getData());
  21692. }
  21693. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21694. for (int i = 0; i < newNumChannels; ++i)
  21695. {
  21696. channels[i] = chan;
  21697. chan += newNumSamples;
  21698. }
  21699. }
  21700. channels [newNumChannels] = 0;
  21701. size = newNumSamples;
  21702. numChannels = newNumChannels;
  21703. }
  21704. }
  21705. void AudioSampleBuffer::clear() throw()
  21706. {
  21707. for (int i = 0; i < numChannels; ++i)
  21708. zeromem (channels[i], size * sizeof (float));
  21709. }
  21710. void AudioSampleBuffer::clear (const int startSample,
  21711. const int numSamples) throw()
  21712. {
  21713. jassert (startSample >= 0 && startSample + numSamples <= size);
  21714. for (int i = 0; i < numChannels; ++i)
  21715. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21716. }
  21717. void AudioSampleBuffer::clear (const int channel,
  21718. const int startSample,
  21719. const int numSamples) throw()
  21720. {
  21721. jassert (isPositiveAndBelow (channel, numChannels));
  21722. jassert (startSample >= 0 && startSample + numSamples <= size);
  21723. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21724. }
  21725. void AudioSampleBuffer::applyGain (const int channel,
  21726. const int startSample,
  21727. int numSamples,
  21728. const float gain) throw()
  21729. {
  21730. jassert (isPositiveAndBelow (channel, numChannels));
  21731. jassert (startSample >= 0 && startSample + numSamples <= size);
  21732. if (gain != 1.0f)
  21733. {
  21734. float* d = channels [channel] + startSample;
  21735. if (gain == 0.0f)
  21736. {
  21737. zeromem (d, sizeof (float) * numSamples);
  21738. }
  21739. else
  21740. {
  21741. while (--numSamples >= 0)
  21742. *d++ *= gain;
  21743. }
  21744. }
  21745. }
  21746. void AudioSampleBuffer::applyGainRamp (const int channel,
  21747. const int startSample,
  21748. int numSamples,
  21749. float startGain,
  21750. float endGain) throw()
  21751. {
  21752. if (startGain == endGain)
  21753. {
  21754. applyGain (channel, startSample, numSamples, startGain);
  21755. }
  21756. else
  21757. {
  21758. jassert (isPositiveAndBelow (channel, numChannels));
  21759. jassert (startSample >= 0 && startSample + numSamples <= size);
  21760. const float increment = (endGain - startGain) / numSamples;
  21761. float* d = channels [channel] + startSample;
  21762. while (--numSamples >= 0)
  21763. {
  21764. *d++ *= startGain;
  21765. startGain += increment;
  21766. }
  21767. }
  21768. }
  21769. void AudioSampleBuffer::applyGain (const int startSample,
  21770. const int numSamples,
  21771. const float gain) throw()
  21772. {
  21773. for (int i = 0; i < numChannels; ++i)
  21774. applyGain (i, startSample, numSamples, gain);
  21775. }
  21776. void AudioSampleBuffer::addFrom (const int destChannel,
  21777. const int destStartSample,
  21778. const AudioSampleBuffer& source,
  21779. const int sourceChannel,
  21780. const int sourceStartSample,
  21781. int numSamples,
  21782. const float gain) throw()
  21783. {
  21784. jassert (&source != this || sourceChannel != destChannel);
  21785. jassert (isPositiveAndBelow (destChannel, numChannels));
  21786. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21787. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21788. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21789. if (gain != 0.0f && numSamples > 0)
  21790. {
  21791. float* d = channels [destChannel] + destStartSample;
  21792. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21793. if (gain != 1.0f)
  21794. {
  21795. while (--numSamples >= 0)
  21796. *d++ += gain * *s++;
  21797. }
  21798. else
  21799. {
  21800. while (--numSamples >= 0)
  21801. *d++ += *s++;
  21802. }
  21803. }
  21804. }
  21805. void AudioSampleBuffer::addFrom (const int destChannel,
  21806. const int destStartSample,
  21807. const float* source,
  21808. int numSamples,
  21809. const float gain) throw()
  21810. {
  21811. jassert (isPositiveAndBelow (destChannel, numChannels));
  21812. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21813. jassert (source != 0);
  21814. if (gain != 0.0f && numSamples > 0)
  21815. {
  21816. float* d = channels [destChannel] + destStartSample;
  21817. if (gain != 1.0f)
  21818. {
  21819. while (--numSamples >= 0)
  21820. *d++ += gain * *source++;
  21821. }
  21822. else
  21823. {
  21824. while (--numSamples >= 0)
  21825. *d++ += *source++;
  21826. }
  21827. }
  21828. }
  21829. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21830. const int destStartSample,
  21831. const float* source,
  21832. int numSamples,
  21833. float startGain,
  21834. const float endGain) throw()
  21835. {
  21836. jassert (isPositiveAndBelow (destChannel, numChannels));
  21837. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21838. jassert (source != 0);
  21839. if (startGain == endGain)
  21840. {
  21841. addFrom (destChannel,
  21842. destStartSample,
  21843. source,
  21844. numSamples,
  21845. startGain);
  21846. }
  21847. else
  21848. {
  21849. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21850. {
  21851. const float increment = (endGain - startGain) / numSamples;
  21852. float* d = channels [destChannel] + destStartSample;
  21853. while (--numSamples >= 0)
  21854. {
  21855. *d++ += startGain * *source++;
  21856. startGain += increment;
  21857. }
  21858. }
  21859. }
  21860. }
  21861. void AudioSampleBuffer::copyFrom (const int destChannel,
  21862. const int destStartSample,
  21863. const AudioSampleBuffer& source,
  21864. const int sourceChannel,
  21865. const int sourceStartSample,
  21866. int numSamples) throw()
  21867. {
  21868. jassert (&source != this || sourceChannel != destChannel);
  21869. jassert (isPositiveAndBelow (destChannel, numChannels));
  21870. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21871. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21872. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21873. if (numSamples > 0)
  21874. {
  21875. memcpy (channels [destChannel] + destStartSample,
  21876. source.channels [sourceChannel] + sourceStartSample,
  21877. sizeof (float) * numSamples);
  21878. }
  21879. }
  21880. void AudioSampleBuffer::copyFrom (const int destChannel,
  21881. const int destStartSample,
  21882. const float* source,
  21883. int numSamples) throw()
  21884. {
  21885. jassert (isPositiveAndBelow (destChannel, numChannels));
  21886. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21887. jassert (source != 0);
  21888. if (numSamples > 0)
  21889. {
  21890. memcpy (channels [destChannel] + destStartSample,
  21891. source,
  21892. sizeof (float) * numSamples);
  21893. }
  21894. }
  21895. void AudioSampleBuffer::copyFrom (const int destChannel,
  21896. const int destStartSample,
  21897. const float* source,
  21898. int numSamples,
  21899. const float gain) throw()
  21900. {
  21901. jassert (isPositiveAndBelow (destChannel, numChannels));
  21902. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21903. jassert (source != 0);
  21904. if (numSamples > 0)
  21905. {
  21906. float* d = channels [destChannel] + destStartSample;
  21907. if (gain != 1.0f)
  21908. {
  21909. if (gain == 0)
  21910. {
  21911. zeromem (d, sizeof (float) * numSamples);
  21912. }
  21913. else
  21914. {
  21915. while (--numSamples >= 0)
  21916. *d++ = gain * *source++;
  21917. }
  21918. }
  21919. else
  21920. {
  21921. memcpy (d, source, sizeof (float) * numSamples);
  21922. }
  21923. }
  21924. }
  21925. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21926. const int destStartSample,
  21927. const float* source,
  21928. int numSamples,
  21929. float startGain,
  21930. float endGain) throw()
  21931. {
  21932. jassert (isPositiveAndBelow (destChannel, numChannels));
  21933. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21934. jassert (source != 0);
  21935. if (startGain == endGain)
  21936. {
  21937. copyFrom (destChannel,
  21938. destStartSample,
  21939. source,
  21940. numSamples,
  21941. startGain);
  21942. }
  21943. else
  21944. {
  21945. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21946. {
  21947. const float increment = (endGain - startGain) / numSamples;
  21948. float* d = channels [destChannel] + destStartSample;
  21949. while (--numSamples >= 0)
  21950. {
  21951. *d++ = startGain * *source++;
  21952. startGain += increment;
  21953. }
  21954. }
  21955. }
  21956. }
  21957. void AudioSampleBuffer::findMinMax (const int channel,
  21958. const int startSample,
  21959. int numSamples,
  21960. float& minVal,
  21961. float& maxVal) const throw()
  21962. {
  21963. jassert (isPositiveAndBelow (channel, numChannels));
  21964. jassert (startSample >= 0 && startSample + numSamples <= size);
  21965. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  21966. }
  21967. float AudioSampleBuffer::getMagnitude (const int channel,
  21968. const int startSample,
  21969. const int numSamples) const throw()
  21970. {
  21971. jassert (isPositiveAndBelow (channel, numChannels));
  21972. jassert (startSample >= 0 && startSample + numSamples <= size);
  21973. float mn, mx;
  21974. findMinMax (channel, startSample, numSamples, mn, mx);
  21975. return jmax (mn, -mn, mx, -mx);
  21976. }
  21977. float AudioSampleBuffer::getMagnitude (const int startSample,
  21978. const int numSamples) const throw()
  21979. {
  21980. float mag = 0.0f;
  21981. for (int i = 0; i < numChannels; ++i)
  21982. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21983. return mag;
  21984. }
  21985. float AudioSampleBuffer::getRMSLevel (const int channel,
  21986. const int startSample,
  21987. const int numSamples) const throw()
  21988. {
  21989. jassert (isPositiveAndBelow (channel, numChannels));
  21990. jassert (startSample >= 0 && startSample + numSamples <= size);
  21991. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21992. return 0.0f;
  21993. const float* const data = channels [channel] + startSample;
  21994. double sum = 0.0;
  21995. for (int i = 0; i < numSamples; ++i)
  21996. {
  21997. const float sample = data [i];
  21998. sum += sample * sample;
  21999. }
  22000. return (float) std::sqrt (sum / numSamples);
  22001. }
  22002. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22003. const int startSample,
  22004. const int numSamples,
  22005. const int readerStartSample,
  22006. const bool useLeftChan,
  22007. const bool useRightChan)
  22008. {
  22009. jassert (reader != 0);
  22010. jassert (startSample >= 0 && startSample + numSamples <= size);
  22011. if (numSamples > 0)
  22012. {
  22013. int* chans[3];
  22014. if (useLeftChan == useRightChan)
  22015. {
  22016. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22017. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22018. }
  22019. else if (useLeftChan || (reader->numChannels == 1))
  22020. {
  22021. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22022. chans[1] = 0;
  22023. }
  22024. else if (useRightChan)
  22025. {
  22026. chans[0] = 0;
  22027. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22028. }
  22029. chans[2] = 0;
  22030. reader->read (chans, 2, readerStartSample, numSamples, true);
  22031. if (! reader->usesFloatingPointData)
  22032. {
  22033. for (int j = 0; j < 2; ++j)
  22034. {
  22035. float* const d = reinterpret_cast <float*> (chans[j]);
  22036. if (d != 0)
  22037. {
  22038. const float multiplier = 1.0f / 0x7fffffff;
  22039. for (int i = 0; i < numSamples; ++i)
  22040. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22041. }
  22042. }
  22043. }
  22044. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22045. {
  22046. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22047. memcpy (getSampleData (1, startSample),
  22048. getSampleData (0, startSample),
  22049. sizeof (float) * numSamples);
  22050. }
  22051. }
  22052. }
  22053. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22054. const int startSample,
  22055. const int numSamples) const
  22056. {
  22057. jassert (writer != 0);
  22058. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22059. }
  22060. END_JUCE_NAMESPACE
  22061. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22062. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22063. BEGIN_JUCE_NAMESPACE
  22064. IIRFilter::IIRFilter()
  22065. : active (false)
  22066. {
  22067. reset();
  22068. }
  22069. IIRFilter::IIRFilter (const IIRFilter& other)
  22070. : active (other.active)
  22071. {
  22072. const ScopedLock sl (other.processLock);
  22073. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22074. reset();
  22075. }
  22076. IIRFilter::~IIRFilter()
  22077. {
  22078. }
  22079. void IIRFilter::reset() throw()
  22080. {
  22081. const ScopedLock sl (processLock);
  22082. x1 = 0;
  22083. x2 = 0;
  22084. y1 = 0;
  22085. y2 = 0;
  22086. }
  22087. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22088. {
  22089. float out = coefficients[0] * in
  22090. + coefficients[1] * x1
  22091. + coefficients[2] * x2
  22092. - coefficients[4] * y1
  22093. - coefficients[5] * y2;
  22094. #if JUCE_INTEL
  22095. if (! (out < -1.0e-8 || out > 1.0e-8))
  22096. out = 0;
  22097. #endif
  22098. x2 = x1;
  22099. x1 = in;
  22100. y2 = y1;
  22101. y1 = out;
  22102. return out;
  22103. }
  22104. void IIRFilter::processSamples (float* const samples,
  22105. const int numSamples) throw()
  22106. {
  22107. const ScopedLock sl (processLock);
  22108. if (active)
  22109. {
  22110. for (int i = 0; i < numSamples; ++i)
  22111. {
  22112. const float in = samples[i];
  22113. float out = coefficients[0] * in
  22114. + coefficients[1] * x1
  22115. + coefficients[2] * x2
  22116. - coefficients[4] * y1
  22117. - coefficients[5] * y2;
  22118. #if JUCE_INTEL
  22119. if (! (out < -1.0e-8 || out > 1.0e-8))
  22120. out = 0;
  22121. #endif
  22122. x2 = x1;
  22123. x1 = in;
  22124. y2 = y1;
  22125. y1 = out;
  22126. samples[i] = out;
  22127. }
  22128. }
  22129. }
  22130. void IIRFilter::makeLowPass (const double sampleRate,
  22131. const double frequency) throw()
  22132. {
  22133. jassert (sampleRate > 0);
  22134. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22135. const double nSquared = n * n;
  22136. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22137. setCoefficients (c1,
  22138. c1 * 2.0f,
  22139. c1,
  22140. 1.0,
  22141. c1 * 2.0 * (1.0 - nSquared),
  22142. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22143. }
  22144. void IIRFilter::makeHighPass (const double sampleRate,
  22145. const double frequency) throw()
  22146. {
  22147. const double n = tan (double_Pi * frequency / sampleRate);
  22148. const double nSquared = n * n;
  22149. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22150. setCoefficients (c1,
  22151. c1 * -2.0f,
  22152. c1,
  22153. 1.0,
  22154. c1 * 2.0 * (nSquared - 1.0),
  22155. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22156. }
  22157. void IIRFilter::makeLowShelf (const double sampleRate,
  22158. const double cutOffFrequency,
  22159. const double Q,
  22160. const float gainFactor) throw()
  22161. {
  22162. jassert (sampleRate > 0);
  22163. jassert (Q > 0);
  22164. const double A = jmax (0.0f, gainFactor);
  22165. const double aminus1 = A - 1.0;
  22166. const double aplus1 = A + 1.0;
  22167. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22168. const double coso = std::cos (omega);
  22169. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22170. const double aminus1TimesCoso = aminus1 * coso;
  22171. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22172. A * 2.0 * (aminus1 - aplus1 * coso),
  22173. A * (aplus1 - aminus1TimesCoso - beta),
  22174. aplus1 + aminus1TimesCoso + beta,
  22175. -2.0 * (aminus1 + aplus1 * coso),
  22176. aplus1 + aminus1TimesCoso - beta);
  22177. }
  22178. void IIRFilter::makeHighShelf (const double sampleRate,
  22179. const double cutOffFrequency,
  22180. const double Q,
  22181. const float gainFactor) throw()
  22182. {
  22183. jassert (sampleRate > 0);
  22184. jassert (Q > 0);
  22185. const double A = jmax (0.0f, gainFactor);
  22186. const double aminus1 = A - 1.0;
  22187. const double aplus1 = A + 1.0;
  22188. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22189. const double coso = std::cos (omega);
  22190. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22191. const double aminus1TimesCoso = aminus1 * coso;
  22192. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22193. A * -2.0 * (aminus1 + aplus1 * coso),
  22194. A * (aplus1 + aminus1TimesCoso - beta),
  22195. aplus1 - aminus1TimesCoso + beta,
  22196. 2.0 * (aminus1 - aplus1 * coso),
  22197. aplus1 - aminus1TimesCoso - beta);
  22198. }
  22199. void IIRFilter::makeBandPass (const double sampleRate,
  22200. const double centreFrequency,
  22201. const double Q,
  22202. const float gainFactor) throw()
  22203. {
  22204. jassert (sampleRate > 0);
  22205. jassert (Q > 0);
  22206. const double A = jmax (0.0f, gainFactor);
  22207. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22208. const double alpha = 0.5 * std::sin (omega) / Q;
  22209. const double c2 = -2.0 * std::cos (omega);
  22210. const double alphaTimesA = alpha * A;
  22211. const double alphaOverA = alpha / A;
  22212. setCoefficients (1.0 + alphaTimesA,
  22213. c2,
  22214. 1.0 - alphaTimesA,
  22215. 1.0 + alphaOverA,
  22216. c2,
  22217. 1.0 - alphaOverA);
  22218. }
  22219. void IIRFilter::makeInactive() throw()
  22220. {
  22221. const ScopedLock sl (processLock);
  22222. active = false;
  22223. }
  22224. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22225. {
  22226. const ScopedLock sl (processLock);
  22227. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22228. active = other.active;
  22229. }
  22230. void IIRFilter::setCoefficients (double c1,
  22231. double c2,
  22232. double c3,
  22233. double c4,
  22234. double c5,
  22235. double c6) throw()
  22236. {
  22237. const double a = 1.0 / c4;
  22238. c1 *= a;
  22239. c2 *= a;
  22240. c3 *= a;
  22241. c5 *= a;
  22242. c6 *= a;
  22243. const ScopedLock sl (processLock);
  22244. coefficients[0] = (float) c1;
  22245. coefficients[1] = (float) c2;
  22246. coefficients[2] = (float) c3;
  22247. coefficients[3] = (float) c4;
  22248. coefficients[4] = (float) c5;
  22249. coefficients[5] = (float) c6;
  22250. active = true;
  22251. }
  22252. END_JUCE_NAMESPACE
  22253. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22254. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22255. BEGIN_JUCE_NAMESPACE
  22256. MidiBuffer::MidiBuffer() throw()
  22257. : bytesUsed (0)
  22258. {
  22259. }
  22260. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22261. : bytesUsed (0)
  22262. {
  22263. addEvent (message, 0);
  22264. }
  22265. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22266. : data (other.data),
  22267. bytesUsed (other.bytesUsed)
  22268. {
  22269. }
  22270. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22271. {
  22272. bytesUsed = other.bytesUsed;
  22273. data = other.data;
  22274. return *this;
  22275. }
  22276. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22277. {
  22278. data.swapWith (other.data);
  22279. swapVariables <int> (bytesUsed, other.bytesUsed);
  22280. }
  22281. MidiBuffer::~MidiBuffer()
  22282. {
  22283. }
  22284. inline uint8* MidiBuffer::getData() const throw()
  22285. {
  22286. return static_cast <uint8*> (data.getData());
  22287. }
  22288. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22289. {
  22290. return *static_cast <const int*> (d);
  22291. }
  22292. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22293. {
  22294. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22295. }
  22296. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22297. {
  22298. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22299. }
  22300. void MidiBuffer::clear() throw()
  22301. {
  22302. bytesUsed = 0;
  22303. }
  22304. void MidiBuffer::clear (const int startSample, const int numSamples)
  22305. {
  22306. uint8* const start = findEventAfter (getData(), startSample - 1);
  22307. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22308. if (end > start)
  22309. {
  22310. const int bytesToMove = bytesUsed - (int) (end - getData());
  22311. if (bytesToMove > 0)
  22312. memmove (start, end, bytesToMove);
  22313. bytesUsed -= (int) (end - start);
  22314. }
  22315. }
  22316. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22317. {
  22318. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22319. }
  22320. namespace MidiBufferHelpers
  22321. {
  22322. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22323. {
  22324. unsigned int byte = (unsigned int) *data;
  22325. int size = 0;
  22326. if (byte == 0xf0 || byte == 0xf7)
  22327. {
  22328. const uint8* d = data + 1;
  22329. while (d < data + maxBytes)
  22330. if (*d++ == 0xf7)
  22331. break;
  22332. size = (int) (d - data);
  22333. }
  22334. else if (byte == 0xff)
  22335. {
  22336. int n;
  22337. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22338. size = jmin (maxBytes, n + 2 + bytesLeft);
  22339. }
  22340. else if (byte >= 0x80)
  22341. {
  22342. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22343. }
  22344. return size;
  22345. }
  22346. }
  22347. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22348. {
  22349. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22350. if (numBytes > 0)
  22351. {
  22352. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22353. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22354. uint8* d = findEventAfter (getData(), sampleNumber);
  22355. const int bytesToMove = bytesUsed - (int) (d - getData());
  22356. if (bytesToMove > 0)
  22357. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22358. *reinterpret_cast <int*> (d) = sampleNumber;
  22359. d += sizeof (int);
  22360. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22361. d += sizeof (uint16);
  22362. memcpy (d, newData, numBytes);
  22363. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22364. }
  22365. }
  22366. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22367. const int startSample,
  22368. const int numSamples,
  22369. const int sampleDeltaToAdd)
  22370. {
  22371. Iterator i (otherBuffer);
  22372. i.setNextSamplePosition (startSample);
  22373. const uint8* eventData;
  22374. int eventSize, position;
  22375. while (i.getNextEvent (eventData, eventSize, position)
  22376. && (position < startSample + numSamples || numSamples < 0))
  22377. {
  22378. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22379. }
  22380. }
  22381. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22382. {
  22383. data.ensureSize (minimumNumBytes);
  22384. }
  22385. bool MidiBuffer::isEmpty() const throw()
  22386. {
  22387. return bytesUsed == 0;
  22388. }
  22389. int MidiBuffer::getNumEvents() const throw()
  22390. {
  22391. int n = 0;
  22392. const uint8* d = getData();
  22393. const uint8* const end = d + bytesUsed;
  22394. while (d < end)
  22395. {
  22396. d += getEventTotalSize (d);
  22397. ++n;
  22398. }
  22399. return n;
  22400. }
  22401. int MidiBuffer::getFirstEventTime() const throw()
  22402. {
  22403. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22404. }
  22405. int MidiBuffer::getLastEventTime() const throw()
  22406. {
  22407. if (bytesUsed == 0)
  22408. return 0;
  22409. const uint8* d = getData();
  22410. const uint8* const endData = d + bytesUsed;
  22411. for (;;)
  22412. {
  22413. const uint8* const nextOne = d + getEventTotalSize (d);
  22414. if (nextOne >= endData)
  22415. return getEventTime (d);
  22416. d = nextOne;
  22417. }
  22418. }
  22419. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22420. {
  22421. const uint8* const endData = getData() + bytesUsed;
  22422. while (d < endData && getEventTime (d) <= samplePosition)
  22423. d += getEventTotalSize (d);
  22424. return d;
  22425. }
  22426. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22427. : buffer (buffer_),
  22428. data (buffer_.getData())
  22429. {
  22430. }
  22431. MidiBuffer::Iterator::~Iterator() throw()
  22432. {
  22433. }
  22434. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22435. {
  22436. data = buffer.getData();
  22437. const uint8* dataEnd = data + buffer.bytesUsed;
  22438. while (data < dataEnd && getEventTime (data) < samplePosition)
  22439. data += getEventTotalSize (data);
  22440. }
  22441. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22442. {
  22443. if (data >= buffer.getData() + buffer.bytesUsed)
  22444. return false;
  22445. samplePosition = getEventTime (data);
  22446. numBytes = getEventDataSize (data);
  22447. data += sizeof (int) + sizeof (uint16);
  22448. midiData = data;
  22449. data += numBytes;
  22450. return true;
  22451. }
  22452. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22453. {
  22454. if (data >= buffer.getData() + buffer.bytesUsed)
  22455. return false;
  22456. samplePosition = getEventTime (data);
  22457. const int numBytes = getEventDataSize (data);
  22458. data += sizeof (int) + sizeof (uint16);
  22459. result = MidiMessage (data, numBytes, samplePosition);
  22460. data += numBytes;
  22461. return true;
  22462. }
  22463. END_JUCE_NAMESPACE
  22464. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22465. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22466. BEGIN_JUCE_NAMESPACE
  22467. namespace MidiFileHelpers
  22468. {
  22469. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22470. {
  22471. unsigned int buffer = v & 0x7F;
  22472. while ((v >>= 7) != 0)
  22473. {
  22474. buffer <<= 8;
  22475. buffer |= ((v & 0x7F) | 0x80);
  22476. }
  22477. for (;;)
  22478. {
  22479. out.writeByte ((char) buffer);
  22480. if (buffer & 0x80)
  22481. buffer >>= 8;
  22482. else
  22483. break;
  22484. }
  22485. }
  22486. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22487. {
  22488. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22489. data += 4;
  22490. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22491. {
  22492. bool ok = false;
  22493. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22494. {
  22495. for (int i = 0; i < 8; ++i)
  22496. {
  22497. ch = ByteOrder::bigEndianInt (data);
  22498. data += 4;
  22499. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22500. {
  22501. ok = true;
  22502. break;
  22503. }
  22504. }
  22505. }
  22506. if (! ok)
  22507. return false;
  22508. }
  22509. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22510. data += 4;
  22511. fileType = (short) ByteOrder::bigEndianShort (data);
  22512. data += 2;
  22513. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22514. data += 2;
  22515. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22516. data += 2;
  22517. bytesRemaining -= 6;
  22518. data += bytesRemaining;
  22519. return true;
  22520. }
  22521. double convertTicksToSeconds (const double time,
  22522. const MidiMessageSequence& tempoEvents,
  22523. const int timeFormat)
  22524. {
  22525. if (timeFormat > 0)
  22526. {
  22527. int numer = 4, denom = 4;
  22528. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22529. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22530. double secsPerTick = 0.5 * tickLen;
  22531. const int numEvents = tempoEvents.getNumEvents();
  22532. for (int i = 0; i < numEvents; ++i)
  22533. {
  22534. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22535. if (time <= m.getTimeStamp())
  22536. break;
  22537. if (timeFormat > 0)
  22538. {
  22539. correctedTempoTime = correctedTempoTime
  22540. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22541. }
  22542. else
  22543. {
  22544. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22545. }
  22546. tempoTime = m.getTimeStamp();
  22547. if (m.isTempoMetaEvent())
  22548. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22549. else if (m.isTimeSignatureMetaEvent())
  22550. m.getTimeSignatureInfo (numer, denom);
  22551. while (i + 1 < numEvents)
  22552. {
  22553. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22554. if (m2.getTimeStamp() == tempoTime)
  22555. {
  22556. ++i;
  22557. if (m2.isTempoMetaEvent())
  22558. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22559. else if (m2.isTimeSignatureMetaEvent())
  22560. m2.getTimeSignatureInfo (numer, denom);
  22561. }
  22562. else
  22563. {
  22564. break;
  22565. }
  22566. }
  22567. }
  22568. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22569. }
  22570. else
  22571. {
  22572. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22573. }
  22574. }
  22575. // a comparator that puts all the note-offs before note-ons that have the same time
  22576. struct Sorter
  22577. {
  22578. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22579. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22580. {
  22581. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22582. if (diff == 0)
  22583. {
  22584. if (first->message.isNoteOff() && second->message.isNoteOn())
  22585. return -1;
  22586. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22587. return 1;
  22588. else
  22589. return 0;
  22590. }
  22591. else
  22592. {
  22593. return (diff > 0) ? 1 : -1;
  22594. }
  22595. }
  22596. };
  22597. }
  22598. MidiFile::MidiFile()
  22599. : timeFormat ((short) (unsigned short) 0xe728)
  22600. {
  22601. }
  22602. MidiFile::~MidiFile()
  22603. {
  22604. clear();
  22605. }
  22606. void MidiFile::clear()
  22607. {
  22608. tracks.clear();
  22609. }
  22610. int MidiFile::getNumTracks() const throw()
  22611. {
  22612. return tracks.size();
  22613. }
  22614. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22615. {
  22616. return tracks [index];
  22617. }
  22618. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22619. {
  22620. tracks.add (new MidiMessageSequence (trackSequence));
  22621. }
  22622. short MidiFile::getTimeFormat() const throw()
  22623. {
  22624. return timeFormat;
  22625. }
  22626. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22627. {
  22628. timeFormat = (short) ticks;
  22629. }
  22630. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22631. const int subframeResolution) throw()
  22632. {
  22633. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22634. }
  22635. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22636. {
  22637. for (int i = tracks.size(); --i >= 0;)
  22638. {
  22639. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22640. for (int j = 0; j < numEvents; ++j)
  22641. {
  22642. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22643. if (m.isTempoMetaEvent())
  22644. tempoChangeEvents.addEvent (m);
  22645. }
  22646. }
  22647. }
  22648. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22649. {
  22650. for (int i = tracks.size(); --i >= 0;)
  22651. {
  22652. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22653. for (int j = 0; j < numEvents; ++j)
  22654. {
  22655. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22656. if (m.isTimeSignatureMetaEvent())
  22657. timeSigEvents.addEvent (m);
  22658. }
  22659. }
  22660. }
  22661. double MidiFile::getLastTimestamp() const
  22662. {
  22663. double t = 0.0;
  22664. for (int i = tracks.size(); --i >= 0;)
  22665. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22666. return t;
  22667. }
  22668. bool MidiFile::readFrom (InputStream& sourceStream)
  22669. {
  22670. clear();
  22671. MemoryBlock data;
  22672. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22673. // (put a sanity-check on the file size, as midi files are generally small)
  22674. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22675. {
  22676. size_t size = data.getSize();
  22677. const uint8* d = static_cast <const uint8*> (data.getData());
  22678. short fileType, expectedTracks;
  22679. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22680. {
  22681. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22682. int track = 0;
  22683. while (size > 0 && track < expectedTracks)
  22684. {
  22685. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22686. d += 4;
  22687. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22688. d += 4;
  22689. if (chunkSize <= 0)
  22690. break;
  22691. if (size < 0)
  22692. return false;
  22693. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22694. {
  22695. readNextTrack (d, chunkSize);
  22696. }
  22697. size -= chunkSize + 8;
  22698. d += chunkSize;
  22699. ++track;
  22700. }
  22701. return true;
  22702. }
  22703. }
  22704. return false;
  22705. }
  22706. void MidiFile::readNextTrack (const uint8* data, int size)
  22707. {
  22708. double time = 0;
  22709. char lastStatusByte = 0;
  22710. MidiMessageSequence result;
  22711. while (size > 0)
  22712. {
  22713. int bytesUsed;
  22714. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22715. data += bytesUsed;
  22716. size -= bytesUsed;
  22717. time += delay;
  22718. int messSize = 0;
  22719. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22720. if (messSize <= 0)
  22721. break;
  22722. size -= messSize;
  22723. data += messSize;
  22724. result.addEvent (mm);
  22725. const char firstByte = *(mm.getRawData());
  22726. if ((firstByte & 0xf0) != 0xf0)
  22727. lastStatusByte = firstByte;
  22728. }
  22729. // use a sort that puts all the note-offs before note-ons that have the same time
  22730. MidiFileHelpers::Sorter sorter;
  22731. result.list.sort (sorter, true);
  22732. result.updateMatchedPairs();
  22733. addTrack (result);
  22734. }
  22735. void MidiFile::convertTimestampTicksToSeconds()
  22736. {
  22737. MidiMessageSequence tempoEvents;
  22738. findAllTempoEvents (tempoEvents);
  22739. findAllTimeSigEvents (tempoEvents);
  22740. for (int i = 0; i < tracks.size(); ++i)
  22741. {
  22742. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22743. for (int j = ms.getNumEvents(); --j >= 0;)
  22744. {
  22745. MidiMessage& m = ms.getEventPointer(j)->message;
  22746. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22747. tempoEvents,
  22748. timeFormat));
  22749. }
  22750. }
  22751. }
  22752. bool MidiFile::writeTo (OutputStream& out)
  22753. {
  22754. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22755. out.writeIntBigEndian (6);
  22756. out.writeShortBigEndian (1); // type
  22757. out.writeShortBigEndian ((short) tracks.size());
  22758. out.writeShortBigEndian (timeFormat);
  22759. for (int i = 0; i < tracks.size(); ++i)
  22760. writeTrack (out, i);
  22761. out.flush();
  22762. return true;
  22763. }
  22764. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22765. {
  22766. MemoryOutputStream out;
  22767. const MidiMessageSequence& ms = *tracks[trackNum];
  22768. int lastTick = 0;
  22769. char lastStatusByte = 0;
  22770. for (int i = 0; i < ms.getNumEvents(); ++i)
  22771. {
  22772. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22773. const int tick = roundToInt (mm.getTimeStamp());
  22774. const int delta = jmax (0, tick - lastTick);
  22775. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22776. lastTick = tick;
  22777. const char statusByte = *(mm.getRawData());
  22778. if ((statusByte == lastStatusByte)
  22779. && ((statusByte & 0xf0) != 0xf0)
  22780. && i > 0
  22781. && mm.getRawDataSize() > 1)
  22782. {
  22783. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22784. }
  22785. else
  22786. {
  22787. out.write (mm.getRawData(), mm.getRawDataSize());
  22788. }
  22789. lastStatusByte = statusByte;
  22790. }
  22791. out.writeByte (0);
  22792. const MidiMessage m (MidiMessage::endOfTrack());
  22793. out.write (m.getRawData(),
  22794. m.getRawDataSize());
  22795. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22796. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22797. mainOut.write (out.getData(), (int) out.getDataSize());
  22798. }
  22799. END_JUCE_NAMESPACE
  22800. /*** End of inlined file: juce_MidiFile.cpp ***/
  22801. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22802. BEGIN_JUCE_NAMESPACE
  22803. MidiKeyboardState::MidiKeyboardState()
  22804. {
  22805. zerostruct (noteStates);
  22806. }
  22807. MidiKeyboardState::~MidiKeyboardState()
  22808. {
  22809. }
  22810. void MidiKeyboardState::reset()
  22811. {
  22812. const ScopedLock sl (lock);
  22813. zerostruct (noteStates);
  22814. eventsToAdd.clear();
  22815. }
  22816. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22817. {
  22818. jassert (midiChannel >= 0 && midiChannel <= 16);
  22819. return isPositiveAndBelow (n, (int) 128)
  22820. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22821. }
  22822. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22823. {
  22824. return isPositiveAndBelow (n, (int) 128)
  22825. && (noteStates[n] & midiChannelMask) != 0;
  22826. }
  22827. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22828. {
  22829. jassert (midiChannel >= 0 && midiChannel <= 16);
  22830. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  22831. const ScopedLock sl (lock);
  22832. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22833. {
  22834. const int timeNow = (int) Time::getMillisecondCounter();
  22835. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22836. eventsToAdd.clear (0, timeNow - 500);
  22837. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22838. }
  22839. }
  22840. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22841. {
  22842. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22843. {
  22844. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22845. for (int i = listeners.size(); --i >= 0;)
  22846. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22847. }
  22848. }
  22849. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22850. {
  22851. const ScopedLock sl (lock);
  22852. if (isNoteOn (midiChannel, midiNoteNumber))
  22853. {
  22854. const int timeNow = (int) Time::getMillisecondCounter();
  22855. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22856. eventsToAdd.clear (0, timeNow - 500);
  22857. noteOffInternal (midiChannel, midiNoteNumber);
  22858. }
  22859. }
  22860. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22861. {
  22862. if (isNoteOn (midiChannel, midiNoteNumber))
  22863. {
  22864. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22865. for (int i = listeners.size(); --i >= 0;)
  22866. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22867. }
  22868. }
  22869. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22870. {
  22871. const ScopedLock sl (lock);
  22872. if (midiChannel <= 0)
  22873. {
  22874. for (int i = 1; i <= 16; ++i)
  22875. allNotesOff (i);
  22876. }
  22877. else
  22878. {
  22879. for (int i = 0; i < 128; ++i)
  22880. noteOff (midiChannel, i);
  22881. }
  22882. }
  22883. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22884. {
  22885. if (message.isNoteOn())
  22886. {
  22887. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22888. }
  22889. else if (message.isNoteOff())
  22890. {
  22891. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22892. }
  22893. else if (message.isAllNotesOff())
  22894. {
  22895. for (int i = 0; i < 128; ++i)
  22896. noteOffInternal (message.getChannel(), i);
  22897. }
  22898. }
  22899. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22900. const int startSample,
  22901. const int numSamples,
  22902. const bool injectIndirectEvents)
  22903. {
  22904. MidiBuffer::Iterator i (buffer);
  22905. MidiMessage message (0xf4, 0.0);
  22906. int time;
  22907. const ScopedLock sl (lock);
  22908. while (i.getNextEvent (message, time))
  22909. processNextMidiEvent (message);
  22910. if (injectIndirectEvents)
  22911. {
  22912. MidiBuffer::Iterator i2 (eventsToAdd);
  22913. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22914. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22915. while (i2.getNextEvent (message, time))
  22916. {
  22917. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22918. buffer.addEvent (message, startSample + pos);
  22919. }
  22920. }
  22921. eventsToAdd.clear();
  22922. }
  22923. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22924. {
  22925. const ScopedLock sl (lock);
  22926. listeners.addIfNotAlreadyThere (listener);
  22927. }
  22928. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22929. {
  22930. const ScopedLock sl (lock);
  22931. listeners.removeValue (listener);
  22932. }
  22933. END_JUCE_NAMESPACE
  22934. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22935. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22936. BEGIN_JUCE_NAMESPACE
  22937. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22938. {
  22939. numBytesUsed = 0;
  22940. int v = 0;
  22941. int i;
  22942. do
  22943. {
  22944. i = (int) *data++;
  22945. if (++numBytesUsed > 6)
  22946. break;
  22947. v = (v << 7) + (i & 0x7f);
  22948. } while (i & 0x80);
  22949. return v;
  22950. }
  22951. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22952. {
  22953. // this method only works for valid starting bytes of a short midi message
  22954. jassert (firstByte >= 0x80 && firstByte != 0xf0 && firstByte != 0xf7);
  22955. static const char messageLengths[] =
  22956. {
  22957. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22958. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22959. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22960. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22961. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22962. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22963. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22964. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22965. };
  22966. return messageLengths [firstByte & 0x7f];
  22967. }
  22968. MidiMessage::MidiMessage() throw()
  22969. : timeStamp (0),
  22970. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22971. size (2)
  22972. {
  22973. data[0] = 0xf0;
  22974. data[1] = 0xf7;
  22975. }
  22976. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22977. : timeStamp (t),
  22978. size (dataSize)
  22979. {
  22980. jassert (dataSize > 0);
  22981. if (dataSize <= 4)
  22982. data = static_cast<uint8*> (preallocatedData.asBytes);
  22983. else
  22984. data = new uint8 [dataSize];
  22985. memcpy (data, d, dataSize);
  22986. // check that the length matches the data..
  22987. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22988. }
  22989. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22990. : timeStamp (t),
  22991. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22992. size (1)
  22993. {
  22994. data[0] = (uint8) byte1;
  22995. // check that the length matches the data..
  22996. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22997. }
  22998. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22999. : timeStamp (t),
  23000. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23001. size (2)
  23002. {
  23003. data[0] = (uint8) byte1;
  23004. data[1] = (uint8) byte2;
  23005. // check that the length matches the data..
  23006. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23007. }
  23008. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23009. : timeStamp (t),
  23010. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23011. size (3)
  23012. {
  23013. data[0] = (uint8) byte1;
  23014. data[1] = (uint8) byte2;
  23015. data[2] = (uint8) byte3;
  23016. // check that the length matches the data..
  23017. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23018. }
  23019. MidiMessage::MidiMessage (const MidiMessage& other)
  23020. : timeStamp (other.timeStamp),
  23021. size (other.size)
  23022. {
  23023. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23024. {
  23025. data = new uint8 [size];
  23026. memcpy (data, other.data, size);
  23027. }
  23028. else
  23029. {
  23030. data = static_cast<uint8*> (preallocatedData.asBytes);
  23031. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23032. }
  23033. }
  23034. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23035. : timeStamp (newTimeStamp),
  23036. size (other.size)
  23037. {
  23038. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23039. {
  23040. data = new uint8 [size];
  23041. memcpy (data, other.data, size);
  23042. }
  23043. else
  23044. {
  23045. data = static_cast<uint8*> (preallocatedData.asBytes);
  23046. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23047. }
  23048. }
  23049. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23050. : timeStamp (t),
  23051. data (static_cast<uint8*> (preallocatedData.asBytes))
  23052. {
  23053. const uint8* src = static_cast <const uint8*> (src_);
  23054. unsigned int byte = (unsigned int) *src;
  23055. if (byte < 0x80)
  23056. {
  23057. byte = (unsigned int) (uint8) lastStatusByte;
  23058. numBytesUsed = -1;
  23059. }
  23060. else
  23061. {
  23062. numBytesUsed = 0;
  23063. --sz;
  23064. ++src;
  23065. }
  23066. if (byte >= 0x80)
  23067. {
  23068. if (byte == 0xf0)
  23069. {
  23070. const uint8* d = src;
  23071. bool haveReadAllLengthBytes = false;
  23072. while (d < src + sz)
  23073. {
  23074. if (*d >= 0x80)
  23075. {
  23076. if (*d == 0xf7)
  23077. {
  23078. ++d; // include the trailing 0xf7 when we hit it
  23079. break;
  23080. }
  23081. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  23082. break; // bytes, assume it's the end of the sysex
  23083. ++d;
  23084. continue;
  23085. }
  23086. haveReadAllLengthBytes = true;
  23087. ++d;
  23088. }
  23089. size = 1 + (int) (d - src);
  23090. data = new uint8 [size];
  23091. *data = (uint8) byte;
  23092. memcpy (data + 1, src, size - 1);
  23093. }
  23094. else if (byte == 0xff)
  23095. {
  23096. int n;
  23097. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23098. size = jmin (sz + 1, n + 2 + bytesLeft);
  23099. data = new uint8 [size];
  23100. *data = (uint8) byte;
  23101. memcpy (data + 1, src, size - 1);
  23102. }
  23103. else
  23104. {
  23105. preallocatedData.asInt32 = 0;
  23106. size = getMessageLengthFromFirstByte ((uint8) byte);
  23107. data[0] = (uint8) byte;
  23108. if (size > 1)
  23109. {
  23110. data[1] = src[0];
  23111. if (size > 2)
  23112. data[2] = src[1];
  23113. }
  23114. }
  23115. numBytesUsed += size;
  23116. }
  23117. else
  23118. {
  23119. preallocatedData.asInt32 = 0;
  23120. size = 0;
  23121. }
  23122. }
  23123. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23124. {
  23125. if (this != &other)
  23126. {
  23127. timeStamp = other.timeStamp;
  23128. size = other.size;
  23129. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23130. delete[] data;
  23131. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23132. {
  23133. data = new uint8 [size];
  23134. memcpy (data, other.data, size);
  23135. }
  23136. else
  23137. {
  23138. data = static_cast<uint8*> (preallocatedData.asBytes);
  23139. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23140. }
  23141. }
  23142. return *this;
  23143. }
  23144. MidiMessage::~MidiMessage()
  23145. {
  23146. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23147. delete[] data;
  23148. }
  23149. int MidiMessage::getChannel() const throw()
  23150. {
  23151. if ((data[0] & 0xf0) != 0xf0)
  23152. return (data[0] & 0xf) + 1;
  23153. else
  23154. return 0;
  23155. }
  23156. bool MidiMessage::isForChannel (const int channel) const throw()
  23157. {
  23158. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23159. return ((data[0] & 0xf) == channel - 1)
  23160. && ((data[0] & 0xf0) != 0xf0);
  23161. }
  23162. void MidiMessage::setChannel (const int channel) throw()
  23163. {
  23164. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23165. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23166. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23167. | (uint8)(channel - 1));
  23168. }
  23169. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23170. {
  23171. return ((data[0] & 0xf0) == 0x90)
  23172. && (returnTrueForVelocity0 || data[2] != 0);
  23173. }
  23174. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23175. {
  23176. return ((data[0] & 0xf0) == 0x80)
  23177. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23178. }
  23179. bool MidiMessage::isNoteOnOrOff() const throw()
  23180. {
  23181. const int d = data[0] & 0xf0;
  23182. return (d == 0x90) || (d == 0x80);
  23183. }
  23184. int MidiMessage::getNoteNumber() const throw()
  23185. {
  23186. return data[1];
  23187. }
  23188. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23189. {
  23190. if (isNoteOnOrOff())
  23191. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23192. }
  23193. uint8 MidiMessage::getVelocity() const throw()
  23194. {
  23195. if (isNoteOnOrOff())
  23196. return data[2];
  23197. else
  23198. return 0;
  23199. }
  23200. float MidiMessage::getFloatVelocity() const throw()
  23201. {
  23202. return getVelocity() * (1.0f / 127.0f);
  23203. }
  23204. void MidiMessage::setVelocity (const float newVelocity) throw()
  23205. {
  23206. if (isNoteOnOrOff())
  23207. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23208. }
  23209. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23210. {
  23211. if (isNoteOnOrOff())
  23212. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23213. }
  23214. bool MidiMessage::isAftertouch() const throw()
  23215. {
  23216. return (data[0] & 0xf0) == 0xa0;
  23217. }
  23218. int MidiMessage::getAfterTouchValue() const throw()
  23219. {
  23220. return data[2];
  23221. }
  23222. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23223. const int noteNum,
  23224. const int aftertouchValue) throw()
  23225. {
  23226. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23227. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23228. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23229. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23230. noteNum & 0x7f,
  23231. aftertouchValue & 0x7f);
  23232. }
  23233. bool MidiMessage::isChannelPressure() const throw()
  23234. {
  23235. return (data[0] & 0xf0) == 0xd0;
  23236. }
  23237. int MidiMessage::getChannelPressureValue() const throw()
  23238. {
  23239. jassert (isChannelPressure());
  23240. return data[1];
  23241. }
  23242. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23243. const int pressure) throw()
  23244. {
  23245. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23246. jassert (isPositiveAndBelow (pressure, (int) 128));
  23247. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23248. pressure & 0x7f);
  23249. }
  23250. bool MidiMessage::isProgramChange() const throw()
  23251. {
  23252. return (data[0] & 0xf0) == 0xc0;
  23253. }
  23254. int MidiMessage::getProgramChangeNumber() const throw()
  23255. {
  23256. return data[1];
  23257. }
  23258. const MidiMessage MidiMessage::programChange (const int channel,
  23259. const int programNumber) throw()
  23260. {
  23261. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23262. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23263. programNumber & 0x7f);
  23264. }
  23265. bool MidiMessage::isPitchWheel() const throw()
  23266. {
  23267. return (data[0] & 0xf0) == 0xe0;
  23268. }
  23269. int MidiMessage::getPitchWheelValue() const throw()
  23270. {
  23271. return data[1] | (data[2] << 7);
  23272. }
  23273. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23274. const int position) throw()
  23275. {
  23276. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23277. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23278. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23279. position & 127,
  23280. (position >> 7) & 127);
  23281. }
  23282. bool MidiMessage::isController() const throw()
  23283. {
  23284. return (data[0] & 0xf0) == 0xb0;
  23285. }
  23286. int MidiMessage::getControllerNumber() const throw()
  23287. {
  23288. jassert (isController());
  23289. return data[1];
  23290. }
  23291. int MidiMessage::getControllerValue() const throw()
  23292. {
  23293. jassert (isController());
  23294. return data[2];
  23295. }
  23296. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23297. const int controllerType,
  23298. const int value) throw()
  23299. {
  23300. // the channel must be between 1 and 16 inclusive
  23301. jassert (channel > 0 && channel <= 16);
  23302. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23303. controllerType & 127,
  23304. value & 127);
  23305. }
  23306. const MidiMessage MidiMessage::noteOn (const int channel,
  23307. const int noteNumber,
  23308. const float velocity) throw()
  23309. {
  23310. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23311. }
  23312. const MidiMessage MidiMessage::noteOn (const int channel,
  23313. const int noteNumber,
  23314. const uint8 velocity) throw()
  23315. {
  23316. jassert (channel > 0 && channel <= 16);
  23317. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23318. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23319. noteNumber & 127,
  23320. jlimit (0, 127, roundToInt (velocity)));
  23321. }
  23322. const MidiMessage MidiMessage::noteOff (const int channel,
  23323. const int noteNumber) throw()
  23324. {
  23325. jassert (channel > 0 && channel <= 16);
  23326. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23327. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23328. }
  23329. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23330. {
  23331. return controllerEvent (channel, 123, 0);
  23332. }
  23333. bool MidiMessage::isAllNotesOff() const throw()
  23334. {
  23335. return (data[0] & 0xf0) == 0xb0 && data[1] == 123;
  23336. }
  23337. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23338. {
  23339. return controllerEvent (channel, 120, 0);
  23340. }
  23341. bool MidiMessage::isAllSoundOff() const throw()
  23342. {
  23343. return (data[0] & 0xf0) == 0xb0 && data[1] == 120;
  23344. }
  23345. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23346. {
  23347. return controllerEvent (channel, 121, 0);
  23348. }
  23349. const MidiMessage MidiMessage::masterVolume (const float volume)
  23350. {
  23351. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23352. uint8 buf[8];
  23353. buf[0] = 0xf0;
  23354. buf[1] = 0x7f;
  23355. buf[2] = 0x7f;
  23356. buf[3] = 0x04;
  23357. buf[4] = 0x01;
  23358. buf[5] = (uint8) (vol & 0x7f);
  23359. buf[6] = (uint8) (vol >> 7);
  23360. buf[7] = 0xf7;
  23361. return MidiMessage (buf, 8);
  23362. }
  23363. bool MidiMessage::isSysEx() const throw()
  23364. {
  23365. return *data == 0xf0;
  23366. }
  23367. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23368. {
  23369. MemoryBlock mm (dataSize + 2);
  23370. uint8* const m = static_cast <uint8*> (mm.getData());
  23371. m[0] = 0xf0;
  23372. memcpy (m + 1, sysexData, dataSize);
  23373. m[dataSize + 1] = 0xf7;
  23374. return MidiMessage (m, dataSize + 2);
  23375. }
  23376. const uint8* MidiMessage::getSysExData() const throw()
  23377. {
  23378. return isSysEx() ? getRawData() + 1 : 0;
  23379. }
  23380. int MidiMessage::getSysExDataSize() const throw()
  23381. {
  23382. return isSysEx() ? size - 2 : 0;
  23383. }
  23384. bool MidiMessage::isMetaEvent() const throw()
  23385. {
  23386. return *data == 0xff;
  23387. }
  23388. bool MidiMessage::isActiveSense() const throw()
  23389. {
  23390. return *data == 0xfe;
  23391. }
  23392. int MidiMessage::getMetaEventType() const throw()
  23393. {
  23394. return *data != 0xff ? -1 : data[1];
  23395. }
  23396. int MidiMessage::getMetaEventLength() const throw()
  23397. {
  23398. if (*data == 0xff)
  23399. {
  23400. int n;
  23401. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23402. }
  23403. return 0;
  23404. }
  23405. const uint8* MidiMessage::getMetaEventData() const throw()
  23406. {
  23407. int n;
  23408. const uint8* d = data + 2;
  23409. readVariableLengthVal (d, n);
  23410. return d + n;
  23411. }
  23412. bool MidiMessage::isTrackMetaEvent() const throw()
  23413. {
  23414. return getMetaEventType() == 0;
  23415. }
  23416. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23417. {
  23418. return getMetaEventType() == 47;
  23419. }
  23420. bool MidiMessage::isTextMetaEvent() const throw()
  23421. {
  23422. const int t = getMetaEventType();
  23423. return t > 0 && t < 16;
  23424. }
  23425. const String MidiMessage::getTextFromTextMetaEvent() const
  23426. {
  23427. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23428. }
  23429. bool MidiMessage::isTrackNameEvent() const throw()
  23430. {
  23431. return (data[1] == 3) && (*data == 0xff);
  23432. }
  23433. bool MidiMessage::isTempoMetaEvent() const throw()
  23434. {
  23435. return (data[1] == 81) && (*data == 0xff);
  23436. }
  23437. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23438. {
  23439. return (data[1] == 0x20) && (*data == 0xff) && (data[2] == 1);
  23440. }
  23441. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23442. {
  23443. return data[3] + 1;
  23444. }
  23445. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23446. {
  23447. if (! isTempoMetaEvent())
  23448. return 0.0;
  23449. const uint8* const d = getMetaEventData();
  23450. return (((unsigned int) d[0] << 16)
  23451. | ((unsigned int) d[1] << 8)
  23452. | d[2])
  23453. / 1000000.0;
  23454. }
  23455. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23456. {
  23457. if (timeFormat > 0)
  23458. {
  23459. if (! isTempoMetaEvent())
  23460. return 0.5 / timeFormat;
  23461. return getTempoSecondsPerQuarterNote() / timeFormat;
  23462. }
  23463. else
  23464. {
  23465. const int frameCode = (-timeFormat) >> 8;
  23466. double framesPerSecond;
  23467. switch (frameCode)
  23468. {
  23469. case 24: framesPerSecond = 24.0; break;
  23470. case 25: framesPerSecond = 25.0; break;
  23471. case 29: framesPerSecond = 29.97; break;
  23472. case 30: framesPerSecond = 30.0; break;
  23473. default: framesPerSecond = 30.0; break;
  23474. }
  23475. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23476. }
  23477. }
  23478. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23479. {
  23480. uint8 d[8];
  23481. d[0] = 0xff;
  23482. d[1] = 81;
  23483. d[2] = 3;
  23484. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23485. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23486. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23487. return MidiMessage (d, 6, 0.0);
  23488. }
  23489. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23490. {
  23491. return (data[1] == 0x58) && (*data == (uint8) 0xff);
  23492. }
  23493. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23494. {
  23495. if (isTimeSignatureMetaEvent())
  23496. {
  23497. const uint8* const d = getMetaEventData();
  23498. numerator = d[0];
  23499. denominator = 1 << d[1];
  23500. }
  23501. else
  23502. {
  23503. numerator = 4;
  23504. denominator = 4;
  23505. }
  23506. }
  23507. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23508. {
  23509. uint8 d[8];
  23510. d[0] = 0xff;
  23511. d[1] = 0x58;
  23512. d[2] = 0x04;
  23513. d[3] = (uint8) numerator;
  23514. int n = 1;
  23515. int powerOfTwo = 0;
  23516. while (n < denominator)
  23517. {
  23518. n <<= 1;
  23519. ++powerOfTwo;
  23520. }
  23521. d[4] = (uint8) powerOfTwo;
  23522. d[5] = 0x01;
  23523. d[6] = 96;
  23524. return MidiMessage (d, 7, 0.0);
  23525. }
  23526. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23527. {
  23528. uint8 d[8];
  23529. d[0] = 0xff;
  23530. d[1] = 0x20;
  23531. d[2] = 0x01;
  23532. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23533. return MidiMessage (d, 4, 0.0);
  23534. }
  23535. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23536. {
  23537. return getMetaEventType() == 89;
  23538. }
  23539. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23540. {
  23541. return (int) *getMetaEventData();
  23542. }
  23543. const MidiMessage MidiMessage::endOfTrack() throw()
  23544. {
  23545. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23546. }
  23547. bool MidiMessage::isSongPositionPointer() const throw()
  23548. {
  23549. return *data == 0xf2;
  23550. }
  23551. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23552. {
  23553. return data[1] | (data[2] << 7);
  23554. }
  23555. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23556. {
  23557. return MidiMessage (0xf2,
  23558. positionInMidiBeats & 127,
  23559. (positionInMidiBeats >> 7) & 127);
  23560. }
  23561. bool MidiMessage::isMidiStart() const throw()
  23562. {
  23563. return *data == 0xfa;
  23564. }
  23565. const MidiMessage MidiMessage::midiStart() throw()
  23566. {
  23567. return MidiMessage (0xfa);
  23568. }
  23569. bool MidiMessage::isMidiContinue() const throw()
  23570. {
  23571. return *data == 0xfb;
  23572. }
  23573. const MidiMessage MidiMessage::midiContinue() throw()
  23574. {
  23575. return MidiMessage (0xfb);
  23576. }
  23577. bool MidiMessage::isMidiStop() const throw()
  23578. {
  23579. return *data == 0xfc;
  23580. }
  23581. const MidiMessage MidiMessage::midiStop() throw()
  23582. {
  23583. return MidiMessage (0xfc);
  23584. }
  23585. bool MidiMessage::isMidiClock() const throw()
  23586. {
  23587. return *data == 0xf8;
  23588. }
  23589. const MidiMessage MidiMessage::midiClock() throw()
  23590. {
  23591. return MidiMessage (0xf8);
  23592. }
  23593. bool MidiMessage::isQuarterFrame() const throw()
  23594. {
  23595. return *data == 0xf1;
  23596. }
  23597. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23598. {
  23599. return ((int) data[1]) >> 4;
  23600. }
  23601. int MidiMessage::getQuarterFrameValue() const throw()
  23602. {
  23603. return ((int) data[1]) & 0x0f;
  23604. }
  23605. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23606. const int value) throw()
  23607. {
  23608. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23609. }
  23610. bool MidiMessage::isFullFrame() const throw()
  23611. {
  23612. return data[0] == 0xf0
  23613. && data[1] == 0x7f
  23614. && size >= 10
  23615. && data[3] == 0x01
  23616. && data[4] == 0x01;
  23617. }
  23618. void MidiMessage::getFullFrameParameters (int& hours,
  23619. int& minutes,
  23620. int& seconds,
  23621. int& frames,
  23622. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23623. {
  23624. jassert (isFullFrame());
  23625. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23626. hours = data[5] & 0x1f;
  23627. minutes = data[6];
  23628. seconds = data[7];
  23629. frames = data[8];
  23630. }
  23631. const MidiMessage MidiMessage::fullFrame (const int hours,
  23632. const int minutes,
  23633. const int seconds,
  23634. const int frames,
  23635. MidiMessage::SmpteTimecodeType timecodeType)
  23636. {
  23637. uint8 d[10];
  23638. d[0] = 0xf0;
  23639. d[1] = 0x7f;
  23640. d[2] = 0x7f;
  23641. d[3] = 0x01;
  23642. d[4] = 0x01;
  23643. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23644. d[6] = (uint8) minutes;
  23645. d[7] = (uint8) seconds;
  23646. d[8] = (uint8) frames;
  23647. d[9] = 0xf7;
  23648. return MidiMessage (d, 10, 0.0);
  23649. }
  23650. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23651. {
  23652. return data[0] == 0xf0
  23653. && data[1] == 0x7f
  23654. && data[3] == 0x06
  23655. && size > 5;
  23656. }
  23657. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23658. {
  23659. jassert (isMidiMachineControlMessage());
  23660. return (MidiMachineControlCommand) data[4];
  23661. }
  23662. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23663. {
  23664. uint8 d[6];
  23665. d[0] = 0xf0;
  23666. d[1] = 0x7f;
  23667. d[2] = 0x00;
  23668. d[3] = 0x06;
  23669. d[4] = (uint8) command;
  23670. d[5] = 0xf7;
  23671. return MidiMessage (d, 6, 0.0);
  23672. }
  23673. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23674. int& minutes,
  23675. int& seconds,
  23676. int& frames) const throw()
  23677. {
  23678. if (size >= 12
  23679. && data[0] == 0xf0
  23680. && data[1] == 0x7f
  23681. && data[3] == 0x06
  23682. && data[4] == 0x44
  23683. && data[5] == 0x06
  23684. && data[6] == 0x01)
  23685. {
  23686. hours = data[7] % 24; // (that some machines send out hours > 24)
  23687. minutes = data[8];
  23688. seconds = data[9];
  23689. frames = data[10];
  23690. return true;
  23691. }
  23692. return false;
  23693. }
  23694. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23695. int minutes,
  23696. int seconds,
  23697. int frames)
  23698. {
  23699. uint8 d[12];
  23700. d[0] = 0xf0;
  23701. d[1] = 0x7f;
  23702. d[2] = 0x00;
  23703. d[3] = 0x06;
  23704. d[4] = 0x44;
  23705. d[5] = 0x06;
  23706. d[6] = 0x01;
  23707. d[7] = (uint8) hours;
  23708. d[8] = (uint8) minutes;
  23709. d[9] = (uint8) seconds;
  23710. d[10] = (uint8) frames;
  23711. d[11] = 0xf7;
  23712. return MidiMessage (d, 12, 0.0);
  23713. }
  23714. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23715. {
  23716. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23717. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23718. if (isPositiveAndBelow (note, (int) 128))
  23719. {
  23720. String s (useSharps ? sharpNoteNames [note % 12]
  23721. : flatNoteNames [note % 12]);
  23722. if (includeOctaveNumber)
  23723. s << (note / 12 + (octaveNumForMiddleC - 5));
  23724. return s;
  23725. }
  23726. return String::empty;
  23727. }
  23728. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23729. {
  23730. noteNumber -= 12 * 6 + 9; // now 0 = A
  23731. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23732. }
  23733. const String MidiMessage::getGMInstrumentName (const int n)
  23734. {
  23735. const char* names[] =
  23736. {
  23737. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23738. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23739. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23740. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23741. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23742. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23743. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23744. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23745. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23746. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23747. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23748. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23749. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23750. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23751. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23752. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23753. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23754. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23755. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23756. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23757. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23758. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23759. "Applause", "Gunshot"
  23760. };
  23761. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23762. }
  23763. const String MidiMessage::getGMInstrumentBankName (const int n)
  23764. {
  23765. const char* names[] =
  23766. {
  23767. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23768. "Bass", "Strings", "Ensemble", "Brass",
  23769. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23770. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23771. };
  23772. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23773. }
  23774. const String MidiMessage::getRhythmInstrumentName (const int n)
  23775. {
  23776. const char* names[] =
  23777. {
  23778. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23779. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23780. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23781. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23782. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23783. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23784. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23785. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23786. "Mute Triangle", "Open Triangle"
  23787. };
  23788. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23789. }
  23790. const String MidiMessage::getControllerName (const int n)
  23791. {
  23792. const char* names[] =
  23793. {
  23794. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23795. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23796. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23797. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23798. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23799. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23800. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23801. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23802. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23803. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23804. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23805. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23806. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23807. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23808. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23809. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23810. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23811. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23812. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23814. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23815. "Poly Operation"
  23816. };
  23817. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23818. }
  23819. END_JUCE_NAMESPACE
  23820. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23821. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23822. BEGIN_JUCE_NAMESPACE
  23823. MidiMessageCollector::MidiMessageCollector()
  23824. : lastCallbackTime (0),
  23825. sampleRate (44100.0001)
  23826. {
  23827. }
  23828. MidiMessageCollector::~MidiMessageCollector()
  23829. {
  23830. }
  23831. void MidiMessageCollector::reset (const double sampleRate_)
  23832. {
  23833. jassert (sampleRate_ > 0);
  23834. const ScopedLock sl (midiCallbackLock);
  23835. sampleRate = sampleRate_;
  23836. incomingMessages.clear();
  23837. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23838. }
  23839. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23840. {
  23841. // you need to call reset() to set the correct sample rate before using this object
  23842. jassert (sampleRate != 44100.0001);
  23843. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23844. // for details of what the number should be.
  23845. jassert (message.getTimeStamp() != 0);
  23846. const ScopedLock sl (midiCallbackLock);
  23847. const int sampleNumber
  23848. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23849. incomingMessages.addEvent (message, sampleNumber);
  23850. // if the messages don't get used for over a second, we'd better
  23851. // get rid of any old ones to avoid the queue getting too big
  23852. if (sampleNumber > sampleRate)
  23853. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23854. }
  23855. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23856. const int numSamples)
  23857. {
  23858. // you need to call reset() to set the correct sample rate before using this object
  23859. jassert (sampleRate != 44100.0001);
  23860. const double timeNow = Time::getMillisecondCounterHiRes();
  23861. const double msElapsed = timeNow - lastCallbackTime;
  23862. const ScopedLock sl (midiCallbackLock);
  23863. lastCallbackTime = timeNow;
  23864. if (! incomingMessages.isEmpty())
  23865. {
  23866. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23867. int startSample = 0;
  23868. int scale = 1 << 16;
  23869. const uint8* midiData;
  23870. int numBytes, samplePosition;
  23871. MidiBuffer::Iterator iter (incomingMessages);
  23872. if (numSourceSamples > numSamples)
  23873. {
  23874. // if our list of events is longer than the buffer we're being
  23875. // asked for, scale them down to squeeze them all in..
  23876. const int maxBlockLengthToUse = numSamples << 5;
  23877. if (numSourceSamples > maxBlockLengthToUse)
  23878. {
  23879. startSample = numSourceSamples - maxBlockLengthToUse;
  23880. numSourceSamples = maxBlockLengthToUse;
  23881. iter.setNextSamplePosition (startSample);
  23882. }
  23883. scale = (numSamples << 10) / numSourceSamples;
  23884. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23885. {
  23886. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23887. destBuffer.addEvent (midiData, numBytes,
  23888. jlimit (0, numSamples - 1, samplePosition));
  23889. }
  23890. }
  23891. else
  23892. {
  23893. // if our event list is shorter than the number we need, put them
  23894. // towards the end of the buffer
  23895. startSample = numSamples - numSourceSamples;
  23896. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23897. {
  23898. destBuffer.addEvent (midiData, numBytes,
  23899. jlimit (0, numSamples - 1, samplePosition + startSample));
  23900. }
  23901. }
  23902. incomingMessages.clear();
  23903. }
  23904. }
  23905. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23906. {
  23907. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23908. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23909. addMessageToQueue (m);
  23910. }
  23911. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23912. {
  23913. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23914. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23915. addMessageToQueue (m);
  23916. }
  23917. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23918. {
  23919. addMessageToQueue (message);
  23920. }
  23921. END_JUCE_NAMESPACE
  23922. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23923. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23924. BEGIN_JUCE_NAMESPACE
  23925. MidiMessageSequence::MidiMessageSequence()
  23926. {
  23927. }
  23928. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23929. {
  23930. list.ensureStorageAllocated (other.list.size());
  23931. for (int i = 0; i < other.list.size(); ++i)
  23932. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23933. }
  23934. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23935. {
  23936. MidiMessageSequence otherCopy (other);
  23937. swapWith (otherCopy);
  23938. return *this;
  23939. }
  23940. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23941. {
  23942. list.swapWithArray (other.list);
  23943. }
  23944. MidiMessageSequence::~MidiMessageSequence()
  23945. {
  23946. }
  23947. void MidiMessageSequence::clear()
  23948. {
  23949. list.clear();
  23950. }
  23951. int MidiMessageSequence::getNumEvents() const
  23952. {
  23953. return list.size();
  23954. }
  23955. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23956. {
  23957. return list [index];
  23958. }
  23959. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23960. {
  23961. const MidiEventHolder* const meh = list [index];
  23962. if (meh != 0 && meh->noteOffObject != 0)
  23963. return meh->noteOffObject->message.getTimeStamp();
  23964. else
  23965. return 0.0;
  23966. }
  23967. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23968. {
  23969. const MidiEventHolder* const meh = list [index];
  23970. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23971. }
  23972. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23973. {
  23974. return list.indexOf (event);
  23975. }
  23976. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23977. {
  23978. const int numEvents = list.size();
  23979. int i;
  23980. for (i = 0; i < numEvents; ++i)
  23981. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23982. break;
  23983. return i;
  23984. }
  23985. double MidiMessageSequence::getStartTime() const
  23986. {
  23987. if (list.size() > 0)
  23988. return list.getUnchecked(0)->message.getTimeStamp();
  23989. else
  23990. return 0;
  23991. }
  23992. double MidiMessageSequence::getEndTime() const
  23993. {
  23994. if (list.size() > 0)
  23995. return list.getLast()->message.getTimeStamp();
  23996. else
  23997. return 0;
  23998. }
  23999. double MidiMessageSequence::getEventTime (const int index) const
  24000. {
  24001. if (isPositiveAndBelow (index, list.size()))
  24002. return list.getUnchecked (index)->message.getTimeStamp();
  24003. return 0.0;
  24004. }
  24005. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24006. double timeAdjustment)
  24007. {
  24008. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24009. timeAdjustment += newMessage.getTimeStamp();
  24010. newOne->message.setTimeStamp (timeAdjustment);
  24011. int i;
  24012. for (i = list.size(); --i >= 0;)
  24013. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24014. break;
  24015. list.insert (i + 1, newOne);
  24016. }
  24017. void MidiMessageSequence::deleteEvent (const int index,
  24018. const bool deleteMatchingNoteUp)
  24019. {
  24020. if (isPositiveAndBelow (index, list.size()))
  24021. {
  24022. if (deleteMatchingNoteUp)
  24023. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24024. list.remove (index);
  24025. }
  24026. }
  24027. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24028. double timeAdjustment,
  24029. double firstAllowableTime,
  24030. double endOfAllowableDestTimes)
  24031. {
  24032. firstAllowableTime -= timeAdjustment;
  24033. endOfAllowableDestTimes -= timeAdjustment;
  24034. for (int i = 0; i < other.list.size(); ++i)
  24035. {
  24036. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24037. const double t = m.getTimeStamp();
  24038. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24039. {
  24040. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24041. newOne->message.setTimeStamp (timeAdjustment + t);
  24042. list.add (newOne);
  24043. }
  24044. }
  24045. sort();
  24046. }
  24047. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24048. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24049. {
  24050. const double diff = first->message.getTimeStamp()
  24051. - second->message.getTimeStamp();
  24052. return (diff > 0) - (diff < 0);
  24053. }
  24054. void MidiMessageSequence::sort()
  24055. {
  24056. list.sort (*this, true);
  24057. }
  24058. void MidiMessageSequence::updateMatchedPairs()
  24059. {
  24060. for (int i = 0; i < list.size(); ++i)
  24061. {
  24062. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24063. if (m1.isNoteOn())
  24064. {
  24065. list.getUnchecked(i)->noteOffObject = 0;
  24066. const int note = m1.getNoteNumber();
  24067. const int chan = m1.getChannel();
  24068. const int len = list.size();
  24069. for (int j = i + 1; j < len; ++j)
  24070. {
  24071. const MidiMessage& m = list.getUnchecked(j)->message;
  24072. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24073. {
  24074. if (m.isNoteOff())
  24075. {
  24076. list.getUnchecked(i)->noteOffObject = list[j];
  24077. break;
  24078. }
  24079. else if (m.isNoteOn())
  24080. {
  24081. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24082. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24083. list.getUnchecked(i)->noteOffObject = list[j];
  24084. break;
  24085. }
  24086. }
  24087. }
  24088. }
  24089. }
  24090. }
  24091. void MidiMessageSequence::addTimeToMessages (const double delta)
  24092. {
  24093. for (int i = list.size(); --i >= 0;)
  24094. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24095. + delta);
  24096. }
  24097. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24098. MidiMessageSequence& destSequence,
  24099. const bool alsoIncludeMetaEvents) const
  24100. {
  24101. for (int i = 0; i < list.size(); ++i)
  24102. {
  24103. const MidiMessage& mm = list.getUnchecked(i)->message;
  24104. if (mm.isForChannel (channelNumberToExtract)
  24105. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24106. {
  24107. destSequence.addEvent (mm);
  24108. }
  24109. }
  24110. }
  24111. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24112. {
  24113. for (int i = 0; i < list.size(); ++i)
  24114. {
  24115. const MidiMessage& mm = list.getUnchecked(i)->message;
  24116. if (mm.isSysEx())
  24117. destSequence.addEvent (mm);
  24118. }
  24119. }
  24120. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24121. {
  24122. for (int i = list.size(); --i >= 0;)
  24123. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24124. list.remove(i);
  24125. }
  24126. void MidiMessageSequence::deleteSysExMessages()
  24127. {
  24128. for (int i = list.size(); --i >= 0;)
  24129. if (list.getUnchecked(i)->message.isSysEx())
  24130. list.remove(i);
  24131. }
  24132. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24133. const double time,
  24134. OwnedArray<MidiMessage>& dest)
  24135. {
  24136. bool doneProg = false;
  24137. bool donePitchWheel = false;
  24138. Array <int> doneControllers;
  24139. doneControllers.ensureStorageAllocated (32);
  24140. for (int i = list.size(); --i >= 0;)
  24141. {
  24142. const MidiMessage& mm = list.getUnchecked(i)->message;
  24143. if (mm.isForChannel (channelNumber)
  24144. && mm.getTimeStamp() <= time)
  24145. {
  24146. if (mm.isProgramChange())
  24147. {
  24148. if (! doneProg)
  24149. {
  24150. dest.add (new MidiMessage (mm, 0.0));
  24151. doneProg = true;
  24152. }
  24153. }
  24154. else if (mm.isController())
  24155. {
  24156. if (! doneControllers.contains (mm.getControllerNumber()))
  24157. {
  24158. dest.add (new MidiMessage (mm, 0.0));
  24159. doneControllers.add (mm.getControllerNumber());
  24160. }
  24161. }
  24162. else if (mm.isPitchWheel())
  24163. {
  24164. if (! donePitchWheel)
  24165. {
  24166. dest.add (new MidiMessage (mm, 0.0));
  24167. donePitchWheel = true;
  24168. }
  24169. }
  24170. }
  24171. }
  24172. }
  24173. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24174. : message (message_),
  24175. noteOffObject (0)
  24176. {
  24177. }
  24178. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24179. {
  24180. }
  24181. END_JUCE_NAMESPACE
  24182. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24183. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24184. BEGIN_JUCE_NAMESPACE
  24185. AudioPluginFormat::AudioPluginFormat() throw()
  24186. {
  24187. }
  24188. AudioPluginFormat::~AudioPluginFormat()
  24189. {
  24190. }
  24191. END_JUCE_NAMESPACE
  24192. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24193. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24194. BEGIN_JUCE_NAMESPACE
  24195. AudioPluginFormatManager::AudioPluginFormatManager()
  24196. {
  24197. }
  24198. AudioPluginFormatManager::~AudioPluginFormatManager()
  24199. {
  24200. clearSingletonInstance();
  24201. }
  24202. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24203. void AudioPluginFormatManager::addDefaultFormats()
  24204. {
  24205. #if JUCE_DEBUG
  24206. // you should only call this method once!
  24207. for (int i = formats.size(); --i >= 0;)
  24208. {
  24209. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24210. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24211. #endif
  24212. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24213. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24214. #endif
  24215. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24216. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24217. #endif
  24218. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24219. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24220. #endif
  24221. }
  24222. #endif
  24223. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24224. formats.add (new AudioUnitPluginFormat());
  24225. #endif
  24226. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24227. formats.add (new VSTPluginFormat());
  24228. #endif
  24229. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24230. formats.add (new DirectXPluginFormat());
  24231. #endif
  24232. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24233. formats.add (new LADSPAPluginFormat());
  24234. #endif
  24235. }
  24236. int AudioPluginFormatManager::getNumFormats()
  24237. {
  24238. return formats.size();
  24239. }
  24240. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24241. {
  24242. return formats [index];
  24243. }
  24244. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24245. {
  24246. formats.add (format);
  24247. }
  24248. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24249. String& errorMessage) const
  24250. {
  24251. AudioPluginInstance* result = 0;
  24252. for (int i = 0; i < formats.size(); ++i)
  24253. {
  24254. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24255. if (result != 0)
  24256. break;
  24257. }
  24258. if (result == 0)
  24259. {
  24260. if (! doesPluginStillExist (description))
  24261. errorMessage = TRANS ("This plug-in file no longer exists");
  24262. else
  24263. errorMessage = TRANS ("This plug-in failed to load correctly");
  24264. }
  24265. return result;
  24266. }
  24267. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24268. {
  24269. for (int i = 0; i < formats.size(); ++i)
  24270. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24271. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24272. return false;
  24273. }
  24274. END_JUCE_NAMESPACE
  24275. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24276. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24277. #define JUCE_PLUGIN_HOST 1
  24278. BEGIN_JUCE_NAMESPACE
  24279. AudioPluginInstance::AudioPluginInstance()
  24280. {
  24281. }
  24282. AudioPluginInstance::~AudioPluginInstance()
  24283. {
  24284. }
  24285. void* AudioPluginInstance::getPlatformSpecificData()
  24286. {
  24287. return 0;
  24288. }
  24289. END_JUCE_NAMESPACE
  24290. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24291. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24292. BEGIN_JUCE_NAMESPACE
  24293. KnownPluginList::KnownPluginList()
  24294. {
  24295. }
  24296. KnownPluginList::~KnownPluginList()
  24297. {
  24298. }
  24299. void KnownPluginList::clear()
  24300. {
  24301. if (types.size() > 0)
  24302. {
  24303. types.clear();
  24304. sendChangeMessage();
  24305. }
  24306. }
  24307. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24308. {
  24309. for (int i = 0; i < types.size(); ++i)
  24310. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24311. return types.getUnchecked(i);
  24312. return 0;
  24313. }
  24314. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24315. {
  24316. for (int i = 0; i < types.size(); ++i)
  24317. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24318. return types.getUnchecked(i);
  24319. return 0;
  24320. }
  24321. bool KnownPluginList::addType (const PluginDescription& type)
  24322. {
  24323. for (int i = types.size(); --i >= 0;)
  24324. {
  24325. if (types.getUnchecked(i)->isDuplicateOf (type))
  24326. {
  24327. // strange - found a duplicate plugin with different info..
  24328. jassert (types.getUnchecked(i)->name == type.name);
  24329. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24330. *types.getUnchecked(i) = type;
  24331. return false;
  24332. }
  24333. }
  24334. types.add (new PluginDescription (type));
  24335. sendChangeMessage();
  24336. return true;
  24337. }
  24338. void KnownPluginList::removeType (const int index)
  24339. {
  24340. types.remove (index);
  24341. sendChangeMessage();
  24342. }
  24343. namespace
  24344. {
  24345. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24346. {
  24347. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24348. return File (fileOrIdentifier).getLastModificationTime();
  24349. return Time();
  24350. }
  24351. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24352. {
  24353. return t1 != t2 || t1 == Time();
  24354. }
  24355. }
  24356. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24357. {
  24358. if (getTypeForFile (fileOrIdentifier) == 0)
  24359. return false;
  24360. for (int i = types.size(); --i >= 0;)
  24361. {
  24362. const PluginDescription* const d = types.getUnchecked(i);
  24363. if (d->fileOrIdentifier == fileOrIdentifier
  24364. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24365. {
  24366. return false;
  24367. }
  24368. }
  24369. return true;
  24370. }
  24371. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24372. const bool dontRescanIfAlreadyInList,
  24373. OwnedArray <PluginDescription>& typesFound,
  24374. AudioPluginFormat& format)
  24375. {
  24376. bool addedOne = false;
  24377. if (dontRescanIfAlreadyInList
  24378. && getTypeForFile (fileOrIdentifier) != 0)
  24379. {
  24380. bool needsRescanning = false;
  24381. for (int i = types.size(); --i >= 0;)
  24382. {
  24383. const PluginDescription* const d = types.getUnchecked(i);
  24384. if (d->fileOrIdentifier == fileOrIdentifier)
  24385. {
  24386. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24387. needsRescanning = true;
  24388. else
  24389. typesFound.add (new PluginDescription (*d));
  24390. }
  24391. }
  24392. if (! needsRescanning)
  24393. return false;
  24394. }
  24395. OwnedArray <PluginDescription> found;
  24396. format.findAllTypesForFile (found, fileOrIdentifier);
  24397. for (int i = 0; i < found.size(); ++i)
  24398. {
  24399. PluginDescription* const desc = found.getUnchecked(i);
  24400. jassert (desc != 0);
  24401. if (addType (*desc))
  24402. addedOne = true;
  24403. typesFound.add (new PluginDescription (*desc));
  24404. }
  24405. return addedOne;
  24406. }
  24407. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24408. OwnedArray <PluginDescription>& typesFound)
  24409. {
  24410. for (int i = 0; i < files.size(); ++i)
  24411. {
  24412. bool loaded = false;
  24413. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24414. {
  24415. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24416. if (scanAndAddFile (files[i], true, typesFound, *format))
  24417. loaded = true;
  24418. }
  24419. if (! loaded)
  24420. {
  24421. const File f (files[i]);
  24422. if (f.isDirectory())
  24423. {
  24424. StringArray s;
  24425. {
  24426. Array<File> subFiles;
  24427. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24428. for (int j = 0; j < subFiles.size(); ++j)
  24429. s.add (subFiles.getReference(j).getFullPathName());
  24430. }
  24431. scanAndAddDragAndDroppedFiles (s, typesFound);
  24432. }
  24433. }
  24434. }
  24435. }
  24436. class PluginSorter
  24437. {
  24438. public:
  24439. KnownPluginList::SortMethod method;
  24440. PluginSorter() throw() {}
  24441. int compareElements (const PluginDescription* const first,
  24442. const PluginDescription* const second) const
  24443. {
  24444. int diff = 0;
  24445. if (method == KnownPluginList::sortByCategory)
  24446. diff = first->category.compareLexicographically (second->category);
  24447. else if (method == KnownPluginList::sortByManufacturer)
  24448. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24449. else if (method == KnownPluginList::sortByFileSystemLocation)
  24450. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24451. .upToLastOccurrenceOf ("/", false, false)
  24452. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24453. .upToLastOccurrenceOf ("/", false, false));
  24454. if (diff == 0)
  24455. diff = first->name.compareLexicographically (second->name);
  24456. return diff;
  24457. }
  24458. };
  24459. void KnownPluginList::sort (const SortMethod method)
  24460. {
  24461. if (method != defaultOrder)
  24462. {
  24463. PluginSorter sorter;
  24464. sorter.method = method;
  24465. types.sort (sorter, true);
  24466. sendChangeMessage();
  24467. }
  24468. }
  24469. XmlElement* KnownPluginList::createXml() const
  24470. {
  24471. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24472. for (int i = 0; i < types.size(); ++i)
  24473. e->addChildElement (types.getUnchecked(i)->createXml());
  24474. return e;
  24475. }
  24476. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24477. {
  24478. clear();
  24479. if (xml.hasTagName ("KNOWNPLUGINS"))
  24480. {
  24481. forEachXmlChildElement (xml, e)
  24482. {
  24483. PluginDescription info;
  24484. if (info.loadFromXml (*e))
  24485. addType (info);
  24486. }
  24487. }
  24488. }
  24489. const int menuIdBase = 0x324503f4;
  24490. // This is used to turn a bunch of paths into a nested menu structure.
  24491. struct PluginFilesystemTree
  24492. {
  24493. private:
  24494. String folder;
  24495. OwnedArray <PluginFilesystemTree> subFolders;
  24496. Array <PluginDescription*> plugins;
  24497. void addPlugin (PluginDescription* const pd, const String& path)
  24498. {
  24499. if (path.isEmpty())
  24500. {
  24501. plugins.add (pd);
  24502. }
  24503. else
  24504. {
  24505. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24506. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24507. for (int i = subFolders.size(); --i >= 0;)
  24508. {
  24509. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24510. {
  24511. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24512. return;
  24513. }
  24514. }
  24515. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24516. newFolder->folder = firstSubFolder;
  24517. subFolders.add (newFolder);
  24518. newFolder->addPlugin (pd, remainingPath);
  24519. }
  24520. }
  24521. // removes any deeply nested folders that don't contain any actual plugins
  24522. void optimise()
  24523. {
  24524. for (int i = subFolders.size(); --i >= 0;)
  24525. {
  24526. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24527. sub->optimise();
  24528. if (sub->plugins.size() == 0)
  24529. {
  24530. for (int j = 0; j < sub->subFolders.size(); ++j)
  24531. subFolders.add (sub->subFolders.getUnchecked(j));
  24532. sub->subFolders.clear (false);
  24533. subFolders.remove (i);
  24534. }
  24535. }
  24536. }
  24537. public:
  24538. void buildTree (const Array <PluginDescription*>& allPlugins)
  24539. {
  24540. for (int i = 0; i < allPlugins.size(); ++i)
  24541. {
  24542. String path (allPlugins.getUnchecked(i)
  24543. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24544. .upToLastOccurrenceOf ("/", false, false));
  24545. if (path.substring (1, 2) == ":")
  24546. path = path.substring (2);
  24547. addPlugin (allPlugins.getUnchecked(i), path);
  24548. }
  24549. optimise();
  24550. }
  24551. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24552. {
  24553. int i;
  24554. for (i = 0; i < subFolders.size(); ++i)
  24555. {
  24556. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24557. PopupMenu subMenu;
  24558. sub->addToMenu (subMenu, allPlugins);
  24559. #if JUCE_MAC
  24560. // avoid the special AU formatting nonsense on Mac..
  24561. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24562. #else
  24563. m.addSubMenu (sub->folder, subMenu);
  24564. #endif
  24565. }
  24566. for (i = 0; i < plugins.size(); ++i)
  24567. {
  24568. PluginDescription* const plugin = plugins.getUnchecked(i);
  24569. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24570. plugin->name, true, false);
  24571. }
  24572. }
  24573. };
  24574. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24575. {
  24576. Array <PluginDescription*> sorted;
  24577. {
  24578. PluginSorter sorter;
  24579. sorter.method = sortMethod;
  24580. for (int i = 0; i < types.size(); ++i)
  24581. sorted.addSorted (sorter, types.getUnchecked(i));
  24582. }
  24583. if (sortMethod == sortByCategory
  24584. || sortMethod == sortByManufacturer)
  24585. {
  24586. String lastSubMenuName;
  24587. PopupMenu sub;
  24588. for (int i = 0; i < sorted.size(); ++i)
  24589. {
  24590. const PluginDescription* const pd = sorted.getUnchecked(i);
  24591. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24592. : pd->manufacturerName);
  24593. if (! thisSubMenuName.containsNonWhitespaceChars())
  24594. thisSubMenuName = "Other";
  24595. if (thisSubMenuName != lastSubMenuName)
  24596. {
  24597. if (sub.getNumItems() > 0)
  24598. {
  24599. menu.addSubMenu (lastSubMenuName, sub);
  24600. sub.clear();
  24601. }
  24602. lastSubMenuName = thisSubMenuName;
  24603. }
  24604. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24605. }
  24606. if (sub.getNumItems() > 0)
  24607. menu.addSubMenu (lastSubMenuName, sub);
  24608. }
  24609. else if (sortMethod == sortByFileSystemLocation)
  24610. {
  24611. PluginFilesystemTree root;
  24612. root.buildTree (sorted);
  24613. root.addToMenu (menu, types);
  24614. }
  24615. else
  24616. {
  24617. for (int i = 0; i < sorted.size(); ++i)
  24618. {
  24619. const PluginDescription* const pd = sorted.getUnchecked(i);
  24620. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24621. }
  24622. }
  24623. }
  24624. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24625. {
  24626. const int i = menuResultCode - menuIdBase;
  24627. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24628. }
  24629. END_JUCE_NAMESPACE
  24630. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24631. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24632. BEGIN_JUCE_NAMESPACE
  24633. PluginDescription::PluginDescription()
  24634. : uid (0),
  24635. isInstrument (false),
  24636. numInputChannels (0),
  24637. numOutputChannels (0)
  24638. {
  24639. }
  24640. PluginDescription::~PluginDescription()
  24641. {
  24642. }
  24643. PluginDescription::PluginDescription (const PluginDescription& other)
  24644. : name (other.name),
  24645. descriptiveName (other.descriptiveName),
  24646. pluginFormatName (other.pluginFormatName),
  24647. category (other.category),
  24648. manufacturerName (other.manufacturerName),
  24649. version (other.version),
  24650. fileOrIdentifier (other.fileOrIdentifier),
  24651. lastFileModTime (other.lastFileModTime),
  24652. uid (other.uid),
  24653. isInstrument (other.isInstrument),
  24654. numInputChannels (other.numInputChannels),
  24655. numOutputChannels (other.numOutputChannels)
  24656. {
  24657. }
  24658. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24659. {
  24660. name = other.name;
  24661. descriptiveName = other.descriptiveName;
  24662. pluginFormatName = other.pluginFormatName;
  24663. category = other.category;
  24664. manufacturerName = other.manufacturerName;
  24665. version = other.version;
  24666. fileOrIdentifier = other.fileOrIdentifier;
  24667. uid = other.uid;
  24668. isInstrument = other.isInstrument;
  24669. lastFileModTime = other.lastFileModTime;
  24670. numInputChannels = other.numInputChannels;
  24671. numOutputChannels = other.numOutputChannels;
  24672. return *this;
  24673. }
  24674. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24675. {
  24676. return fileOrIdentifier == other.fileOrIdentifier
  24677. && uid == other.uid;
  24678. }
  24679. const String PluginDescription::createIdentifierString() const
  24680. {
  24681. return pluginFormatName
  24682. + "-" + name
  24683. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24684. + "-" + String::toHexString (uid);
  24685. }
  24686. XmlElement* PluginDescription::createXml() const
  24687. {
  24688. XmlElement* const e = new XmlElement ("PLUGIN");
  24689. e->setAttribute ("name", name);
  24690. if (descriptiveName != name)
  24691. e->setAttribute ("descriptiveName", descriptiveName);
  24692. e->setAttribute ("format", pluginFormatName);
  24693. e->setAttribute ("category", category);
  24694. e->setAttribute ("manufacturer", manufacturerName);
  24695. e->setAttribute ("version", version);
  24696. e->setAttribute ("file", fileOrIdentifier);
  24697. e->setAttribute ("uid", String::toHexString (uid));
  24698. e->setAttribute ("isInstrument", isInstrument);
  24699. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24700. e->setAttribute ("numInputs", numInputChannels);
  24701. e->setAttribute ("numOutputs", numOutputChannels);
  24702. return e;
  24703. }
  24704. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24705. {
  24706. if (xml.hasTagName ("PLUGIN"))
  24707. {
  24708. name = xml.getStringAttribute ("name");
  24709. descriptiveName = xml.getStringAttribute ("name", name);
  24710. pluginFormatName = xml.getStringAttribute ("format");
  24711. category = xml.getStringAttribute ("category");
  24712. manufacturerName = xml.getStringAttribute ("manufacturer");
  24713. version = xml.getStringAttribute ("version");
  24714. fileOrIdentifier = xml.getStringAttribute ("file");
  24715. uid = xml.getStringAttribute ("uid").getHexValue32();
  24716. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24717. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24718. numInputChannels = xml.getIntAttribute ("numInputs");
  24719. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24720. return true;
  24721. }
  24722. return false;
  24723. }
  24724. END_JUCE_NAMESPACE
  24725. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24726. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24727. BEGIN_JUCE_NAMESPACE
  24728. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24729. AudioPluginFormat& formatToLookFor,
  24730. FileSearchPath directoriesToSearch,
  24731. const bool recursive,
  24732. const File& deadMansPedalFile_)
  24733. : list (listToAddTo),
  24734. format (formatToLookFor),
  24735. deadMansPedalFile (deadMansPedalFile_),
  24736. nextIndex (0),
  24737. progress (0)
  24738. {
  24739. directoriesToSearch.removeRedundantPaths();
  24740. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24741. // If any plugins have crashed recently when being loaded, move them to the
  24742. // end of the list to give the others a chance to load correctly..
  24743. const StringArray crashedPlugins (getDeadMansPedalFile());
  24744. for (int i = 0; i < crashedPlugins.size(); ++i)
  24745. {
  24746. const String f = crashedPlugins[i];
  24747. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24748. if (f == filesOrIdentifiersToScan[j])
  24749. filesOrIdentifiersToScan.move (j, -1);
  24750. }
  24751. }
  24752. PluginDirectoryScanner::~PluginDirectoryScanner()
  24753. {
  24754. }
  24755. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24756. {
  24757. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24758. }
  24759. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24760. {
  24761. String file (filesOrIdentifiersToScan [nextIndex]);
  24762. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24763. {
  24764. OwnedArray <PluginDescription> typesFound;
  24765. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24766. StringArray crashedPlugins (getDeadMansPedalFile());
  24767. crashedPlugins.removeString (file);
  24768. crashedPlugins.add (file);
  24769. setDeadMansPedalFile (crashedPlugins);
  24770. list.scanAndAddFile (file,
  24771. dontRescanIfAlreadyInList,
  24772. typesFound,
  24773. format);
  24774. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24775. crashedPlugins.removeString (file);
  24776. setDeadMansPedalFile (crashedPlugins);
  24777. if (typesFound.size() == 0)
  24778. failedFiles.add (file);
  24779. }
  24780. return skipNextFile();
  24781. }
  24782. bool PluginDirectoryScanner::skipNextFile()
  24783. {
  24784. if (nextIndex >= filesOrIdentifiersToScan.size())
  24785. return false;
  24786. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24787. return nextIndex < filesOrIdentifiersToScan.size();
  24788. }
  24789. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24790. {
  24791. StringArray lines;
  24792. if (deadMansPedalFile != File::nonexistent)
  24793. {
  24794. lines.addLines (deadMansPedalFile.loadFileAsString());
  24795. lines.removeEmptyStrings();
  24796. }
  24797. return lines;
  24798. }
  24799. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24800. {
  24801. if (deadMansPedalFile != File::nonexistent)
  24802. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24803. }
  24804. END_JUCE_NAMESPACE
  24805. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24806. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24807. BEGIN_JUCE_NAMESPACE
  24808. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24809. const File& deadMansPedalFile_,
  24810. PropertiesFile* const propertiesToUse_)
  24811. : list (listToEdit),
  24812. deadMansPedalFile (deadMansPedalFile_),
  24813. optionsButton ("Options..."),
  24814. propertiesToUse (propertiesToUse_)
  24815. {
  24816. listBox.setModel (this);
  24817. addAndMakeVisible (&listBox);
  24818. addAndMakeVisible (&optionsButton);
  24819. optionsButton.addListener (this);
  24820. optionsButton.setTriggeredOnMouseDown (true);
  24821. setSize (400, 600);
  24822. list.addChangeListener (this);
  24823. changeListenerCallback (0);
  24824. }
  24825. PluginListComponent::~PluginListComponent()
  24826. {
  24827. list.removeChangeListener (this);
  24828. }
  24829. void PluginListComponent::resized()
  24830. {
  24831. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24832. optionsButton.changeWidthToFitText (24);
  24833. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24834. }
  24835. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24836. {
  24837. listBox.updateContent();
  24838. listBox.repaint();
  24839. }
  24840. int PluginListComponent::getNumRows()
  24841. {
  24842. return list.getNumTypes();
  24843. }
  24844. void PluginListComponent::paintListBoxItem (int row,
  24845. Graphics& g,
  24846. int width, int height,
  24847. bool rowIsSelected)
  24848. {
  24849. if (rowIsSelected)
  24850. g.fillAll (findColour (TextEditor::highlightColourId));
  24851. const PluginDescription* const pd = list.getType (row);
  24852. if (pd != 0)
  24853. {
  24854. GlyphArrangement ga;
  24855. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24856. g.setColour (Colours::black);
  24857. ga.draw (g);
  24858. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24859. String desc;
  24860. desc << pd->pluginFormatName
  24861. << (pd->isInstrument ? " instrument" : " effect")
  24862. << " - "
  24863. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24864. << " / "
  24865. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24866. if (pd->manufacturerName.isNotEmpty())
  24867. desc << " - " << pd->manufacturerName;
  24868. if (pd->version.isNotEmpty())
  24869. desc << " - " << pd->version;
  24870. if (pd->category.isNotEmpty())
  24871. desc << " - category: '" << pd->category << '\'';
  24872. g.setColour (Colours::grey);
  24873. ga.clear();
  24874. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24875. ga.draw (g);
  24876. }
  24877. }
  24878. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24879. {
  24880. list.removeType (lastRowSelected);
  24881. }
  24882. void PluginListComponent::buttonClicked (Button* button)
  24883. {
  24884. if (button == &optionsButton)
  24885. {
  24886. PopupMenu menu;
  24887. menu.addItem (1, TRANS("Clear list"));
  24888. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24889. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24890. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24891. menu.addSeparator();
  24892. menu.addItem (2, TRANS("Sort alphabetically"));
  24893. menu.addItem (3, TRANS("Sort by category"));
  24894. menu.addItem (4, TRANS("Sort by manufacturer"));
  24895. menu.addSeparator();
  24896. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24897. {
  24898. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24899. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24900. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24901. }
  24902. const int r = menu.showAt (&optionsButton);
  24903. if (r == 1)
  24904. {
  24905. list.clear();
  24906. }
  24907. else if (r == 2)
  24908. {
  24909. list.sort (KnownPluginList::sortAlphabetically);
  24910. }
  24911. else if (r == 3)
  24912. {
  24913. list.sort (KnownPluginList::sortByCategory);
  24914. }
  24915. else if (r == 4)
  24916. {
  24917. list.sort (KnownPluginList::sortByManufacturer);
  24918. }
  24919. else if (r == 5)
  24920. {
  24921. const SparseSet <int> selected (listBox.getSelectedRows());
  24922. for (int i = list.getNumTypes(); --i >= 0;)
  24923. if (selected.contains (i))
  24924. list.removeType (i);
  24925. }
  24926. else if (r == 6)
  24927. {
  24928. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  24929. if (desc != 0)
  24930. {
  24931. if (File (desc->fileOrIdentifier).existsAsFile())
  24932. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24933. }
  24934. }
  24935. else if (r == 7)
  24936. {
  24937. for (int i = list.getNumTypes(); --i >= 0;)
  24938. {
  24939. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24940. {
  24941. list.removeType (i);
  24942. }
  24943. }
  24944. }
  24945. else if (r != 0)
  24946. {
  24947. typeToScan = r - 10;
  24948. startTimer (1);
  24949. }
  24950. }
  24951. }
  24952. void PluginListComponent::timerCallback()
  24953. {
  24954. stopTimer();
  24955. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24956. }
  24957. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24958. {
  24959. return true;
  24960. }
  24961. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24962. {
  24963. OwnedArray <PluginDescription> typesFound;
  24964. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24965. }
  24966. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24967. {
  24968. if (format == 0)
  24969. return;
  24970. FileSearchPath path (format->getDefaultLocationsToSearch());
  24971. if (propertiesToUse != 0)
  24972. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24973. {
  24974. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24975. FileSearchPathListComponent pathList;
  24976. pathList.setSize (500, 300);
  24977. pathList.setPath (path);
  24978. aw.addCustomComponent (&pathList);
  24979. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24980. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24981. if (aw.runModalLoop() == 0)
  24982. return;
  24983. path = pathList.getPath();
  24984. }
  24985. if (propertiesToUse != 0)
  24986. {
  24987. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24988. propertiesToUse->saveIfNeeded();
  24989. }
  24990. double progress = 0.0;
  24991. AlertWindow aw (TRANS("Scanning for plugins..."),
  24992. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24993. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24994. aw.addProgressBarComponent (progress);
  24995. aw.enterModalState();
  24996. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24997. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24998. for (;;)
  24999. {
  25000. aw.setMessage (TRANS("Testing:\n\n")
  25001. + scanner.getNextPluginFileThatWillBeScanned());
  25002. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25003. if (! scanner.scanNextFile (true))
  25004. break;
  25005. if (! aw.isCurrentlyModal())
  25006. break;
  25007. progress = scanner.getProgress();
  25008. }
  25009. if (scanner.getFailedFiles().size() > 0)
  25010. {
  25011. StringArray shortNames;
  25012. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25013. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25014. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25015. TRANS("Scan complete"),
  25016. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25017. + shortNames.joinIntoString (", "));
  25018. }
  25019. }
  25020. END_JUCE_NAMESPACE
  25021. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25022. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25023. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25024. #include <AudioUnit/AudioUnit.h>
  25025. #include <AudioUnit/AUCocoaUIView.h>
  25026. #include <CoreAudioKit/AUGenericView.h>
  25027. #if JUCE_SUPPORT_CARBON
  25028. #include <AudioToolbox/AudioUnitUtilities.h>
  25029. #include <AudioUnit/AudioUnitCarbonView.h>
  25030. #endif
  25031. BEGIN_JUCE_NAMESPACE
  25032. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25033. #endif
  25034. #if JUCE_MAC
  25035. // Change this to disable logging of various activities
  25036. #ifndef AU_LOGGING
  25037. #define AU_LOGGING 1
  25038. #endif
  25039. #if AU_LOGGING
  25040. #define log(a) Logger::writeToLog(a);
  25041. #else
  25042. #define log(a)
  25043. #endif
  25044. namespace AudioUnitFormatHelpers
  25045. {
  25046. static int insideCallback = 0;
  25047. const String osTypeToString (OSType type)
  25048. {
  25049. char s[4];
  25050. s[0] = (char) (((uint32) type) >> 24);
  25051. s[1] = (char) (((uint32) type) >> 16);
  25052. s[2] = (char) (((uint32) type) >> 8);
  25053. s[3] = (char) ((uint32) type);
  25054. return String (s, 4);
  25055. }
  25056. OSType stringToOSType (const String& s1)
  25057. {
  25058. const String s (s1 + " ");
  25059. return (((OSType) (unsigned char) s[0]) << 24)
  25060. | (((OSType) (unsigned char) s[1]) << 16)
  25061. | (((OSType) (unsigned char) s[2]) << 8)
  25062. | ((OSType) (unsigned char) s[3]);
  25063. }
  25064. static const char* auIdentifierPrefix = "AudioUnit:";
  25065. const String createAUPluginIdentifier (const ComponentDescription& desc)
  25066. {
  25067. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25068. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25069. String s (auIdentifierPrefix);
  25070. if (desc.componentType == kAudioUnitType_MusicDevice)
  25071. s << "Synths/";
  25072. else if (desc.componentType == kAudioUnitType_MusicEffect
  25073. || desc.componentType == kAudioUnitType_Effect)
  25074. s << "Effects/";
  25075. else if (desc.componentType == kAudioUnitType_Generator)
  25076. s << "Generators/";
  25077. else if (desc.componentType == kAudioUnitType_Panner)
  25078. s << "Panners/";
  25079. s << osTypeToString (desc.componentType) << ","
  25080. << osTypeToString (desc.componentSubType) << ","
  25081. << osTypeToString (desc.componentManufacturer);
  25082. return s;
  25083. }
  25084. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25085. {
  25086. Handle componentNameHandle = NewHandle (sizeof (void*));
  25087. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25088. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25089. {
  25090. ComponentDescription desc;
  25091. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25092. {
  25093. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25094. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25095. if (nameString != 0 && nameString[0] != 0)
  25096. {
  25097. const String all ((const char*) nameString + 1, nameString[0]);
  25098. DBG ("name: "+ all);
  25099. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25100. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25101. }
  25102. if (infoString != 0 && infoString[0] != 0)
  25103. {
  25104. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25105. }
  25106. if (name.isEmpty())
  25107. name = "<Unknown>";
  25108. }
  25109. DisposeHandle (componentNameHandle);
  25110. DisposeHandle (componentInfoHandle);
  25111. }
  25112. }
  25113. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25114. String& name, String& version, String& manufacturer)
  25115. {
  25116. zerostruct (desc);
  25117. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25118. {
  25119. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25120. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25121. StringArray tokens;
  25122. tokens.addTokens (s, ",", String::empty);
  25123. tokens.trim();
  25124. tokens.removeEmptyStrings();
  25125. if (tokens.size() == 3)
  25126. {
  25127. desc.componentType = stringToOSType (tokens[0]);
  25128. desc.componentSubType = stringToOSType (tokens[1]);
  25129. desc.componentManufacturer = stringToOSType (tokens[2]);
  25130. ComponentRecord* comp = FindNextComponent (0, &desc);
  25131. if (comp != 0)
  25132. {
  25133. getAUDetails (comp, name, manufacturer);
  25134. return true;
  25135. }
  25136. }
  25137. }
  25138. return false;
  25139. }
  25140. }
  25141. class AudioUnitPluginWindowCarbon;
  25142. class AudioUnitPluginWindowCocoa;
  25143. class AudioUnitPluginInstance : public AudioPluginInstance
  25144. {
  25145. public:
  25146. ~AudioUnitPluginInstance();
  25147. void initialise();
  25148. // AudioPluginInstance methods:
  25149. void fillInPluginDescription (PluginDescription& desc) const
  25150. {
  25151. desc.name = pluginName;
  25152. desc.descriptiveName = pluginName;
  25153. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25154. desc.uid = ((int) componentDesc.componentType)
  25155. ^ ((int) componentDesc.componentSubType)
  25156. ^ ((int) componentDesc.componentManufacturer);
  25157. desc.lastFileModTime = Time();
  25158. desc.pluginFormatName = "AudioUnit";
  25159. desc.category = getCategory();
  25160. desc.manufacturerName = manufacturer;
  25161. desc.version = version;
  25162. desc.numInputChannels = getNumInputChannels();
  25163. desc.numOutputChannels = getNumOutputChannels();
  25164. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25165. }
  25166. void* getPlatformSpecificData() { return audioUnit; }
  25167. const String getName() const { return pluginName; }
  25168. bool acceptsMidi() const { return wantsMidiMessages; }
  25169. bool producesMidi() const { return false; }
  25170. // AudioProcessor methods:
  25171. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25172. void releaseResources();
  25173. void processBlock (AudioSampleBuffer& buffer,
  25174. MidiBuffer& midiMessages);
  25175. bool hasEditor() const;
  25176. AudioProcessorEditor* createEditor();
  25177. const String getInputChannelName (int index) const;
  25178. bool isInputChannelStereoPair (int index) const;
  25179. const String getOutputChannelName (int index) const;
  25180. bool isOutputChannelStereoPair (int index) const;
  25181. int getNumParameters();
  25182. float getParameter (int index);
  25183. void setParameter (int index, float newValue);
  25184. const String getParameterName (int index);
  25185. const String getParameterText (int index);
  25186. bool isParameterAutomatable (int index) const;
  25187. int getNumPrograms();
  25188. int getCurrentProgram();
  25189. void setCurrentProgram (int index);
  25190. const String getProgramName (int index);
  25191. void changeProgramName (int index, const String& newName);
  25192. void getStateInformation (MemoryBlock& destData);
  25193. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25194. void setStateInformation (const void* data, int sizeInBytes);
  25195. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25196. private:
  25197. friend class AudioUnitPluginWindowCarbon;
  25198. friend class AudioUnitPluginWindowCocoa;
  25199. friend class AudioUnitPluginFormat;
  25200. ComponentDescription componentDesc;
  25201. String pluginName, manufacturer, version;
  25202. String fileOrIdentifier;
  25203. CriticalSection lock;
  25204. bool wantsMidiMessages, wasPlaying, prepared;
  25205. HeapBlock <AudioBufferList> outputBufferList;
  25206. AudioTimeStamp timeStamp;
  25207. AudioSampleBuffer* currentBuffer;
  25208. AudioUnit audioUnit;
  25209. Array <int> parameterIds;
  25210. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25211. void setPluginCallbacks();
  25212. void getParameterListFromPlugin();
  25213. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25214. const AudioTimeStamp* inTimeStamp,
  25215. UInt32 inBusNumber,
  25216. UInt32 inNumberFrames,
  25217. AudioBufferList* ioData) const;
  25218. static OSStatus renderGetInputCallback (void* inRefCon,
  25219. AudioUnitRenderActionFlags* ioActionFlags,
  25220. const AudioTimeStamp* inTimeStamp,
  25221. UInt32 inBusNumber,
  25222. UInt32 inNumberFrames,
  25223. AudioBufferList* ioData)
  25224. {
  25225. return ((AudioUnitPluginInstance*) inRefCon)
  25226. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25227. }
  25228. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25229. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25230. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25231. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25232. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25233. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25234. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25235. {
  25236. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25237. }
  25238. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25239. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25240. Float64* outCurrentMeasureDownBeat)
  25241. {
  25242. return ((AudioUnitPluginInstance*) inHostUserData)
  25243. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25244. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25245. }
  25246. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25247. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25248. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25249. {
  25250. return ((AudioUnitPluginInstance*) inHostUserData)
  25251. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25252. outCurrentSampleInTimeLine, outIsCycling,
  25253. outCycleStartBeat, outCycleEndBeat);
  25254. }
  25255. void getNumChannels (int& numIns, int& numOuts)
  25256. {
  25257. numIns = 0;
  25258. numOuts = 0;
  25259. AUChannelInfo supportedChannels [128];
  25260. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25261. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25262. 0, supportedChannels, &supportedChannelsSize) == noErr
  25263. && supportedChannelsSize > 0)
  25264. {
  25265. int explicitNumIns = 0;
  25266. int explicitNumOuts = 0;
  25267. int maximumNumIns = 0;
  25268. int maximumNumOuts = 0;
  25269. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25270. {
  25271. const int inChannels = (int) supportedChannels[i].inChannels;
  25272. const int outChannels = (int) supportedChannels[i].outChannels;
  25273. if (inChannels < 0)
  25274. maximumNumIns = jmin (maximumNumIns, inChannels);
  25275. else
  25276. explicitNumIns = jmax (explicitNumIns, inChannels);
  25277. if (outChannels < 0)
  25278. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25279. else
  25280. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25281. }
  25282. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25283. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25284. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25285. {
  25286. numIns = numOuts = 2;
  25287. }
  25288. else
  25289. {
  25290. numIns = explicitNumIns;
  25291. numOuts = explicitNumOuts;
  25292. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25293. numIns = 2;
  25294. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25295. numOuts = 2;
  25296. }
  25297. }
  25298. else
  25299. {
  25300. // (this really means the plugin will take any number of ins/outs as long
  25301. // as they are the same)
  25302. numIns = numOuts = 2;
  25303. }
  25304. }
  25305. const String getCategory() const;
  25306. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25307. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25308. };
  25309. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25310. : fileOrIdentifier (fileOrIdentifier),
  25311. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25312. currentBuffer (0),
  25313. audioUnit (0)
  25314. {
  25315. using namespace AudioUnitFormatHelpers;
  25316. try
  25317. {
  25318. ++insideCallback;
  25319. log ("Opening AU: " + fileOrIdentifier);
  25320. if (getComponentDescFromFile (fileOrIdentifier))
  25321. {
  25322. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25323. if (comp != 0)
  25324. {
  25325. audioUnit = (AudioUnit) OpenComponent (comp);
  25326. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25327. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25328. }
  25329. }
  25330. --insideCallback;
  25331. }
  25332. catch (...)
  25333. {
  25334. --insideCallback;
  25335. }
  25336. }
  25337. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25338. {
  25339. const ScopedLock sl (lock);
  25340. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25341. if (audioUnit != 0)
  25342. {
  25343. AudioUnitUninitialize (audioUnit);
  25344. CloseComponent (audioUnit);
  25345. audioUnit = 0;
  25346. }
  25347. }
  25348. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25349. {
  25350. zerostruct (componentDesc);
  25351. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25352. return true;
  25353. const File file (fileOrIdentifier);
  25354. if (! file.hasFileExtension (".component"))
  25355. return false;
  25356. const char* const utf8 = fileOrIdentifier.toUTF8();
  25357. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25358. strlen (utf8), file.isDirectory());
  25359. if (url != 0)
  25360. {
  25361. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25362. CFRelease (url);
  25363. if (bundleRef != 0)
  25364. {
  25365. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25366. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25367. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25368. if (pluginName.isEmpty())
  25369. pluginName = file.getFileNameWithoutExtension();
  25370. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25371. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25372. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25373. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25374. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25375. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25376. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25377. UseResFile (resFileId);
  25378. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25379. {
  25380. Handle h = Get1IndResource ('thng', i);
  25381. if (h != 0)
  25382. {
  25383. HLock (h);
  25384. const uint32* const types = (const uint32*) *h;
  25385. if (types[0] == kAudioUnitType_MusicDevice
  25386. || types[0] == kAudioUnitType_MusicEffect
  25387. || types[0] == kAudioUnitType_Effect
  25388. || types[0] == kAudioUnitType_Generator
  25389. || types[0] == kAudioUnitType_Panner)
  25390. {
  25391. componentDesc.componentType = types[0];
  25392. componentDesc.componentSubType = types[1];
  25393. componentDesc.componentManufacturer = types[2];
  25394. break;
  25395. }
  25396. HUnlock (h);
  25397. ReleaseResource (h);
  25398. }
  25399. }
  25400. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25401. CFRelease (bundleRef);
  25402. }
  25403. }
  25404. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25405. }
  25406. void AudioUnitPluginInstance::initialise()
  25407. {
  25408. getParameterListFromPlugin();
  25409. setPluginCallbacks();
  25410. int numIns, numOuts;
  25411. getNumChannels (numIns, numOuts);
  25412. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25413. setLatencySamples (0);
  25414. }
  25415. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25416. {
  25417. parameterIds.clear();
  25418. if (audioUnit != 0)
  25419. {
  25420. UInt32 paramListSize = 0;
  25421. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25422. 0, 0, &paramListSize);
  25423. if (paramListSize > 0)
  25424. {
  25425. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25426. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25427. 0, &parameterIds.getReference(0), &paramListSize);
  25428. }
  25429. }
  25430. }
  25431. void AudioUnitPluginInstance::setPluginCallbacks()
  25432. {
  25433. if (audioUnit != 0)
  25434. {
  25435. {
  25436. AURenderCallbackStruct info;
  25437. zerostruct (info);
  25438. info.inputProcRefCon = this;
  25439. info.inputProc = renderGetInputCallback;
  25440. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25441. 0, &info, sizeof (info));
  25442. }
  25443. {
  25444. HostCallbackInfo info;
  25445. zerostruct (info);
  25446. info.hostUserData = this;
  25447. info.beatAndTempoProc = getBeatAndTempoCallback;
  25448. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25449. info.transportStateProc = getTransportStateCallback;
  25450. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25451. 0, &info, sizeof (info));
  25452. }
  25453. }
  25454. }
  25455. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25456. int samplesPerBlockExpected)
  25457. {
  25458. if (audioUnit != 0)
  25459. {
  25460. releaseResources();
  25461. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25462. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25463. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25464. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25465. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25466. {
  25467. Float64 sr = sampleRate_;
  25468. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25469. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25470. }
  25471. int numIns, numOuts;
  25472. getNumChannels (numIns, numOuts);
  25473. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25474. Float64 latencySecs = 0.0;
  25475. UInt32 latencySize = sizeof (latencySecs);
  25476. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25477. 0, &latencySecs, &latencySize);
  25478. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25479. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25480. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25481. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25482. {
  25483. AudioStreamBasicDescription stream;
  25484. zerostruct (stream);
  25485. stream.mSampleRate = sampleRate_;
  25486. stream.mFormatID = kAudioFormatLinearPCM;
  25487. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25488. stream.mFramesPerPacket = 1;
  25489. stream.mBytesPerPacket = 4;
  25490. stream.mBytesPerFrame = 4;
  25491. stream.mBitsPerChannel = 32;
  25492. stream.mChannelsPerFrame = numIns;
  25493. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25494. 0, &stream, sizeof (stream));
  25495. stream.mChannelsPerFrame = numOuts;
  25496. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25497. 0, &stream, sizeof (stream));
  25498. }
  25499. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25500. outputBufferList->mNumberBuffers = numOuts;
  25501. for (int i = numOuts; --i >= 0;)
  25502. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25503. zerostruct (timeStamp);
  25504. timeStamp.mSampleTime = 0;
  25505. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25506. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25507. currentBuffer = 0;
  25508. wasPlaying = false;
  25509. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25510. }
  25511. }
  25512. void AudioUnitPluginInstance::releaseResources()
  25513. {
  25514. if (prepared)
  25515. {
  25516. AudioUnitUninitialize (audioUnit);
  25517. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25518. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25519. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25520. outputBufferList.free();
  25521. currentBuffer = 0;
  25522. prepared = false;
  25523. }
  25524. }
  25525. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25526. const AudioTimeStamp* inTimeStamp,
  25527. UInt32 inBusNumber,
  25528. UInt32 inNumberFrames,
  25529. AudioBufferList* ioData) const
  25530. {
  25531. if (inBusNumber == 0
  25532. && currentBuffer != 0)
  25533. {
  25534. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25535. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25536. {
  25537. if (i < currentBuffer->getNumChannels())
  25538. {
  25539. memcpy (ioData->mBuffers[i].mData,
  25540. currentBuffer->getSampleData (i, 0),
  25541. sizeof (float) * inNumberFrames);
  25542. }
  25543. else
  25544. {
  25545. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25546. }
  25547. }
  25548. }
  25549. return noErr;
  25550. }
  25551. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25552. MidiBuffer& midiMessages)
  25553. {
  25554. const int numSamples = buffer.getNumSamples();
  25555. if (prepared)
  25556. {
  25557. AudioUnitRenderActionFlags flags = 0;
  25558. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25559. for (int i = getNumOutputChannels(); --i >= 0;)
  25560. {
  25561. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25562. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25563. }
  25564. currentBuffer = &buffer;
  25565. if (wantsMidiMessages)
  25566. {
  25567. const uint8* midiEventData;
  25568. int midiEventSize, midiEventPosition;
  25569. MidiBuffer::Iterator i (midiMessages);
  25570. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25571. {
  25572. if (midiEventSize <= 3)
  25573. MusicDeviceMIDIEvent (audioUnit,
  25574. midiEventData[0], midiEventData[1], midiEventData[2],
  25575. midiEventPosition);
  25576. else
  25577. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25578. }
  25579. midiMessages.clear();
  25580. }
  25581. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25582. 0, numSamples, outputBufferList);
  25583. timeStamp.mSampleTime += numSamples;
  25584. }
  25585. else
  25586. {
  25587. // Plugin not working correctly, so just bypass..
  25588. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25589. buffer.clear (i, 0, buffer.getNumSamples());
  25590. }
  25591. }
  25592. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25593. {
  25594. AudioPlayHead* const ph = getPlayHead();
  25595. AudioPlayHead::CurrentPositionInfo result;
  25596. if (ph != 0 && ph->getCurrentPosition (result))
  25597. {
  25598. if (outCurrentBeat != 0)
  25599. *outCurrentBeat = result.ppqPosition;
  25600. if (outCurrentTempo != 0)
  25601. *outCurrentTempo = result.bpm;
  25602. }
  25603. else
  25604. {
  25605. if (outCurrentBeat != 0)
  25606. *outCurrentBeat = 0;
  25607. if (outCurrentTempo != 0)
  25608. *outCurrentTempo = 120.0;
  25609. }
  25610. return noErr;
  25611. }
  25612. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25613. Float32* outTimeSig_Numerator,
  25614. UInt32* outTimeSig_Denominator,
  25615. Float64* outCurrentMeasureDownBeat) const
  25616. {
  25617. AudioPlayHead* const ph = getPlayHead();
  25618. AudioPlayHead::CurrentPositionInfo result;
  25619. if (ph != 0 && ph->getCurrentPosition (result))
  25620. {
  25621. if (outTimeSig_Numerator != 0)
  25622. *outTimeSig_Numerator = result.timeSigNumerator;
  25623. if (outTimeSig_Denominator != 0)
  25624. *outTimeSig_Denominator = result.timeSigDenominator;
  25625. if (outDeltaSampleOffsetToNextBeat != 0)
  25626. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25627. if (outCurrentMeasureDownBeat != 0)
  25628. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25629. }
  25630. else
  25631. {
  25632. if (outDeltaSampleOffsetToNextBeat != 0)
  25633. *outDeltaSampleOffsetToNextBeat = 0;
  25634. if (outTimeSig_Numerator != 0)
  25635. *outTimeSig_Numerator = 4;
  25636. if (outTimeSig_Denominator != 0)
  25637. *outTimeSig_Denominator = 4;
  25638. if (outCurrentMeasureDownBeat != 0)
  25639. *outCurrentMeasureDownBeat = 0;
  25640. }
  25641. return noErr;
  25642. }
  25643. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25644. Boolean* outTransportStateChanged,
  25645. Float64* outCurrentSampleInTimeLine,
  25646. Boolean* outIsCycling,
  25647. Float64* outCycleStartBeat,
  25648. Float64* outCycleEndBeat)
  25649. {
  25650. AudioPlayHead* const ph = getPlayHead();
  25651. AudioPlayHead::CurrentPositionInfo result;
  25652. if (ph != 0 && ph->getCurrentPosition (result))
  25653. {
  25654. if (outIsPlaying != 0)
  25655. *outIsPlaying = result.isPlaying;
  25656. if (outTransportStateChanged != 0)
  25657. {
  25658. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25659. wasPlaying = result.isPlaying;
  25660. }
  25661. if (outCurrentSampleInTimeLine != 0)
  25662. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25663. if (outIsCycling != 0)
  25664. *outIsCycling = false;
  25665. if (outCycleStartBeat != 0)
  25666. *outCycleStartBeat = 0;
  25667. if (outCycleEndBeat != 0)
  25668. *outCycleEndBeat = 0;
  25669. }
  25670. else
  25671. {
  25672. if (outIsPlaying != 0)
  25673. *outIsPlaying = false;
  25674. if (outTransportStateChanged != 0)
  25675. *outTransportStateChanged = false;
  25676. if (outCurrentSampleInTimeLine != 0)
  25677. *outCurrentSampleInTimeLine = 0;
  25678. if (outIsCycling != 0)
  25679. *outIsCycling = false;
  25680. if (outCycleStartBeat != 0)
  25681. *outCycleStartBeat = 0;
  25682. if (outCycleEndBeat != 0)
  25683. *outCycleEndBeat = 0;
  25684. }
  25685. return noErr;
  25686. }
  25687. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25688. public Timer
  25689. {
  25690. public:
  25691. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25692. : AudioProcessorEditor (&plugin_),
  25693. plugin (plugin_)
  25694. {
  25695. addAndMakeVisible (&wrapper);
  25696. setOpaque (true);
  25697. setVisible (true);
  25698. setSize (100, 100);
  25699. createView (createGenericViewIfNeeded);
  25700. }
  25701. ~AudioUnitPluginWindowCocoa()
  25702. {
  25703. const bool wasValid = isValid();
  25704. wrapper.setView (0);
  25705. if (wasValid)
  25706. plugin.editorBeingDeleted (this);
  25707. }
  25708. bool isValid() const { return wrapper.getView() != 0; }
  25709. void paint (Graphics& g)
  25710. {
  25711. g.fillAll (Colours::white);
  25712. }
  25713. void resized()
  25714. {
  25715. wrapper.setSize (getWidth(), getHeight());
  25716. }
  25717. void timerCallback()
  25718. {
  25719. wrapper.resizeToFitView();
  25720. startTimer (jmin (713, getTimerInterval() + 51));
  25721. }
  25722. void childBoundsChanged (Component* child)
  25723. {
  25724. setSize (wrapper.getWidth(), wrapper.getHeight());
  25725. startTimer (70);
  25726. }
  25727. private:
  25728. AudioUnitPluginInstance& plugin;
  25729. NSViewComponent wrapper;
  25730. bool createView (const bool createGenericViewIfNeeded)
  25731. {
  25732. NSView* pluginView = 0;
  25733. UInt32 dataSize = 0;
  25734. Boolean isWritable = false;
  25735. AudioUnitInitialize (plugin.audioUnit);
  25736. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25737. 0, &dataSize, &isWritable) == noErr
  25738. && dataSize != 0
  25739. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25740. 0, &dataSize, &isWritable) == noErr)
  25741. {
  25742. HeapBlock <AudioUnitCocoaViewInfo> info;
  25743. info.calloc (dataSize, 1);
  25744. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25745. 0, info, &dataSize) == noErr)
  25746. {
  25747. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25748. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25749. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25750. Class viewClass = [viewBundle classNamed: viewClassName];
  25751. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25752. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25753. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25754. {
  25755. id factory = [[[viewClass alloc] init] autorelease];
  25756. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25757. withSize: NSMakeSize (getWidth(), getHeight())];
  25758. }
  25759. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25760. CFRelease (info->mCocoaAUViewClass[i]);
  25761. CFRelease (info->mCocoaAUViewBundleLocation);
  25762. }
  25763. }
  25764. if (createGenericViewIfNeeded && (pluginView == 0))
  25765. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25766. wrapper.setView (pluginView);
  25767. if (pluginView != 0)
  25768. {
  25769. timerCallback();
  25770. startTimer (70);
  25771. }
  25772. return pluginView != 0;
  25773. }
  25774. };
  25775. #if JUCE_SUPPORT_CARBON
  25776. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25777. {
  25778. public:
  25779. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25780. : AudioProcessorEditor (&plugin_),
  25781. plugin (plugin_),
  25782. viewComponent (0)
  25783. {
  25784. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25785. setOpaque (true);
  25786. setVisible (true);
  25787. setSize (400, 300);
  25788. ComponentDescription viewList [16];
  25789. UInt32 viewListSize = sizeof (viewList);
  25790. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25791. 0, &viewList, &viewListSize);
  25792. componentRecord = FindNextComponent (0, &viewList[0]);
  25793. }
  25794. ~AudioUnitPluginWindowCarbon()
  25795. {
  25796. innerWrapper = 0;
  25797. if (isValid())
  25798. plugin.editorBeingDeleted (this);
  25799. }
  25800. bool isValid() const throw() { return componentRecord != 0; }
  25801. void paint (Graphics& g)
  25802. {
  25803. g.fillAll (Colours::black);
  25804. }
  25805. void resized()
  25806. {
  25807. innerWrapper->setSize (getWidth(), getHeight());
  25808. }
  25809. bool keyStateChanged (bool)
  25810. {
  25811. return false;
  25812. }
  25813. bool keyPressed (const KeyPress&)
  25814. {
  25815. return false;
  25816. }
  25817. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25818. AudioUnitCarbonView getViewComponent()
  25819. {
  25820. if (viewComponent == 0 && componentRecord != 0)
  25821. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25822. return viewComponent;
  25823. }
  25824. void closeViewComponent()
  25825. {
  25826. if (viewComponent != 0)
  25827. {
  25828. log ("Closing AU GUI: " + plugin.getName());
  25829. CloseComponent (viewComponent);
  25830. viewComponent = 0;
  25831. }
  25832. }
  25833. private:
  25834. AudioUnitPluginInstance& plugin;
  25835. ComponentRecord* componentRecord;
  25836. AudioUnitCarbonView viewComponent;
  25837. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25838. {
  25839. public:
  25840. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25841. : owner (owner_)
  25842. {
  25843. }
  25844. ~InnerWrapperComponent()
  25845. {
  25846. deleteWindow();
  25847. }
  25848. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25849. {
  25850. log ("Opening AU GUI: " + owner->plugin.getName());
  25851. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25852. if (viewComponent == 0)
  25853. return 0;
  25854. Float32Point pos = { 0, 0 };
  25855. Float32Point size = { 250, 200 };
  25856. HIViewRef pluginView = 0;
  25857. AudioUnitCarbonViewCreate (viewComponent,
  25858. owner->getAudioUnit(),
  25859. windowRef,
  25860. rootView,
  25861. &pos,
  25862. &size,
  25863. (ControlRef*) &pluginView);
  25864. return pluginView;
  25865. }
  25866. void removeView (HIViewRef)
  25867. {
  25868. owner->closeViewComponent();
  25869. }
  25870. private:
  25871. AudioUnitPluginWindowCarbon* const owner;
  25872. };
  25873. friend class InnerWrapperComponent;
  25874. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25875. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  25876. };
  25877. #endif
  25878. bool AudioUnitPluginInstance::hasEditor() const
  25879. {
  25880. return true;
  25881. }
  25882. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25883. {
  25884. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25885. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25886. w = 0;
  25887. #if JUCE_SUPPORT_CARBON
  25888. if (w == 0)
  25889. {
  25890. w = new AudioUnitPluginWindowCarbon (*this);
  25891. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25892. w = 0;
  25893. }
  25894. #endif
  25895. if (w == 0)
  25896. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25897. return w.release();
  25898. }
  25899. const String AudioUnitPluginInstance::getCategory() const
  25900. {
  25901. const char* result = 0;
  25902. switch (componentDesc.componentType)
  25903. {
  25904. case kAudioUnitType_Effect:
  25905. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  25906. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  25907. case kAudioUnitType_Generator: result = "Generator"; break;
  25908. case kAudioUnitType_Panner: result = "Panner"; break;
  25909. default: break;
  25910. }
  25911. return result;
  25912. }
  25913. int AudioUnitPluginInstance::getNumParameters()
  25914. {
  25915. return parameterIds.size();
  25916. }
  25917. float AudioUnitPluginInstance::getParameter (int index)
  25918. {
  25919. const ScopedLock sl (lock);
  25920. Float32 value = 0.0f;
  25921. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25922. {
  25923. AudioUnitGetParameter (audioUnit,
  25924. (UInt32) parameterIds.getUnchecked (index),
  25925. kAudioUnitScope_Global, 0,
  25926. &value);
  25927. }
  25928. return value;
  25929. }
  25930. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25931. {
  25932. const ScopedLock sl (lock);
  25933. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25934. {
  25935. AudioUnitSetParameter (audioUnit,
  25936. (UInt32) parameterIds.getUnchecked (index),
  25937. kAudioUnitScope_Global, 0,
  25938. newValue, 0);
  25939. }
  25940. }
  25941. const String AudioUnitPluginInstance::getParameterName (int index)
  25942. {
  25943. AudioUnitParameterInfo info;
  25944. zerostruct (info);
  25945. UInt32 sz = sizeof (info);
  25946. String name;
  25947. if (AudioUnitGetProperty (audioUnit,
  25948. kAudioUnitProperty_ParameterInfo,
  25949. kAudioUnitScope_Global,
  25950. parameterIds [index], &info, &sz) == noErr)
  25951. {
  25952. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25953. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25954. else
  25955. name = String (info.name, sizeof (info.name));
  25956. }
  25957. return name;
  25958. }
  25959. const String AudioUnitPluginInstance::getParameterText (int index)
  25960. {
  25961. return String (getParameter (index));
  25962. }
  25963. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25964. {
  25965. AudioUnitParameterInfo info;
  25966. UInt32 sz = sizeof (info);
  25967. if (AudioUnitGetProperty (audioUnit,
  25968. kAudioUnitProperty_ParameterInfo,
  25969. kAudioUnitScope_Global,
  25970. parameterIds [index], &info, &sz) == noErr)
  25971. {
  25972. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25973. }
  25974. return true;
  25975. }
  25976. int AudioUnitPluginInstance::getNumPrograms()
  25977. {
  25978. CFArrayRef presets;
  25979. UInt32 sz = sizeof (CFArrayRef);
  25980. int num = 0;
  25981. if (AudioUnitGetProperty (audioUnit,
  25982. kAudioUnitProperty_FactoryPresets,
  25983. kAudioUnitScope_Global,
  25984. 0, &presets, &sz) == noErr)
  25985. {
  25986. num = (int) CFArrayGetCount (presets);
  25987. CFRelease (presets);
  25988. }
  25989. return num;
  25990. }
  25991. int AudioUnitPluginInstance::getCurrentProgram()
  25992. {
  25993. AUPreset current;
  25994. current.presetNumber = 0;
  25995. UInt32 sz = sizeof (AUPreset);
  25996. AudioUnitGetProperty (audioUnit,
  25997. kAudioUnitProperty_FactoryPresets,
  25998. kAudioUnitScope_Global,
  25999. 0, &current, &sz);
  26000. return current.presetNumber;
  26001. }
  26002. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26003. {
  26004. AUPreset current;
  26005. current.presetNumber = newIndex;
  26006. current.presetName = 0;
  26007. AudioUnitSetProperty (audioUnit,
  26008. kAudioUnitProperty_FactoryPresets,
  26009. kAudioUnitScope_Global,
  26010. 0, &current, sizeof (AUPreset));
  26011. }
  26012. const String AudioUnitPluginInstance::getProgramName (int index)
  26013. {
  26014. String s;
  26015. CFArrayRef presets;
  26016. UInt32 sz = sizeof (CFArrayRef);
  26017. if (AudioUnitGetProperty (audioUnit,
  26018. kAudioUnitProperty_FactoryPresets,
  26019. kAudioUnitScope_Global,
  26020. 0, &presets, &sz) == noErr)
  26021. {
  26022. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26023. {
  26024. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26025. if (p != 0 && p->presetNumber == index)
  26026. {
  26027. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26028. break;
  26029. }
  26030. }
  26031. CFRelease (presets);
  26032. }
  26033. return s;
  26034. }
  26035. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26036. {
  26037. jassertfalse; // xxx not implemented!
  26038. }
  26039. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26040. {
  26041. if (isPositiveAndBelow (index, getNumInputChannels()))
  26042. return "Input " + String (index + 1);
  26043. return String::empty;
  26044. }
  26045. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26046. {
  26047. if (! isPositiveAndBelow (index, getNumInputChannels()))
  26048. return false;
  26049. return true;
  26050. }
  26051. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26052. {
  26053. if (isPositiveAndBelow (index, getNumOutputChannels()))
  26054. return "Output " + String (index + 1);
  26055. return String::empty;
  26056. }
  26057. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26058. {
  26059. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  26060. return false;
  26061. return true;
  26062. }
  26063. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26064. {
  26065. getCurrentProgramStateInformation (destData);
  26066. }
  26067. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26068. {
  26069. CFPropertyListRef propertyList = 0;
  26070. UInt32 sz = sizeof (CFPropertyListRef);
  26071. if (AudioUnitGetProperty (audioUnit,
  26072. kAudioUnitProperty_ClassInfo,
  26073. kAudioUnitScope_Global,
  26074. 0, &propertyList, &sz) == noErr)
  26075. {
  26076. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26077. CFWriteStreamOpen (stream);
  26078. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26079. CFWriteStreamClose (stream);
  26080. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26081. destData.setSize (bytesWritten);
  26082. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26083. CFRelease (data);
  26084. CFRelease (stream);
  26085. CFRelease (propertyList);
  26086. }
  26087. }
  26088. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26089. {
  26090. setCurrentProgramStateInformation (data, sizeInBytes);
  26091. }
  26092. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26093. {
  26094. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26095. (const UInt8*) data,
  26096. sizeInBytes,
  26097. kCFAllocatorNull);
  26098. CFReadStreamOpen (stream);
  26099. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26100. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26101. stream,
  26102. 0,
  26103. kCFPropertyListImmutable,
  26104. &format,
  26105. 0);
  26106. CFRelease (stream);
  26107. if (propertyList != 0)
  26108. AudioUnitSetProperty (audioUnit,
  26109. kAudioUnitProperty_ClassInfo,
  26110. kAudioUnitScope_Global,
  26111. 0, &propertyList, sizeof (propertyList));
  26112. }
  26113. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26114. {
  26115. }
  26116. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26117. {
  26118. }
  26119. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26120. const String& fileOrIdentifier)
  26121. {
  26122. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26123. return;
  26124. PluginDescription desc;
  26125. desc.fileOrIdentifier = fileOrIdentifier;
  26126. desc.uid = 0;
  26127. try
  26128. {
  26129. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26130. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26131. if (auInstance != 0)
  26132. {
  26133. auInstance->fillInPluginDescription (desc);
  26134. results.add (new PluginDescription (desc));
  26135. }
  26136. }
  26137. catch (...)
  26138. {
  26139. // crashed while loading...
  26140. }
  26141. }
  26142. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26143. {
  26144. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26145. {
  26146. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26147. if (result->audioUnit != 0)
  26148. {
  26149. result->initialise();
  26150. return result.release();
  26151. }
  26152. }
  26153. return 0;
  26154. }
  26155. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26156. const bool /*recursive*/)
  26157. {
  26158. StringArray result;
  26159. ComponentRecord* comp = 0;
  26160. ComponentDescription desc;
  26161. zerostruct (desc);
  26162. for (;;)
  26163. {
  26164. zerostruct (desc);
  26165. comp = FindNextComponent (comp, &desc);
  26166. if (comp == 0)
  26167. break;
  26168. GetComponentInfo (comp, &desc, 0, 0, 0);
  26169. if (desc.componentType == kAudioUnitType_MusicDevice
  26170. || desc.componentType == kAudioUnitType_MusicEffect
  26171. || desc.componentType == kAudioUnitType_Effect
  26172. || desc.componentType == kAudioUnitType_Generator
  26173. || desc.componentType == kAudioUnitType_Panner)
  26174. {
  26175. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26176. DBG (s);
  26177. result.add (s);
  26178. }
  26179. }
  26180. return result;
  26181. }
  26182. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26183. {
  26184. ComponentDescription desc;
  26185. String name, version, manufacturer;
  26186. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26187. return FindNextComponent (0, &desc) != 0;
  26188. const File f (fileOrIdentifier);
  26189. return f.hasFileExtension (".component")
  26190. && f.isDirectory();
  26191. }
  26192. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26193. {
  26194. ComponentDescription desc;
  26195. String name, version, manufacturer;
  26196. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26197. if (name.isEmpty())
  26198. name = fileOrIdentifier;
  26199. return name;
  26200. }
  26201. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26202. {
  26203. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26204. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26205. else
  26206. return File (desc.fileOrIdentifier).exists();
  26207. }
  26208. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26209. {
  26210. return FileSearchPath ("/(Default AudioUnit locations)");
  26211. }
  26212. #endif
  26213. END_JUCE_NAMESPACE
  26214. #undef log
  26215. #endif
  26216. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26217. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26218. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26219. #define JUCE_MAC_VST_INCLUDED 1
  26220. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26221. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26222. #if JUCE_WINDOWS
  26223. #undef _WIN32_WINNT
  26224. #define _WIN32_WINNT 0x500
  26225. #undef STRICT
  26226. #define STRICT
  26227. #include <windows.h>
  26228. #include <float.h>
  26229. #pragma warning (disable : 4312 4355)
  26230. #elif JUCE_LINUX
  26231. #include <float.h>
  26232. #include <sys/time.h>
  26233. #include <X11/Xlib.h>
  26234. #include <X11/Xutil.h>
  26235. #include <X11/Xatom.h>
  26236. #undef Font
  26237. #undef KeyPress
  26238. #undef Drawable
  26239. #undef Time
  26240. #else
  26241. #include <Cocoa/Cocoa.h>
  26242. #include <Carbon/Carbon.h>
  26243. #endif
  26244. #if ! (JUCE_MAC && JUCE_64BIT)
  26245. BEGIN_JUCE_NAMESPACE
  26246. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26247. #endif
  26248. #undef PRAGMA_ALIGN_SUPPORTED
  26249. #define VST_FORCE_DEPRECATED 0
  26250. #if JUCE_MSVC
  26251. #pragma warning (push)
  26252. #pragma warning (disable: 4996)
  26253. #endif
  26254. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26255. your include path if you want to add VST support.
  26256. If you're not interested in VSTs, you can disable them by changing the
  26257. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26258. */
  26259. #include <pluginterfaces/vst2.x/aeffectx.h>
  26260. #if JUCE_MSVC
  26261. #pragma warning (pop)
  26262. #endif
  26263. #if JUCE_LINUX
  26264. #define Font JUCE_NAMESPACE::Font
  26265. #define KeyPress JUCE_NAMESPACE::KeyPress
  26266. #define Drawable JUCE_NAMESPACE::Drawable
  26267. #define Time JUCE_NAMESPACE::Time
  26268. #endif
  26269. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26270. #ifdef __aeffect__
  26271. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26272. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26273. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26274. events to the list.
  26275. This is used by both the VST hosting code and the plugin wrapper.
  26276. */
  26277. class VSTMidiEventList
  26278. {
  26279. public:
  26280. VSTMidiEventList()
  26281. : numEventsUsed (0), numEventsAllocated (0)
  26282. {
  26283. }
  26284. ~VSTMidiEventList()
  26285. {
  26286. freeEvents();
  26287. }
  26288. void clear()
  26289. {
  26290. numEventsUsed = 0;
  26291. if (events != 0)
  26292. events->numEvents = 0;
  26293. }
  26294. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26295. {
  26296. ensureSize (numEventsUsed + 1);
  26297. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26298. events->numEvents = ++numEventsUsed;
  26299. if (numBytes <= 4)
  26300. {
  26301. if (e->type == kVstSysExType)
  26302. {
  26303. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26304. e->type = kVstMidiType;
  26305. e->byteSize = sizeof (VstMidiEvent);
  26306. e->noteLength = 0;
  26307. e->noteOffset = 0;
  26308. e->detune = 0;
  26309. e->noteOffVelocity = 0;
  26310. }
  26311. e->deltaFrames = frameOffset;
  26312. memcpy (e->midiData, midiData, numBytes);
  26313. }
  26314. else
  26315. {
  26316. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26317. if (se->type == kVstSysExType)
  26318. delete[] se->sysexDump;
  26319. se->sysexDump = new char [numBytes];
  26320. memcpy (se->sysexDump, midiData, numBytes);
  26321. se->type = kVstSysExType;
  26322. se->byteSize = sizeof (VstMidiSysexEvent);
  26323. se->deltaFrames = frameOffset;
  26324. se->flags = 0;
  26325. se->dumpBytes = numBytes;
  26326. se->resvd1 = 0;
  26327. se->resvd2 = 0;
  26328. }
  26329. }
  26330. // Handy method to pull the events out of an event buffer supplied by the host
  26331. // or plugin.
  26332. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26333. {
  26334. for (int i = 0; i < events->numEvents; ++i)
  26335. {
  26336. const VstEvent* const e = events->events[i];
  26337. if (e != 0)
  26338. {
  26339. if (e->type == kVstMidiType)
  26340. {
  26341. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26342. 4, e->deltaFrames);
  26343. }
  26344. else if (e->type == kVstSysExType)
  26345. {
  26346. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26347. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26348. e->deltaFrames);
  26349. }
  26350. }
  26351. }
  26352. }
  26353. void ensureSize (int numEventsNeeded)
  26354. {
  26355. if (numEventsNeeded > numEventsAllocated)
  26356. {
  26357. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26358. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26359. if (events == 0)
  26360. events.calloc (size, 1);
  26361. else
  26362. events.realloc (size, 1);
  26363. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26364. {
  26365. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26366. (int) sizeof (VstMidiSysexEvent)));
  26367. e->type = kVstMidiType;
  26368. e->byteSize = sizeof (VstMidiEvent);
  26369. events->events[i] = (VstEvent*) e;
  26370. }
  26371. numEventsAllocated = numEventsNeeded;
  26372. }
  26373. }
  26374. void freeEvents()
  26375. {
  26376. if (events != 0)
  26377. {
  26378. for (int i = numEventsAllocated; --i >= 0;)
  26379. {
  26380. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26381. if (e->type == kVstSysExType)
  26382. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26383. juce_free (e);
  26384. }
  26385. events.free();
  26386. numEventsUsed = 0;
  26387. numEventsAllocated = 0;
  26388. }
  26389. }
  26390. HeapBlock <VstEvents> events;
  26391. private:
  26392. int numEventsUsed, numEventsAllocated;
  26393. };
  26394. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26395. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26396. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26397. #if ! JUCE_WINDOWS
  26398. static void _fpreset() {}
  26399. static void _clearfp() {}
  26400. #endif
  26401. extern void juce_callAnyTimersSynchronously();
  26402. const int fxbVersionNum = 1;
  26403. struct fxProgram
  26404. {
  26405. long chunkMagic; // 'CcnK'
  26406. long byteSize; // of this chunk, excl. magic + byteSize
  26407. long fxMagic; // 'FxCk'
  26408. long version;
  26409. long fxID; // fx unique id
  26410. long fxVersion;
  26411. long numParams;
  26412. char prgName[28];
  26413. float params[1]; // variable no. of parameters
  26414. };
  26415. struct fxSet
  26416. {
  26417. long chunkMagic; // 'CcnK'
  26418. long byteSize; // of this chunk, excl. magic + byteSize
  26419. long fxMagic; // 'FxBk'
  26420. long version;
  26421. long fxID; // fx unique id
  26422. long fxVersion;
  26423. long numPrograms;
  26424. char future[128];
  26425. fxProgram programs[1]; // variable no. of programs
  26426. };
  26427. struct fxChunkSet
  26428. {
  26429. long chunkMagic; // 'CcnK'
  26430. long byteSize; // of this chunk, excl. magic + byteSize
  26431. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26432. long version;
  26433. long fxID; // fx unique id
  26434. long fxVersion;
  26435. long numPrograms;
  26436. char future[128];
  26437. long chunkSize;
  26438. char chunk[8]; // variable
  26439. };
  26440. struct fxProgramSet
  26441. {
  26442. long chunkMagic; // 'CcnK'
  26443. long byteSize; // of this chunk, excl. magic + byteSize
  26444. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26445. long version;
  26446. long fxID; // fx unique id
  26447. long fxVersion;
  26448. long numPrograms;
  26449. char name[28];
  26450. long chunkSize;
  26451. char chunk[8]; // variable
  26452. };
  26453. namespace
  26454. {
  26455. long vst_swap (const long x) throw()
  26456. {
  26457. #ifdef JUCE_LITTLE_ENDIAN
  26458. return (long) ByteOrder::swap ((uint32) x);
  26459. #else
  26460. return x;
  26461. #endif
  26462. }
  26463. float vst_swapFloat (const float x) throw()
  26464. {
  26465. #ifdef JUCE_LITTLE_ENDIAN
  26466. union { uint32 asInt; float asFloat; } n;
  26467. n.asFloat = x;
  26468. n.asInt = ByteOrder::swap (n.asInt);
  26469. return n.asFloat;
  26470. #else
  26471. return x;
  26472. #endif
  26473. }
  26474. double getVSTHostTimeNanoseconds()
  26475. {
  26476. #if JUCE_WINDOWS
  26477. return timeGetTime() * 1000000.0;
  26478. #elif JUCE_LINUX
  26479. timeval micro;
  26480. gettimeofday (&micro, 0);
  26481. return micro.tv_usec * 1000.0;
  26482. #elif JUCE_MAC
  26483. UnsignedWide micro;
  26484. Microseconds (&micro);
  26485. return micro.lo * 1000.0;
  26486. #endif
  26487. }
  26488. }
  26489. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26490. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26491. static int shellUIDToCreate = 0;
  26492. static int insideVSTCallback = 0;
  26493. class VSTPluginWindow;
  26494. // Change this to disable logging of various VST activities
  26495. #ifndef VST_LOGGING
  26496. #define VST_LOGGING 1
  26497. #endif
  26498. #if VST_LOGGING
  26499. #define log(a) Logger::writeToLog(a);
  26500. #else
  26501. #define log(a)
  26502. #endif
  26503. #if JUCE_MAC && JUCE_PPC
  26504. static void* NewCFMFromMachO (void* const machofp) throw()
  26505. {
  26506. void* result = (void*) new char[8];
  26507. ((void**) result)[0] = machofp;
  26508. ((void**) result)[1] = result;
  26509. return result;
  26510. }
  26511. #endif
  26512. #if JUCE_LINUX
  26513. extern Display* display;
  26514. extern XContext windowHandleXContext;
  26515. typedef void (*EventProcPtr) (XEvent* ev);
  26516. static bool xErrorTriggered;
  26517. namespace
  26518. {
  26519. int temporaryErrorHandler (Display*, XErrorEvent*)
  26520. {
  26521. xErrorTriggered = true;
  26522. return 0;
  26523. }
  26524. int getPropertyFromXWindow (Window handle, Atom atom)
  26525. {
  26526. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26527. xErrorTriggered = false;
  26528. int userSize;
  26529. unsigned long bytes, userCount;
  26530. unsigned char* data;
  26531. Atom userType;
  26532. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26533. &userType, &userSize, &userCount, &bytes, &data);
  26534. XSetErrorHandler (oldErrorHandler);
  26535. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26536. : 0;
  26537. }
  26538. Window getChildWindow (Window windowToCheck)
  26539. {
  26540. Window rootWindow, parentWindow;
  26541. Window* childWindows;
  26542. unsigned int numChildren;
  26543. XQueryTree (display,
  26544. windowToCheck,
  26545. &rootWindow,
  26546. &parentWindow,
  26547. &childWindows,
  26548. &numChildren);
  26549. if (numChildren > 0)
  26550. return childWindows [0];
  26551. return 0;
  26552. }
  26553. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26554. {
  26555. if (e.mods.isLeftButtonDown())
  26556. {
  26557. ev.xbutton.button = Button1;
  26558. ev.xbutton.state |= Button1Mask;
  26559. }
  26560. else if (e.mods.isRightButtonDown())
  26561. {
  26562. ev.xbutton.button = Button3;
  26563. ev.xbutton.state |= Button3Mask;
  26564. }
  26565. else if (e.mods.isMiddleButtonDown())
  26566. {
  26567. ev.xbutton.button = Button2;
  26568. ev.xbutton.state |= Button2Mask;
  26569. }
  26570. }
  26571. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26572. {
  26573. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26574. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26575. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26576. }
  26577. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26578. {
  26579. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26580. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26581. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26582. }
  26583. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26584. {
  26585. if (increment < 0)
  26586. {
  26587. ev.xbutton.button = Button5;
  26588. ev.xbutton.state |= Button5Mask;
  26589. }
  26590. else if (increment > 0)
  26591. {
  26592. ev.xbutton.button = Button4;
  26593. ev.xbutton.state |= Button4Mask;
  26594. }
  26595. }
  26596. }
  26597. #endif
  26598. class ModuleHandle : public ReferenceCountedObject
  26599. {
  26600. public:
  26601. File file;
  26602. MainCall moduleMain;
  26603. String pluginName;
  26604. static Array <ModuleHandle*>& getActiveModules()
  26605. {
  26606. static Array <ModuleHandle*> activeModules;
  26607. return activeModules;
  26608. }
  26609. static ModuleHandle* findOrCreateModule (const File& file)
  26610. {
  26611. for (int i = getActiveModules().size(); --i >= 0;)
  26612. {
  26613. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26614. if (module->file == file)
  26615. return module;
  26616. }
  26617. _fpreset(); // (doesn't do any harm)
  26618. ++insideVSTCallback;
  26619. shellUIDToCreate = 0;
  26620. log ("Attempting to load VST: " + file.getFullPathName());
  26621. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26622. if (! m->open())
  26623. m = 0;
  26624. --insideVSTCallback;
  26625. _fpreset(); // (doesn't do any harm)
  26626. return m.release();
  26627. }
  26628. ModuleHandle (const File& file_)
  26629. : file (file_),
  26630. moduleMain (0),
  26631. #if JUCE_WINDOWS || JUCE_LINUX
  26632. hModule (0)
  26633. #elif JUCE_MAC
  26634. fragId (0),
  26635. resHandle (0),
  26636. bundleRef (0),
  26637. resFileId (0)
  26638. #endif
  26639. {
  26640. getActiveModules().add (this);
  26641. #if JUCE_WINDOWS || JUCE_LINUX
  26642. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26643. #elif JUCE_MAC
  26644. FSRef ref;
  26645. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26646. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26647. #endif
  26648. }
  26649. ~ModuleHandle()
  26650. {
  26651. getActiveModules().removeValue (this);
  26652. close();
  26653. }
  26654. #if JUCE_WINDOWS || JUCE_LINUX
  26655. void* hModule;
  26656. String fullParentDirectoryPathName;
  26657. bool open()
  26658. {
  26659. #if JUCE_WINDOWS
  26660. static bool timePeriodSet = false;
  26661. if (! timePeriodSet)
  26662. {
  26663. timePeriodSet = true;
  26664. timeBeginPeriod (2);
  26665. }
  26666. #endif
  26667. pluginName = file.getFileNameWithoutExtension();
  26668. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26669. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26670. if (moduleMain == 0)
  26671. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26672. return moduleMain != 0;
  26673. }
  26674. void close()
  26675. {
  26676. _fpreset(); // (doesn't do any harm)
  26677. PlatformUtilities::freeDynamicLibrary (hModule);
  26678. }
  26679. void closeEffect (AEffect* eff)
  26680. {
  26681. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26682. }
  26683. #else
  26684. CFragConnectionID fragId;
  26685. Handle resHandle;
  26686. CFBundleRef bundleRef;
  26687. FSSpec parentDirFSSpec;
  26688. short resFileId;
  26689. bool open()
  26690. {
  26691. bool ok = false;
  26692. const String filename (file.getFullPathName());
  26693. if (file.hasFileExtension (".vst"))
  26694. {
  26695. const char* const utf8 = filename.toUTF8();
  26696. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26697. strlen (utf8), file.isDirectory());
  26698. if (url != 0)
  26699. {
  26700. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26701. CFRelease (url);
  26702. if (bundleRef != 0)
  26703. {
  26704. if (CFBundleLoadExecutable (bundleRef))
  26705. {
  26706. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26707. if (moduleMain == 0)
  26708. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26709. if (moduleMain != 0)
  26710. {
  26711. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26712. if (name != 0)
  26713. {
  26714. if (CFGetTypeID (name) == CFStringGetTypeID())
  26715. {
  26716. char buffer[1024];
  26717. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26718. pluginName = buffer;
  26719. }
  26720. }
  26721. if (pluginName.isEmpty())
  26722. pluginName = file.getFileNameWithoutExtension();
  26723. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26724. ok = true;
  26725. }
  26726. }
  26727. if (! ok)
  26728. {
  26729. CFBundleUnloadExecutable (bundleRef);
  26730. CFRelease (bundleRef);
  26731. bundleRef = 0;
  26732. }
  26733. }
  26734. }
  26735. }
  26736. #if JUCE_PPC
  26737. else
  26738. {
  26739. FSRef fn;
  26740. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26741. {
  26742. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26743. if (resFileId != -1)
  26744. {
  26745. const int numEffs = Count1Resources ('aEff');
  26746. for (int i = 0; i < numEffs; ++i)
  26747. {
  26748. resHandle = Get1IndResource ('aEff', i + 1);
  26749. if (resHandle != 0)
  26750. {
  26751. OSType type;
  26752. Str255 name;
  26753. SInt16 id;
  26754. GetResInfo (resHandle, &id, &type, name);
  26755. pluginName = String ((const char*) name + 1, name[0]);
  26756. DetachResource (resHandle);
  26757. HLock (resHandle);
  26758. Ptr ptr;
  26759. Str255 errorText;
  26760. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26761. name, kPrivateCFragCopy,
  26762. &fragId, &ptr, errorText);
  26763. if (err == noErr)
  26764. {
  26765. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26766. ok = true;
  26767. }
  26768. else
  26769. {
  26770. HUnlock (resHandle);
  26771. }
  26772. break;
  26773. }
  26774. }
  26775. if (! ok)
  26776. CloseResFile (resFileId);
  26777. }
  26778. }
  26779. }
  26780. #endif
  26781. return ok;
  26782. }
  26783. void close()
  26784. {
  26785. #if JUCE_PPC
  26786. if (fragId != 0)
  26787. {
  26788. if (moduleMain != 0)
  26789. disposeMachOFromCFM ((void*) moduleMain);
  26790. CloseConnection (&fragId);
  26791. HUnlock (resHandle);
  26792. if (resFileId != 0)
  26793. CloseResFile (resFileId);
  26794. }
  26795. else
  26796. #endif
  26797. if (bundleRef != 0)
  26798. {
  26799. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26800. if (CFGetRetainCount (bundleRef) == 1)
  26801. CFBundleUnloadExecutable (bundleRef);
  26802. if (CFGetRetainCount (bundleRef) > 0)
  26803. CFRelease (bundleRef);
  26804. }
  26805. }
  26806. void closeEffect (AEffect* eff)
  26807. {
  26808. #if JUCE_PPC
  26809. if (fragId != 0)
  26810. {
  26811. Array<void*> thingsToDelete;
  26812. thingsToDelete.add ((void*) eff->dispatcher);
  26813. thingsToDelete.add ((void*) eff->process);
  26814. thingsToDelete.add ((void*) eff->setParameter);
  26815. thingsToDelete.add ((void*) eff->getParameter);
  26816. thingsToDelete.add ((void*) eff->processReplacing);
  26817. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26818. for (int i = thingsToDelete.size(); --i >= 0;)
  26819. disposeMachOFromCFM (thingsToDelete[i]);
  26820. }
  26821. else
  26822. #endif
  26823. {
  26824. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26825. }
  26826. }
  26827. #if JUCE_PPC
  26828. static void* newMachOFromCFM (void* cfmfp)
  26829. {
  26830. if (cfmfp == 0)
  26831. return 0;
  26832. UInt32* const mfp = new UInt32[6];
  26833. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26834. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26835. mfp[2] = 0x800c0000;
  26836. mfp[3] = 0x804c0004;
  26837. mfp[4] = 0x7c0903a6;
  26838. mfp[5] = 0x4e800420;
  26839. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26840. return mfp;
  26841. }
  26842. static void disposeMachOFromCFM (void* ptr)
  26843. {
  26844. delete[] static_cast <UInt32*> (ptr);
  26845. }
  26846. void coerceAEffectFunctionCalls (AEffect* eff)
  26847. {
  26848. if (fragId != 0)
  26849. {
  26850. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26851. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26852. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26853. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26854. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26855. }
  26856. }
  26857. #endif
  26858. #endif
  26859. private:
  26860. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  26861. };
  26862. /**
  26863. An instance of a plugin, created by a VSTPluginFormat.
  26864. */
  26865. class VSTPluginInstance : public AudioPluginInstance,
  26866. private Timer,
  26867. private AsyncUpdater
  26868. {
  26869. public:
  26870. ~VSTPluginInstance();
  26871. // AudioPluginInstance methods:
  26872. void fillInPluginDescription (PluginDescription& desc) const
  26873. {
  26874. desc.name = name;
  26875. {
  26876. char buffer [512];
  26877. zerostruct (buffer);
  26878. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26879. desc.descriptiveName = String (buffer).trim();
  26880. if (desc.descriptiveName.isEmpty())
  26881. desc.descriptiveName = name;
  26882. }
  26883. desc.fileOrIdentifier = module->file.getFullPathName();
  26884. desc.uid = getUID();
  26885. desc.lastFileModTime = module->file.getLastModificationTime();
  26886. desc.pluginFormatName = "VST";
  26887. desc.category = getCategory();
  26888. {
  26889. char buffer [kVstMaxVendorStrLen + 8];
  26890. zerostruct (buffer);
  26891. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26892. desc.manufacturerName = buffer;
  26893. }
  26894. desc.version = getVersion();
  26895. desc.numInputChannels = getNumInputChannels();
  26896. desc.numOutputChannels = getNumOutputChannels();
  26897. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26898. }
  26899. void* getPlatformSpecificData() { return effect; }
  26900. const String getName() const { return name; }
  26901. int getUID() const;
  26902. bool acceptsMidi() const { return wantsMidiMessages; }
  26903. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26904. // AudioProcessor methods:
  26905. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26906. void releaseResources();
  26907. void processBlock (AudioSampleBuffer& buffer,
  26908. MidiBuffer& midiMessages);
  26909. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26910. AudioProcessorEditor* createEditor();
  26911. const String getInputChannelName (int index) const;
  26912. bool isInputChannelStereoPair (int index) const;
  26913. const String getOutputChannelName (int index) const;
  26914. bool isOutputChannelStereoPair (int index) const;
  26915. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26916. float getParameter (int index);
  26917. void setParameter (int index, float newValue);
  26918. const String getParameterName (int index);
  26919. const String getParameterText (int index);
  26920. bool isParameterAutomatable (int index) const;
  26921. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26922. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26923. void setCurrentProgram (int index);
  26924. const String getProgramName (int index);
  26925. void changeProgramName (int index, const String& newName);
  26926. void getStateInformation (MemoryBlock& destData);
  26927. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26928. void setStateInformation (const void* data, int sizeInBytes);
  26929. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26930. void timerCallback();
  26931. void handleAsyncUpdate();
  26932. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26933. private:
  26934. friend class VSTPluginWindow;
  26935. friend class VSTPluginFormat;
  26936. AEffect* effect;
  26937. String name;
  26938. CriticalSection lock;
  26939. bool wantsMidiMessages, initialised, isPowerOn;
  26940. mutable StringArray programNames;
  26941. AudioSampleBuffer tempBuffer;
  26942. CriticalSection midiInLock;
  26943. MidiBuffer incomingMidi;
  26944. VSTMidiEventList midiEventsToSend;
  26945. VstTimeInfo vstHostTime;
  26946. ReferenceCountedObjectPtr <ModuleHandle> module;
  26947. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26948. bool restoreProgramSettings (const fxProgram* const prog);
  26949. const String getCurrentProgramName();
  26950. void setParamsInProgramBlock (fxProgram* const prog);
  26951. void updateStoredProgramNames();
  26952. void initialise();
  26953. void handleMidiFromPlugin (const VstEvents* const events);
  26954. void createTempParameterStore (MemoryBlock& dest);
  26955. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26956. const String getParameterLabel (int index) const;
  26957. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26958. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26959. void setChunkData (const char* data, int size, bool isPreset);
  26960. bool loadFromFXBFile (const void* data, int numBytes);
  26961. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26962. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26963. const String getVersion() const;
  26964. const String getCategory() const;
  26965. void setPower (const bool on);
  26966. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26967. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  26968. };
  26969. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26970. : effect (0),
  26971. wantsMidiMessages (false),
  26972. initialised (false),
  26973. isPowerOn (false),
  26974. tempBuffer (1, 1),
  26975. module (module_)
  26976. {
  26977. try
  26978. {
  26979. _fpreset();
  26980. ++insideVSTCallback;
  26981. name = module->pluginName;
  26982. log ("Creating VST instance: " + name);
  26983. #if JUCE_MAC
  26984. if (module->resFileId != 0)
  26985. UseResFile (module->resFileId);
  26986. #if JUCE_PPC
  26987. if (module->fragId != 0)
  26988. {
  26989. static void* audioMasterCoerced = 0;
  26990. if (audioMasterCoerced == 0)
  26991. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26992. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26993. }
  26994. else
  26995. #endif
  26996. #endif
  26997. {
  26998. effect = module->moduleMain (&audioMaster);
  26999. }
  27000. --insideVSTCallback;
  27001. if (effect != 0 && effect->magic == kEffectMagic)
  27002. {
  27003. #if JUCE_PPC
  27004. module->coerceAEffectFunctionCalls (effect);
  27005. #endif
  27006. jassert (effect->resvd2 == 0);
  27007. jassert (effect->object != 0);
  27008. _fpreset(); // some dodgy plugs fuck around with this
  27009. }
  27010. else
  27011. {
  27012. effect = 0;
  27013. }
  27014. }
  27015. catch (...)
  27016. {
  27017. --insideVSTCallback;
  27018. }
  27019. }
  27020. VSTPluginInstance::~VSTPluginInstance()
  27021. {
  27022. const ScopedLock sl (lock);
  27023. jassert (insideVSTCallback == 0);
  27024. if (effect != 0 && effect->magic == kEffectMagic)
  27025. {
  27026. try
  27027. {
  27028. #if JUCE_MAC
  27029. if (module->resFileId != 0)
  27030. UseResFile (module->resFileId);
  27031. #endif
  27032. // Must delete any editors before deleting the plugin instance!
  27033. jassert (getActiveEditor() == 0);
  27034. _fpreset(); // some dodgy plugs fuck around with this
  27035. module->closeEffect (effect);
  27036. }
  27037. catch (...)
  27038. {}
  27039. }
  27040. module = 0;
  27041. effect = 0;
  27042. }
  27043. void VSTPluginInstance::initialise()
  27044. {
  27045. if (initialised || effect == 0)
  27046. return;
  27047. log ("Initialising VST: " + module->pluginName);
  27048. initialised = true;
  27049. dispatch (effIdentify, 0, 0, 0, 0);
  27050. if (getSampleRate() > 0)
  27051. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27052. if (getBlockSize() > 0)
  27053. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27054. dispatch (effOpen, 0, 0, 0, 0);
  27055. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27056. getSampleRate(), getBlockSize());
  27057. if (getNumPrograms() > 1)
  27058. setCurrentProgram (0);
  27059. else
  27060. dispatch (effSetProgram, 0, 0, 0, 0);
  27061. int i;
  27062. for (i = effect->numInputs; --i >= 0;)
  27063. dispatch (effConnectInput, i, 1, 0, 0);
  27064. for (i = effect->numOutputs; --i >= 0;)
  27065. dispatch (effConnectOutput, i, 1, 0, 0);
  27066. updateStoredProgramNames();
  27067. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27068. setLatencySamples (effect->initialDelay);
  27069. }
  27070. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27071. int samplesPerBlockExpected)
  27072. {
  27073. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27074. sampleRate_, samplesPerBlockExpected);
  27075. setLatencySamples (effect->initialDelay);
  27076. vstHostTime.tempo = 120.0;
  27077. vstHostTime.timeSigNumerator = 4;
  27078. vstHostTime.timeSigDenominator = 4;
  27079. vstHostTime.sampleRate = sampleRate_;
  27080. vstHostTime.samplePos = 0;
  27081. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27082. initialise();
  27083. if (initialised)
  27084. {
  27085. wantsMidiMessages = wantsMidiMessages
  27086. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27087. if (wantsMidiMessages)
  27088. midiEventsToSend.ensureSize (256);
  27089. else
  27090. midiEventsToSend.freeEvents();
  27091. incomingMidi.clear();
  27092. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27093. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27094. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27095. if (! isPowerOn)
  27096. setPower (true);
  27097. // dodgy hack to force some plugins to initialise the sample rate..
  27098. if ((! hasEditor()) && getNumParameters() > 0)
  27099. {
  27100. const float old = getParameter (0);
  27101. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27102. setParameter (0, old);
  27103. }
  27104. dispatch (effStartProcess, 0, 0, 0, 0);
  27105. }
  27106. }
  27107. void VSTPluginInstance::releaseResources()
  27108. {
  27109. if (initialised)
  27110. {
  27111. dispatch (effStopProcess, 0, 0, 0, 0);
  27112. setPower (false);
  27113. }
  27114. tempBuffer.setSize (1, 1);
  27115. incomingMidi.clear();
  27116. midiEventsToSend.freeEvents();
  27117. }
  27118. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27119. MidiBuffer& midiMessages)
  27120. {
  27121. const int numSamples = buffer.getNumSamples();
  27122. if (initialised)
  27123. {
  27124. AudioPlayHead* playHead = getPlayHead();
  27125. if (playHead != 0)
  27126. {
  27127. AudioPlayHead::CurrentPositionInfo position;
  27128. playHead->getCurrentPosition (position);
  27129. vstHostTime.tempo = position.bpm;
  27130. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27131. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27132. vstHostTime.ppqPos = position.ppqPosition;
  27133. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27134. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27135. if (position.isPlaying)
  27136. vstHostTime.flags |= kVstTransportPlaying;
  27137. else
  27138. vstHostTime.flags &= ~kVstTransportPlaying;
  27139. }
  27140. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27141. if (wantsMidiMessages)
  27142. {
  27143. midiEventsToSend.clear();
  27144. midiEventsToSend.ensureSize (1);
  27145. MidiBuffer::Iterator iter (midiMessages);
  27146. const uint8* midiData;
  27147. int numBytesOfMidiData, samplePosition;
  27148. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27149. {
  27150. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27151. jlimit (0, numSamples - 1, samplePosition));
  27152. }
  27153. try
  27154. {
  27155. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27156. }
  27157. catch (...)
  27158. {}
  27159. }
  27160. _clearfp();
  27161. if ((effect->flags & effFlagsCanReplacing) != 0)
  27162. {
  27163. try
  27164. {
  27165. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27166. }
  27167. catch (...)
  27168. {}
  27169. }
  27170. else
  27171. {
  27172. tempBuffer.setSize (effect->numOutputs, numSamples);
  27173. tempBuffer.clear();
  27174. try
  27175. {
  27176. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27177. }
  27178. catch (...)
  27179. {}
  27180. for (int i = effect->numOutputs; --i >= 0;)
  27181. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27182. }
  27183. }
  27184. else
  27185. {
  27186. // Not initialised, so just bypass..
  27187. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27188. buffer.clear (i, 0, buffer.getNumSamples());
  27189. }
  27190. {
  27191. // copy any incoming midi..
  27192. const ScopedLock sl (midiInLock);
  27193. midiMessages.swapWith (incomingMidi);
  27194. incomingMidi.clear();
  27195. }
  27196. }
  27197. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27198. {
  27199. if (events != 0)
  27200. {
  27201. const ScopedLock sl (midiInLock);
  27202. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27203. }
  27204. }
  27205. static Array <VSTPluginWindow*> activeVSTWindows;
  27206. class VSTPluginWindow : public AudioProcessorEditor,
  27207. #if ! JUCE_MAC
  27208. public ComponentMovementWatcher,
  27209. #endif
  27210. public Timer
  27211. {
  27212. public:
  27213. VSTPluginWindow (VSTPluginInstance& plugin_)
  27214. : AudioProcessorEditor (&plugin_),
  27215. #if ! JUCE_MAC
  27216. ComponentMovementWatcher (this),
  27217. #endif
  27218. plugin (plugin_),
  27219. isOpen (false),
  27220. recursiveResize (false),
  27221. pluginWantsKeys (false),
  27222. pluginRefusesToResize (false),
  27223. alreadyInside (false)
  27224. {
  27225. #if JUCE_WINDOWS
  27226. sizeCheckCount = 0;
  27227. pluginHWND = 0;
  27228. #elif JUCE_LINUX
  27229. pluginWindow = None;
  27230. pluginProc = None;
  27231. #else
  27232. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27233. #endif
  27234. activeVSTWindows.add (this);
  27235. setSize (1, 1);
  27236. setOpaque (true);
  27237. setVisible (true);
  27238. }
  27239. ~VSTPluginWindow()
  27240. {
  27241. #if JUCE_MAC
  27242. innerWrapper = 0;
  27243. #else
  27244. closePluginWindow();
  27245. #endif
  27246. activeVSTWindows.removeValue (this);
  27247. plugin.editorBeingDeleted (this);
  27248. }
  27249. #if ! JUCE_MAC
  27250. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27251. {
  27252. if (recursiveResize)
  27253. return;
  27254. Component* const topComp = getTopLevelComponent();
  27255. if (topComp->getPeer() != 0)
  27256. {
  27257. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27258. recursiveResize = true;
  27259. #if JUCE_WINDOWS
  27260. if (pluginHWND != 0)
  27261. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27262. #elif JUCE_LINUX
  27263. if (pluginWindow != 0)
  27264. {
  27265. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27266. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27267. XMapRaised (display, pluginWindow);
  27268. }
  27269. #endif
  27270. recursiveResize = false;
  27271. }
  27272. }
  27273. void componentVisibilityChanged()
  27274. {
  27275. if (isShowing())
  27276. openPluginWindow();
  27277. else
  27278. closePluginWindow();
  27279. componentMovedOrResized (true, true);
  27280. }
  27281. void componentPeerChanged()
  27282. {
  27283. closePluginWindow();
  27284. openPluginWindow();
  27285. }
  27286. #endif
  27287. bool keyStateChanged (bool)
  27288. {
  27289. return pluginWantsKeys;
  27290. }
  27291. bool keyPressed (const KeyPress&)
  27292. {
  27293. return pluginWantsKeys;
  27294. }
  27295. #if JUCE_MAC
  27296. void paint (Graphics& g)
  27297. {
  27298. g.fillAll (Colours::black);
  27299. }
  27300. #else
  27301. void paint (Graphics& g)
  27302. {
  27303. if (isOpen)
  27304. {
  27305. ComponentPeer* const peer = getPeer();
  27306. if (peer != 0)
  27307. {
  27308. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27309. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27310. #if JUCE_LINUX
  27311. if (pluginWindow != 0)
  27312. {
  27313. const Rectangle<int> clip (g.getClipBounds());
  27314. XEvent ev;
  27315. zerostruct (ev);
  27316. ev.xexpose.type = Expose;
  27317. ev.xexpose.display = display;
  27318. ev.xexpose.window = pluginWindow;
  27319. ev.xexpose.x = clip.getX();
  27320. ev.xexpose.y = clip.getY();
  27321. ev.xexpose.width = clip.getWidth();
  27322. ev.xexpose.height = clip.getHeight();
  27323. sendEventToChild (&ev);
  27324. }
  27325. #endif
  27326. }
  27327. }
  27328. else
  27329. {
  27330. g.fillAll (Colours::black);
  27331. }
  27332. }
  27333. #endif
  27334. void timerCallback()
  27335. {
  27336. #if JUCE_WINDOWS
  27337. if (--sizeCheckCount <= 0)
  27338. {
  27339. sizeCheckCount = 10;
  27340. checkPluginWindowSize();
  27341. }
  27342. #endif
  27343. try
  27344. {
  27345. static bool reentrant = false;
  27346. if (! reentrant)
  27347. {
  27348. reentrant = true;
  27349. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27350. reentrant = false;
  27351. }
  27352. }
  27353. catch (...)
  27354. {}
  27355. }
  27356. void mouseDown (const MouseEvent& e)
  27357. {
  27358. #if JUCE_LINUX
  27359. if (pluginWindow == 0)
  27360. return;
  27361. toFront (true);
  27362. XEvent ev;
  27363. zerostruct (ev);
  27364. ev.xbutton.display = display;
  27365. ev.xbutton.type = ButtonPress;
  27366. ev.xbutton.window = pluginWindow;
  27367. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27368. ev.xbutton.time = CurrentTime;
  27369. ev.xbutton.x = e.x;
  27370. ev.xbutton.y = e.y;
  27371. ev.xbutton.x_root = e.getScreenX();
  27372. ev.xbutton.y_root = e.getScreenY();
  27373. translateJuceToXButtonModifiers (e, ev);
  27374. sendEventToChild (&ev);
  27375. #elif JUCE_WINDOWS
  27376. (void) e;
  27377. toFront (true);
  27378. #endif
  27379. }
  27380. void broughtToFront()
  27381. {
  27382. activeVSTWindows.removeValue (this);
  27383. activeVSTWindows.add (this);
  27384. #if JUCE_MAC
  27385. dispatch (effEditTop, 0, 0, 0, 0);
  27386. #endif
  27387. }
  27388. private:
  27389. VSTPluginInstance& plugin;
  27390. bool isOpen, recursiveResize;
  27391. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27392. #if JUCE_WINDOWS
  27393. HWND pluginHWND;
  27394. void* originalWndProc;
  27395. int sizeCheckCount;
  27396. #elif JUCE_LINUX
  27397. Window pluginWindow;
  27398. EventProcPtr pluginProc;
  27399. #endif
  27400. #if JUCE_MAC
  27401. void openPluginWindow (WindowRef parentWindow)
  27402. {
  27403. if (isOpen || parentWindow == 0)
  27404. return;
  27405. isOpen = true;
  27406. ERect* rect = 0;
  27407. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27408. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27409. // do this before and after like in the steinberg example
  27410. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27411. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27412. // Install keyboard hooks
  27413. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27414. // double-check it's not too tiny
  27415. int w = 250, h = 150;
  27416. if (rect != 0)
  27417. {
  27418. w = rect->right - rect->left;
  27419. h = rect->bottom - rect->top;
  27420. if (w == 0 || h == 0)
  27421. {
  27422. w = 250;
  27423. h = 150;
  27424. }
  27425. }
  27426. w = jmax (w, 32);
  27427. h = jmax (h, 32);
  27428. setSize (w, h);
  27429. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27430. repaint();
  27431. }
  27432. #else
  27433. void openPluginWindow()
  27434. {
  27435. if (isOpen || getWindowHandle() == 0)
  27436. return;
  27437. log ("Opening VST UI: " + plugin.name);
  27438. isOpen = true;
  27439. ERect* rect = 0;
  27440. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27441. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27442. // do this before and after like in the steinberg example
  27443. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27444. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27445. // Install keyboard hooks
  27446. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27447. #if JUCE_WINDOWS
  27448. originalWndProc = 0;
  27449. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27450. if (pluginHWND == 0)
  27451. {
  27452. isOpen = false;
  27453. setSize (300, 150);
  27454. return;
  27455. }
  27456. #pragma warning (push)
  27457. #pragma warning (disable: 4244)
  27458. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27459. if (! pluginWantsKeys)
  27460. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27461. #pragma warning (pop)
  27462. int w, h;
  27463. RECT r;
  27464. GetWindowRect (pluginHWND, &r);
  27465. w = r.right - r.left;
  27466. h = r.bottom - r.top;
  27467. if (rect != 0)
  27468. {
  27469. const int rw = rect->right - rect->left;
  27470. const int rh = rect->bottom - rect->top;
  27471. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27472. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27473. {
  27474. // very dodgy logic to decide which size is right.
  27475. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27476. {
  27477. SetWindowPos (pluginHWND, 0,
  27478. 0, 0, rw, rh,
  27479. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27480. GetWindowRect (pluginHWND, &r);
  27481. w = r.right - r.left;
  27482. h = r.bottom - r.top;
  27483. pluginRefusesToResize = (w != rw) || (h != rh);
  27484. w = rw;
  27485. h = rh;
  27486. }
  27487. }
  27488. }
  27489. #elif JUCE_LINUX
  27490. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27491. if (pluginWindow != 0)
  27492. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27493. XInternAtom (display, "_XEventProc", False));
  27494. int w = 250, h = 150;
  27495. if (rect != 0)
  27496. {
  27497. w = rect->right - rect->left;
  27498. h = rect->bottom - rect->top;
  27499. if (w == 0 || h == 0)
  27500. {
  27501. w = 250;
  27502. h = 150;
  27503. }
  27504. }
  27505. if (pluginWindow != 0)
  27506. XMapRaised (display, pluginWindow);
  27507. #endif
  27508. // double-check it's not too tiny
  27509. w = jmax (w, 32);
  27510. h = jmax (h, 32);
  27511. setSize (w, h);
  27512. #if JUCE_WINDOWS
  27513. checkPluginWindowSize();
  27514. #endif
  27515. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27516. repaint();
  27517. }
  27518. #endif
  27519. #if ! JUCE_MAC
  27520. void closePluginWindow()
  27521. {
  27522. if (isOpen)
  27523. {
  27524. log ("Closing VST UI: " + plugin.getName());
  27525. isOpen = false;
  27526. dispatch (effEditClose, 0, 0, 0, 0);
  27527. #if JUCE_WINDOWS
  27528. #pragma warning (push)
  27529. #pragma warning (disable: 4244)
  27530. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27531. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27532. #pragma warning (pop)
  27533. stopTimer();
  27534. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27535. DestroyWindow (pluginHWND);
  27536. pluginHWND = 0;
  27537. #elif JUCE_LINUX
  27538. stopTimer();
  27539. pluginWindow = 0;
  27540. pluginProc = 0;
  27541. #endif
  27542. }
  27543. }
  27544. #endif
  27545. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27546. {
  27547. return plugin.dispatch (opcode, index, value, ptr, opt);
  27548. }
  27549. #if JUCE_WINDOWS
  27550. void checkPluginWindowSize()
  27551. {
  27552. RECT r;
  27553. GetWindowRect (pluginHWND, &r);
  27554. const int w = r.right - r.left;
  27555. const int h = r.bottom - r.top;
  27556. if (isShowing() && w > 0 && h > 0
  27557. && (w != getWidth() || h != getHeight())
  27558. && ! pluginRefusesToResize)
  27559. {
  27560. setSize (w, h);
  27561. sizeCheckCount = 0;
  27562. }
  27563. }
  27564. // hooks to get keyboard events from VST windows..
  27565. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27566. {
  27567. for (int i = activeVSTWindows.size(); --i >= 0;)
  27568. {
  27569. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27570. if (w->pluginHWND == hW)
  27571. {
  27572. if (message == WM_CHAR
  27573. || message == WM_KEYDOWN
  27574. || message == WM_SYSKEYDOWN
  27575. || message == WM_KEYUP
  27576. || message == WM_SYSKEYUP
  27577. || message == WM_APPCOMMAND)
  27578. {
  27579. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27580. message, wParam, lParam);
  27581. }
  27582. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27583. (HWND) w->pluginHWND,
  27584. message,
  27585. wParam,
  27586. lParam);
  27587. }
  27588. }
  27589. return DefWindowProc (hW, message, wParam, lParam);
  27590. }
  27591. #endif
  27592. #if JUCE_LINUX
  27593. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27594. void sendEventToChild (XEvent* event)
  27595. {
  27596. if (pluginProc != 0)
  27597. {
  27598. // if the plugin publishes an event procedure, pass the event directly..
  27599. pluginProc (event);
  27600. }
  27601. else if (pluginWindow != 0)
  27602. {
  27603. // if the plugin has a window, then send the event to the window so that
  27604. // its message thread will pick it up..
  27605. XSendEvent (display, pluginWindow, False, 0L, event);
  27606. XFlush (display);
  27607. }
  27608. }
  27609. void mouseEnter (const MouseEvent& e)
  27610. {
  27611. if (pluginWindow != 0)
  27612. {
  27613. XEvent ev;
  27614. zerostruct (ev);
  27615. ev.xcrossing.display = display;
  27616. ev.xcrossing.type = EnterNotify;
  27617. ev.xcrossing.window = pluginWindow;
  27618. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27619. ev.xcrossing.time = CurrentTime;
  27620. ev.xcrossing.x = e.x;
  27621. ev.xcrossing.y = e.y;
  27622. ev.xcrossing.x_root = e.getScreenX();
  27623. ev.xcrossing.y_root = e.getScreenY();
  27624. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27625. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27626. translateJuceToXCrossingModifiers (e, ev);
  27627. sendEventToChild (&ev);
  27628. }
  27629. }
  27630. void mouseExit (const MouseEvent& e)
  27631. {
  27632. if (pluginWindow != 0)
  27633. {
  27634. XEvent ev;
  27635. zerostruct (ev);
  27636. ev.xcrossing.display = display;
  27637. ev.xcrossing.type = LeaveNotify;
  27638. ev.xcrossing.window = pluginWindow;
  27639. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27640. ev.xcrossing.time = CurrentTime;
  27641. ev.xcrossing.x = e.x;
  27642. ev.xcrossing.y = e.y;
  27643. ev.xcrossing.x_root = e.getScreenX();
  27644. ev.xcrossing.y_root = e.getScreenY();
  27645. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27646. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27647. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27648. translateJuceToXCrossingModifiers (e, ev);
  27649. sendEventToChild (&ev);
  27650. }
  27651. }
  27652. void mouseMove (const MouseEvent& e)
  27653. {
  27654. if (pluginWindow != 0)
  27655. {
  27656. XEvent ev;
  27657. zerostruct (ev);
  27658. ev.xmotion.display = display;
  27659. ev.xmotion.type = MotionNotify;
  27660. ev.xmotion.window = pluginWindow;
  27661. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27662. ev.xmotion.time = CurrentTime;
  27663. ev.xmotion.is_hint = NotifyNormal;
  27664. ev.xmotion.x = e.x;
  27665. ev.xmotion.y = e.y;
  27666. ev.xmotion.x_root = e.getScreenX();
  27667. ev.xmotion.y_root = e.getScreenY();
  27668. sendEventToChild (&ev);
  27669. }
  27670. }
  27671. void mouseDrag (const MouseEvent& e)
  27672. {
  27673. if (pluginWindow != 0)
  27674. {
  27675. XEvent ev;
  27676. zerostruct (ev);
  27677. ev.xmotion.display = display;
  27678. ev.xmotion.type = MotionNotify;
  27679. ev.xmotion.window = pluginWindow;
  27680. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27681. ev.xmotion.time = CurrentTime;
  27682. ev.xmotion.x = e.x ;
  27683. ev.xmotion.y = e.y;
  27684. ev.xmotion.x_root = e.getScreenX();
  27685. ev.xmotion.y_root = e.getScreenY();
  27686. ev.xmotion.is_hint = NotifyNormal;
  27687. translateJuceToXMotionModifiers (e, ev);
  27688. sendEventToChild (&ev);
  27689. }
  27690. }
  27691. void mouseUp (const MouseEvent& e)
  27692. {
  27693. if (pluginWindow != 0)
  27694. {
  27695. XEvent ev;
  27696. zerostruct (ev);
  27697. ev.xbutton.display = display;
  27698. ev.xbutton.type = ButtonRelease;
  27699. ev.xbutton.window = pluginWindow;
  27700. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27701. ev.xbutton.time = CurrentTime;
  27702. ev.xbutton.x = e.x;
  27703. ev.xbutton.y = e.y;
  27704. ev.xbutton.x_root = e.getScreenX();
  27705. ev.xbutton.y_root = e.getScreenY();
  27706. translateJuceToXButtonModifiers (e, ev);
  27707. sendEventToChild (&ev);
  27708. }
  27709. }
  27710. void mouseWheelMove (const MouseEvent& e,
  27711. float incrementX,
  27712. float incrementY)
  27713. {
  27714. if (pluginWindow != 0)
  27715. {
  27716. XEvent ev;
  27717. zerostruct (ev);
  27718. ev.xbutton.display = display;
  27719. ev.xbutton.type = ButtonPress;
  27720. ev.xbutton.window = pluginWindow;
  27721. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27722. ev.xbutton.time = CurrentTime;
  27723. ev.xbutton.x = e.x;
  27724. ev.xbutton.y = e.y;
  27725. ev.xbutton.x_root = e.getScreenX();
  27726. ev.xbutton.y_root = e.getScreenY();
  27727. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27728. sendEventToChild (&ev);
  27729. // TODO - put a usleep here ?
  27730. ev.xbutton.type = ButtonRelease;
  27731. sendEventToChild (&ev);
  27732. }
  27733. }
  27734. #endif
  27735. #if JUCE_MAC
  27736. #if ! JUCE_SUPPORT_CARBON
  27737. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27738. #endif
  27739. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27740. {
  27741. public:
  27742. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27743. : owner (owner_),
  27744. alreadyInside (false)
  27745. {
  27746. }
  27747. ~InnerWrapperComponent()
  27748. {
  27749. deleteWindow();
  27750. }
  27751. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27752. {
  27753. owner->openPluginWindow (windowRef);
  27754. return 0;
  27755. }
  27756. void removeView (HIViewRef)
  27757. {
  27758. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27759. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27760. }
  27761. bool getEmbeddedViewSize (int& w, int& h)
  27762. {
  27763. ERect* rect = 0;
  27764. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27765. w = rect->right - rect->left;
  27766. h = rect->bottom - rect->top;
  27767. return true;
  27768. }
  27769. void mouseDown (int x, int y)
  27770. {
  27771. if (! alreadyInside)
  27772. {
  27773. alreadyInside = true;
  27774. getTopLevelComponent()->toFront (true);
  27775. owner->dispatch (effEditMouse, x, y, 0, 0);
  27776. alreadyInside = false;
  27777. }
  27778. else
  27779. {
  27780. PostEvent (::mouseDown, 0);
  27781. }
  27782. }
  27783. void paint()
  27784. {
  27785. ComponentPeer* const peer = getPeer();
  27786. if (peer != 0)
  27787. {
  27788. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27789. ERect r;
  27790. r.left = pos.getX();
  27791. r.right = r.left + getWidth();
  27792. r.top = pos.getY();
  27793. r.bottom = r.top + getHeight();
  27794. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27795. }
  27796. }
  27797. private:
  27798. VSTPluginWindow* const owner;
  27799. bool alreadyInside;
  27800. };
  27801. friend class InnerWrapperComponent;
  27802. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27803. void resized()
  27804. {
  27805. innerWrapper->setSize (getWidth(), getHeight());
  27806. }
  27807. #endif
  27808. private:
  27809. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27810. };
  27811. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27812. {
  27813. if (hasEditor())
  27814. return new VSTPluginWindow (*this);
  27815. return 0;
  27816. }
  27817. void VSTPluginInstance::handleAsyncUpdate()
  27818. {
  27819. // indicates that something about the plugin has changed..
  27820. updateHostDisplay();
  27821. }
  27822. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27823. {
  27824. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27825. {
  27826. changeProgramName (getCurrentProgram(), prog->prgName);
  27827. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27828. setParameter (i, vst_swapFloat (prog->params[i]));
  27829. return true;
  27830. }
  27831. return false;
  27832. }
  27833. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27834. const int dataSize)
  27835. {
  27836. if (dataSize < 28)
  27837. return false;
  27838. const fxSet* const set = (const fxSet*) data;
  27839. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27840. || vst_swap (set->version) > fxbVersionNum)
  27841. return false;
  27842. if (vst_swap (set->fxMagic) == 'FxBk')
  27843. {
  27844. // bank of programs
  27845. if (vst_swap (set->numPrograms) >= 0)
  27846. {
  27847. const int oldProg = getCurrentProgram();
  27848. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27849. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27850. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27851. {
  27852. if (i != oldProg)
  27853. {
  27854. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27855. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27856. return false;
  27857. if (vst_swap (set->numPrograms) > 0)
  27858. setCurrentProgram (i);
  27859. if (! restoreProgramSettings (prog))
  27860. return false;
  27861. }
  27862. }
  27863. if (vst_swap (set->numPrograms) > 0)
  27864. setCurrentProgram (oldProg);
  27865. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27866. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27867. return false;
  27868. if (! restoreProgramSettings (prog))
  27869. return false;
  27870. }
  27871. }
  27872. else if (vst_swap (set->fxMagic) == 'FxCk')
  27873. {
  27874. // single program
  27875. const fxProgram* const prog = (const fxProgram*) data;
  27876. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27877. return false;
  27878. changeProgramName (getCurrentProgram(), prog->prgName);
  27879. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27880. setParameter (i, vst_swapFloat (prog->params[i]));
  27881. }
  27882. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27883. {
  27884. // non-preset chunk
  27885. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27886. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27887. return false;
  27888. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27889. }
  27890. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27891. {
  27892. // preset chunk
  27893. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27894. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27895. return false;
  27896. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27897. changeProgramName (getCurrentProgram(), cset->name);
  27898. }
  27899. else
  27900. {
  27901. return false;
  27902. }
  27903. return true;
  27904. }
  27905. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27906. {
  27907. const int numParams = getNumParameters();
  27908. prog->chunkMagic = vst_swap ('CcnK');
  27909. prog->byteSize = 0;
  27910. prog->fxMagic = vst_swap ('FxCk');
  27911. prog->version = vst_swap (fxbVersionNum);
  27912. prog->fxID = vst_swap (getUID());
  27913. prog->fxVersion = vst_swap (getVersionNumber());
  27914. prog->numParams = vst_swap (numParams);
  27915. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27916. for (int i = 0; i < numParams; ++i)
  27917. prog->params[i] = vst_swapFloat (getParameter (i));
  27918. }
  27919. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27920. {
  27921. const int numPrograms = getNumPrograms();
  27922. const int numParams = getNumParameters();
  27923. if (usesChunks())
  27924. {
  27925. if (isFXB)
  27926. {
  27927. MemoryBlock chunk;
  27928. getChunkData (chunk, false, maxSizeMB);
  27929. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27930. dest.setSize (totalLen, true);
  27931. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27932. set->chunkMagic = vst_swap ('CcnK');
  27933. set->byteSize = 0;
  27934. set->fxMagic = vst_swap ('FBCh');
  27935. set->version = vst_swap (fxbVersionNum);
  27936. set->fxID = vst_swap (getUID());
  27937. set->fxVersion = vst_swap (getVersionNumber());
  27938. set->numPrograms = vst_swap (numPrograms);
  27939. set->chunkSize = vst_swap ((long) chunk.getSize());
  27940. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27941. }
  27942. else
  27943. {
  27944. MemoryBlock chunk;
  27945. getChunkData (chunk, true, maxSizeMB);
  27946. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27947. dest.setSize (totalLen, true);
  27948. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27949. set->chunkMagic = vst_swap ('CcnK');
  27950. set->byteSize = 0;
  27951. set->fxMagic = vst_swap ('FPCh');
  27952. set->version = vst_swap (fxbVersionNum);
  27953. set->fxID = vst_swap (getUID());
  27954. set->fxVersion = vst_swap (getVersionNumber());
  27955. set->numPrograms = vst_swap (numPrograms);
  27956. set->chunkSize = vst_swap ((long) chunk.getSize());
  27957. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27958. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27959. }
  27960. }
  27961. else
  27962. {
  27963. if (isFXB)
  27964. {
  27965. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27966. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27967. dest.setSize (len, true);
  27968. fxSet* const set = (fxSet*) dest.getData();
  27969. set->chunkMagic = vst_swap ('CcnK');
  27970. set->byteSize = 0;
  27971. set->fxMagic = vst_swap ('FxBk');
  27972. set->version = vst_swap (fxbVersionNum);
  27973. set->fxID = vst_swap (getUID());
  27974. set->fxVersion = vst_swap (getVersionNumber());
  27975. set->numPrograms = vst_swap (numPrograms);
  27976. const int oldProgram = getCurrentProgram();
  27977. MemoryBlock oldSettings;
  27978. createTempParameterStore (oldSettings);
  27979. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27980. for (int i = 0; i < numPrograms; ++i)
  27981. {
  27982. if (i != oldProgram)
  27983. {
  27984. setCurrentProgram (i);
  27985. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27986. }
  27987. }
  27988. setCurrentProgram (oldProgram);
  27989. restoreFromTempParameterStore (oldSettings);
  27990. }
  27991. else
  27992. {
  27993. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27994. dest.setSize (totalLen, true);
  27995. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27996. }
  27997. }
  27998. return true;
  27999. }
  28000. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28001. {
  28002. if (usesChunks())
  28003. {
  28004. void* data = 0;
  28005. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28006. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28007. {
  28008. mb.setSize (bytes);
  28009. mb.copyFrom (data, 0, bytes);
  28010. }
  28011. }
  28012. }
  28013. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28014. {
  28015. if (size > 0 && usesChunks())
  28016. {
  28017. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28018. if (! isPreset)
  28019. updateStoredProgramNames();
  28020. }
  28021. }
  28022. void VSTPluginInstance::timerCallback()
  28023. {
  28024. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28025. stopTimer();
  28026. }
  28027. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28028. {
  28029. const ScopedLock sl (lock);
  28030. ++insideVSTCallback;
  28031. int result = 0;
  28032. try
  28033. {
  28034. if (effect != 0)
  28035. {
  28036. #if JUCE_MAC
  28037. if (module->resFileId != 0)
  28038. UseResFile (module->resFileId);
  28039. #endif
  28040. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28041. #if JUCE_MAC
  28042. module->resFileId = CurResFile();
  28043. #endif
  28044. --insideVSTCallback;
  28045. return result;
  28046. }
  28047. }
  28048. catch (...)
  28049. {
  28050. }
  28051. --insideVSTCallback;
  28052. return result;
  28053. }
  28054. namespace
  28055. {
  28056. static const int defaultVSTSampleRateValue = 16384;
  28057. static const int defaultVSTBlockSizeValue = 512;
  28058. // handles non plugin-specific callbacks..
  28059. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28060. {
  28061. (void) index;
  28062. (void) value;
  28063. (void) opt;
  28064. switch (opcode)
  28065. {
  28066. case audioMasterCanDo:
  28067. {
  28068. static const char* canDos[] = { "supplyIdle",
  28069. "sendVstEvents",
  28070. "sendVstMidiEvent",
  28071. "sendVstTimeInfo",
  28072. "receiveVstEvents",
  28073. "receiveVstMidiEvent",
  28074. "supportShell",
  28075. "shellCategory" };
  28076. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28077. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28078. return 1;
  28079. return 0;
  28080. }
  28081. case audioMasterVersion: return 0x2400;
  28082. case audioMasterCurrentId: return shellUIDToCreate;
  28083. case audioMasterGetNumAutomatableParameters: return 0;
  28084. case audioMasterGetAutomationState: return 1;
  28085. case audioMasterGetVendorVersion: return 0x0101;
  28086. case audioMasterGetVendorString:
  28087. case audioMasterGetProductString:
  28088. {
  28089. String hostName ("Juce VST Host");
  28090. if (JUCEApplication::getInstance() != 0)
  28091. hostName = JUCEApplication::getInstance()->getApplicationName();
  28092. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28093. break;
  28094. }
  28095. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28096. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28097. case audioMasterSetOutputSampleRate: return 0;
  28098. default:
  28099. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28100. break;
  28101. }
  28102. return 0;
  28103. }
  28104. }
  28105. // handles callbacks for a specific plugin
  28106. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28107. {
  28108. switch (opcode)
  28109. {
  28110. case audioMasterAutomate:
  28111. sendParamChangeMessageToListeners (index, opt);
  28112. break;
  28113. case audioMasterProcessEvents:
  28114. handleMidiFromPlugin ((const VstEvents*) ptr);
  28115. break;
  28116. case audioMasterGetTime:
  28117. #if JUCE_MSVC
  28118. #pragma warning (push)
  28119. #pragma warning (disable: 4311)
  28120. #endif
  28121. return (VstIntPtr) &vstHostTime;
  28122. #if JUCE_MSVC
  28123. #pragma warning (pop)
  28124. #endif
  28125. break;
  28126. case audioMasterIdle:
  28127. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28128. {
  28129. ++insideVSTCallback;
  28130. #if JUCE_MAC
  28131. if (getActiveEditor() != 0)
  28132. dispatch (effEditIdle, 0, 0, 0, 0);
  28133. #endif
  28134. juce_callAnyTimersSynchronously();
  28135. handleUpdateNowIfNeeded();
  28136. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28137. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28138. --insideVSTCallback;
  28139. }
  28140. break;
  28141. case audioMasterUpdateDisplay:
  28142. triggerAsyncUpdate();
  28143. break;
  28144. case audioMasterTempoAt:
  28145. // returns (10000 * bpm)
  28146. break;
  28147. case audioMasterNeedIdle:
  28148. startTimer (50);
  28149. break;
  28150. case audioMasterSizeWindow:
  28151. if (getActiveEditor() != 0)
  28152. getActiveEditor()->setSize (index, value);
  28153. return 1;
  28154. case audioMasterGetSampleRate:
  28155. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28156. case audioMasterGetBlockSize:
  28157. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28158. case audioMasterWantMidi:
  28159. wantsMidiMessages = true;
  28160. break;
  28161. case audioMasterGetDirectory:
  28162. #if JUCE_MAC
  28163. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28164. #else
  28165. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28166. #endif
  28167. case audioMasterGetAutomationState:
  28168. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28169. break;
  28170. // none of these are handled (yet)..
  28171. case audioMasterBeginEdit:
  28172. case audioMasterEndEdit:
  28173. case audioMasterSetTime:
  28174. case audioMasterPinConnected:
  28175. case audioMasterGetParameterQuantization:
  28176. case audioMasterIOChanged:
  28177. case audioMasterGetInputLatency:
  28178. case audioMasterGetOutputLatency:
  28179. case audioMasterGetPreviousPlug:
  28180. case audioMasterGetNextPlug:
  28181. case audioMasterWillReplaceOrAccumulate:
  28182. case audioMasterGetCurrentProcessLevel:
  28183. case audioMasterOfflineStart:
  28184. case audioMasterOfflineRead:
  28185. case audioMasterOfflineWrite:
  28186. case audioMasterOfflineGetCurrentPass:
  28187. case audioMasterOfflineGetCurrentMetaPass:
  28188. case audioMasterVendorSpecific:
  28189. case audioMasterSetIcon:
  28190. case audioMasterGetLanguage:
  28191. case audioMasterOpenWindow:
  28192. case audioMasterCloseWindow:
  28193. break;
  28194. default:
  28195. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28196. }
  28197. return 0;
  28198. }
  28199. // entry point for all callbacks from the plugin
  28200. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28201. {
  28202. try
  28203. {
  28204. if (effect != 0 && effect->resvd2 != 0)
  28205. {
  28206. return ((VSTPluginInstance*)(effect->resvd2))
  28207. ->handleCallback (opcode, index, value, ptr, opt);
  28208. }
  28209. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28210. }
  28211. catch (...)
  28212. {
  28213. return 0;
  28214. }
  28215. }
  28216. const String VSTPluginInstance::getVersion() const
  28217. {
  28218. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28219. String s;
  28220. if (v == 0 || v == -1)
  28221. v = getVersionNumber();
  28222. if (v != 0)
  28223. {
  28224. int versionBits[4];
  28225. int n = 0;
  28226. while (v != 0)
  28227. {
  28228. versionBits [n++] = (v & 0xff);
  28229. v >>= 8;
  28230. }
  28231. s << 'V';
  28232. while (n > 0)
  28233. {
  28234. s << versionBits [--n];
  28235. if (n > 0)
  28236. s << '.';
  28237. }
  28238. }
  28239. return s;
  28240. }
  28241. int VSTPluginInstance::getUID() const
  28242. {
  28243. int uid = effect != 0 ? effect->uniqueID : 0;
  28244. if (uid == 0)
  28245. uid = module->file.hashCode();
  28246. return uid;
  28247. }
  28248. const String VSTPluginInstance::getCategory() const
  28249. {
  28250. const char* result = 0;
  28251. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28252. {
  28253. case kPlugCategEffect: result = "Effect"; break;
  28254. case kPlugCategSynth: result = "Synth"; break;
  28255. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28256. case kPlugCategMastering: result = "Mastering"; break;
  28257. case kPlugCategSpacializer: result = "Spacial"; break;
  28258. case kPlugCategRoomFx: result = "Reverb"; break;
  28259. case kPlugSurroundFx: result = "Surround"; break;
  28260. case kPlugCategRestoration: result = "Restoration"; break;
  28261. case kPlugCategGenerator: result = "Tone generation"; break;
  28262. default: break;
  28263. }
  28264. return result;
  28265. }
  28266. float VSTPluginInstance::getParameter (int index)
  28267. {
  28268. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28269. {
  28270. try
  28271. {
  28272. const ScopedLock sl (lock);
  28273. return effect->getParameter (effect, index);
  28274. }
  28275. catch (...)
  28276. {
  28277. }
  28278. }
  28279. return 0.0f;
  28280. }
  28281. void VSTPluginInstance::setParameter (int index, float newValue)
  28282. {
  28283. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28284. {
  28285. try
  28286. {
  28287. const ScopedLock sl (lock);
  28288. if (effect->getParameter (effect, index) != newValue)
  28289. effect->setParameter (effect, index, newValue);
  28290. }
  28291. catch (...)
  28292. {
  28293. }
  28294. }
  28295. }
  28296. const String VSTPluginInstance::getParameterName (int index)
  28297. {
  28298. if (effect != 0)
  28299. {
  28300. jassert (index >= 0 && index < effect->numParams);
  28301. char nm [256];
  28302. zerostruct (nm);
  28303. dispatch (effGetParamName, index, 0, nm, 0);
  28304. return String (nm).trim();
  28305. }
  28306. return String::empty;
  28307. }
  28308. const String VSTPluginInstance::getParameterLabel (int index) const
  28309. {
  28310. if (effect != 0)
  28311. {
  28312. jassert (index >= 0 && index < effect->numParams);
  28313. char nm [256];
  28314. zerostruct (nm);
  28315. dispatch (effGetParamLabel, index, 0, nm, 0);
  28316. return String (nm).trim();
  28317. }
  28318. return String::empty;
  28319. }
  28320. const String VSTPluginInstance::getParameterText (int index)
  28321. {
  28322. if (effect != 0)
  28323. {
  28324. jassert (index >= 0 && index < effect->numParams);
  28325. char nm [256];
  28326. zerostruct (nm);
  28327. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28328. return String (nm).trim();
  28329. }
  28330. return String::empty;
  28331. }
  28332. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28333. {
  28334. if (effect != 0)
  28335. {
  28336. jassert (index >= 0 && index < effect->numParams);
  28337. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28338. }
  28339. return false;
  28340. }
  28341. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28342. {
  28343. dest.setSize (64 + 4 * getNumParameters());
  28344. dest.fillWith (0);
  28345. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28346. float* const p = (float*) (((char*) dest.getData()) + 64);
  28347. for (int i = 0; i < getNumParameters(); ++i)
  28348. p[i] = getParameter(i);
  28349. }
  28350. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28351. {
  28352. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28353. float* p = (float*) (((char*) m.getData()) + 64);
  28354. for (int i = 0; i < getNumParameters(); ++i)
  28355. setParameter (i, p[i]);
  28356. }
  28357. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28358. {
  28359. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28360. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28361. }
  28362. const String VSTPluginInstance::getProgramName (int index)
  28363. {
  28364. if (index == getCurrentProgram())
  28365. {
  28366. return getCurrentProgramName();
  28367. }
  28368. else if (effect != 0)
  28369. {
  28370. char nm [256];
  28371. zerostruct (nm);
  28372. if (dispatch (effGetProgramNameIndexed,
  28373. jlimit (0, getNumPrograms(), index),
  28374. -1, nm, 0) != 0)
  28375. {
  28376. return String (nm).trim();
  28377. }
  28378. }
  28379. return programNames [index];
  28380. }
  28381. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28382. {
  28383. if (index == getCurrentProgram())
  28384. {
  28385. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28386. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28387. }
  28388. else
  28389. {
  28390. jassertfalse; // xxx not implemented!
  28391. }
  28392. }
  28393. void VSTPluginInstance::updateStoredProgramNames()
  28394. {
  28395. if (effect != 0 && getNumPrograms() > 0)
  28396. {
  28397. char nm [256];
  28398. zerostruct (nm);
  28399. // only do this if the plugin can't use indexed names..
  28400. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28401. {
  28402. const int oldProgram = getCurrentProgram();
  28403. MemoryBlock oldSettings;
  28404. createTempParameterStore (oldSettings);
  28405. for (int i = 0; i < getNumPrograms(); ++i)
  28406. {
  28407. setCurrentProgram (i);
  28408. getCurrentProgramName(); // (this updates the list)
  28409. }
  28410. setCurrentProgram (oldProgram);
  28411. restoreFromTempParameterStore (oldSettings);
  28412. }
  28413. }
  28414. }
  28415. const String VSTPluginInstance::getCurrentProgramName()
  28416. {
  28417. if (effect != 0)
  28418. {
  28419. char nm [256];
  28420. zerostruct (nm);
  28421. dispatch (effGetProgramName, 0, 0, nm, 0);
  28422. const int index = getCurrentProgram();
  28423. if (programNames[index].isEmpty())
  28424. {
  28425. while (programNames.size() < index)
  28426. programNames.add (String::empty);
  28427. programNames.set (index, String (nm).trim());
  28428. }
  28429. return String (nm).trim();
  28430. }
  28431. return String::empty;
  28432. }
  28433. const String VSTPluginInstance::getInputChannelName (int index) const
  28434. {
  28435. if (index >= 0 && index < getNumInputChannels())
  28436. {
  28437. VstPinProperties pinProps;
  28438. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28439. return String (pinProps.label, sizeof (pinProps.label));
  28440. }
  28441. return String::empty;
  28442. }
  28443. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28444. {
  28445. if (index < 0 || index >= getNumInputChannels())
  28446. return false;
  28447. VstPinProperties pinProps;
  28448. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28449. return (pinProps.flags & kVstPinIsStereo) != 0;
  28450. return true;
  28451. }
  28452. const String VSTPluginInstance::getOutputChannelName (int index) const
  28453. {
  28454. if (index >= 0 && index < getNumOutputChannels())
  28455. {
  28456. VstPinProperties pinProps;
  28457. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28458. return String (pinProps.label, sizeof (pinProps.label));
  28459. }
  28460. return String::empty;
  28461. }
  28462. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28463. {
  28464. if (index < 0 || index >= getNumOutputChannels())
  28465. return false;
  28466. VstPinProperties pinProps;
  28467. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28468. return (pinProps.flags & kVstPinIsStereo) != 0;
  28469. return true;
  28470. }
  28471. void VSTPluginInstance::setPower (const bool on)
  28472. {
  28473. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28474. isPowerOn = on;
  28475. }
  28476. const int defaultMaxSizeMB = 64;
  28477. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28478. {
  28479. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28480. }
  28481. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28482. {
  28483. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28484. }
  28485. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28486. {
  28487. loadFromFXBFile (data, sizeInBytes);
  28488. }
  28489. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28490. {
  28491. loadFromFXBFile (data, sizeInBytes);
  28492. }
  28493. VSTPluginFormat::VSTPluginFormat()
  28494. {
  28495. }
  28496. VSTPluginFormat::~VSTPluginFormat()
  28497. {
  28498. }
  28499. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28500. const String& fileOrIdentifier)
  28501. {
  28502. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28503. return;
  28504. PluginDescription desc;
  28505. desc.fileOrIdentifier = fileOrIdentifier;
  28506. desc.uid = 0;
  28507. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28508. if (instance == 0)
  28509. return;
  28510. try
  28511. {
  28512. #if JUCE_MAC
  28513. if (instance->module->resFileId != 0)
  28514. UseResFile (instance->module->resFileId);
  28515. #endif
  28516. instance->fillInPluginDescription (desc);
  28517. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28518. if (category != kPlugCategShell)
  28519. {
  28520. // Normal plugin...
  28521. results.add (new PluginDescription (desc));
  28522. ++insideVSTCallback;
  28523. instance->dispatch (effOpen, 0, 0, 0, 0);
  28524. --insideVSTCallback;
  28525. }
  28526. else
  28527. {
  28528. // It's a shell plugin, so iterate all the subtypes...
  28529. char shellEffectName [64];
  28530. for (;;)
  28531. {
  28532. zerostruct (shellEffectName);
  28533. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28534. if (uid == 0)
  28535. {
  28536. break;
  28537. }
  28538. else
  28539. {
  28540. desc.uid = uid;
  28541. desc.name = shellEffectName;
  28542. desc.descriptiveName = shellEffectName;
  28543. bool alreadyThere = false;
  28544. for (int i = results.size(); --i >= 0;)
  28545. {
  28546. PluginDescription* const d = results.getUnchecked(i);
  28547. if (d->isDuplicateOf (desc))
  28548. {
  28549. alreadyThere = true;
  28550. break;
  28551. }
  28552. }
  28553. if (! alreadyThere)
  28554. results.add (new PluginDescription (desc));
  28555. }
  28556. }
  28557. }
  28558. }
  28559. catch (...)
  28560. {
  28561. // crashed while loading...
  28562. }
  28563. }
  28564. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28565. {
  28566. ScopedPointer <VSTPluginInstance> result;
  28567. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28568. {
  28569. File file (desc.fileOrIdentifier);
  28570. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28571. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28572. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28573. if (module != 0)
  28574. {
  28575. shellUIDToCreate = desc.uid;
  28576. result = new VSTPluginInstance (module);
  28577. if (result->effect != 0)
  28578. {
  28579. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28580. result->initialise();
  28581. }
  28582. else
  28583. {
  28584. result = 0;
  28585. }
  28586. }
  28587. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28588. }
  28589. return result.release();
  28590. }
  28591. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28592. {
  28593. const File f (fileOrIdentifier);
  28594. #if JUCE_MAC
  28595. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28596. return true;
  28597. #if JUCE_PPC
  28598. FSRef fileRef;
  28599. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28600. {
  28601. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28602. if (resFileId != -1)
  28603. {
  28604. const int numEffects = Count1Resources ('aEff');
  28605. CloseResFile (resFileId);
  28606. if (numEffects > 0)
  28607. return true;
  28608. }
  28609. }
  28610. #endif
  28611. return false;
  28612. #elif JUCE_WINDOWS
  28613. return f.existsAsFile() && f.hasFileExtension (".dll");
  28614. #elif JUCE_LINUX
  28615. return f.existsAsFile() && f.hasFileExtension (".so");
  28616. #endif
  28617. }
  28618. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28619. {
  28620. return fileOrIdentifier;
  28621. }
  28622. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28623. {
  28624. return File (desc.fileOrIdentifier).exists();
  28625. }
  28626. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28627. {
  28628. StringArray results;
  28629. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28630. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28631. return results;
  28632. }
  28633. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28634. {
  28635. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28636. // .component or .vst directories.
  28637. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28638. while (iter.next())
  28639. {
  28640. const File f (iter.getFile());
  28641. bool isPlugin = false;
  28642. if (fileMightContainThisPluginType (f.getFullPathName()))
  28643. {
  28644. isPlugin = true;
  28645. results.add (f.getFullPathName());
  28646. }
  28647. if (recursive && (! isPlugin) && f.isDirectory())
  28648. recursiveFileSearch (results, f, true);
  28649. }
  28650. }
  28651. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28652. {
  28653. #if JUCE_MAC
  28654. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28655. #elif JUCE_WINDOWS
  28656. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28657. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28658. #elif JUCE_LINUX
  28659. return FileSearchPath ("/usr/lib/vst");
  28660. #endif
  28661. }
  28662. END_JUCE_NAMESPACE
  28663. #endif
  28664. #undef log
  28665. #endif
  28666. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28667. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28668. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28669. BEGIN_JUCE_NAMESPACE
  28670. AudioProcessor::AudioProcessor()
  28671. : playHead (0),
  28672. sampleRate (0),
  28673. blockSize (0),
  28674. numInputChannels (0),
  28675. numOutputChannels (0),
  28676. latencySamples (0),
  28677. suspended (false),
  28678. nonRealtime (false)
  28679. {
  28680. }
  28681. AudioProcessor::~AudioProcessor()
  28682. {
  28683. // ooh, nasty - the editor should have been deleted before the filter
  28684. // that it refers to is deleted..
  28685. jassert (activeEditor == 0);
  28686. #if JUCE_DEBUG
  28687. // This will fail if you've called beginParameterChangeGesture() for one
  28688. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28689. jassert (changingParams.countNumberOfSetBits() == 0);
  28690. #endif
  28691. }
  28692. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28693. {
  28694. playHead = newPlayHead;
  28695. }
  28696. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28697. {
  28698. const ScopedLock sl (listenerLock);
  28699. listeners.addIfNotAlreadyThere (newListener);
  28700. }
  28701. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28702. {
  28703. const ScopedLock sl (listenerLock);
  28704. listeners.removeValue (listenerToRemove);
  28705. }
  28706. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28707. const int numOuts,
  28708. const double sampleRate_,
  28709. const int blockSize_) throw()
  28710. {
  28711. numInputChannels = numIns;
  28712. numOutputChannels = numOuts;
  28713. sampleRate = sampleRate_;
  28714. blockSize = blockSize_;
  28715. }
  28716. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28717. {
  28718. nonRealtime = nonRealtime_;
  28719. }
  28720. void AudioProcessor::setLatencySamples (const int newLatency)
  28721. {
  28722. if (latencySamples != newLatency)
  28723. {
  28724. latencySamples = newLatency;
  28725. updateHostDisplay();
  28726. }
  28727. }
  28728. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28729. const float newValue)
  28730. {
  28731. setParameter (parameterIndex, newValue);
  28732. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28733. }
  28734. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28735. {
  28736. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28737. for (int i = listeners.size(); --i >= 0;)
  28738. {
  28739. AudioProcessorListener* l;
  28740. {
  28741. const ScopedLock sl (listenerLock);
  28742. l = listeners [i];
  28743. }
  28744. if (l != 0)
  28745. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28746. }
  28747. }
  28748. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28749. {
  28750. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28751. #if JUCE_DEBUG
  28752. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28753. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28754. jassert (! changingParams [parameterIndex]);
  28755. changingParams.setBit (parameterIndex);
  28756. #endif
  28757. for (int i = listeners.size(); --i >= 0;)
  28758. {
  28759. AudioProcessorListener* l;
  28760. {
  28761. const ScopedLock sl (listenerLock);
  28762. l = listeners [i];
  28763. }
  28764. if (l != 0)
  28765. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28766. }
  28767. }
  28768. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28769. {
  28770. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28771. #if JUCE_DEBUG
  28772. // This means you've called endParameterChangeGesture without having previously called
  28773. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28774. // calls matched correctly.
  28775. jassert (changingParams [parameterIndex]);
  28776. changingParams.clearBit (parameterIndex);
  28777. #endif
  28778. for (int i = listeners.size(); --i >= 0;)
  28779. {
  28780. AudioProcessorListener* l;
  28781. {
  28782. const ScopedLock sl (listenerLock);
  28783. l = listeners [i];
  28784. }
  28785. if (l != 0)
  28786. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28787. }
  28788. }
  28789. void AudioProcessor::updateHostDisplay()
  28790. {
  28791. for (int i = listeners.size(); --i >= 0;)
  28792. {
  28793. AudioProcessorListener* l;
  28794. {
  28795. const ScopedLock sl (listenerLock);
  28796. l = listeners [i];
  28797. }
  28798. if (l != 0)
  28799. l->audioProcessorChanged (this);
  28800. }
  28801. }
  28802. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28803. {
  28804. return true;
  28805. }
  28806. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28807. {
  28808. return false;
  28809. }
  28810. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28811. {
  28812. const ScopedLock sl (callbackLock);
  28813. suspended = shouldBeSuspended;
  28814. }
  28815. void AudioProcessor::reset()
  28816. {
  28817. }
  28818. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28819. {
  28820. const ScopedLock sl (callbackLock);
  28821. if (activeEditor == editor)
  28822. activeEditor = 0;
  28823. }
  28824. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28825. {
  28826. if (activeEditor != 0)
  28827. return activeEditor;
  28828. AudioProcessorEditor* const ed = createEditor();
  28829. // You must make your hasEditor() method return a consistent result!
  28830. jassert (hasEditor() == (ed != 0));
  28831. if (ed != 0)
  28832. {
  28833. // you must give your editor comp a size before returning it..
  28834. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28835. const ScopedLock sl (callbackLock);
  28836. activeEditor = ed;
  28837. }
  28838. return ed;
  28839. }
  28840. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28841. {
  28842. getStateInformation (destData);
  28843. }
  28844. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28845. {
  28846. setStateInformation (data, sizeInBytes);
  28847. }
  28848. // magic number to identify memory blocks that we've stored as XML
  28849. const uint32 magicXmlNumber = 0x21324356;
  28850. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28851. JUCE_NAMESPACE::MemoryBlock& destData)
  28852. {
  28853. const String xmlString (xml.createDocument (String::empty, true, false));
  28854. const int stringLength = xmlString.getNumBytesAsUTF8();
  28855. destData.setSize (stringLength + 10);
  28856. char* const d = static_cast<char*> (destData.getData());
  28857. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28858. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28859. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28860. }
  28861. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28862. const int sizeInBytes)
  28863. {
  28864. if (sizeInBytes > 8
  28865. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28866. {
  28867. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28868. if (stringLength > 0)
  28869. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28870. jmin ((sizeInBytes - 8), stringLength)));
  28871. }
  28872. return 0;
  28873. }
  28874. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28875. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28876. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28877. {
  28878. return timeInSeconds == other.timeInSeconds
  28879. && ppqPosition == other.ppqPosition
  28880. && editOriginTime == other.editOriginTime
  28881. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28882. && frameRate == other.frameRate
  28883. && isPlaying == other.isPlaying
  28884. && isRecording == other.isRecording
  28885. && bpm == other.bpm
  28886. && timeSigNumerator == other.timeSigNumerator
  28887. && timeSigDenominator == other.timeSigDenominator;
  28888. }
  28889. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28890. {
  28891. return ! operator== (other);
  28892. }
  28893. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28894. {
  28895. zerostruct (*this);
  28896. timeSigNumerator = 4;
  28897. timeSigDenominator = 4;
  28898. bpm = 120;
  28899. }
  28900. END_JUCE_NAMESPACE
  28901. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28902. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28903. BEGIN_JUCE_NAMESPACE
  28904. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28905. : owner (owner_)
  28906. {
  28907. // the filter must be valid..
  28908. jassert (owner != 0);
  28909. }
  28910. AudioProcessorEditor::~AudioProcessorEditor()
  28911. {
  28912. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28913. // filter for some reason..
  28914. jassert (owner->getActiveEditor() != this);
  28915. }
  28916. END_JUCE_NAMESPACE
  28917. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28918. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28919. BEGIN_JUCE_NAMESPACE
  28920. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28921. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28922. : id (id_),
  28923. processor (processor_),
  28924. isPrepared (false)
  28925. {
  28926. jassert (processor_ != 0);
  28927. }
  28928. AudioProcessorGraph::Node::~Node()
  28929. {
  28930. }
  28931. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28932. AudioProcessorGraph* const graph)
  28933. {
  28934. if (! isPrepared)
  28935. {
  28936. isPrepared = true;
  28937. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28938. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28939. if (ioProc != 0)
  28940. ioProc->setParentGraph (graph);
  28941. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28942. processor->getNumOutputChannels(),
  28943. sampleRate, blockSize);
  28944. processor->prepareToPlay (sampleRate, blockSize);
  28945. }
  28946. }
  28947. void AudioProcessorGraph::Node::unprepare()
  28948. {
  28949. if (isPrepared)
  28950. {
  28951. isPrepared = false;
  28952. processor->releaseResources();
  28953. }
  28954. }
  28955. AudioProcessorGraph::AudioProcessorGraph()
  28956. : lastNodeId (0),
  28957. renderingBuffers (1, 1),
  28958. currentAudioOutputBuffer (1, 1)
  28959. {
  28960. }
  28961. AudioProcessorGraph::~AudioProcessorGraph()
  28962. {
  28963. clearRenderingSequence();
  28964. clear();
  28965. }
  28966. const String AudioProcessorGraph::getName() const
  28967. {
  28968. return "Audio Graph";
  28969. }
  28970. void AudioProcessorGraph::clear()
  28971. {
  28972. nodes.clear();
  28973. connections.clear();
  28974. triggerAsyncUpdate();
  28975. }
  28976. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28977. {
  28978. for (int i = nodes.size(); --i >= 0;)
  28979. if (nodes.getUnchecked(i)->id == nodeId)
  28980. return nodes.getUnchecked(i);
  28981. return 0;
  28982. }
  28983. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28984. uint32 nodeId)
  28985. {
  28986. if (newProcessor == 0)
  28987. {
  28988. jassertfalse;
  28989. return 0;
  28990. }
  28991. if (nodeId == 0)
  28992. {
  28993. nodeId = ++lastNodeId;
  28994. }
  28995. else
  28996. {
  28997. // you can't add a node with an id that already exists in the graph..
  28998. jassert (getNodeForId (nodeId) == 0);
  28999. removeNode (nodeId);
  29000. }
  29001. lastNodeId = nodeId;
  29002. Node* const n = new Node (nodeId, newProcessor);
  29003. nodes.add (n);
  29004. triggerAsyncUpdate();
  29005. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29006. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29007. if (ioProc != 0)
  29008. ioProc->setParentGraph (this);
  29009. return n;
  29010. }
  29011. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29012. {
  29013. disconnectNode (nodeId);
  29014. for (int i = nodes.size(); --i >= 0;)
  29015. {
  29016. if (nodes.getUnchecked(i)->id == nodeId)
  29017. {
  29018. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29019. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29020. if (ioProc != 0)
  29021. ioProc->setParentGraph (0);
  29022. nodes.remove (i);
  29023. triggerAsyncUpdate();
  29024. return true;
  29025. }
  29026. }
  29027. return false;
  29028. }
  29029. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29030. const int sourceChannelIndex,
  29031. const uint32 destNodeId,
  29032. const int destChannelIndex) const
  29033. {
  29034. for (int i = connections.size(); --i >= 0;)
  29035. {
  29036. const Connection* const c = connections.getUnchecked(i);
  29037. if (c->sourceNodeId == sourceNodeId
  29038. && c->destNodeId == destNodeId
  29039. && c->sourceChannelIndex == sourceChannelIndex
  29040. && c->destChannelIndex == destChannelIndex)
  29041. {
  29042. return c;
  29043. }
  29044. }
  29045. return 0;
  29046. }
  29047. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29048. const uint32 possibleDestNodeId) const
  29049. {
  29050. for (int i = connections.size(); --i >= 0;)
  29051. {
  29052. const Connection* const c = connections.getUnchecked(i);
  29053. if (c->sourceNodeId == possibleSourceNodeId
  29054. && c->destNodeId == possibleDestNodeId)
  29055. {
  29056. return true;
  29057. }
  29058. }
  29059. return false;
  29060. }
  29061. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29062. const int sourceChannelIndex,
  29063. const uint32 destNodeId,
  29064. const int destChannelIndex) const
  29065. {
  29066. if (sourceChannelIndex < 0
  29067. || destChannelIndex < 0
  29068. || sourceNodeId == destNodeId
  29069. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29070. return false;
  29071. const Node* const source = getNodeForId (sourceNodeId);
  29072. if (source == 0
  29073. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29074. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29075. return false;
  29076. const Node* const dest = getNodeForId (destNodeId);
  29077. if (dest == 0
  29078. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29079. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29080. return false;
  29081. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29082. destNodeId, destChannelIndex) == 0;
  29083. }
  29084. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29085. const int sourceChannelIndex,
  29086. const uint32 destNodeId,
  29087. const int destChannelIndex)
  29088. {
  29089. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29090. return false;
  29091. Connection* const c = new Connection();
  29092. c->sourceNodeId = sourceNodeId;
  29093. c->sourceChannelIndex = sourceChannelIndex;
  29094. c->destNodeId = destNodeId;
  29095. c->destChannelIndex = destChannelIndex;
  29096. connections.add (c);
  29097. triggerAsyncUpdate();
  29098. return true;
  29099. }
  29100. void AudioProcessorGraph::removeConnection (const int index)
  29101. {
  29102. connections.remove (index);
  29103. triggerAsyncUpdate();
  29104. }
  29105. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29106. const uint32 destNodeId, const int destChannelIndex)
  29107. {
  29108. bool doneAnything = false;
  29109. for (int i = connections.size(); --i >= 0;)
  29110. {
  29111. const Connection* const c = connections.getUnchecked(i);
  29112. if (c->sourceNodeId == sourceNodeId
  29113. && c->destNodeId == destNodeId
  29114. && c->sourceChannelIndex == sourceChannelIndex
  29115. && c->destChannelIndex == destChannelIndex)
  29116. {
  29117. removeConnection (i);
  29118. doneAnything = true;
  29119. triggerAsyncUpdate();
  29120. }
  29121. }
  29122. return doneAnything;
  29123. }
  29124. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29125. {
  29126. bool doneAnything = false;
  29127. for (int i = connections.size(); --i >= 0;)
  29128. {
  29129. const Connection* const c = connections.getUnchecked(i);
  29130. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29131. {
  29132. removeConnection (i);
  29133. doneAnything = true;
  29134. triggerAsyncUpdate();
  29135. }
  29136. }
  29137. return doneAnything;
  29138. }
  29139. bool AudioProcessorGraph::removeIllegalConnections()
  29140. {
  29141. bool doneAnything = false;
  29142. for (int i = connections.size(); --i >= 0;)
  29143. {
  29144. const Connection* const c = connections.getUnchecked(i);
  29145. const Node* const source = getNodeForId (c->sourceNodeId);
  29146. const Node* const dest = getNodeForId (c->destNodeId);
  29147. if (source == 0 || dest == 0
  29148. || (c->sourceChannelIndex != midiChannelIndex
  29149. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  29150. || (c->sourceChannelIndex == midiChannelIndex
  29151. && ! source->processor->producesMidi())
  29152. || (c->destChannelIndex != midiChannelIndex
  29153. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  29154. || (c->destChannelIndex == midiChannelIndex
  29155. && ! dest->processor->acceptsMidi()))
  29156. {
  29157. removeConnection (i);
  29158. doneAnything = true;
  29159. triggerAsyncUpdate();
  29160. }
  29161. }
  29162. return doneAnything;
  29163. }
  29164. namespace GraphRenderingOps
  29165. {
  29166. class AudioGraphRenderingOp
  29167. {
  29168. public:
  29169. AudioGraphRenderingOp() {}
  29170. virtual ~AudioGraphRenderingOp() {}
  29171. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29172. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29173. const int numSamples) = 0;
  29174. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29175. };
  29176. class ClearChannelOp : public AudioGraphRenderingOp
  29177. {
  29178. public:
  29179. ClearChannelOp (const int channelNum_)
  29180. : channelNum (channelNum_)
  29181. {}
  29182. ~ClearChannelOp() {}
  29183. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29184. {
  29185. sharedBufferChans.clear (channelNum, 0, numSamples);
  29186. }
  29187. private:
  29188. const int channelNum;
  29189. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29190. };
  29191. class CopyChannelOp : public AudioGraphRenderingOp
  29192. {
  29193. public:
  29194. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29195. : srcChannelNum (srcChannelNum_),
  29196. dstChannelNum (dstChannelNum_)
  29197. {}
  29198. ~CopyChannelOp() {}
  29199. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29200. {
  29201. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29202. }
  29203. private:
  29204. const int srcChannelNum, dstChannelNum;
  29205. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29206. };
  29207. class AddChannelOp : public AudioGraphRenderingOp
  29208. {
  29209. public:
  29210. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29211. : srcChannelNum (srcChannelNum_),
  29212. dstChannelNum (dstChannelNum_)
  29213. {}
  29214. ~AddChannelOp() {}
  29215. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29216. {
  29217. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29218. }
  29219. private:
  29220. const int srcChannelNum, dstChannelNum;
  29221. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29222. };
  29223. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29224. {
  29225. public:
  29226. ClearMidiBufferOp (const int bufferNum_)
  29227. : bufferNum (bufferNum_)
  29228. {}
  29229. ~ClearMidiBufferOp() {}
  29230. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29231. {
  29232. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29233. }
  29234. private:
  29235. const int bufferNum;
  29236. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29237. };
  29238. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29239. {
  29240. public:
  29241. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29242. : srcBufferNum (srcBufferNum_),
  29243. dstBufferNum (dstBufferNum_)
  29244. {}
  29245. ~CopyMidiBufferOp() {}
  29246. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29247. {
  29248. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29249. }
  29250. private:
  29251. const int srcBufferNum, dstBufferNum;
  29252. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29253. };
  29254. class AddMidiBufferOp : public AudioGraphRenderingOp
  29255. {
  29256. public:
  29257. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29258. : srcBufferNum (srcBufferNum_),
  29259. dstBufferNum (dstBufferNum_)
  29260. {}
  29261. ~AddMidiBufferOp() {}
  29262. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29263. {
  29264. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29265. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29266. }
  29267. private:
  29268. const int srcBufferNum, dstBufferNum;
  29269. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29270. };
  29271. class ProcessBufferOp : public AudioGraphRenderingOp
  29272. {
  29273. public:
  29274. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29275. const Array <int>& audioChannelsToUse_,
  29276. const int totalChans_,
  29277. const int midiBufferToUse_)
  29278. : node (node_),
  29279. processor (node_->getProcessor()),
  29280. audioChannelsToUse (audioChannelsToUse_),
  29281. totalChans (jmax (1, totalChans_)),
  29282. midiBufferToUse (midiBufferToUse_)
  29283. {
  29284. channels.calloc (totalChans);
  29285. while (audioChannelsToUse.size() < totalChans)
  29286. audioChannelsToUse.add (0);
  29287. }
  29288. ~ProcessBufferOp()
  29289. {
  29290. }
  29291. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29292. {
  29293. for (int i = totalChans; --i >= 0;)
  29294. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29295. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29296. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29297. }
  29298. const AudioProcessorGraph::Node::Ptr node;
  29299. AudioProcessor* const processor;
  29300. private:
  29301. Array <int> audioChannelsToUse;
  29302. HeapBlock <float*> channels;
  29303. int totalChans;
  29304. int midiBufferToUse;
  29305. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29306. };
  29307. /** Used to calculate the correct sequence of rendering ops needed, based on
  29308. the best re-use of shared buffers at each stage.
  29309. */
  29310. class RenderingOpSequenceCalculator
  29311. {
  29312. public:
  29313. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29314. const Array<void*>& orderedNodes_,
  29315. Array<void*>& renderingOps)
  29316. : graph (graph_),
  29317. orderedNodes (orderedNodes_)
  29318. {
  29319. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29320. channels.add (0);
  29321. midiNodeIds.add ((uint32) zeroNodeID);
  29322. for (int i = 0; i < orderedNodes.size(); ++i)
  29323. {
  29324. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29325. renderingOps, i);
  29326. markAnyUnusedBuffersAsFree (i);
  29327. }
  29328. }
  29329. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29330. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29331. private:
  29332. AudioProcessorGraph& graph;
  29333. const Array<void*>& orderedNodes;
  29334. Array <int> channels;
  29335. Array <uint32> nodeIds, midiNodeIds;
  29336. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29337. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29338. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29339. Array<void*>& renderingOps,
  29340. const int ourRenderingIndex)
  29341. {
  29342. const int numIns = node->getProcessor()->getNumInputChannels();
  29343. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29344. const int totalChans = jmax (numIns, numOuts);
  29345. Array <int> audioChannelsToUse;
  29346. int midiBufferToUse = -1;
  29347. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29348. {
  29349. // get a list of all the inputs to this node
  29350. Array <int> sourceNodes, sourceOutputChans;
  29351. for (int i = graph.getNumConnections(); --i >= 0;)
  29352. {
  29353. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29354. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29355. {
  29356. sourceNodes.add (c->sourceNodeId);
  29357. sourceOutputChans.add (c->sourceChannelIndex);
  29358. }
  29359. }
  29360. int bufIndex = -1;
  29361. if (sourceNodes.size() == 0)
  29362. {
  29363. // unconnected input channel
  29364. if (inputChan >= numOuts)
  29365. {
  29366. bufIndex = getReadOnlyEmptyBuffer();
  29367. jassert (bufIndex >= 0);
  29368. }
  29369. else
  29370. {
  29371. bufIndex = getFreeBuffer (false);
  29372. renderingOps.add (new ClearChannelOp (bufIndex));
  29373. }
  29374. }
  29375. else if (sourceNodes.size() == 1)
  29376. {
  29377. // channel with a straightforward single input..
  29378. const int srcNode = sourceNodes.getUnchecked(0);
  29379. const int srcChan = sourceOutputChans.getUnchecked(0);
  29380. bufIndex = getBufferContaining (srcNode, srcChan);
  29381. if (bufIndex < 0)
  29382. {
  29383. // if not found, this is probably a feedback loop
  29384. bufIndex = getReadOnlyEmptyBuffer();
  29385. jassert (bufIndex >= 0);
  29386. }
  29387. if (inputChan < numOuts
  29388. && isBufferNeededLater (ourRenderingIndex,
  29389. inputChan,
  29390. srcNode, srcChan))
  29391. {
  29392. // can't mess up this channel because it's needed later by another node, so we
  29393. // need to use a copy of it..
  29394. const int newFreeBuffer = getFreeBuffer (false);
  29395. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29396. bufIndex = newFreeBuffer;
  29397. }
  29398. }
  29399. else
  29400. {
  29401. // channel with a mix of several inputs..
  29402. // try to find a re-usable channel from our inputs..
  29403. int reusableInputIndex = -1;
  29404. for (int i = 0; i < sourceNodes.size(); ++i)
  29405. {
  29406. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29407. sourceOutputChans.getUnchecked(i));
  29408. if (sourceBufIndex >= 0
  29409. && ! isBufferNeededLater (ourRenderingIndex,
  29410. inputChan,
  29411. sourceNodes.getUnchecked(i),
  29412. sourceOutputChans.getUnchecked(i)))
  29413. {
  29414. // we've found one of our input chans that can be re-used..
  29415. reusableInputIndex = i;
  29416. bufIndex = sourceBufIndex;
  29417. break;
  29418. }
  29419. }
  29420. if (reusableInputIndex < 0)
  29421. {
  29422. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29423. bufIndex = getFreeBuffer (false);
  29424. jassert (bufIndex != 0);
  29425. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29426. sourceOutputChans.getUnchecked (0));
  29427. if (srcIndex < 0)
  29428. {
  29429. // if not found, this is probably a feedback loop
  29430. renderingOps.add (new ClearChannelOp (bufIndex));
  29431. }
  29432. else
  29433. {
  29434. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29435. }
  29436. reusableInputIndex = 0;
  29437. }
  29438. for (int j = 0; j < sourceNodes.size(); ++j)
  29439. {
  29440. if (j != reusableInputIndex)
  29441. {
  29442. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29443. sourceOutputChans.getUnchecked(j));
  29444. if (srcIndex >= 0)
  29445. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29446. }
  29447. }
  29448. }
  29449. jassert (bufIndex >= 0);
  29450. audioChannelsToUse.add (bufIndex);
  29451. if (inputChan < numOuts)
  29452. markBufferAsContaining (bufIndex, node->id, inputChan);
  29453. }
  29454. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29455. {
  29456. const int bufIndex = getFreeBuffer (false);
  29457. jassert (bufIndex != 0);
  29458. audioChannelsToUse.add (bufIndex);
  29459. markBufferAsContaining (bufIndex, node->id, outputChan);
  29460. }
  29461. // Now the same thing for midi..
  29462. Array <int> midiSourceNodes;
  29463. for (int i = graph.getNumConnections(); --i >= 0;)
  29464. {
  29465. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29466. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29467. midiSourceNodes.add (c->sourceNodeId);
  29468. }
  29469. if (midiSourceNodes.size() == 0)
  29470. {
  29471. // No midi inputs..
  29472. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29473. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29474. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29475. }
  29476. else if (midiSourceNodes.size() == 1)
  29477. {
  29478. // One midi input..
  29479. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29480. AudioProcessorGraph::midiChannelIndex);
  29481. if (midiBufferToUse >= 0)
  29482. {
  29483. if (isBufferNeededLater (ourRenderingIndex,
  29484. AudioProcessorGraph::midiChannelIndex,
  29485. midiSourceNodes.getUnchecked(0),
  29486. AudioProcessorGraph::midiChannelIndex))
  29487. {
  29488. // can't mess up this channel because it's needed later by another node, so we
  29489. // need to use a copy of it..
  29490. const int newFreeBuffer = getFreeBuffer (true);
  29491. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29492. midiBufferToUse = newFreeBuffer;
  29493. }
  29494. }
  29495. else
  29496. {
  29497. // probably a feedback loop, so just use an empty one..
  29498. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29499. }
  29500. }
  29501. else
  29502. {
  29503. // More than one midi input being mixed..
  29504. int reusableInputIndex = -1;
  29505. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29506. {
  29507. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29508. AudioProcessorGraph::midiChannelIndex);
  29509. if (sourceBufIndex >= 0
  29510. && ! isBufferNeededLater (ourRenderingIndex,
  29511. AudioProcessorGraph::midiChannelIndex,
  29512. midiSourceNodes.getUnchecked(i),
  29513. AudioProcessorGraph::midiChannelIndex))
  29514. {
  29515. // we've found one of our input buffers that can be re-used..
  29516. reusableInputIndex = i;
  29517. midiBufferToUse = sourceBufIndex;
  29518. break;
  29519. }
  29520. }
  29521. if (reusableInputIndex < 0)
  29522. {
  29523. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29524. midiBufferToUse = getFreeBuffer (true);
  29525. jassert (midiBufferToUse >= 0);
  29526. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29527. AudioProcessorGraph::midiChannelIndex);
  29528. if (srcIndex >= 0)
  29529. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29530. else
  29531. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29532. reusableInputIndex = 0;
  29533. }
  29534. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29535. {
  29536. if (j != reusableInputIndex)
  29537. {
  29538. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29539. AudioProcessorGraph::midiChannelIndex);
  29540. if (srcIndex >= 0)
  29541. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29542. }
  29543. }
  29544. }
  29545. if (node->getProcessor()->producesMidi())
  29546. markBufferAsContaining (midiBufferToUse, node->id,
  29547. AudioProcessorGraph::midiChannelIndex);
  29548. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29549. totalChans, midiBufferToUse));
  29550. }
  29551. int getFreeBuffer (const bool forMidi)
  29552. {
  29553. if (forMidi)
  29554. {
  29555. for (int i = 1; i < midiNodeIds.size(); ++i)
  29556. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29557. return i;
  29558. midiNodeIds.add ((uint32) freeNodeID);
  29559. return midiNodeIds.size() - 1;
  29560. }
  29561. else
  29562. {
  29563. for (int i = 1; i < nodeIds.size(); ++i)
  29564. if (nodeIds.getUnchecked(i) == freeNodeID)
  29565. return i;
  29566. nodeIds.add ((uint32) freeNodeID);
  29567. channels.add (0);
  29568. return nodeIds.size() - 1;
  29569. }
  29570. }
  29571. int getReadOnlyEmptyBuffer() const
  29572. {
  29573. return 0;
  29574. }
  29575. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29576. {
  29577. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29578. {
  29579. for (int i = midiNodeIds.size(); --i >= 0;)
  29580. if (midiNodeIds.getUnchecked(i) == nodeId)
  29581. return i;
  29582. }
  29583. else
  29584. {
  29585. for (int i = nodeIds.size(); --i >= 0;)
  29586. if (nodeIds.getUnchecked(i) == nodeId
  29587. && channels.getUnchecked(i) == outputChannel)
  29588. return i;
  29589. }
  29590. return -1;
  29591. }
  29592. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29593. {
  29594. int i;
  29595. for (i = 0; i < nodeIds.size(); ++i)
  29596. {
  29597. if (isNodeBusy (nodeIds.getUnchecked(i))
  29598. && ! isBufferNeededLater (stepIndex, -1,
  29599. nodeIds.getUnchecked(i),
  29600. channels.getUnchecked(i)))
  29601. {
  29602. nodeIds.set (i, (uint32) freeNodeID);
  29603. }
  29604. }
  29605. for (i = 0; i < midiNodeIds.size(); ++i)
  29606. {
  29607. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29608. && ! isBufferNeededLater (stepIndex, -1,
  29609. midiNodeIds.getUnchecked(i),
  29610. AudioProcessorGraph::midiChannelIndex))
  29611. {
  29612. midiNodeIds.set (i, (uint32) freeNodeID);
  29613. }
  29614. }
  29615. }
  29616. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29617. int inputChannelOfIndexToIgnore,
  29618. const uint32 nodeId,
  29619. const int outputChanIndex) const
  29620. {
  29621. while (stepIndexToSearchFrom < orderedNodes.size())
  29622. {
  29623. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29624. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29625. {
  29626. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29627. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29628. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29629. return true;
  29630. }
  29631. else
  29632. {
  29633. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29634. if (i != inputChannelOfIndexToIgnore
  29635. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29636. node->id, i) != 0)
  29637. return true;
  29638. }
  29639. inputChannelOfIndexToIgnore = -1;
  29640. ++stepIndexToSearchFrom;
  29641. }
  29642. return false;
  29643. }
  29644. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29645. {
  29646. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29647. {
  29648. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29649. midiNodeIds.set (bufferNum, nodeId);
  29650. }
  29651. else
  29652. {
  29653. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29654. nodeIds.set (bufferNum, nodeId);
  29655. channels.set (bufferNum, outputIndex);
  29656. }
  29657. }
  29658. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29659. };
  29660. }
  29661. void AudioProcessorGraph::clearRenderingSequence()
  29662. {
  29663. const ScopedLock sl (renderLock);
  29664. for (int i = renderingOps.size(); --i >= 0;)
  29665. {
  29666. GraphRenderingOps::AudioGraphRenderingOp* const r
  29667. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29668. renderingOps.remove (i);
  29669. delete r;
  29670. }
  29671. }
  29672. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29673. const uint32 possibleDestinationId,
  29674. const int recursionCheck) const
  29675. {
  29676. if (recursionCheck > 0)
  29677. {
  29678. for (int i = connections.size(); --i >= 0;)
  29679. {
  29680. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29681. if (c->destNodeId == possibleDestinationId
  29682. && (c->sourceNodeId == possibleInputId
  29683. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29684. return true;
  29685. }
  29686. }
  29687. return false;
  29688. }
  29689. void AudioProcessorGraph::buildRenderingSequence()
  29690. {
  29691. Array<void*> newRenderingOps;
  29692. int numRenderingBuffersNeeded = 2;
  29693. int numMidiBuffersNeeded = 1;
  29694. {
  29695. MessageManagerLock mml;
  29696. Array<void*> orderedNodes;
  29697. int i;
  29698. for (i = 0; i < nodes.size(); ++i)
  29699. {
  29700. Node* const node = nodes.getUnchecked(i);
  29701. node->prepare (getSampleRate(), getBlockSize(), this);
  29702. int j = 0;
  29703. for (; j < orderedNodes.size(); ++j)
  29704. if (isAnInputTo (node->id,
  29705. ((Node*) orderedNodes.getUnchecked (j))->id,
  29706. nodes.size() + 1))
  29707. break;
  29708. orderedNodes.insert (j, node);
  29709. }
  29710. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29711. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29712. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29713. }
  29714. Array<void*> oldRenderingOps (renderingOps);
  29715. {
  29716. // swap over to the new rendering sequence..
  29717. const ScopedLock sl (renderLock);
  29718. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29719. renderingBuffers.clear();
  29720. for (int i = midiBuffers.size(); --i >= 0;)
  29721. midiBuffers.getUnchecked(i)->clear();
  29722. while (midiBuffers.size() < numMidiBuffersNeeded)
  29723. midiBuffers.add (new MidiBuffer());
  29724. renderingOps = newRenderingOps;
  29725. }
  29726. for (int i = oldRenderingOps.size(); --i >= 0;)
  29727. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29728. }
  29729. void AudioProcessorGraph::handleAsyncUpdate()
  29730. {
  29731. buildRenderingSequence();
  29732. }
  29733. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29734. {
  29735. currentAudioInputBuffer = 0;
  29736. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29737. currentMidiInputBuffer = 0;
  29738. currentMidiOutputBuffer.clear();
  29739. clearRenderingSequence();
  29740. buildRenderingSequence();
  29741. }
  29742. void AudioProcessorGraph::releaseResources()
  29743. {
  29744. for (int i = 0; i < nodes.size(); ++i)
  29745. nodes.getUnchecked(i)->unprepare();
  29746. renderingBuffers.setSize (1, 1);
  29747. midiBuffers.clear();
  29748. currentAudioInputBuffer = 0;
  29749. currentAudioOutputBuffer.setSize (1, 1);
  29750. currentMidiInputBuffer = 0;
  29751. currentMidiOutputBuffer.clear();
  29752. }
  29753. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29754. {
  29755. const int numSamples = buffer.getNumSamples();
  29756. const ScopedLock sl (renderLock);
  29757. currentAudioInputBuffer = &buffer;
  29758. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29759. currentAudioOutputBuffer.clear();
  29760. currentMidiInputBuffer = &midiMessages;
  29761. currentMidiOutputBuffer.clear();
  29762. int i;
  29763. for (i = 0; i < renderingOps.size(); ++i)
  29764. {
  29765. GraphRenderingOps::AudioGraphRenderingOp* const op
  29766. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29767. op->perform (renderingBuffers, midiBuffers, numSamples);
  29768. }
  29769. for (i = 0; i < buffer.getNumChannels(); ++i)
  29770. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29771. midiMessages.clear();
  29772. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29773. }
  29774. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29775. {
  29776. return "Input " + String (channelIndex + 1);
  29777. }
  29778. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29779. {
  29780. return "Output " + String (channelIndex + 1);
  29781. }
  29782. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29783. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29784. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29785. bool AudioProcessorGraph::producesMidi() const { return true; }
  29786. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29787. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29788. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29789. : type (type_),
  29790. graph (0)
  29791. {
  29792. }
  29793. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29794. {
  29795. }
  29796. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29797. {
  29798. switch (type)
  29799. {
  29800. case audioOutputNode: return "Audio Output";
  29801. case audioInputNode: return "Audio Input";
  29802. case midiOutputNode: return "Midi Output";
  29803. case midiInputNode: return "Midi Input";
  29804. default: break;
  29805. }
  29806. return String::empty;
  29807. }
  29808. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29809. {
  29810. d.name = getName();
  29811. d.uid = d.name.hashCode();
  29812. d.category = "I/O devices";
  29813. d.pluginFormatName = "Internal";
  29814. d.manufacturerName = "Raw Material Software";
  29815. d.version = "1.0";
  29816. d.isInstrument = false;
  29817. d.numInputChannels = getNumInputChannels();
  29818. if (type == audioOutputNode && graph != 0)
  29819. d.numInputChannels = graph->getNumInputChannels();
  29820. d.numOutputChannels = getNumOutputChannels();
  29821. if (type == audioInputNode && graph != 0)
  29822. d.numOutputChannels = graph->getNumOutputChannels();
  29823. }
  29824. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29825. {
  29826. jassert (graph != 0);
  29827. }
  29828. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29829. {
  29830. }
  29831. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29832. MidiBuffer& midiMessages)
  29833. {
  29834. jassert (graph != 0);
  29835. switch (type)
  29836. {
  29837. case audioOutputNode:
  29838. {
  29839. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29840. buffer.getNumChannels()); --i >= 0;)
  29841. {
  29842. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29843. }
  29844. break;
  29845. }
  29846. case audioInputNode:
  29847. {
  29848. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29849. buffer.getNumChannels()); --i >= 0;)
  29850. {
  29851. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29852. }
  29853. break;
  29854. }
  29855. case midiOutputNode:
  29856. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29857. break;
  29858. case midiInputNode:
  29859. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29860. break;
  29861. default:
  29862. break;
  29863. }
  29864. }
  29865. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29866. {
  29867. return type == midiOutputNode;
  29868. }
  29869. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29870. {
  29871. return type == midiInputNode;
  29872. }
  29873. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29874. {
  29875. switch (type)
  29876. {
  29877. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29878. case midiOutputNode: return "Midi Output";
  29879. default: break;
  29880. }
  29881. return String::empty;
  29882. }
  29883. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29884. {
  29885. switch (type)
  29886. {
  29887. case audioInputNode: return "Input " + String (channelIndex + 1);
  29888. case midiInputNode: return "Midi Input";
  29889. default: break;
  29890. }
  29891. return String::empty;
  29892. }
  29893. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29894. {
  29895. return type == audioInputNode || type == audioOutputNode;
  29896. }
  29897. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29898. {
  29899. return isInputChannelStereoPair (index);
  29900. }
  29901. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29902. {
  29903. return type == audioInputNode || type == midiInputNode;
  29904. }
  29905. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29906. {
  29907. return type == audioOutputNode || type == midiOutputNode;
  29908. }
  29909. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29910. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29911. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29912. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29913. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29914. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29915. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29916. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29917. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29918. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29919. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29920. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29921. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29922. {
  29923. }
  29924. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29925. {
  29926. }
  29927. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29928. {
  29929. graph = newGraph;
  29930. if (graph != 0)
  29931. {
  29932. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29933. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29934. getSampleRate(),
  29935. getBlockSize());
  29936. updateHostDisplay();
  29937. }
  29938. }
  29939. END_JUCE_NAMESPACE
  29940. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29941. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29942. BEGIN_JUCE_NAMESPACE
  29943. AudioProcessorPlayer::AudioProcessorPlayer()
  29944. : processor (0),
  29945. sampleRate (0),
  29946. blockSize (0),
  29947. isPrepared (false),
  29948. numInputChans (0),
  29949. numOutputChans (0),
  29950. tempBuffer (1, 1)
  29951. {
  29952. }
  29953. AudioProcessorPlayer::~AudioProcessorPlayer()
  29954. {
  29955. setProcessor (0);
  29956. }
  29957. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29958. {
  29959. if (processor != processorToPlay)
  29960. {
  29961. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29962. {
  29963. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29964. sampleRate, blockSize);
  29965. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29966. }
  29967. AudioProcessor* oldOne;
  29968. {
  29969. const ScopedLock sl (lock);
  29970. oldOne = isPrepared ? processor : 0;
  29971. processor = processorToPlay;
  29972. isPrepared = true;
  29973. }
  29974. if (oldOne != 0)
  29975. oldOne->releaseResources();
  29976. }
  29977. }
  29978. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29979. const int numInputChannels,
  29980. float** const outputChannelData,
  29981. const int numOutputChannels,
  29982. const int numSamples)
  29983. {
  29984. // these should have been prepared by audioDeviceAboutToStart()...
  29985. jassert (sampleRate > 0 && blockSize > 0);
  29986. incomingMidi.clear();
  29987. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29988. int i, totalNumChans = 0;
  29989. if (numInputChannels > numOutputChannels)
  29990. {
  29991. // if there aren't enough output channels for the number of
  29992. // inputs, we need to create some temporary extra ones (can't
  29993. // use the input data in case it gets written to)
  29994. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29995. false, false, true);
  29996. for (i = 0; i < numOutputChannels; ++i)
  29997. {
  29998. channels[totalNumChans] = outputChannelData[i];
  29999. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30000. ++totalNumChans;
  30001. }
  30002. for (i = numOutputChannels; i < numInputChannels; ++i)
  30003. {
  30004. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30005. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30006. ++totalNumChans;
  30007. }
  30008. }
  30009. else
  30010. {
  30011. for (i = 0; i < numInputChannels; ++i)
  30012. {
  30013. channels[totalNumChans] = outputChannelData[i];
  30014. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30015. ++totalNumChans;
  30016. }
  30017. for (i = numInputChannels; i < numOutputChannels; ++i)
  30018. {
  30019. channels[totalNumChans] = outputChannelData[i];
  30020. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30021. ++totalNumChans;
  30022. }
  30023. }
  30024. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30025. const ScopedLock sl (lock);
  30026. if (processor != 0)
  30027. {
  30028. const ScopedLock sl2 (processor->getCallbackLock());
  30029. if (processor->isSuspended())
  30030. {
  30031. for (i = 0; i < numOutputChannels; ++i)
  30032. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30033. }
  30034. else
  30035. {
  30036. processor->processBlock (buffer, incomingMidi);
  30037. }
  30038. }
  30039. }
  30040. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30041. {
  30042. const ScopedLock sl (lock);
  30043. sampleRate = device->getCurrentSampleRate();
  30044. blockSize = device->getCurrentBufferSizeSamples();
  30045. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30046. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30047. messageCollector.reset (sampleRate);
  30048. zeromem (channels, sizeof (channels));
  30049. if (processor != 0)
  30050. {
  30051. if (isPrepared)
  30052. processor->releaseResources();
  30053. AudioProcessor* const oldProcessor = processor;
  30054. setProcessor (0);
  30055. setProcessor (oldProcessor);
  30056. }
  30057. }
  30058. void AudioProcessorPlayer::audioDeviceStopped()
  30059. {
  30060. const ScopedLock sl (lock);
  30061. if (processor != 0 && isPrepared)
  30062. processor->releaseResources();
  30063. sampleRate = 0.0;
  30064. blockSize = 0;
  30065. isPrepared = false;
  30066. tempBuffer.setSize (1, 1);
  30067. }
  30068. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30069. {
  30070. messageCollector.addMessageToQueue (message);
  30071. }
  30072. END_JUCE_NAMESPACE
  30073. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30074. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30075. BEGIN_JUCE_NAMESPACE
  30076. class ProcessorParameterPropertyComp : public PropertyComponent,
  30077. public AudioProcessorListener,
  30078. public Timer
  30079. {
  30080. public:
  30081. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30082. : PropertyComponent (name),
  30083. owner (owner_),
  30084. index (index_),
  30085. paramHasChanged (false),
  30086. slider (owner_, index_)
  30087. {
  30088. startTimer (100);
  30089. addAndMakeVisible (&slider);
  30090. owner_.addListener (this);
  30091. }
  30092. ~ProcessorParameterPropertyComp()
  30093. {
  30094. owner.removeListener (this);
  30095. }
  30096. void refresh()
  30097. {
  30098. paramHasChanged = false;
  30099. slider.setValue (owner.getParameter (index), false);
  30100. }
  30101. void audioProcessorChanged (AudioProcessor*) {}
  30102. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30103. {
  30104. if (parameterIndex == index)
  30105. paramHasChanged = true;
  30106. }
  30107. void timerCallback()
  30108. {
  30109. if (paramHasChanged)
  30110. {
  30111. refresh();
  30112. startTimer (1000 / 50);
  30113. }
  30114. else
  30115. {
  30116. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30117. }
  30118. }
  30119. private:
  30120. class ParamSlider : public Slider
  30121. {
  30122. public:
  30123. ParamSlider (AudioProcessor& owner_, const int index_)
  30124. : owner (owner_),
  30125. index (index_)
  30126. {
  30127. setRange (0.0, 1.0, 0.0);
  30128. setSliderStyle (Slider::LinearBar);
  30129. setTextBoxIsEditable (false);
  30130. setScrollWheelEnabled (false);
  30131. }
  30132. void valueChanged()
  30133. {
  30134. const float newVal = (float) getValue();
  30135. if (owner.getParameter (index) != newVal)
  30136. owner.setParameter (index, newVal);
  30137. }
  30138. const String getTextFromValue (double /*value*/)
  30139. {
  30140. return owner.getParameterText (index);
  30141. }
  30142. private:
  30143. AudioProcessor& owner;
  30144. const int index;
  30145. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  30146. };
  30147. AudioProcessor& owner;
  30148. const int index;
  30149. bool volatile paramHasChanged;
  30150. ParamSlider slider;
  30151. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  30152. };
  30153. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30154. : AudioProcessorEditor (owner_)
  30155. {
  30156. jassert (owner_ != 0);
  30157. setOpaque (true);
  30158. addAndMakeVisible (&panel);
  30159. Array <PropertyComponent*> params;
  30160. const int numParams = owner_->getNumParameters();
  30161. int totalHeight = 0;
  30162. for (int i = 0; i < numParams; ++i)
  30163. {
  30164. String name (owner_->getParameterName (i));
  30165. if (name.trim().isEmpty())
  30166. name = "Unnamed";
  30167. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30168. params.add (pc);
  30169. totalHeight += pc->getPreferredHeight();
  30170. }
  30171. panel.addProperties (params);
  30172. setSize (400, jlimit (25, 400, totalHeight));
  30173. }
  30174. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30175. {
  30176. }
  30177. void GenericAudioProcessorEditor::paint (Graphics& g)
  30178. {
  30179. g.fillAll (Colours::white);
  30180. }
  30181. void GenericAudioProcessorEditor::resized()
  30182. {
  30183. panel.setBounds (getLocalBounds());
  30184. }
  30185. END_JUCE_NAMESPACE
  30186. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30187. /*** Start of inlined file: juce_Sampler.cpp ***/
  30188. BEGIN_JUCE_NAMESPACE
  30189. SamplerSound::SamplerSound (const String& name_,
  30190. AudioFormatReader& source,
  30191. const BigInteger& midiNotes_,
  30192. const int midiNoteForNormalPitch,
  30193. const double attackTimeSecs,
  30194. const double releaseTimeSecs,
  30195. const double maxSampleLengthSeconds)
  30196. : name (name_),
  30197. midiNotes (midiNotes_),
  30198. midiRootNote (midiNoteForNormalPitch)
  30199. {
  30200. sourceSampleRate = source.sampleRate;
  30201. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30202. {
  30203. length = 0;
  30204. attackSamples = 0;
  30205. releaseSamples = 0;
  30206. }
  30207. else
  30208. {
  30209. length = jmin ((int) source.lengthInSamples,
  30210. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30211. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30212. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30213. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30214. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30215. }
  30216. }
  30217. SamplerSound::~SamplerSound()
  30218. {
  30219. }
  30220. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30221. {
  30222. return midiNotes [midiNoteNumber];
  30223. }
  30224. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30225. {
  30226. return true;
  30227. }
  30228. SamplerVoice::SamplerVoice()
  30229. : pitchRatio (0.0),
  30230. sourceSamplePosition (0.0),
  30231. lgain (0.0f),
  30232. rgain (0.0f),
  30233. isInAttack (false),
  30234. isInRelease (false)
  30235. {
  30236. }
  30237. SamplerVoice::~SamplerVoice()
  30238. {
  30239. }
  30240. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30241. {
  30242. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30243. }
  30244. void SamplerVoice::startNote (const int midiNoteNumber,
  30245. const float velocity,
  30246. SynthesiserSound* s,
  30247. const int /*currentPitchWheelPosition*/)
  30248. {
  30249. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30250. jassert (sound != 0); // this object can only play SamplerSounds!
  30251. if (sound != 0)
  30252. {
  30253. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30254. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30255. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30256. sourceSamplePosition = 0.0;
  30257. lgain = velocity;
  30258. rgain = velocity;
  30259. isInAttack = (sound->attackSamples > 0);
  30260. isInRelease = false;
  30261. if (isInAttack)
  30262. {
  30263. attackReleaseLevel = 0.0f;
  30264. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30265. }
  30266. else
  30267. {
  30268. attackReleaseLevel = 1.0f;
  30269. attackDelta = 0.0f;
  30270. }
  30271. if (sound->releaseSamples > 0)
  30272. {
  30273. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30274. }
  30275. else
  30276. {
  30277. releaseDelta = 0.0f;
  30278. }
  30279. }
  30280. }
  30281. void SamplerVoice::stopNote (const bool allowTailOff)
  30282. {
  30283. if (allowTailOff)
  30284. {
  30285. isInAttack = false;
  30286. isInRelease = true;
  30287. }
  30288. else
  30289. {
  30290. clearCurrentNote();
  30291. }
  30292. }
  30293. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30294. {
  30295. }
  30296. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30297. const int /*newValue*/)
  30298. {
  30299. }
  30300. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30301. {
  30302. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30303. if (playingSound != 0)
  30304. {
  30305. const float* const inL = playingSound->data->getSampleData (0, 0);
  30306. const float* const inR = playingSound->data->getNumChannels() > 1
  30307. ? playingSound->data->getSampleData (1, 0) : 0;
  30308. float* outL = outputBuffer.getSampleData (0, startSample);
  30309. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30310. while (--numSamples >= 0)
  30311. {
  30312. const int pos = (int) sourceSamplePosition;
  30313. const float alpha = (float) (sourceSamplePosition - pos);
  30314. const float invAlpha = 1.0f - alpha;
  30315. // just using a very simple linear interpolation here..
  30316. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30317. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30318. : l;
  30319. l *= lgain;
  30320. r *= rgain;
  30321. if (isInAttack)
  30322. {
  30323. l *= attackReleaseLevel;
  30324. r *= attackReleaseLevel;
  30325. attackReleaseLevel += attackDelta;
  30326. if (attackReleaseLevel >= 1.0f)
  30327. {
  30328. attackReleaseLevel = 1.0f;
  30329. isInAttack = false;
  30330. }
  30331. }
  30332. else if (isInRelease)
  30333. {
  30334. l *= attackReleaseLevel;
  30335. r *= attackReleaseLevel;
  30336. attackReleaseLevel += releaseDelta;
  30337. if (attackReleaseLevel <= 0.0f)
  30338. {
  30339. stopNote (false);
  30340. break;
  30341. }
  30342. }
  30343. if (outR != 0)
  30344. {
  30345. *outL++ += l;
  30346. *outR++ += r;
  30347. }
  30348. else
  30349. {
  30350. *outL++ += (l + r) * 0.5f;
  30351. }
  30352. sourceSamplePosition += pitchRatio;
  30353. if (sourceSamplePosition > playingSound->length)
  30354. {
  30355. stopNote (false);
  30356. break;
  30357. }
  30358. }
  30359. }
  30360. }
  30361. END_JUCE_NAMESPACE
  30362. /*** End of inlined file: juce_Sampler.cpp ***/
  30363. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30364. BEGIN_JUCE_NAMESPACE
  30365. SynthesiserSound::SynthesiserSound()
  30366. {
  30367. }
  30368. SynthesiserSound::~SynthesiserSound()
  30369. {
  30370. }
  30371. SynthesiserVoice::SynthesiserVoice()
  30372. : currentSampleRate (44100.0),
  30373. currentlyPlayingNote (-1),
  30374. noteOnTime (0),
  30375. currentlyPlayingSound (0)
  30376. {
  30377. }
  30378. SynthesiserVoice::~SynthesiserVoice()
  30379. {
  30380. }
  30381. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30382. {
  30383. return currentlyPlayingSound != 0
  30384. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30385. }
  30386. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30387. {
  30388. currentSampleRate = newRate;
  30389. }
  30390. void SynthesiserVoice::clearCurrentNote()
  30391. {
  30392. currentlyPlayingNote = -1;
  30393. currentlyPlayingSound = 0;
  30394. }
  30395. Synthesiser::Synthesiser()
  30396. : sampleRate (0),
  30397. lastNoteOnCounter (0),
  30398. shouldStealNotes (true)
  30399. {
  30400. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30401. lastPitchWheelValues[i] = 0x2000;
  30402. }
  30403. Synthesiser::~Synthesiser()
  30404. {
  30405. }
  30406. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30407. {
  30408. const ScopedLock sl (lock);
  30409. return voices [index];
  30410. }
  30411. void Synthesiser::clearVoices()
  30412. {
  30413. const ScopedLock sl (lock);
  30414. voices.clear();
  30415. }
  30416. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30417. {
  30418. const ScopedLock sl (lock);
  30419. voices.add (newVoice);
  30420. }
  30421. void Synthesiser::removeVoice (const int index)
  30422. {
  30423. const ScopedLock sl (lock);
  30424. voices.remove (index);
  30425. }
  30426. void Synthesiser::clearSounds()
  30427. {
  30428. const ScopedLock sl (lock);
  30429. sounds.clear();
  30430. }
  30431. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30432. {
  30433. const ScopedLock sl (lock);
  30434. sounds.add (newSound);
  30435. }
  30436. void Synthesiser::removeSound (const int index)
  30437. {
  30438. const ScopedLock sl (lock);
  30439. sounds.remove (index);
  30440. }
  30441. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30442. {
  30443. shouldStealNotes = shouldStealNotes_;
  30444. }
  30445. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30446. {
  30447. if (sampleRate != newRate)
  30448. {
  30449. const ScopedLock sl (lock);
  30450. allNotesOff (0, false);
  30451. sampleRate = newRate;
  30452. for (int i = voices.size(); --i >= 0;)
  30453. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30454. }
  30455. }
  30456. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30457. const MidiBuffer& midiData,
  30458. int startSample,
  30459. int numSamples)
  30460. {
  30461. // must set the sample rate before using this!
  30462. jassert (sampleRate != 0);
  30463. const ScopedLock sl (lock);
  30464. MidiBuffer::Iterator midiIterator (midiData);
  30465. midiIterator.setNextSamplePosition (startSample);
  30466. MidiMessage m (0xf4, 0.0);
  30467. while (numSamples > 0)
  30468. {
  30469. int midiEventPos;
  30470. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30471. && midiEventPos < startSample + numSamples;
  30472. const int numThisTime = useEvent ? midiEventPos - startSample
  30473. : numSamples;
  30474. if (numThisTime > 0)
  30475. {
  30476. for (int i = voices.size(); --i >= 0;)
  30477. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30478. }
  30479. if (useEvent)
  30480. {
  30481. if (m.isNoteOn())
  30482. {
  30483. const int channel = m.getChannel();
  30484. noteOn (channel,
  30485. m.getNoteNumber(),
  30486. m.getFloatVelocity());
  30487. }
  30488. else if (m.isNoteOff())
  30489. {
  30490. noteOff (m.getChannel(),
  30491. m.getNoteNumber(),
  30492. true);
  30493. }
  30494. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30495. {
  30496. allNotesOff (m.getChannel(), true);
  30497. }
  30498. else if (m.isPitchWheel())
  30499. {
  30500. const int channel = m.getChannel();
  30501. const int wheelPos = m.getPitchWheelValue();
  30502. lastPitchWheelValues [channel - 1] = wheelPos;
  30503. handlePitchWheel (channel, wheelPos);
  30504. }
  30505. else if (m.isController())
  30506. {
  30507. handleController (m.getChannel(),
  30508. m.getControllerNumber(),
  30509. m.getControllerValue());
  30510. }
  30511. }
  30512. startSample += numThisTime;
  30513. numSamples -= numThisTime;
  30514. }
  30515. }
  30516. void Synthesiser::noteOn (const int midiChannel,
  30517. const int midiNoteNumber,
  30518. const float velocity)
  30519. {
  30520. const ScopedLock sl (lock);
  30521. for (int i = sounds.size(); --i >= 0;)
  30522. {
  30523. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30524. if (sound->appliesToNote (midiNoteNumber)
  30525. && sound->appliesToChannel (midiChannel))
  30526. {
  30527. startVoice (findFreeVoice (sound, shouldStealNotes),
  30528. sound, midiChannel, midiNoteNumber, velocity);
  30529. }
  30530. }
  30531. }
  30532. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30533. SynthesiserSound* const sound,
  30534. const int midiChannel,
  30535. const int midiNoteNumber,
  30536. const float velocity)
  30537. {
  30538. if (voice != 0 && sound != 0)
  30539. {
  30540. if (voice->currentlyPlayingSound != 0)
  30541. voice->stopNote (false);
  30542. voice->startNote (midiNoteNumber,
  30543. velocity,
  30544. sound,
  30545. lastPitchWheelValues [midiChannel - 1]);
  30546. voice->currentlyPlayingNote = midiNoteNumber;
  30547. voice->noteOnTime = ++lastNoteOnCounter;
  30548. voice->currentlyPlayingSound = sound;
  30549. }
  30550. }
  30551. void Synthesiser::noteOff (const int midiChannel,
  30552. const int midiNoteNumber,
  30553. const bool allowTailOff)
  30554. {
  30555. const ScopedLock sl (lock);
  30556. for (int i = voices.size(); --i >= 0;)
  30557. {
  30558. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30559. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30560. {
  30561. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30562. if (sound != 0
  30563. && sound->appliesToNote (midiNoteNumber)
  30564. && sound->appliesToChannel (midiChannel))
  30565. {
  30566. voice->stopNote (allowTailOff);
  30567. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30568. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30569. }
  30570. }
  30571. }
  30572. }
  30573. void Synthesiser::allNotesOff (const int midiChannel,
  30574. const bool allowTailOff)
  30575. {
  30576. const ScopedLock sl (lock);
  30577. for (int i = voices.size(); --i >= 0;)
  30578. {
  30579. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30580. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30581. voice->stopNote (allowTailOff);
  30582. }
  30583. }
  30584. void Synthesiser::handlePitchWheel (const int midiChannel,
  30585. const int wheelValue)
  30586. {
  30587. const ScopedLock sl (lock);
  30588. for (int i = voices.size(); --i >= 0;)
  30589. {
  30590. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30591. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30592. {
  30593. voice->pitchWheelMoved (wheelValue);
  30594. }
  30595. }
  30596. }
  30597. void Synthesiser::handleController (const int midiChannel,
  30598. const int controllerNumber,
  30599. const int controllerValue)
  30600. {
  30601. const ScopedLock sl (lock);
  30602. for (int i = voices.size(); --i >= 0;)
  30603. {
  30604. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30605. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30606. voice->controllerMoved (controllerNumber, controllerValue);
  30607. }
  30608. }
  30609. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30610. const bool stealIfNoneAvailable) const
  30611. {
  30612. const ScopedLock sl (lock);
  30613. for (int i = voices.size(); --i >= 0;)
  30614. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30615. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30616. return voices.getUnchecked (i);
  30617. if (stealIfNoneAvailable)
  30618. {
  30619. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30620. SynthesiserVoice* oldest = 0;
  30621. for (int i = voices.size(); --i >= 0;)
  30622. {
  30623. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30624. if (voice->canPlaySound (soundToPlay)
  30625. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30626. oldest = voice;
  30627. }
  30628. jassert (oldest != 0);
  30629. return oldest;
  30630. }
  30631. return 0;
  30632. }
  30633. END_JUCE_NAMESPACE
  30634. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30635. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30636. BEGIN_JUCE_NAMESPACE
  30637. // special message of our own with a string in it
  30638. class ActionMessage : public Message
  30639. {
  30640. public:
  30641. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30642. : message (messageText)
  30643. {
  30644. pointerParameter = listener_;
  30645. }
  30646. const String message;
  30647. private:
  30648. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30649. };
  30650. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30651. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30652. {
  30653. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30654. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30655. if (owner->actionListeners.contains (target))
  30656. target->actionListenerCallback (am.message);
  30657. }
  30658. ActionBroadcaster::ActionBroadcaster()
  30659. {
  30660. // are you trying to create this object before or after juce has been intialised??
  30661. jassert (MessageManager::instance != 0);
  30662. callback.owner = this;
  30663. }
  30664. ActionBroadcaster::~ActionBroadcaster()
  30665. {
  30666. // all event-based objects must be deleted BEFORE juce is shut down!
  30667. jassert (MessageManager::instance != 0);
  30668. }
  30669. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30670. {
  30671. const ScopedLock sl (actionListenerLock);
  30672. if (listener != 0)
  30673. actionListeners.add (listener);
  30674. }
  30675. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30676. {
  30677. const ScopedLock sl (actionListenerLock);
  30678. actionListeners.removeValue (listener);
  30679. }
  30680. void ActionBroadcaster::removeAllActionListeners()
  30681. {
  30682. const ScopedLock sl (actionListenerLock);
  30683. actionListeners.clear();
  30684. }
  30685. void ActionBroadcaster::sendActionMessage (const String& message) const
  30686. {
  30687. const ScopedLock sl (actionListenerLock);
  30688. for (int i = actionListeners.size(); --i >= 0;)
  30689. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30690. }
  30691. END_JUCE_NAMESPACE
  30692. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30693. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30694. BEGIN_JUCE_NAMESPACE
  30695. class AsyncUpdaterMessage : public CallbackMessage
  30696. {
  30697. public:
  30698. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30699. : owner (owner_)
  30700. {
  30701. }
  30702. void messageCallback()
  30703. {
  30704. if (shouldDeliver.compareAndSetBool (0, 1))
  30705. owner.handleAsyncUpdate();
  30706. }
  30707. Atomic<int> shouldDeliver;
  30708. private:
  30709. AsyncUpdater& owner;
  30710. };
  30711. AsyncUpdater::AsyncUpdater()
  30712. {
  30713. message = new AsyncUpdaterMessage (*this);
  30714. }
  30715. inline Atomic<int>& AsyncUpdater::getDeliveryFlag() const throw()
  30716. {
  30717. return static_cast <AsyncUpdaterMessage*> (message.getObject())->shouldDeliver;
  30718. }
  30719. AsyncUpdater::~AsyncUpdater()
  30720. {
  30721. // You're deleting this object with a background thread while there's an update
  30722. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30723. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30724. // deleting this object, or find some other way to avoid such a race condition.
  30725. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30726. getDeliveryFlag().set (0);
  30727. }
  30728. void AsyncUpdater::triggerAsyncUpdate()
  30729. {
  30730. if (getDeliveryFlag().compareAndSetBool (1, 0))
  30731. message->post();
  30732. }
  30733. void AsyncUpdater::cancelPendingUpdate() throw()
  30734. {
  30735. getDeliveryFlag().set (0);
  30736. }
  30737. void AsyncUpdater::handleUpdateNowIfNeeded()
  30738. {
  30739. // This can only be called by the event thread.
  30740. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30741. if (getDeliveryFlag().exchange (0) != 0)
  30742. handleAsyncUpdate();
  30743. }
  30744. bool AsyncUpdater::isUpdatePending() const throw()
  30745. {
  30746. return getDeliveryFlag().value != 0;
  30747. }
  30748. END_JUCE_NAMESPACE
  30749. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30750. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30751. BEGIN_JUCE_NAMESPACE
  30752. ChangeBroadcaster::ChangeBroadcaster() throw()
  30753. {
  30754. // are you trying to create this object before or after juce has been intialised??
  30755. jassert (MessageManager::instance != 0);
  30756. callback.owner = this;
  30757. }
  30758. ChangeBroadcaster::~ChangeBroadcaster()
  30759. {
  30760. // all event-based objects must be deleted BEFORE juce is shut down!
  30761. jassert (MessageManager::instance != 0);
  30762. }
  30763. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30764. {
  30765. // Listeners can only be safely added when the event thread is locked
  30766. // You can use a MessageManagerLock if you need to call this from another thread.
  30767. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30768. changeListeners.add (listener);
  30769. }
  30770. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30771. {
  30772. // Listeners can only be safely added when the event thread is locked
  30773. // You can use a MessageManagerLock if you need to call this from another thread.
  30774. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30775. changeListeners.remove (listener);
  30776. }
  30777. void ChangeBroadcaster::removeAllChangeListeners()
  30778. {
  30779. // Listeners can only be safely added when the event thread is locked
  30780. // You can use a MessageManagerLock if you need to call this from another thread.
  30781. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30782. changeListeners.clear();
  30783. }
  30784. void ChangeBroadcaster::sendChangeMessage()
  30785. {
  30786. if (changeListeners.size() > 0)
  30787. callback.triggerAsyncUpdate();
  30788. }
  30789. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30790. {
  30791. // This can only be called by the event thread.
  30792. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30793. callback.cancelPendingUpdate();
  30794. callListeners();
  30795. }
  30796. void ChangeBroadcaster::dispatchPendingMessages()
  30797. {
  30798. callback.handleUpdateNowIfNeeded();
  30799. }
  30800. void ChangeBroadcaster::callListeners()
  30801. {
  30802. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30803. }
  30804. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30805. : owner (0)
  30806. {
  30807. }
  30808. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30809. {
  30810. jassert (owner != 0);
  30811. owner->callListeners();
  30812. }
  30813. END_JUCE_NAMESPACE
  30814. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30815. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30816. BEGIN_JUCE_NAMESPACE
  30817. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30818. const uint32 magicMessageHeaderNumber)
  30819. : Thread ("Juce IPC connection"),
  30820. callbackConnectionState (false),
  30821. useMessageThread (callbacksOnMessageThread),
  30822. magicMessageHeader (magicMessageHeaderNumber),
  30823. pipeReceiveMessageTimeout (-1)
  30824. {
  30825. }
  30826. InterprocessConnection::~InterprocessConnection()
  30827. {
  30828. callbackConnectionState = false;
  30829. disconnect();
  30830. }
  30831. bool InterprocessConnection::connectToSocket (const String& hostName,
  30832. const int portNumber,
  30833. const int timeOutMillisecs)
  30834. {
  30835. disconnect();
  30836. const ScopedLock sl (pipeAndSocketLock);
  30837. socket = new StreamingSocket();
  30838. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30839. {
  30840. connectionMadeInt();
  30841. startThread();
  30842. return true;
  30843. }
  30844. else
  30845. {
  30846. socket = 0;
  30847. return false;
  30848. }
  30849. }
  30850. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30851. const int pipeReceiveMessageTimeoutMs)
  30852. {
  30853. disconnect();
  30854. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30855. if (newPipe->openExisting (pipeName))
  30856. {
  30857. const ScopedLock sl (pipeAndSocketLock);
  30858. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30859. initialiseWithPipe (newPipe.release());
  30860. return true;
  30861. }
  30862. return false;
  30863. }
  30864. bool InterprocessConnection::createPipe (const String& pipeName,
  30865. const int pipeReceiveMessageTimeoutMs)
  30866. {
  30867. disconnect();
  30868. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30869. if (newPipe->createNewPipe (pipeName))
  30870. {
  30871. const ScopedLock sl (pipeAndSocketLock);
  30872. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30873. initialiseWithPipe (newPipe.release());
  30874. return true;
  30875. }
  30876. return false;
  30877. }
  30878. void InterprocessConnection::disconnect()
  30879. {
  30880. if (socket != 0)
  30881. socket->close();
  30882. if (pipe != 0)
  30883. {
  30884. pipe->cancelPendingReads();
  30885. pipe->close();
  30886. }
  30887. stopThread (4000);
  30888. {
  30889. const ScopedLock sl (pipeAndSocketLock);
  30890. socket = 0;
  30891. pipe = 0;
  30892. }
  30893. connectionLostInt();
  30894. }
  30895. bool InterprocessConnection::isConnected() const
  30896. {
  30897. const ScopedLock sl (pipeAndSocketLock);
  30898. return ((socket != 0 && socket->isConnected())
  30899. || (pipe != 0 && pipe->isOpen()))
  30900. && isThreadRunning();
  30901. }
  30902. const String InterprocessConnection::getConnectedHostName() const
  30903. {
  30904. if (pipe != 0)
  30905. {
  30906. return "localhost";
  30907. }
  30908. else if (socket != 0)
  30909. {
  30910. if (! socket->isLocal())
  30911. return socket->getHostName();
  30912. return "localhost";
  30913. }
  30914. return String::empty;
  30915. }
  30916. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30917. {
  30918. uint32 messageHeader[2];
  30919. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30920. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30921. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30922. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30923. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30924. size_t bytesWritten = 0;
  30925. const ScopedLock sl (pipeAndSocketLock);
  30926. if (socket != 0)
  30927. {
  30928. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30929. }
  30930. else if (pipe != 0)
  30931. {
  30932. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30933. }
  30934. if (bytesWritten < 0)
  30935. {
  30936. // error..
  30937. return false;
  30938. }
  30939. return (bytesWritten == messageData.getSize());
  30940. }
  30941. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30942. {
  30943. jassert (socket == 0);
  30944. socket = socket_;
  30945. connectionMadeInt();
  30946. startThread();
  30947. }
  30948. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30949. {
  30950. jassert (pipe == 0);
  30951. pipe = pipe_;
  30952. connectionMadeInt();
  30953. startThread();
  30954. }
  30955. const int messageMagicNumber = 0xb734128b;
  30956. void InterprocessConnection::handleMessage (const Message& message)
  30957. {
  30958. if (message.intParameter1 == messageMagicNumber)
  30959. {
  30960. switch (message.intParameter2)
  30961. {
  30962. case 0:
  30963. {
  30964. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30965. messageReceived (*data);
  30966. break;
  30967. }
  30968. case 1:
  30969. connectionMade();
  30970. break;
  30971. case 2:
  30972. connectionLost();
  30973. break;
  30974. }
  30975. }
  30976. }
  30977. void InterprocessConnection::connectionMadeInt()
  30978. {
  30979. if (! callbackConnectionState)
  30980. {
  30981. callbackConnectionState = true;
  30982. if (useMessageThread)
  30983. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30984. else
  30985. connectionMade();
  30986. }
  30987. }
  30988. void InterprocessConnection::connectionLostInt()
  30989. {
  30990. if (callbackConnectionState)
  30991. {
  30992. callbackConnectionState = false;
  30993. if (useMessageThread)
  30994. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30995. else
  30996. connectionLost();
  30997. }
  30998. }
  30999. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31000. {
  31001. jassert (callbackConnectionState);
  31002. if (useMessageThread)
  31003. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31004. else
  31005. messageReceived (data);
  31006. }
  31007. bool InterprocessConnection::readNextMessageInt()
  31008. {
  31009. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31010. uint32 messageHeader[2];
  31011. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31012. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31013. if (bytes == sizeof (messageHeader)
  31014. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31015. {
  31016. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31017. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31018. {
  31019. MemoryBlock messageData (bytesInMessage, true);
  31020. int bytesRead = 0;
  31021. while (bytesInMessage > 0)
  31022. {
  31023. if (threadShouldExit())
  31024. return false;
  31025. const int numThisTime = jmin (bytesInMessage, 65536);
  31026. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31027. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31028. if (bytesIn <= 0)
  31029. break;
  31030. bytesRead += bytesIn;
  31031. bytesInMessage -= bytesIn;
  31032. }
  31033. if (bytesRead >= 0)
  31034. deliverDataInt (messageData);
  31035. }
  31036. }
  31037. else if (bytes < 0)
  31038. {
  31039. {
  31040. const ScopedLock sl (pipeAndSocketLock);
  31041. socket = 0;
  31042. }
  31043. connectionLostInt();
  31044. return false;
  31045. }
  31046. return true;
  31047. }
  31048. void InterprocessConnection::run()
  31049. {
  31050. while (! threadShouldExit())
  31051. {
  31052. if (socket != 0)
  31053. {
  31054. const int ready = socket->waitUntilReady (true, 0);
  31055. if (ready < 0)
  31056. {
  31057. {
  31058. const ScopedLock sl (pipeAndSocketLock);
  31059. socket = 0;
  31060. }
  31061. connectionLostInt();
  31062. break;
  31063. }
  31064. else if (ready > 0)
  31065. {
  31066. if (! readNextMessageInt())
  31067. break;
  31068. }
  31069. else
  31070. {
  31071. Thread::sleep (2);
  31072. }
  31073. }
  31074. else if (pipe != 0)
  31075. {
  31076. if (! pipe->isOpen())
  31077. {
  31078. {
  31079. const ScopedLock sl (pipeAndSocketLock);
  31080. pipe = 0;
  31081. }
  31082. connectionLostInt();
  31083. break;
  31084. }
  31085. else
  31086. {
  31087. if (! readNextMessageInt())
  31088. break;
  31089. }
  31090. }
  31091. else
  31092. {
  31093. break;
  31094. }
  31095. }
  31096. }
  31097. END_JUCE_NAMESPACE
  31098. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31099. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31100. BEGIN_JUCE_NAMESPACE
  31101. InterprocessConnectionServer::InterprocessConnectionServer()
  31102. : Thread ("Juce IPC server")
  31103. {
  31104. }
  31105. InterprocessConnectionServer::~InterprocessConnectionServer()
  31106. {
  31107. stop();
  31108. }
  31109. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31110. {
  31111. stop();
  31112. socket = new StreamingSocket();
  31113. if (socket->createListener (portNumber))
  31114. {
  31115. startThread();
  31116. return true;
  31117. }
  31118. socket = 0;
  31119. return false;
  31120. }
  31121. void InterprocessConnectionServer::stop()
  31122. {
  31123. signalThreadShouldExit();
  31124. if (socket != 0)
  31125. socket->close();
  31126. stopThread (4000);
  31127. socket = 0;
  31128. }
  31129. void InterprocessConnectionServer::run()
  31130. {
  31131. while ((! threadShouldExit()) && socket != 0)
  31132. {
  31133. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31134. if (clientSocket != 0)
  31135. {
  31136. InterprocessConnection* newConnection = createConnectionObject();
  31137. if (newConnection != 0)
  31138. newConnection->initialiseWithSocket (clientSocket.release());
  31139. }
  31140. }
  31141. }
  31142. END_JUCE_NAMESPACE
  31143. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31144. /*** Start of inlined file: juce_Message.cpp ***/
  31145. BEGIN_JUCE_NAMESPACE
  31146. Message::Message() throw()
  31147. : intParameter1 (0),
  31148. intParameter2 (0),
  31149. intParameter3 (0),
  31150. pointerParameter (0),
  31151. messageRecipient (0)
  31152. {
  31153. }
  31154. Message::Message (const int intParameter1_,
  31155. const int intParameter2_,
  31156. const int intParameter3_,
  31157. void* const pointerParameter_) throw()
  31158. : intParameter1 (intParameter1_),
  31159. intParameter2 (intParameter2_),
  31160. intParameter3 (intParameter3_),
  31161. pointerParameter (pointerParameter_),
  31162. messageRecipient (0)
  31163. {
  31164. }
  31165. Message::~Message()
  31166. {
  31167. }
  31168. END_JUCE_NAMESPACE
  31169. /*** End of inlined file: juce_Message.cpp ***/
  31170. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31171. BEGIN_JUCE_NAMESPACE
  31172. MessageListener::MessageListener() throw()
  31173. {
  31174. // are you trying to create a messagelistener before or after juce has been intialised??
  31175. jassert (MessageManager::instance != 0);
  31176. if (MessageManager::instance != 0)
  31177. MessageManager::instance->messageListeners.add (this);
  31178. }
  31179. MessageListener::~MessageListener()
  31180. {
  31181. if (MessageManager::instance != 0)
  31182. MessageManager::instance->messageListeners.removeValue (this);
  31183. }
  31184. void MessageListener::postMessage (Message* const message) const throw()
  31185. {
  31186. message->messageRecipient = const_cast <MessageListener*> (this);
  31187. if (MessageManager::instance == 0)
  31188. MessageManager::getInstance();
  31189. MessageManager::instance->postMessageToQueue (message);
  31190. }
  31191. bool MessageListener::isValidMessageListener() const throw()
  31192. {
  31193. return (MessageManager::instance != 0)
  31194. && MessageManager::instance->messageListeners.contains (this);
  31195. }
  31196. END_JUCE_NAMESPACE
  31197. /*** End of inlined file: juce_MessageListener.cpp ***/
  31198. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31199. BEGIN_JUCE_NAMESPACE
  31200. // platform-specific functions..
  31201. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31202. bool juce_postMessageToSystemQueue (Message* message);
  31203. MessageManager* MessageManager::instance = 0;
  31204. static const int quitMessageId = 0xfffff321;
  31205. MessageManager::MessageManager() throw()
  31206. : quitMessagePosted (false),
  31207. quitMessageReceived (false),
  31208. threadWithLock (0)
  31209. {
  31210. messageThreadId = Thread::getCurrentThreadId();
  31211. if (JUCEApplication::isStandaloneApp())
  31212. Thread::setCurrentThreadName ("Juce Message Thread");
  31213. }
  31214. MessageManager::~MessageManager() throw()
  31215. {
  31216. broadcaster = 0;
  31217. doPlatformSpecificShutdown();
  31218. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31219. jassert (messageListeners.size() == 0);
  31220. jassert (instance == this);
  31221. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31222. }
  31223. MessageManager* MessageManager::getInstance() throw()
  31224. {
  31225. if (instance == 0)
  31226. {
  31227. instance = new MessageManager();
  31228. doPlatformSpecificInitialisation();
  31229. }
  31230. return instance;
  31231. }
  31232. void MessageManager::postMessageToQueue (Message* const message)
  31233. {
  31234. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31235. Message::Ptr deleter (message); // (this will delete messages that were just created with a 0 ref count)
  31236. }
  31237. CallbackMessage::CallbackMessage() throw() {}
  31238. CallbackMessage::~CallbackMessage() {}
  31239. void CallbackMessage::post()
  31240. {
  31241. if (MessageManager::instance != 0)
  31242. MessageManager::instance->postMessageToQueue (this);
  31243. }
  31244. // not for public use..
  31245. void MessageManager::deliverMessage (Message* const message)
  31246. {
  31247. JUCE_TRY
  31248. {
  31249. MessageListener* const recipient = message->messageRecipient;
  31250. if (recipient == 0)
  31251. {
  31252. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31253. if (callbackMessage != 0)
  31254. {
  31255. callbackMessage->messageCallback();
  31256. }
  31257. else if (message->intParameter1 == quitMessageId)
  31258. {
  31259. quitMessageReceived = true;
  31260. }
  31261. }
  31262. else if (messageListeners.contains (recipient))
  31263. {
  31264. recipient->handleMessage (*message);
  31265. }
  31266. }
  31267. JUCE_CATCH_EXCEPTION
  31268. }
  31269. #if ! (JUCE_MAC || JUCE_IOS)
  31270. void MessageManager::runDispatchLoop()
  31271. {
  31272. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31273. runDispatchLoopUntil (-1);
  31274. }
  31275. void MessageManager::stopDispatchLoop()
  31276. {
  31277. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31278. quitMessagePosted = true;
  31279. }
  31280. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31281. {
  31282. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31283. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31284. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31285. && ! quitMessageReceived)
  31286. {
  31287. JUCE_TRY
  31288. {
  31289. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31290. {
  31291. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31292. if (msToWait > 0)
  31293. Thread::sleep (jmin (5, msToWait));
  31294. }
  31295. }
  31296. JUCE_CATCH_EXCEPTION
  31297. }
  31298. return ! quitMessageReceived;
  31299. }
  31300. #endif
  31301. void MessageManager::deliverBroadcastMessage (const String& value)
  31302. {
  31303. if (broadcaster != 0)
  31304. broadcaster->sendActionMessage (value);
  31305. }
  31306. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31307. {
  31308. if (broadcaster == 0)
  31309. broadcaster = new ActionBroadcaster();
  31310. broadcaster->addActionListener (listener);
  31311. }
  31312. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31313. {
  31314. if (broadcaster != 0)
  31315. broadcaster->removeActionListener (listener);
  31316. }
  31317. bool MessageManager::isThisTheMessageThread() const throw()
  31318. {
  31319. return Thread::getCurrentThreadId() == messageThreadId;
  31320. }
  31321. void MessageManager::setCurrentThreadAsMessageThread()
  31322. {
  31323. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31324. if (messageThreadId != thisThread)
  31325. {
  31326. messageThreadId = thisThread;
  31327. // This is needed on windows to make sure the message window is created by this thread
  31328. doPlatformSpecificShutdown();
  31329. doPlatformSpecificInitialisation();
  31330. }
  31331. }
  31332. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31333. {
  31334. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31335. return thisThread == messageThreadId || thisThread == threadWithLock;
  31336. }
  31337. /* The only safe way to lock the message thread while another thread does
  31338. some work is by posting a special message, whose purpose is to tie up the event
  31339. loop until the other thread has finished its business.
  31340. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31341. get locked before making an event callback, because if the same OS lock gets indirectly
  31342. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31343. in Cocoa).
  31344. */
  31345. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31346. {
  31347. public:
  31348. BlockingMessage() {}
  31349. void messageCallback()
  31350. {
  31351. lockedEvent.signal();
  31352. releaseEvent.wait();
  31353. }
  31354. WaitableEvent lockedEvent, releaseEvent;
  31355. private:
  31356. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31357. };
  31358. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31359. : locked (false)
  31360. {
  31361. init (threadToCheck, 0);
  31362. }
  31363. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31364. : locked (false)
  31365. {
  31366. init (0, jobToCheckForExitSignal);
  31367. }
  31368. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31369. {
  31370. if (MessageManager::instance != 0)
  31371. {
  31372. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31373. {
  31374. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31375. }
  31376. else
  31377. {
  31378. if (threadToCheck == 0 && job == 0)
  31379. {
  31380. MessageManager::instance->lockingLock.enter();
  31381. }
  31382. else
  31383. {
  31384. while (! MessageManager::instance->lockingLock.tryEnter())
  31385. {
  31386. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31387. || (job != 0 && job->shouldExit()))
  31388. return;
  31389. Thread::sleep (1);
  31390. }
  31391. }
  31392. blockingMessage = new BlockingMessage();
  31393. blockingMessage->post();
  31394. while (! blockingMessage->lockedEvent.wait (20))
  31395. {
  31396. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31397. || (job != 0 && job->shouldExit()))
  31398. {
  31399. blockingMessage->releaseEvent.signal();
  31400. blockingMessage = 0;
  31401. MessageManager::instance->lockingLock.exit();
  31402. return;
  31403. }
  31404. }
  31405. jassert (MessageManager::instance->threadWithLock == 0);
  31406. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31407. locked = true;
  31408. }
  31409. }
  31410. }
  31411. MessageManagerLock::~MessageManagerLock() throw()
  31412. {
  31413. if (blockingMessage != 0)
  31414. {
  31415. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31416. blockingMessage->releaseEvent.signal();
  31417. blockingMessage = 0;
  31418. if (MessageManager::instance != 0)
  31419. {
  31420. MessageManager::instance->threadWithLock = 0;
  31421. MessageManager::instance->lockingLock.exit();
  31422. }
  31423. }
  31424. }
  31425. END_JUCE_NAMESPACE
  31426. /*** End of inlined file: juce_MessageManager.cpp ***/
  31427. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31428. BEGIN_JUCE_NAMESPACE
  31429. class MultiTimer::MultiTimerCallback : public Timer
  31430. {
  31431. public:
  31432. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31433. : timerId (timerId_),
  31434. owner (owner_)
  31435. {
  31436. }
  31437. ~MultiTimerCallback()
  31438. {
  31439. }
  31440. void timerCallback()
  31441. {
  31442. owner.timerCallback (timerId);
  31443. }
  31444. const int timerId;
  31445. private:
  31446. MultiTimer& owner;
  31447. };
  31448. MultiTimer::MultiTimer() throw()
  31449. {
  31450. }
  31451. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31452. {
  31453. }
  31454. MultiTimer::~MultiTimer()
  31455. {
  31456. const ScopedLock sl (timerListLock);
  31457. timers.clear();
  31458. }
  31459. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31460. {
  31461. const ScopedLock sl (timerListLock);
  31462. for (int i = timers.size(); --i >= 0;)
  31463. {
  31464. MultiTimerCallback* const t = timers.getUnchecked(i);
  31465. if (t->timerId == timerId)
  31466. {
  31467. t->startTimer (intervalInMilliseconds);
  31468. return;
  31469. }
  31470. }
  31471. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31472. timers.add (newTimer);
  31473. newTimer->startTimer (intervalInMilliseconds);
  31474. }
  31475. void MultiTimer::stopTimer (const int timerId) throw()
  31476. {
  31477. const ScopedLock sl (timerListLock);
  31478. for (int i = timers.size(); --i >= 0;)
  31479. {
  31480. MultiTimerCallback* const t = timers.getUnchecked(i);
  31481. if (t->timerId == timerId)
  31482. t->stopTimer();
  31483. }
  31484. }
  31485. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31486. {
  31487. const ScopedLock sl (timerListLock);
  31488. for (int i = timers.size(); --i >= 0;)
  31489. {
  31490. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31491. if (t->timerId == timerId)
  31492. return t->isTimerRunning();
  31493. }
  31494. return false;
  31495. }
  31496. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31497. {
  31498. const ScopedLock sl (timerListLock);
  31499. for (int i = timers.size(); --i >= 0;)
  31500. {
  31501. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31502. if (t->timerId == timerId)
  31503. return t->getTimerInterval();
  31504. }
  31505. return 0;
  31506. }
  31507. END_JUCE_NAMESPACE
  31508. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31509. /*** Start of inlined file: juce_Timer.cpp ***/
  31510. BEGIN_JUCE_NAMESPACE
  31511. class InternalTimerThread : private Thread,
  31512. private MessageListener,
  31513. private DeletedAtShutdown,
  31514. private AsyncUpdater
  31515. {
  31516. public:
  31517. InternalTimerThread()
  31518. : Thread ("Juce Timer"),
  31519. firstTimer (0),
  31520. callbackNeeded (0)
  31521. {
  31522. triggerAsyncUpdate();
  31523. }
  31524. ~InternalTimerThread() throw()
  31525. {
  31526. stopThread (4000);
  31527. jassert (instance == this || instance == 0);
  31528. if (instance == this)
  31529. instance = 0;
  31530. }
  31531. void run()
  31532. {
  31533. uint32 lastTime = Time::getMillisecondCounter();
  31534. Message::Ptr message (new Message());
  31535. while (! threadShouldExit())
  31536. {
  31537. const uint32 now = Time::getMillisecondCounter();
  31538. if (now <= lastTime)
  31539. {
  31540. wait (2);
  31541. continue;
  31542. }
  31543. const int elapsed = now - lastTime;
  31544. lastTime = now;
  31545. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31546. if (timeUntilFirstTimer <= 0)
  31547. {
  31548. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31549. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31550. but if it fails it means the message-thread changed the value from under us so at least
  31551. some processing is happenening and we can just loop around and try again
  31552. */
  31553. if (callbackNeeded.compareAndSetBool (1, 0))
  31554. {
  31555. postMessage (message);
  31556. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31557. when the app has a modal loop), so this is how long to wait before assuming the
  31558. message has been lost and trying again.
  31559. */
  31560. const uint32 messageDeliveryTimeout = now + 2000;
  31561. while (callbackNeeded.get() != 0)
  31562. {
  31563. wait (4);
  31564. if (threadShouldExit())
  31565. return;
  31566. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31567. break;
  31568. }
  31569. }
  31570. }
  31571. else
  31572. {
  31573. // don't wait for too long because running this loop also helps keep the
  31574. // Time::getApproximateMillisecondTimer value stay up-to-date
  31575. wait (jlimit (1, 50, timeUntilFirstTimer));
  31576. }
  31577. }
  31578. }
  31579. void callTimers()
  31580. {
  31581. const ScopedLock sl (lock);
  31582. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31583. {
  31584. Timer* const t = firstTimer;
  31585. t->countdownMs = t->periodMs;
  31586. removeTimer (t);
  31587. addTimer (t);
  31588. const ScopedUnlock ul (lock);
  31589. JUCE_TRY
  31590. {
  31591. t->timerCallback();
  31592. }
  31593. JUCE_CATCH_EXCEPTION
  31594. }
  31595. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31596. before the boolean is set. This set should never fail since if it was false in the first place,
  31597. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31598. get a message then the value is true and the other thread can only set it to true again and
  31599. we will get another callback to set it to false.
  31600. */
  31601. callbackNeeded.set (0);
  31602. }
  31603. void handleMessage (const Message&)
  31604. {
  31605. callTimers();
  31606. }
  31607. void callTimersSynchronously()
  31608. {
  31609. if (! isThreadRunning())
  31610. {
  31611. // (This is relied on by some plugins in cases where the MM has
  31612. // had to restart and the async callback never started)
  31613. cancelPendingUpdate();
  31614. triggerAsyncUpdate();
  31615. }
  31616. callTimers();
  31617. }
  31618. static void callAnyTimersSynchronously()
  31619. {
  31620. if (InternalTimerThread::instance != 0)
  31621. InternalTimerThread::instance->callTimersSynchronously();
  31622. }
  31623. static inline void add (Timer* const tim) throw()
  31624. {
  31625. if (instance == 0)
  31626. instance = new InternalTimerThread();
  31627. const ScopedLock sl (instance->lock);
  31628. instance->addTimer (tim);
  31629. }
  31630. static inline void remove (Timer* const tim) throw()
  31631. {
  31632. if (instance != 0)
  31633. {
  31634. const ScopedLock sl (instance->lock);
  31635. instance->removeTimer (tim);
  31636. }
  31637. }
  31638. static inline void resetCounter (Timer* const tim,
  31639. const int newCounter) throw()
  31640. {
  31641. if (instance != 0)
  31642. {
  31643. tim->countdownMs = newCounter;
  31644. tim->periodMs = newCounter;
  31645. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31646. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31647. {
  31648. const ScopedLock sl (instance->lock);
  31649. instance->removeTimer (tim);
  31650. instance->addTimer (tim);
  31651. }
  31652. }
  31653. }
  31654. private:
  31655. friend class Timer;
  31656. static InternalTimerThread* instance;
  31657. static CriticalSection lock;
  31658. Timer* volatile firstTimer;
  31659. Atomic <int> callbackNeeded;
  31660. void addTimer (Timer* const t) throw()
  31661. {
  31662. #if JUCE_DEBUG
  31663. Timer* tt = firstTimer;
  31664. while (tt != 0)
  31665. {
  31666. // trying to add a timer that's already here - shouldn't get to this point,
  31667. // so if you get this assertion, let me know!
  31668. jassert (tt != t);
  31669. tt = tt->next;
  31670. }
  31671. jassert (t->previous == 0 && t->next == 0);
  31672. #endif
  31673. Timer* i = firstTimer;
  31674. if (i == 0 || i->countdownMs > t->countdownMs)
  31675. {
  31676. t->next = firstTimer;
  31677. firstTimer = t;
  31678. }
  31679. else
  31680. {
  31681. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31682. i = i->next;
  31683. jassert (i != 0);
  31684. t->next = i->next;
  31685. t->previous = i;
  31686. i->next = t;
  31687. }
  31688. if (t->next != 0)
  31689. t->next->previous = t;
  31690. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31691. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31692. notify();
  31693. }
  31694. void removeTimer (Timer* const t) throw()
  31695. {
  31696. #if JUCE_DEBUG
  31697. Timer* tt = firstTimer;
  31698. bool found = false;
  31699. while (tt != 0)
  31700. {
  31701. if (tt == t)
  31702. {
  31703. found = true;
  31704. break;
  31705. }
  31706. tt = tt->next;
  31707. }
  31708. // trying to remove a timer that's not here - shouldn't get to this point,
  31709. // so if you get this assertion, let me know!
  31710. jassert (found);
  31711. #endif
  31712. if (t->previous != 0)
  31713. {
  31714. jassert (firstTimer != t);
  31715. t->previous->next = t->next;
  31716. }
  31717. else
  31718. {
  31719. jassert (firstTimer == t);
  31720. firstTimer = t->next;
  31721. }
  31722. if (t->next != 0)
  31723. t->next->previous = t->previous;
  31724. t->next = 0;
  31725. t->previous = 0;
  31726. }
  31727. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31728. {
  31729. const ScopedLock sl (lock);
  31730. for (Timer* t = firstTimer; t != 0; t = t->next)
  31731. t->countdownMs -= numMillisecsElapsed;
  31732. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31733. }
  31734. void handleAsyncUpdate()
  31735. {
  31736. startThread (7);
  31737. }
  31738. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalTimerThread);
  31739. };
  31740. InternalTimerThread* InternalTimerThread::instance = 0;
  31741. CriticalSection InternalTimerThread::lock;
  31742. void juce_callAnyTimersSynchronously()
  31743. {
  31744. InternalTimerThread::callAnyTimersSynchronously();
  31745. }
  31746. #if JUCE_DEBUG
  31747. static SortedSet <Timer*> activeTimers;
  31748. #endif
  31749. Timer::Timer() throw()
  31750. : countdownMs (0),
  31751. periodMs (0),
  31752. previous (0),
  31753. next (0)
  31754. {
  31755. #if JUCE_DEBUG
  31756. activeTimers.add (this);
  31757. #endif
  31758. }
  31759. Timer::Timer (const Timer&) throw()
  31760. : countdownMs (0),
  31761. periodMs (0),
  31762. previous (0),
  31763. next (0)
  31764. {
  31765. #if JUCE_DEBUG
  31766. activeTimers.add (this);
  31767. #endif
  31768. }
  31769. Timer::~Timer()
  31770. {
  31771. stopTimer();
  31772. #if JUCE_DEBUG
  31773. activeTimers.removeValue (this);
  31774. #endif
  31775. }
  31776. void Timer::startTimer (const int interval) throw()
  31777. {
  31778. const ScopedLock sl (InternalTimerThread::lock);
  31779. #if JUCE_DEBUG
  31780. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31781. jassert (activeTimers.contains (this));
  31782. #endif
  31783. if (periodMs == 0)
  31784. {
  31785. countdownMs = interval;
  31786. periodMs = jmax (1, interval);
  31787. InternalTimerThread::add (this);
  31788. }
  31789. else
  31790. {
  31791. InternalTimerThread::resetCounter (this, interval);
  31792. }
  31793. }
  31794. void Timer::stopTimer() throw()
  31795. {
  31796. const ScopedLock sl (InternalTimerThread::lock);
  31797. #if JUCE_DEBUG
  31798. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31799. jassert (activeTimers.contains (this));
  31800. #endif
  31801. if (periodMs > 0)
  31802. {
  31803. InternalTimerThread::remove (this);
  31804. periodMs = 0;
  31805. }
  31806. }
  31807. END_JUCE_NAMESPACE
  31808. /*** End of inlined file: juce_Timer.cpp ***/
  31809. #endif
  31810. #if JUCE_BUILD_GUI
  31811. /*** Start of inlined file: juce_Component.cpp ***/
  31812. BEGIN_JUCE_NAMESPACE
  31813. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31814. Component* Component::currentlyFocusedComponent = 0;
  31815. class Component::MouseListenerList
  31816. {
  31817. public:
  31818. MouseListenerList()
  31819. : numDeepMouseListeners (0)
  31820. {
  31821. }
  31822. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31823. {
  31824. if (! listeners.contains (newListener))
  31825. {
  31826. if (wantsEventsForAllNestedChildComponents)
  31827. {
  31828. listeners.insert (0, newListener);
  31829. ++numDeepMouseListeners;
  31830. }
  31831. else
  31832. {
  31833. listeners.add (newListener);
  31834. }
  31835. }
  31836. }
  31837. void removeListener (MouseListener* const listenerToRemove)
  31838. {
  31839. const int index = listeners.indexOf (listenerToRemove);
  31840. if (index >= 0)
  31841. {
  31842. if (index < numDeepMouseListeners)
  31843. --numDeepMouseListeners;
  31844. listeners.remove (index);
  31845. }
  31846. }
  31847. static void sendMouseEvent (Component& comp, BailOutChecker& checker,
  31848. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  31849. {
  31850. if (checker.shouldBailOut())
  31851. return;
  31852. {
  31853. MouseListenerList* const list = comp.mouseListeners;
  31854. if (list != 0)
  31855. {
  31856. for (int i = list->listeners.size(); --i >= 0;)
  31857. {
  31858. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31859. if (checker.shouldBailOut())
  31860. return;
  31861. i = jmin (i, list->listeners.size());
  31862. }
  31863. }
  31864. }
  31865. Component* p = comp.parentComponent;
  31866. while (p != 0)
  31867. {
  31868. MouseListenerList* const list = p->mouseListeners;
  31869. if (list != 0 && list->numDeepMouseListeners > 0)
  31870. {
  31871. BailOutChecker2 checker2 (checker, p);
  31872. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31873. {
  31874. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31875. if (checker2.shouldBailOut())
  31876. return;
  31877. i = jmin (i, list->numDeepMouseListeners);
  31878. }
  31879. }
  31880. p = p->parentComponent;
  31881. }
  31882. }
  31883. static void sendWheelEvent (Component& comp, BailOutChecker& checker, const MouseEvent& e,
  31884. const float wheelIncrementX, const float wheelIncrementY)
  31885. {
  31886. {
  31887. MouseListenerList* const list = comp.mouseListeners;
  31888. if (list != 0)
  31889. {
  31890. for (int i = list->listeners.size(); --i >= 0;)
  31891. {
  31892. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31893. if (checker.shouldBailOut())
  31894. return;
  31895. i = jmin (i, list->listeners.size());
  31896. }
  31897. }
  31898. }
  31899. Component* p = comp.parentComponent;
  31900. while (p != 0)
  31901. {
  31902. MouseListenerList* const list = p->mouseListeners;
  31903. if (list != 0 && list->numDeepMouseListeners > 0)
  31904. {
  31905. BailOutChecker2 checker2 (checker, p);
  31906. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31907. {
  31908. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31909. if (checker2.shouldBailOut())
  31910. return;
  31911. i = jmin (i, list->numDeepMouseListeners);
  31912. }
  31913. }
  31914. p = p->parentComponent;
  31915. }
  31916. }
  31917. private:
  31918. Array <MouseListener*> listeners;
  31919. int numDeepMouseListeners;
  31920. class BailOutChecker2
  31921. {
  31922. public:
  31923. BailOutChecker2 (BailOutChecker& checker_, Component* const component)
  31924. : checker (checker_), safePointer (component)
  31925. {
  31926. }
  31927. bool shouldBailOut() const throw()
  31928. {
  31929. return checker.shouldBailOut() || safePointer == 0;
  31930. }
  31931. private:
  31932. BailOutChecker& checker;
  31933. const WeakReference<Component> safePointer;
  31934. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2);
  31935. };
  31936. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  31937. };
  31938. class Component::ComponentHelpers
  31939. {
  31940. public:
  31941. static void* runModalLoopCallback (void* userData)
  31942. {
  31943. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  31944. }
  31945. static const Identifier getColourPropertyId (const int colourId)
  31946. {
  31947. String s;
  31948. s.preallocateStorage (18);
  31949. s << "jcclr_" << String::toHexString (colourId);
  31950. return s;
  31951. }
  31952. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  31953. {
  31954. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  31955. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  31956. && comp.hitTest (localPoint.getX(), localPoint.getY());
  31957. }
  31958. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  31959. {
  31960. if (comp.affineTransform == 0)
  31961. return pointInParentSpace - comp.getPosition();
  31962. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  31963. }
  31964. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  31965. {
  31966. if (comp.affineTransform == 0)
  31967. return areaInParentSpace - comp.getPosition();
  31968. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  31969. }
  31970. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  31971. {
  31972. if (comp.affineTransform == 0)
  31973. return pointInLocalSpace + comp.getPosition();
  31974. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  31975. }
  31976. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  31977. {
  31978. if (comp.affineTransform == 0)
  31979. return areaInLocalSpace + comp.getPosition();
  31980. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  31981. }
  31982. template <typename Type>
  31983. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  31984. {
  31985. const Component* const directParent = target.getParentComponent();
  31986. jassert (directParent != 0);
  31987. if (directParent == parent)
  31988. return convertFromParentSpace (target, coordInParent);
  31989. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  31990. }
  31991. template <typename Type>
  31992. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  31993. {
  31994. while (source != 0)
  31995. {
  31996. if (source == target)
  31997. return p;
  31998. if (source->isParentOf (target))
  31999. return convertFromDistantParentSpace (source, *target, p);
  32000. if (source->isOnDesktop())
  32001. {
  32002. p = source->getPeer()->localToGlobal (p);
  32003. source = 0;
  32004. }
  32005. else
  32006. {
  32007. p = convertToParentSpace (*source, p);
  32008. source = source->getParentComponent();
  32009. }
  32010. }
  32011. jassert (source == 0);
  32012. if (target == 0)
  32013. return p;
  32014. const Component* const topLevelComp = target->getTopLevelComponent();
  32015. if (topLevelComp->isOnDesktop())
  32016. p = topLevelComp->getPeer()->globalToLocal (p);
  32017. else
  32018. p = convertFromParentSpace (*topLevelComp, p);
  32019. if (topLevelComp == target)
  32020. return p;
  32021. return convertFromDistantParentSpace (topLevelComp, *target, p);
  32022. }
  32023. static const Rectangle<int> getUnclippedArea (const Component& comp)
  32024. {
  32025. Rectangle<int> r (comp.getLocalBounds());
  32026. Component* const p = comp.getParentComponent();
  32027. if (p != 0)
  32028. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  32029. return r;
  32030. }
  32031. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  32032. {
  32033. for (int i = comp.childComponentList.size(); --i >= 0;)
  32034. {
  32035. const Component& child = *comp.childComponentList.getUnchecked(i);
  32036. if (child.isVisible() && ! child.isTransformed())
  32037. {
  32038. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  32039. if (! newClip.isEmpty())
  32040. {
  32041. if (child.isOpaque())
  32042. {
  32043. g.excludeClipRegion (newClip + delta);
  32044. }
  32045. else
  32046. {
  32047. const Point<int> childPos (child.getPosition());
  32048. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  32049. }
  32050. }
  32051. }
  32052. }
  32053. }
  32054. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  32055. const Point<int>& delta,
  32056. const Rectangle<int>& clipRect,
  32057. const Component* const compToAvoid)
  32058. {
  32059. for (int i = comp.childComponentList.size(); --i >= 0;)
  32060. {
  32061. const Component* const c = comp.childComponentList.getUnchecked(i);
  32062. if (c != compToAvoid && c->isVisible())
  32063. {
  32064. if (c->isOpaque())
  32065. {
  32066. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  32067. childBounds.translate (delta.getX(), delta.getY());
  32068. result.subtract (childBounds);
  32069. }
  32070. else
  32071. {
  32072. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  32073. newClip.translate (-c->getX(), -c->getY());
  32074. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  32075. newClip, compToAvoid);
  32076. }
  32077. }
  32078. }
  32079. }
  32080. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  32081. {
  32082. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  32083. : Desktop::getInstance().getMainMonitorArea();
  32084. }
  32085. };
  32086. Component::Component()
  32087. : parentComponent (0),
  32088. lookAndFeel (0),
  32089. effect (0),
  32090. componentFlags (0),
  32091. componentTransparency (0)
  32092. {
  32093. }
  32094. Component::Component (const String& name)
  32095. : componentName (name),
  32096. parentComponent (0),
  32097. lookAndFeel (0),
  32098. effect (0),
  32099. componentFlags (0),
  32100. componentTransparency (0)
  32101. {
  32102. }
  32103. Component::~Component()
  32104. {
  32105. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  32106. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  32107. #endif
  32108. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32109. weakReferenceMaster.clear();
  32110. while (childComponentList.size() > 0)
  32111. removeChildComponent (childComponentList.size() - 1, false, true);
  32112. if (parentComponent != 0)
  32113. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  32114. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32115. giveAwayFocus (currentlyFocusedComponent != this);
  32116. if (flags.hasHeavyweightPeerFlag)
  32117. removeFromDesktop();
  32118. // Something has added some children to this component during its destructor! Not a smart idea!
  32119. jassert (childComponentList.size() == 0);
  32120. }
  32121. const WeakReference<Component>::SharedRef& Component::getWeakReference()
  32122. {
  32123. return weakReferenceMaster (this);
  32124. }
  32125. void Component::setName (const String& name)
  32126. {
  32127. // if component methods are being called from threads other than the message
  32128. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32129. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32130. if (componentName != name)
  32131. {
  32132. componentName = name;
  32133. if (flags.hasHeavyweightPeerFlag)
  32134. {
  32135. ComponentPeer* const peer = getPeer();
  32136. jassert (peer != 0);
  32137. if (peer != 0)
  32138. peer->setTitle (name);
  32139. }
  32140. BailOutChecker checker (this);
  32141. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32142. }
  32143. }
  32144. void Component::setComponentID (const String& newID)
  32145. {
  32146. componentID = newID;
  32147. }
  32148. void Component::setVisible (bool shouldBeVisible)
  32149. {
  32150. if (flags.visibleFlag != shouldBeVisible)
  32151. {
  32152. // if component methods are being called from threads other than the message
  32153. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32154. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32155. WeakReference<Component> safePointer (this);
  32156. flags.visibleFlag = shouldBeVisible;
  32157. internalRepaint (0, 0, getWidth(), getHeight());
  32158. sendFakeMouseMove();
  32159. if (! shouldBeVisible)
  32160. {
  32161. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32162. {
  32163. if (parentComponent != 0)
  32164. parentComponent->grabKeyboardFocus();
  32165. else
  32166. giveAwayFocus (true);
  32167. }
  32168. }
  32169. if (safePointer != 0)
  32170. {
  32171. sendVisibilityChangeMessage();
  32172. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32173. {
  32174. ComponentPeer* const peer = getPeer();
  32175. jassert (peer != 0);
  32176. if (peer != 0)
  32177. {
  32178. peer->setVisible (shouldBeVisible);
  32179. internalHierarchyChanged();
  32180. }
  32181. }
  32182. }
  32183. }
  32184. }
  32185. void Component::visibilityChanged()
  32186. {
  32187. }
  32188. void Component::sendVisibilityChangeMessage()
  32189. {
  32190. BailOutChecker checker (this);
  32191. visibilityChanged();
  32192. if (! checker.shouldBailOut())
  32193. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32194. }
  32195. bool Component::isShowing() const
  32196. {
  32197. if (flags.visibleFlag)
  32198. {
  32199. if (parentComponent != 0)
  32200. {
  32201. return parentComponent->isShowing();
  32202. }
  32203. else
  32204. {
  32205. const ComponentPeer* const peer = getPeer();
  32206. return peer != 0 && ! peer->isMinimised();
  32207. }
  32208. }
  32209. return false;
  32210. }
  32211. void* Component::getWindowHandle() const
  32212. {
  32213. const ComponentPeer* const peer = getPeer();
  32214. if (peer != 0)
  32215. return peer->getNativeHandle();
  32216. return 0;
  32217. }
  32218. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32219. {
  32220. // if component methods are being called from threads other than the message
  32221. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32222. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32223. if (isOpaque())
  32224. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32225. else
  32226. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32227. int currentStyleFlags = 0;
  32228. // don't use getPeer(), so that we only get the peer that's specifically
  32229. // for this comp, and not for one of its parents.
  32230. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32231. if (peer != 0)
  32232. currentStyleFlags = peer->getStyleFlags();
  32233. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32234. {
  32235. WeakReference<Component> safePointer (this);
  32236. #if JUCE_LINUX
  32237. // it's wise to give the component a non-zero size before
  32238. // putting it on the desktop, as X windows get confused by this, and
  32239. // a (1, 1) minimum size is enforced here.
  32240. setSize (jmax (1, getWidth()),
  32241. jmax (1, getHeight()));
  32242. #endif
  32243. const Point<int> topLeft (getScreenPosition());
  32244. bool wasFullscreen = false;
  32245. bool wasMinimised = false;
  32246. ComponentBoundsConstrainer* currentConstainer = 0;
  32247. Rectangle<int> oldNonFullScreenBounds;
  32248. if (peer != 0)
  32249. {
  32250. wasFullscreen = peer->isFullScreen();
  32251. wasMinimised = peer->isMinimised();
  32252. currentConstainer = peer->getConstrainer();
  32253. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32254. removeFromDesktop();
  32255. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32256. }
  32257. if (parentComponent != 0)
  32258. parentComponent->removeChildComponent (this);
  32259. if (safePointer != 0)
  32260. {
  32261. flags.hasHeavyweightPeerFlag = true;
  32262. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32263. Desktop::getInstance().addDesktopComponent (this);
  32264. bounds.setPosition (topLeft);
  32265. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32266. peer->setVisible (isVisible());
  32267. if (wasFullscreen)
  32268. {
  32269. peer->setFullScreen (true);
  32270. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32271. }
  32272. if (wasMinimised)
  32273. peer->setMinimised (true);
  32274. if (isAlwaysOnTop())
  32275. peer->setAlwaysOnTop (true);
  32276. peer->setConstrainer (currentConstainer);
  32277. repaint();
  32278. }
  32279. internalHierarchyChanged();
  32280. }
  32281. }
  32282. void Component::removeFromDesktop()
  32283. {
  32284. // if component methods are being called from threads other than the message
  32285. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32286. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32287. if (flags.hasHeavyweightPeerFlag)
  32288. {
  32289. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32290. flags.hasHeavyweightPeerFlag = false;
  32291. jassert (peer != 0);
  32292. delete peer;
  32293. Desktop::getInstance().removeDesktopComponent (this);
  32294. }
  32295. }
  32296. bool Component::isOnDesktop() const throw()
  32297. {
  32298. return flags.hasHeavyweightPeerFlag;
  32299. }
  32300. void Component::userTriedToCloseWindow()
  32301. {
  32302. /* This means that the user's trying to get rid of your window with the 'close window' system
  32303. menu option (on windows) or possibly the task manager - you should really handle this
  32304. and delete or hide your component in an appropriate way.
  32305. If you want to ignore the event and don't want to trigger this assertion, just override
  32306. this method and do nothing.
  32307. */
  32308. jassertfalse;
  32309. }
  32310. void Component::minimisationStateChanged (bool)
  32311. {
  32312. }
  32313. void Component::setOpaque (const bool shouldBeOpaque)
  32314. {
  32315. if (shouldBeOpaque != flags.opaqueFlag)
  32316. {
  32317. flags.opaqueFlag = shouldBeOpaque;
  32318. if (flags.hasHeavyweightPeerFlag)
  32319. {
  32320. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32321. if (peer != 0)
  32322. {
  32323. // to make it recreate the heavyweight window
  32324. addToDesktop (peer->getStyleFlags());
  32325. }
  32326. }
  32327. repaint();
  32328. }
  32329. }
  32330. bool Component::isOpaque() const throw()
  32331. {
  32332. return flags.opaqueFlag;
  32333. }
  32334. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32335. {
  32336. if (shouldBeBuffered != flags.bufferToImageFlag)
  32337. {
  32338. bufferedImage = Image::null;
  32339. flags.bufferToImageFlag = shouldBeBuffered;
  32340. }
  32341. }
  32342. void Component::moveChildInternal (const int sourceIndex, const int destIndex)
  32343. {
  32344. if (sourceIndex != destIndex)
  32345. {
  32346. Component* const c = childComponentList.getUnchecked (sourceIndex);
  32347. jassert (c != 0);
  32348. c->repaintParent();
  32349. childComponentList.move (sourceIndex, destIndex);
  32350. sendFakeMouseMove();
  32351. internalChildrenChanged();
  32352. }
  32353. }
  32354. void Component::toFront (const bool setAsForeground)
  32355. {
  32356. // if component methods are being called from threads other than the message
  32357. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32358. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32359. if (flags.hasHeavyweightPeerFlag)
  32360. {
  32361. ComponentPeer* const peer = getPeer();
  32362. if (peer != 0)
  32363. {
  32364. peer->toFront (setAsForeground);
  32365. if (setAsForeground && ! hasKeyboardFocus (true))
  32366. grabKeyboardFocus();
  32367. }
  32368. }
  32369. else if (parentComponent != 0)
  32370. {
  32371. const Array<Component*>& childList = parentComponent->childComponentList;
  32372. if (childList.getLast() != this)
  32373. {
  32374. const int index = childList.indexOf (this);
  32375. if (index >= 0)
  32376. {
  32377. int insertIndex = -1;
  32378. if (! flags.alwaysOnTopFlag)
  32379. {
  32380. insertIndex = childList.size() - 1;
  32381. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32382. --insertIndex;
  32383. }
  32384. parentComponent->moveChildInternal (index, insertIndex);
  32385. }
  32386. }
  32387. if (setAsForeground)
  32388. {
  32389. internalBroughtToFront();
  32390. grabKeyboardFocus();
  32391. }
  32392. }
  32393. }
  32394. void Component::toBehind (Component* const other)
  32395. {
  32396. if (other != 0 && other != this)
  32397. {
  32398. // the two components must belong to the same parent..
  32399. jassert (parentComponent == other->parentComponent);
  32400. if (parentComponent != 0)
  32401. {
  32402. const Array<Component*>& childList = parentComponent->childComponentList;
  32403. const int index = childList.indexOf (this);
  32404. if (index >= 0 && childList [index + 1] != other)
  32405. {
  32406. int otherIndex = childList.indexOf (other);
  32407. if (otherIndex >= 0)
  32408. {
  32409. if (index < otherIndex)
  32410. --otherIndex;
  32411. parentComponent->moveChildInternal (index, otherIndex);
  32412. }
  32413. }
  32414. }
  32415. else if (isOnDesktop())
  32416. {
  32417. jassert (other->isOnDesktop());
  32418. if (other->isOnDesktop())
  32419. {
  32420. ComponentPeer* const us = getPeer();
  32421. ComponentPeer* const them = other->getPeer();
  32422. jassert (us != 0 && them != 0);
  32423. if (us != 0 && them != 0)
  32424. us->toBehind (them);
  32425. }
  32426. }
  32427. }
  32428. }
  32429. void Component::toBack()
  32430. {
  32431. if (isOnDesktop())
  32432. {
  32433. jassertfalse; //xxx need to add this to native window
  32434. }
  32435. else if (parentComponent != 0)
  32436. {
  32437. const Array<Component*>& childList = parentComponent->childComponentList;
  32438. if (childList.getFirst() != this)
  32439. {
  32440. const int index = childList.indexOf (this);
  32441. if (index > 0)
  32442. {
  32443. int insertIndex = 0;
  32444. if (flags.alwaysOnTopFlag)
  32445. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32446. ++insertIndex;
  32447. parentComponent->moveChildInternal (index, insertIndex);
  32448. }
  32449. }
  32450. }
  32451. }
  32452. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32453. {
  32454. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32455. {
  32456. flags.alwaysOnTopFlag = shouldStayOnTop;
  32457. if (isOnDesktop())
  32458. {
  32459. ComponentPeer* const peer = getPeer();
  32460. jassert (peer != 0);
  32461. if (peer != 0)
  32462. {
  32463. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32464. {
  32465. // some kinds of peer can't change their always-on-top status, so
  32466. // for these, we'll need to create a new window
  32467. const int oldFlags = peer->getStyleFlags();
  32468. removeFromDesktop();
  32469. addToDesktop (oldFlags);
  32470. }
  32471. }
  32472. }
  32473. if (shouldStayOnTop)
  32474. toFront (false);
  32475. internalHierarchyChanged();
  32476. }
  32477. }
  32478. bool Component::isAlwaysOnTop() const throw()
  32479. {
  32480. return flags.alwaysOnTopFlag;
  32481. }
  32482. int Component::proportionOfWidth (const float proportion) const throw()
  32483. {
  32484. return roundToInt (proportion * bounds.getWidth());
  32485. }
  32486. int Component::proportionOfHeight (const float proportion) const throw()
  32487. {
  32488. return roundToInt (proportion * bounds.getHeight());
  32489. }
  32490. int Component::getParentWidth() const throw()
  32491. {
  32492. return (parentComponent != 0) ? parentComponent->getWidth()
  32493. : getParentMonitorArea().getWidth();
  32494. }
  32495. int Component::getParentHeight() const throw()
  32496. {
  32497. return (parentComponent != 0) ? parentComponent->getHeight()
  32498. : getParentMonitorArea().getHeight();
  32499. }
  32500. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32501. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32502. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32503. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32504. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32505. {
  32506. return ComponentHelpers::convertCoordinate (this, source, point);
  32507. }
  32508. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32509. {
  32510. return ComponentHelpers::convertCoordinate (this, source, area);
  32511. }
  32512. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32513. {
  32514. return ComponentHelpers::convertCoordinate (0, this, point);
  32515. }
  32516. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32517. {
  32518. return ComponentHelpers::convertCoordinate (0, this, area);
  32519. }
  32520. /* Deprecated methods... */
  32521. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32522. {
  32523. return localPointToGlobal (relativePosition);
  32524. }
  32525. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32526. {
  32527. return getLocalPoint (0, screenPosition);
  32528. }
  32529. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32530. {
  32531. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32532. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32533. }
  32534. void Component::setBounds (const int x, const int y, int w, int h)
  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 (w < 0) w = 0;
  32540. if (h < 0) h = 0;
  32541. const bool wasResized = (getWidth() != w || getHeight() != h);
  32542. const bool wasMoved = (getX() != x || getY() != y);
  32543. #if JUCE_DEBUG
  32544. // It's a very bad idea to try to resize a window during its paint() method!
  32545. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32546. #endif
  32547. if (wasMoved || wasResized)
  32548. {
  32549. const bool showing = isShowing();
  32550. if (showing)
  32551. {
  32552. // send a fake mouse move to trigger enter/exit messages if needed..
  32553. sendFakeMouseMove();
  32554. if (! flags.hasHeavyweightPeerFlag)
  32555. repaintParent();
  32556. }
  32557. bounds.setBounds (x, y, w, h);
  32558. if (showing)
  32559. {
  32560. if (wasResized)
  32561. repaint();
  32562. else if (! flags.hasHeavyweightPeerFlag)
  32563. repaintParent();
  32564. }
  32565. if (flags.hasHeavyweightPeerFlag)
  32566. {
  32567. ComponentPeer* const peer = getPeer();
  32568. if (peer != 0)
  32569. {
  32570. if (wasMoved && wasResized)
  32571. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32572. else if (wasMoved)
  32573. peer->setPosition (getX(), getY());
  32574. else if (wasResized)
  32575. peer->setSize (getWidth(), getHeight());
  32576. }
  32577. }
  32578. sendMovedResizedMessages (wasMoved, wasResized);
  32579. }
  32580. }
  32581. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32582. {
  32583. BailOutChecker checker (this);
  32584. if (wasMoved)
  32585. {
  32586. moved();
  32587. if (checker.shouldBailOut())
  32588. return;
  32589. }
  32590. if (wasResized)
  32591. {
  32592. resized();
  32593. if (checker.shouldBailOut())
  32594. return;
  32595. for (int i = childComponentList.size(); --i >= 0;)
  32596. {
  32597. childComponentList.getUnchecked(i)->parentSizeChanged();
  32598. if (checker.shouldBailOut())
  32599. return;
  32600. i = jmin (i, childComponentList.size());
  32601. }
  32602. }
  32603. if (parentComponent != 0)
  32604. parentComponent->childBoundsChanged (this);
  32605. if (! checker.shouldBailOut())
  32606. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32607. *this, wasMoved, wasResized);
  32608. }
  32609. void Component::setSize (const int w, const int h)
  32610. {
  32611. setBounds (getX(), getY(), w, h);
  32612. }
  32613. void Component::setTopLeftPosition (const int x, const int y)
  32614. {
  32615. setBounds (x, y, getWidth(), getHeight());
  32616. }
  32617. void Component::setTopRightPosition (const int x, const int y)
  32618. {
  32619. setTopLeftPosition (x - getWidth(), y);
  32620. }
  32621. void Component::setBounds (const Rectangle<int>& r)
  32622. {
  32623. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32624. }
  32625. void Component::setBounds (const RelativeRectangle& newBounds)
  32626. {
  32627. newBounds.applyToComponent (*this);
  32628. }
  32629. void Component::setBoundsRelative (const float x, const float y,
  32630. const float w, const float h)
  32631. {
  32632. const int pw = getParentWidth();
  32633. const int ph = getParentHeight();
  32634. setBounds (roundToInt (x * pw),
  32635. roundToInt (y * ph),
  32636. roundToInt (w * pw),
  32637. roundToInt (h * ph));
  32638. }
  32639. void Component::setCentrePosition (const int x, const int y)
  32640. {
  32641. setTopLeftPosition (x - getWidth() / 2,
  32642. y - getHeight() / 2);
  32643. }
  32644. void Component::setCentreRelative (const float x, const float y)
  32645. {
  32646. setCentrePosition (roundToInt (getParentWidth() * x),
  32647. roundToInt (getParentHeight() * y));
  32648. }
  32649. void Component::centreWithSize (const int width, const int height)
  32650. {
  32651. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32652. setBounds (parentArea.getCentreX() - width / 2,
  32653. parentArea.getCentreY() - height / 2,
  32654. width, height);
  32655. }
  32656. void Component::setBoundsInset (const BorderSize<int>& borders)
  32657. {
  32658. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32659. }
  32660. void Component::setBoundsToFit (int x, int y, int width, int height,
  32661. const Justification& justification,
  32662. const bool onlyReduceInSize)
  32663. {
  32664. // it's no good calling this method unless both the component and
  32665. // target rectangle have a finite size.
  32666. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32667. if (getWidth() > 0 && getHeight() > 0
  32668. && width > 0 && height > 0)
  32669. {
  32670. int newW, newH;
  32671. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32672. {
  32673. newW = getWidth();
  32674. newH = getHeight();
  32675. }
  32676. else
  32677. {
  32678. const double imageRatio = getHeight() / (double) getWidth();
  32679. const double targetRatio = height / (double) width;
  32680. if (imageRatio <= targetRatio)
  32681. {
  32682. newW = width;
  32683. newH = jmin (height, roundToInt (newW * imageRatio));
  32684. }
  32685. else
  32686. {
  32687. newH = height;
  32688. newW = jmin (width, roundToInt (newH / imageRatio));
  32689. }
  32690. }
  32691. if (newW > 0 && newH > 0)
  32692. setBounds (justification.appliedToRectangle (Rectangle<int> (0, 0, newW, newH),
  32693. Rectangle<int> (x, y, width, height)));
  32694. }
  32695. }
  32696. bool Component::isTransformed() const throw()
  32697. {
  32698. return affineTransform != 0;
  32699. }
  32700. void Component::setTransform (const AffineTransform& newTransform)
  32701. {
  32702. // If you pass in a transform with no inverse, the component will have no dimensions,
  32703. // and there will be all sorts of maths errors when converting coordinates.
  32704. jassert (! newTransform.isSingularity());
  32705. if (newTransform.isIdentity())
  32706. {
  32707. if (affineTransform != 0)
  32708. {
  32709. repaint();
  32710. affineTransform = 0;
  32711. repaint();
  32712. sendMovedResizedMessages (false, false);
  32713. }
  32714. }
  32715. else if (affineTransform == 0)
  32716. {
  32717. repaint();
  32718. affineTransform = new AffineTransform (newTransform);
  32719. repaint();
  32720. sendMovedResizedMessages (false, false);
  32721. }
  32722. else if (*affineTransform != newTransform)
  32723. {
  32724. repaint();
  32725. *affineTransform = newTransform;
  32726. repaint();
  32727. sendMovedResizedMessages (false, false);
  32728. }
  32729. }
  32730. const AffineTransform Component::getTransform() const
  32731. {
  32732. return affineTransform != 0 ? *affineTransform : AffineTransform::identity;
  32733. }
  32734. bool Component::hitTest (int x, int y)
  32735. {
  32736. if (! flags.ignoresMouseClicksFlag)
  32737. return true;
  32738. if (flags.allowChildMouseClicksFlag)
  32739. {
  32740. for (int i = getNumChildComponents(); --i >= 0;)
  32741. {
  32742. Component& child = *getChildComponent (i);
  32743. if (child.isVisible()
  32744. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32745. return true;
  32746. }
  32747. }
  32748. return false;
  32749. }
  32750. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32751. const bool allowClicksOnChildComponents) throw()
  32752. {
  32753. flags.ignoresMouseClicksFlag = ! allowClicks;
  32754. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32755. }
  32756. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32757. bool& allowsClicksOnChildComponents) const throw()
  32758. {
  32759. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32760. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32761. }
  32762. bool Component::contains (const Point<int>& point)
  32763. {
  32764. if (ComponentHelpers::hitTest (*this, point))
  32765. {
  32766. if (parentComponent != 0)
  32767. {
  32768. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32769. }
  32770. else if (flags.hasHeavyweightPeerFlag)
  32771. {
  32772. const ComponentPeer* const peer = getPeer();
  32773. if (peer != 0)
  32774. return peer->contains (point, true);
  32775. }
  32776. }
  32777. return false;
  32778. }
  32779. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32780. {
  32781. if (! contains (point))
  32782. return false;
  32783. Component* const top = getTopLevelComponent();
  32784. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32785. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32786. }
  32787. Component* Component::getComponentAt (const Point<int>& position)
  32788. {
  32789. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32790. {
  32791. for (int i = childComponentList.size(); --i >= 0;)
  32792. {
  32793. Component* child = childComponentList.getUnchecked(i);
  32794. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32795. if (child != 0)
  32796. return child;
  32797. }
  32798. return this;
  32799. }
  32800. return 0;
  32801. }
  32802. Component* Component::getComponentAt (const int x, const int y)
  32803. {
  32804. return getComponentAt (Point<int> (x, y));
  32805. }
  32806. void Component::addChildComponent (Component* const child, int zOrder)
  32807. {
  32808. // if component methods are being called from threads other than the message
  32809. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32810. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32811. if (child != 0 && child->parentComponent != this)
  32812. {
  32813. if (child->parentComponent != 0)
  32814. child->parentComponent->removeChildComponent (child);
  32815. else
  32816. child->removeFromDesktop();
  32817. child->parentComponent = this;
  32818. if (child->isVisible())
  32819. child->repaintParent();
  32820. if (! child->isAlwaysOnTop())
  32821. {
  32822. if (zOrder < 0 || zOrder > childComponentList.size())
  32823. zOrder = childComponentList.size();
  32824. while (zOrder > 0)
  32825. {
  32826. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32827. break;
  32828. --zOrder;
  32829. }
  32830. }
  32831. childComponentList.insert (zOrder, child);
  32832. child->internalHierarchyChanged();
  32833. internalChildrenChanged();
  32834. }
  32835. }
  32836. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32837. {
  32838. if (child != 0)
  32839. {
  32840. child->setVisible (true);
  32841. addChildComponent (child, zOrder);
  32842. }
  32843. }
  32844. void Component::removeChildComponent (Component* const child)
  32845. {
  32846. removeChildComponent (childComponentList.indexOf (child), true, true);
  32847. }
  32848. Component* Component::removeChildComponent (const int index)
  32849. {
  32850. return removeChildComponent (index, true, true);
  32851. }
  32852. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  32853. {
  32854. // if component methods are being called from threads other than the message
  32855. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32856. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32857. Component* const child = childComponentList [index];
  32858. if (child != 0)
  32859. {
  32860. sendParentEvents = sendParentEvents && child->isShowing();
  32861. if (sendParentEvents)
  32862. {
  32863. sendFakeMouseMove();
  32864. child->repaintParent();
  32865. }
  32866. childComponentList.remove (index);
  32867. child->parentComponent = 0;
  32868. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  32869. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  32870. {
  32871. if (sendParentEvents)
  32872. {
  32873. const WeakReference<Component> thisPointer (this);
  32874. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32875. if (thisPointer == 0)
  32876. return child;
  32877. grabKeyboardFocus();
  32878. }
  32879. else
  32880. {
  32881. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32882. }
  32883. }
  32884. if (sendChildEvents)
  32885. child->internalHierarchyChanged();
  32886. if (sendParentEvents)
  32887. internalChildrenChanged();
  32888. }
  32889. return child;
  32890. }
  32891. void Component::removeAllChildren()
  32892. {
  32893. while (childComponentList.size() > 0)
  32894. removeChildComponent (childComponentList.size() - 1);
  32895. }
  32896. void Component::deleteAllChildren()
  32897. {
  32898. while (childComponentList.size() > 0)
  32899. delete (removeChildComponent (childComponentList.size() - 1));
  32900. }
  32901. int Component::getNumChildComponents() const throw()
  32902. {
  32903. return childComponentList.size();
  32904. }
  32905. Component* Component::getChildComponent (const int index) const throw()
  32906. {
  32907. return childComponentList [index];
  32908. }
  32909. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32910. {
  32911. return childComponentList.indexOf (const_cast <Component*> (child));
  32912. }
  32913. Component* Component::getTopLevelComponent() const throw()
  32914. {
  32915. const Component* comp = this;
  32916. while (comp->parentComponent != 0)
  32917. comp = comp->parentComponent;
  32918. return const_cast <Component*> (comp);
  32919. }
  32920. bool Component::isParentOf (const Component* possibleChild) const throw()
  32921. {
  32922. while (possibleChild != 0)
  32923. {
  32924. possibleChild = possibleChild->parentComponent;
  32925. if (possibleChild == this)
  32926. return true;
  32927. }
  32928. return false;
  32929. }
  32930. void Component::parentHierarchyChanged()
  32931. {
  32932. }
  32933. void Component::childrenChanged()
  32934. {
  32935. }
  32936. void Component::internalChildrenChanged()
  32937. {
  32938. if (componentListeners.isEmpty())
  32939. {
  32940. childrenChanged();
  32941. }
  32942. else
  32943. {
  32944. BailOutChecker checker (this);
  32945. childrenChanged();
  32946. if (! checker.shouldBailOut())
  32947. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32948. }
  32949. }
  32950. void Component::internalHierarchyChanged()
  32951. {
  32952. BailOutChecker checker (this);
  32953. parentHierarchyChanged();
  32954. if (checker.shouldBailOut())
  32955. return;
  32956. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32957. if (checker.shouldBailOut())
  32958. return;
  32959. for (int i = childComponentList.size(); --i >= 0;)
  32960. {
  32961. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  32962. if (checker.shouldBailOut())
  32963. {
  32964. // you really shouldn't delete the parent component during a callback telling you
  32965. // that it's changed..
  32966. jassertfalse;
  32967. return;
  32968. }
  32969. i = jmin (i, childComponentList.size());
  32970. }
  32971. }
  32972. int Component::runModalLoop()
  32973. {
  32974. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32975. {
  32976. // use a callback so this can be called from non-gui threads
  32977. return (int) (pointer_sized_int) MessageManager::getInstance()
  32978. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  32979. }
  32980. if (! isCurrentlyModal())
  32981. enterModalState (true);
  32982. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32983. }
  32984. void Component::enterModalState (const bool shouldTakeKeyboardFocus, ModalComponentManager::Callback* const callback)
  32985. {
  32986. // if component methods are being called from threads other than the message
  32987. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32988. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32989. // Check for an attempt to make a component modal when it already is!
  32990. // This can cause nasty problems..
  32991. jassert (! flags.currentlyModalFlag);
  32992. if (! isCurrentlyModal())
  32993. {
  32994. ModalComponentManager::getInstance()->startModal (this, callback);
  32995. flags.currentlyModalFlag = true;
  32996. setVisible (true);
  32997. if (shouldTakeKeyboardFocus)
  32998. grabKeyboardFocus();
  32999. }
  33000. }
  33001. void Component::exitModalState (const int returnValue)
  33002. {
  33003. if (flags.currentlyModalFlag)
  33004. {
  33005. if (MessageManager::getInstance()->isThisTheMessageThread())
  33006. {
  33007. ModalComponentManager::getInstance()->endModal (this, returnValue);
  33008. flags.currentlyModalFlag = false;
  33009. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33010. }
  33011. else
  33012. {
  33013. class ExitModalStateMessage : public CallbackMessage
  33014. {
  33015. public:
  33016. ExitModalStateMessage (Component* const target_, const int result_)
  33017. : target (target_), result (result_) {}
  33018. void messageCallback()
  33019. {
  33020. if (target.get() != 0) // (get() required for VS2003 bug)
  33021. target->exitModalState (result);
  33022. }
  33023. private:
  33024. WeakReference<Component> target;
  33025. int result;
  33026. };
  33027. (new ExitModalStateMessage (this, returnValue))->post();
  33028. }
  33029. }
  33030. }
  33031. bool Component::isCurrentlyModal() const throw()
  33032. {
  33033. return flags.currentlyModalFlag
  33034. && getCurrentlyModalComponent() == this;
  33035. }
  33036. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33037. {
  33038. Component* const mc = getCurrentlyModalComponent();
  33039. return mc != 0
  33040. && mc != this
  33041. && (! mc->isParentOf (this))
  33042. && ! mc->canModalEventBeSentToComponent (this);
  33043. }
  33044. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33045. {
  33046. return ModalComponentManager::getInstance()->getNumModalComponents();
  33047. }
  33048. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33049. {
  33050. return ModalComponentManager::getInstance()->getModalComponent (index);
  33051. }
  33052. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33053. {
  33054. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33055. }
  33056. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33057. {
  33058. return flags.bringToFrontOnClickFlag;
  33059. }
  33060. void Component::setMouseCursor (const MouseCursor& newCursor)
  33061. {
  33062. if (cursor != newCursor)
  33063. {
  33064. cursor = newCursor;
  33065. if (flags.visibleFlag)
  33066. updateMouseCursor();
  33067. }
  33068. }
  33069. const MouseCursor Component::getMouseCursor()
  33070. {
  33071. return cursor;
  33072. }
  33073. void Component::updateMouseCursor() const
  33074. {
  33075. sendFakeMouseMove();
  33076. }
  33077. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33078. {
  33079. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33080. }
  33081. void Component::setAlpha (const float newAlpha)
  33082. {
  33083. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33084. if (componentTransparency != newIntAlpha)
  33085. {
  33086. componentTransparency = newIntAlpha;
  33087. if (flags.hasHeavyweightPeerFlag)
  33088. {
  33089. ComponentPeer* const peer = getPeer();
  33090. if (peer != 0)
  33091. peer->setAlpha (newAlpha);
  33092. }
  33093. else
  33094. {
  33095. repaint();
  33096. }
  33097. }
  33098. }
  33099. float Component::getAlpha() const
  33100. {
  33101. return (255 - componentTransparency) / 255.0f;
  33102. }
  33103. void Component::repaintParent()
  33104. {
  33105. if (flags.visibleFlag)
  33106. internalRepaint (0, 0, getWidth(), getHeight());
  33107. }
  33108. void Component::repaint()
  33109. {
  33110. repaint (0, 0, getWidth(), getHeight());
  33111. }
  33112. void Component::repaint (const int x, const int y,
  33113. const int w, const int h)
  33114. {
  33115. bufferedImage = Image::null;
  33116. if (flags.visibleFlag)
  33117. internalRepaint (x, y, w, h);
  33118. }
  33119. void Component::repaint (const Rectangle<int>& area)
  33120. {
  33121. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33122. }
  33123. void Component::internalRepaint (int x, int y, int w, int h)
  33124. {
  33125. // if component methods are being called from threads other than the message
  33126. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33127. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33128. if (x < 0)
  33129. {
  33130. w += x;
  33131. x = 0;
  33132. }
  33133. if (x + w > getWidth())
  33134. w = getWidth() - x;
  33135. if (w > 0)
  33136. {
  33137. if (y < 0)
  33138. {
  33139. h += y;
  33140. y = 0;
  33141. }
  33142. if (y + h > getHeight())
  33143. h = getHeight() - y;
  33144. if (h > 0)
  33145. {
  33146. if (parentComponent != 0)
  33147. {
  33148. if (parentComponent->flags.visibleFlag)
  33149. {
  33150. if (affineTransform == 0)
  33151. {
  33152. parentComponent->internalRepaint (x + getX(), y + getY(), w, h);
  33153. }
  33154. else
  33155. {
  33156. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  33157. parentComponent->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  33158. }
  33159. }
  33160. }
  33161. else if (flags.hasHeavyweightPeerFlag)
  33162. {
  33163. ComponentPeer* const peer = getPeer();
  33164. if (peer != 0)
  33165. peer->repaint (Rectangle<int> (x, y, w, h));
  33166. }
  33167. }
  33168. }
  33169. }
  33170. void Component::paintComponent (Graphics& g)
  33171. {
  33172. if (flags.bufferToImageFlag)
  33173. {
  33174. if (bufferedImage.isNull())
  33175. {
  33176. bufferedImage = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33177. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33178. Graphics imG (bufferedImage);
  33179. paint (imG);
  33180. }
  33181. g.setColour (Colours::black.withAlpha (getAlpha()));
  33182. g.drawImageAt (bufferedImage, 0, 0);
  33183. }
  33184. else
  33185. {
  33186. paint (g);
  33187. }
  33188. }
  33189. void Component::paintWithinParentContext (Graphics& g)
  33190. {
  33191. g.setOrigin (getX(), getY());
  33192. paintEntireComponent (g, false);
  33193. }
  33194. void Component::paintComponentAndChildren (Graphics& g)
  33195. {
  33196. const Rectangle<int> clipBounds (g.getClipBounds());
  33197. if (flags.dontClipGraphicsFlag)
  33198. {
  33199. paintComponent (g);
  33200. }
  33201. else
  33202. {
  33203. g.saveState();
  33204. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33205. if (! g.isClipEmpty())
  33206. paintComponent (g);
  33207. g.restoreState();
  33208. }
  33209. for (int i = 0; i < childComponentList.size(); ++i)
  33210. {
  33211. Component& child = *childComponentList.getUnchecked (i);
  33212. if (child.isVisible())
  33213. {
  33214. if (child.affineTransform != 0)
  33215. {
  33216. g.saveState();
  33217. g.addTransform (*child.affineTransform);
  33218. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33219. child.paintWithinParentContext (g);
  33220. g.restoreState();
  33221. }
  33222. else if (clipBounds.intersects (child.getBounds()))
  33223. {
  33224. g.saveState();
  33225. if (child.flags.dontClipGraphicsFlag)
  33226. {
  33227. child.paintWithinParentContext (g);
  33228. }
  33229. else if (g.reduceClipRegion (child.getBounds()))
  33230. {
  33231. bool nothingClipped = true;
  33232. for (int j = i + 1; j < childComponentList.size(); ++j)
  33233. {
  33234. const Component& sibling = *childComponentList.getUnchecked (j);
  33235. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == 0)
  33236. {
  33237. nothingClipped = false;
  33238. g.excludeClipRegion (sibling.getBounds());
  33239. }
  33240. }
  33241. if (nothingClipped || ! g.isClipEmpty())
  33242. child.paintWithinParentContext (g);
  33243. }
  33244. g.restoreState();
  33245. }
  33246. }
  33247. }
  33248. g.saveState();
  33249. paintOverChildren (g);
  33250. g.restoreState();
  33251. }
  33252. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33253. {
  33254. jassert (! g.isClipEmpty());
  33255. #if JUCE_DEBUG
  33256. flags.isInsidePaintCall = true;
  33257. #endif
  33258. if (effect != 0)
  33259. {
  33260. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33261. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33262. {
  33263. Graphics g2 (effectImage);
  33264. paintComponentAndChildren (g2);
  33265. }
  33266. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33267. }
  33268. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33269. {
  33270. if (componentTransparency < 255)
  33271. {
  33272. g.beginTransparencyLayer (getAlpha());
  33273. paintComponentAndChildren (g);
  33274. g.endTransparencyLayer();
  33275. }
  33276. }
  33277. else
  33278. {
  33279. paintComponentAndChildren (g);
  33280. }
  33281. #if JUCE_DEBUG
  33282. flags.isInsidePaintCall = false;
  33283. #endif
  33284. }
  33285. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33286. {
  33287. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33288. }
  33289. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33290. const bool clipImageToComponentBounds)
  33291. {
  33292. Rectangle<int> r (areaToGrab);
  33293. if (clipImageToComponentBounds)
  33294. r = r.getIntersection (getLocalBounds());
  33295. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33296. jmax (1, r.getWidth()),
  33297. jmax (1, r.getHeight()),
  33298. true);
  33299. Graphics imageContext (componentImage);
  33300. imageContext.setOrigin (-r.getX(), -r.getY());
  33301. paintEntireComponent (imageContext, true);
  33302. return componentImage;
  33303. }
  33304. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  33305. {
  33306. if (effect != newEffect)
  33307. {
  33308. effect = newEffect;
  33309. repaint();
  33310. }
  33311. }
  33312. LookAndFeel& Component::getLookAndFeel() const throw()
  33313. {
  33314. const Component* c = this;
  33315. do
  33316. {
  33317. if (c->lookAndFeel != 0)
  33318. return *(c->lookAndFeel);
  33319. c = c->parentComponent;
  33320. }
  33321. while (c != 0);
  33322. return LookAndFeel::getDefaultLookAndFeel();
  33323. }
  33324. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33325. {
  33326. if (lookAndFeel != newLookAndFeel)
  33327. {
  33328. lookAndFeel = newLookAndFeel;
  33329. sendLookAndFeelChange();
  33330. }
  33331. }
  33332. void Component::lookAndFeelChanged()
  33333. {
  33334. }
  33335. void Component::sendLookAndFeelChange()
  33336. {
  33337. repaint();
  33338. WeakReference<Component> safePointer (this);
  33339. lookAndFeelChanged();
  33340. if (safePointer != 0)
  33341. {
  33342. for (int i = childComponentList.size(); --i >= 0;)
  33343. {
  33344. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  33345. if (safePointer == 0)
  33346. return;
  33347. i = jmin (i, childComponentList.size());
  33348. }
  33349. }
  33350. }
  33351. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33352. {
  33353. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33354. if (v != 0)
  33355. return Colour ((int) *v);
  33356. if (inheritFromParent && parentComponent != 0)
  33357. return parentComponent->findColour (colourId, true);
  33358. return getLookAndFeel().findColour (colourId);
  33359. }
  33360. bool Component::isColourSpecified (const int colourId) const
  33361. {
  33362. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33363. }
  33364. void Component::removeColour (const int colourId)
  33365. {
  33366. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33367. colourChanged();
  33368. }
  33369. void Component::setColour (const int colourId, const Colour& colour)
  33370. {
  33371. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33372. colourChanged();
  33373. }
  33374. void Component::copyAllExplicitColoursTo (Component& target) const
  33375. {
  33376. bool changed = false;
  33377. for (int i = properties.size(); --i >= 0;)
  33378. {
  33379. const Identifier name (properties.getName(i));
  33380. if (name.toString().startsWith ("jcclr_"))
  33381. if (target.properties.set (name, properties [name]))
  33382. changed = true;
  33383. }
  33384. if (changed)
  33385. target.colourChanged();
  33386. }
  33387. void Component::colourChanged()
  33388. {
  33389. }
  33390. MarkerList* Component::getMarkers (bool /*xAxis*/)
  33391. {
  33392. return 0;
  33393. }
  33394. Component::Positioner::Positioner (Component& component_) throw()
  33395. : component (component_)
  33396. {
  33397. }
  33398. Component::Positioner* Component::getPositioner() const throw()
  33399. {
  33400. return positioner;
  33401. }
  33402. void Component::setPositioner (Positioner* newPositioner)
  33403. {
  33404. // You can only assign a positioner to the component that it was created for!
  33405. jassert (newPositioner == 0 || this == &(newPositioner->getComponent()));
  33406. positioner = newPositioner;
  33407. }
  33408. const Rectangle<int> Component::getLocalBounds() const throw()
  33409. {
  33410. return Rectangle<int> (getWidth(), getHeight());
  33411. }
  33412. const Rectangle<int> Component::getBoundsInParent() const throw()
  33413. {
  33414. return affineTransform == 0 ? bounds
  33415. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  33416. }
  33417. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33418. {
  33419. result.clear();
  33420. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33421. if (! unclipped.isEmpty())
  33422. {
  33423. result.add (unclipped);
  33424. if (includeSiblings)
  33425. {
  33426. const Component* const c = getTopLevelComponent();
  33427. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33428. c->getLocalBounds(), this);
  33429. }
  33430. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33431. result.consolidate();
  33432. }
  33433. }
  33434. void Component::mouseEnter (const MouseEvent&)
  33435. {
  33436. // base class does nothing
  33437. }
  33438. void Component::mouseExit (const MouseEvent&)
  33439. {
  33440. // base class does nothing
  33441. }
  33442. void Component::mouseDown (const MouseEvent&)
  33443. {
  33444. // base class does nothing
  33445. }
  33446. void Component::mouseUp (const MouseEvent&)
  33447. {
  33448. // base class does nothing
  33449. }
  33450. void Component::mouseDrag (const MouseEvent&)
  33451. {
  33452. // base class does nothing
  33453. }
  33454. void Component::mouseMove (const MouseEvent&)
  33455. {
  33456. // base class does nothing
  33457. }
  33458. void Component::mouseDoubleClick (const MouseEvent&)
  33459. {
  33460. // base class does nothing
  33461. }
  33462. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33463. {
  33464. // the base class just passes this event up to its parent..
  33465. if (parentComponent != 0)
  33466. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  33467. wheelIncrementX, wheelIncrementY);
  33468. }
  33469. void Component::resized()
  33470. {
  33471. // base class does nothing
  33472. }
  33473. void Component::moved()
  33474. {
  33475. // base class does nothing
  33476. }
  33477. void Component::childBoundsChanged (Component*)
  33478. {
  33479. // base class does nothing
  33480. }
  33481. void Component::parentSizeChanged()
  33482. {
  33483. // base class does nothing
  33484. }
  33485. void Component::addComponentListener (ComponentListener* const newListener)
  33486. {
  33487. // if component methods are being called from threads other than the message
  33488. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33489. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33490. componentListeners.add (newListener);
  33491. }
  33492. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33493. {
  33494. componentListeners.remove (listenerToRemove);
  33495. }
  33496. void Component::inputAttemptWhenModal()
  33497. {
  33498. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33499. getLookAndFeel().playAlertSound();
  33500. }
  33501. bool Component::canModalEventBeSentToComponent (const Component*)
  33502. {
  33503. return false;
  33504. }
  33505. void Component::internalModalInputAttempt()
  33506. {
  33507. Component* const current = getCurrentlyModalComponent();
  33508. if (current != 0)
  33509. current->inputAttemptWhenModal();
  33510. }
  33511. void Component::paint (Graphics&)
  33512. {
  33513. // all painting is done in the subclasses
  33514. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33515. }
  33516. void Component::paintOverChildren (Graphics&)
  33517. {
  33518. // all painting is done in the subclasses
  33519. }
  33520. void Component::postCommandMessage (const int commandId)
  33521. {
  33522. class CustomCommandMessage : public CallbackMessage
  33523. {
  33524. public:
  33525. CustomCommandMessage (Component* const target_, const int commandId_)
  33526. : target (target_), commandId (commandId_) {}
  33527. void messageCallback()
  33528. {
  33529. if (target.get() != 0) // (get() required for VS2003 bug)
  33530. target->handleCommandMessage (commandId);
  33531. }
  33532. private:
  33533. WeakReference<Component> target;
  33534. int commandId;
  33535. };
  33536. (new CustomCommandMessage (this, commandId))->post();
  33537. }
  33538. void Component::handleCommandMessage (int)
  33539. {
  33540. // used by subclasses
  33541. }
  33542. void Component::addMouseListener (MouseListener* const newListener,
  33543. const bool wantsEventsForAllNestedChildComponents)
  33544. {
  33545. // if component methods are being called from threads other than the message
  33546. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33547. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33548. // If you register a component as a mouselistener for itself, it'll receive all the events
  33549. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33550. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33551. if (mouseListeners == 0)
  33552. mouseListeners = new MouseListenerList();
  33553. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33554. }
  33555. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33556. {
  33557. // if component methods are being called from threads other than the message
  33558. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33559. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33560. if (mouseListeners != 0)
  33561. mouseListeners->removeListener (listenerToRemove);
  33562. }
  33563. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33564. {
  33565. if (isCurrentlyBlockedByAnotherModalComponent())
  33566. {
  33567. // if something else is modal, always just show a normal mouse cursor
  33568. source.showMouseCursor (MouseCursor::NormalCursor);
  33569. return;
  33570. }
  33571. if (! flags.mouseInsideFlag)
  33572. {
  33573. flags.mouseInsideFlag = true;
  33574. flags.mouseOverFlag = true;
  33575. flags.mouseDownFlag = false;
  33576. BailOutChecker checker (this);
  33577. if (flags.repaintOnMouseActivityFlag)
  33578. repaint();
  33579. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33580. this, this, time, relativePos, time, 0, false);
  33581. mouseEnter (me);
  33582. if (checker.shouldBailOut())
  33583. return;
  33584. Desktop& desktop = Desktop::getInstance();
  33585. desktop.resetTimer();
  33586. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33587. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  33588. }
  33589. }
  33590. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33591. {
  33592. BailOutChecker checker (this);
  33593. if (flags.mouseDownFlag)
  33594. {
  33595. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33596. if (checker.shouldBailOut())
  33597. return;
  33598. }
  33599. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33600. {
  33601. flags.mouseInsideFlag = false;
  33602. flags.mouseOverFlag = false;
  33603. flags.mouseDownFlag = false;
  33604. if (flags.repaintOnMouseActivityFlag)
  33605. repaint();
  33606. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33607. this, this, time, relativePos, time, 0, false);
  33608. mouseExit (me);
  33609. if (checker.shouldBailOut())
  33610. return;
  33611. Desktop& desktop = Desktop::getInstance();
  33612. desktop.resetTimer();
  33613. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33614. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  33615. }
  33616. }
  33617. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33618. {
  33619. Desktop& desktop = Desktop::getInstance();
  33620. BailOutChecker checker (this);
  33621. if (isCurrentlyBlockedByAnotherModalComponent())
  33622. {
  33623. internalModalInputAttempt();
  33624. if (checker.shouldBailOut())
  33625. return;
  33626. // If processing the input attempt has exited the modal loop, we'll allow the event
  33627. // to be delivered..
  33628. if (isCurrentlyBlockedByAnotherModalComponent())
  33629. {
  33630. // allow blocked mouse-events to go to global listeners..
  33631. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33632. this, this, time, relativePos, time,
  33633. source.getNumberOfMultipleClicks(), false);
  33634. desktop.resetTimer();
  33635. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33636. return;
  33637. }
  33638. }
  33639. {
  33640. Component* c = this;
  33641. while (c != 0)
  33642. {
  33643. if (c->isBroughtToFrontOnMouseClick())
  33644. {
  33645. c->toFront (true);
  33646. if (checker.shouldBailOut())
  33647. return;
  33648. }
  33649. c = c->parentComponent;
  33650. }
  33651. }
  33652. if (! flags.dontFocusOnMouseClickFlag)
  33653. {
  33654. grabFocusInternal (focusChangedByMouseClick);
  33655. if (checker.shouldBailOut())
  33656. return;
  33657. }
  33658. flags.mouseDownFlag = true;
  33659. flags.mouseOverFlag = true;
  33660. if (flags.repaintOnMouseActivityFlag)
  33661. repaint();
  33662. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33663. this, this, time, relativePos, time,
  33664. source.getNumberOfMultipleClicks(), false);
  33665. mouseDown (me);
  33666. if (checker.shouldBailOut())
  33667. return;
  33668. desktop.resetTimer();
  33669. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33670. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  33671. }
  33672. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33673. {
  33674. if (flags.mouseDownFlag)
  33675. {
  33676. flags.mouseDownFlag = false;
  33677. BailOutChecker checker (this);
  33678. if (flags.repaintOnMouseActivityFlag)
  33679. repaint();
  33680. const MouseEvent me (source, relativePos,
  33681. oldModifiers, this, this, time,
  33682. getLocalPoint (0, source.getLastMouseDownPosition()),
  33683. source.getLastMouseDownTime(),
  33684. source.getNumberOfMultipleClicks(),
  33685. source.hasMouseMovedSignificantlySincePressed());
  33686. mouseUp (me);
  33687. if (checker.shouldBailOut())
  33688. return;
  33689. Desktop& desktop = Desktop::getInstance();
  33690. desktop.resetTimer();
  33691. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33692. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  33693. if (checker.shouldBailOut())
  33694. return;
  33695. // check for double-click
  33696. if (me.getNumberOfClicks() >= 2)
  33697. {
  33698. mouseDoubleClick (me);
  33699. if (checker.shouldBailOut())
  33700. return;
  33701. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33702. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  33703. }
  33704. }
  33705. }
  33706. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33707. {
  33708. if (flags.mouseDownFlag)
  33709. {
  33710. flags.mouseOverFlag = reallyContains (relativePos, false);
  33711. BailOutChecker checker (this);
  33712. const MouseEvent me (source, relativePos,
  33713. source.getCurrentModifiers(), this, this, time,
  33714. getLocalPoint (0, source.getLastMouseDownPosition()),
  33715. source.getLastMouseDownTime(),
  33716. source.getNumberOfMultipleClicks(),
  33717. source.hasMouseMovedSignificantlySincePressed());
  33718. mouseDrag (me);
  33719. if (checker.shouldBailOut())
  33720. return;
  33721. Desktop& desktop = Desktop::getInstance();
  33722. desktop.resetTimer();
  33723. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33724. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  33725. }
  33726. }
  33727. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33728. {
  33729. Desktop& desktop = Desktop::getInstance();
  33730. BailOutChecker checker (this);
  33731. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33732. this, this, time, relativePos, time, 0, false);
  33733. if (isCurrentlyBlockedByAnotherModalComponent())
  33734. {
  33735. // allow blocked mouse-events to go to global listeners..
  33736. desktop.sendMouseMove();
  33737. }
  33738. else
  33739. {
  33740. flags.mouseOverFlag = true;
  33741. mouseMove (me);
  33742. if (checker.shouldBailOut())
  33743. return;
  33744. desktop.resetTimer();
  33745. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33746. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  33747. }
  33748. }
  33749. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33750. const Time& time, const float amountX, const float amountY)
  33751. {
  33752. Desktop& desktop = Desktop::getInstance();
  33753. BailOutChecker checker (this);
  33754. const float wheelIncrementX = amountX / 256.0f;
  33755. const float wheelIncrementY = amountY / 256.0f;
  33756. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33757. this, this, time, relativePos, time, 0, false);
  33758. if (isCurrentlyBlockedByAnotherModalComponent())
  33759. {
  33760. // allow blocked mouse-events to go to global listeners..
  33761. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33762. }
  33763. else
  33764. {
  33765. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33766. if (checker.shouldBailOut())
  33767. return;
  33768. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33769. if (! checker.shouldBailOut())
  33770. MouseListenerList::sendWheelEvent (*this, checker, me, wheelIncrementX, wheelIncrementY);
  33771. }
  33772. }
  33773. void Component::sendFakeMouseMove() const
  33774. {
  33775. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33776. if (! mainMouse.isDragging())
  33777. mainMouse.triggerFakeMove();
  33778. }
  33779. void Component::beginDragAutoRepeat (const int interval)
  33780. {
  33781. Desktop::getInstance().beginDragAutoRepeat (interval);
  33782. }
  33783. void Component::broughtToFront()
  33784. {
  33785. }
  33786. void Component::internalBroughtToFront()
  33787. {
  33788. if (flags.hasHeavyweightPeerFlag)
  33789. Desktop::getInstance().componentBroughtToFront (this);
  33790. BailOutChecker checker (this);
  33791. broughtToFront();
  33792. if (checker.shouldBailOut())
  33793. return;
  33794. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33795. if (checker.shouldBailOut())
  33796. return;
  33797. // When brought to the front and there's a modal component blocking this one,
  33798. // we need to bring the modal one to the front instead..
  33799. Component* const cm = getCurrentlyModalComponent();
  33800. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33801. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33802. }
  33803. void Component::focusGained (FocusChangeType)
  33804. {
  33805. // base class does nothing
  33806. }
  33807. void Component::internalFocusGain (const FocusChangeType cause)
  33808. {
  33809. internalFocusGain (cause, WeakReference<Component> (this));
  33810. }
  33811. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  33812. {
  33813. focusGained (cause);
  33814. if (safePointer != 0)
  33815. internalChildFocusChange (cause, safePointer);
  33816. }
  33817. void Component::focusLost (FocusChangeType)
  33818. {
  33819. // base class does nothing
  33820. }
  33821. void Component::internalFocusLoss (const FocusChangeType cause)
  33822. {
  33823. WeakReference<Component> safePointer (this);
  33824. focusLost (focusChangedDirectly);
  33825. if (safePointer != 0)
  33826. internalChildFocusChange (cause, safePointer);
  33827. }
  33828. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33829. {
  33830. // base class does nothing
  33831. }
  33832. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  33833. {
  33834. const bool childIsNowFocused = hasKeyboardFocus (true);
  33835. if (flags.childCompFocusedFlag != childIsNowFocused)
  33836. {
  33837. flags.childCompFocusedFlag = childIsNowFocused;
  33838. focusOfChildComponentChanged (cause);
  33839. if (safePointer == 0)
  33840. return;
  33841. }
  33842. if (parentComponent != 0)
  33843. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  33844. }
  33845. bool Component::isEnabled() const throw()
  33846. {
  33847. return (! flags.isDisabledFlag)
  33848. && (parentComponent == 0 || parentComponent->isEnabled());
  33849. }
  33850. void Component::setEnabled (const bool shouldBeEnabled)
  33851. {
  33852. if (flags.isDisabledFlag == shouldBeEnabled)
  33853. {
  33854. flags.isDisabledFlag = ! shouldBeEnabled;
  33855. // if any parent components are disabled, setting our flag won't make a difference,
  33856. // so no need to send a change message
  33857. if (parentComponent == 0 || parentComponent->isEnabled())
  33858. sendEnablementChangeMessage();
  33859. }
  33860. }
  33861. void Component::sendEnablementChangeMessage()
  33862. {
  33863. WeakReference<Component> safePointer (this);
  33864. enablementChanged();
  33865. if (safePointer == 0)
  33866. return;
  33867. for (int i = getNumChildComponents(); --i >= 0;)
  33868. {
  33869. Component* const c = getChildComponent (i);
  33870. if (c != 0)
  33871. {
  33872. c->sendEnablementChangeMessage();
  33873. if (safePointer == 0)
  33874. return;
  33875. }
  33876. }
  33877. }
  33878. void Component::enablementChanged()
  33879. {
  33880. }
  33881. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33882. {
  33883. flags.wantsFocusFlag = wantsFocus;
  33884. }
  33885. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33886. {
  33887. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33888. }
  33889. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33890. {
  33891. return ! flags.dontFocusOnMouseClickFlag;
  33892. }
  33893. bool Component::getWantsKeyboardFocus() const throw()
  33894. {
  33895. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33896. }
  33897. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33898. {
  33899. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33900. }
  33901. bool Component::isFocusContainer() const throw()
  33902. {
  33903. return flags.isFocusContainerFlag;
  33904. }
  33905. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33906. int Component::getExplicitFocusOrder() const
  33907. {
  33908. return properties [juce_explicitFocusOrderId];
  33909. }
  33910. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33911. {
  33912. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33913. }
  33914. KeyboardFocusTraverser* Component::createFocusTraverser()
  33915. {
  33916. if (flags.isFocusContainerFlag || parentComponent == 0)
  33917. return new KeyboardFocusTraverser();
  33918. return parentComponent->createFocusTraverser();
  33919. }
  33920. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33921. {
  33922. // give the focus to this component
  33923. if (currentlyFocusedComponent != this)
  33924. {
  33925. // get the focus onto our desktop window
  33926. ComponentPeer* const peer = getPeer();
  33927. if (peer != 0)
  33928. {
  33929. WeakReference<Component> safePointer (this);
  33930. peer->grabFocus();
  33931. if (peer->isFocused() && currentlyFocusedComponent != this)
  33932. {
  33933. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  33934. currentlyFocusedComponent = this;
  33935. Desktop::getInstance().triggerFocusCallback();
  33936. // call this after setting currentlyFocusedComponent so that the one that's
  33937. // losing it has a chance to see where focus is going
  33938. if (componentLosingFocus != 0)
  33939. componentLosingFocus->internalFocusLoss (cause);
  33940. if (currentlyFocusedComponent == this)
  33941. internalFocusGain (cause, safePointer);
  33942. }
  33943. }
  33944. }
  33945. }
  33946. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33947. {
  33948. if (isShowing())
  33949. {
  33950. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == 0))
  33951. {
  33952. takeKeyboardFocus (cause);
  33953. }
  33954. else
  33955. {
  33956. if (isParentOf (currentlyFocusedComponent)
  33957. && currentlyFocusedComponent->isShowing())
  33958. {
  33959. // do nothing if the focused component is actually a child of ours..
  33960. }
  33961. else
  33962. {
  33963. // find the default child component..
  33964. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33965. if (traverser != 0)
  33966. {
  33967. Component* const defaultComp = traverser->getDefaultComponent (this);
  33968. traverser = 0;
  33969. if (defaultComp != 0)
  33970. {
  33971. defaultComp->grabFocusInternal (cause, false);
  33972. return;
  33973. }
  33974. }
  33975. if (canTryParent && parentComponent != 0)
  33976. {
  33977. // if no children want it and we're allowed to try our parent comp,
  33978. // then pass up to parent, which will try our siblings.
  33979. parentComponent->grabFocusInternal (cause, true);
  33980. }
  33981. }
  33982. }
  33983. }
  33984. }
  33985. void Component::grabKeyboardFocus()
  33986. {
  33987. // if component methods are being called from threads other than the message
  33988. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33989. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33990. grabFocusInternal (focusChangedDirectly);
  33991. }
  33992. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33993. {
  33994. // if component methods are being called from threads other than the message
  33995. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33996. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33997. if (parentComponent != 0)
  33998. {
  33999. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34000. if (traverser != 0)
  34001. {
  34002. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34003. : traverser->getPreviousComponent (this);
  34004. traverser = 0;
  34005. if (nextComp != 0)
  34006. {
  34007. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34008. {
  34009. WeakReference<Component> nextCompPointer (nextComp);
  34010. internalModalInputAttempt();
  34011. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34012. return;
  34013. }
  34014. nextComp->grabFocusInternal (focusChangedByTabKey);
  34015. return;
  34016. }
  34017. }
  34018. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  34019. }
  34020. }
  34021. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34022. {
  34023. return (currentlyFocusedComponent == this)
  34024. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34025. }
  34026. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34027. {
  34028. return currentlyFocusedComponent;
  34029. }
  34030. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  34031. {
  34032. Component* const componentLosingFocus = currentlyFocusedComponent;
  34033. currentlyFocusedComponent = 0;
  34034. if (sendFocusLossEvent && componentLosingFocus != 0)
  34035. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34036. Desktop::getInstance().triggerFocusCallback();
  34037. }
  34038. bool Component::isMouseOver (const bool includeChildren) const
  34039. {
  34040. if (flags.mouseOverFlag)
  34041. return true;
  34042. if (includeChildren)
  34043. {
  34044. Desktop& desktop = Desktop::getInstance();
  34045. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34046. {
  34047. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  34048. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  34049. return true;
  34050. }
  34051. }
  34052. return false;
  34053. }
  34054. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  34055. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  34056. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34057. {
  34058. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34059. }
  34060. const Point<int> Component::getMouseXYRelative() const
  34061. {
  34062. return getLocalPoint (0, Desktop::getMousePosition());
  34063. }
  34064. const Rectangle<int> Component::getParentMonitorArea() const
  34065. {
  34066. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  34067. }
  34068. void Component::addKeyListener (KeyListener* const newListener)
  34069. {
  34070. if (keyListeners == 0)
  34071. keyListeners = new Array <KeyListener*>();
  34072. keyListeners->addIfNotAlreadyThere (newListener);
  34073. }
  34074. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34075. {
  34076. if (keyListeners != 0)
  34077. keyListeners->removeValue (listenerToRemove);
  34078. }
  34079. bool Component::keyPressed (const KeyPress&)
  34080. {
  34081. return false;
  34082. }
  34083. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34084. {
  34085. return false;
  34086. }
  34087. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34088. {
  34089. if (parentComponent != 0)
  34090. parentComponent->modifierKeysChanged (modifiers);
  34091. }
  34092. void Component::internalModifierKeysChanged()
  34093. {
  34094. sendFakeMouseMove();
  34095. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34096. }
  34097. ComponentPeer* Component::getPeer() const
  34098. {
  34099. if (flags.hasHeavyweightPeerFlag)
  34100. return ComponentPeer::getPeerFor (this);
  34101. else if (parentComponent == 0)
  34102. return 0;
  34103. return parentComponent->getPeer();
  34104. }
  34105. Component::BailOutChecker::BailOutChecker (Component* const component)
  34106. : safePointer (component)
  34107. {
  34108. jassert (component != 0);
  34109. }
  34110. bool Component::BailOutChecker::shouldBailOut() const throw()
  34111. {
  34112. return safePointer == 0;
  34113. }
  34114. END_JUCE_NAMESPACE
  34115. /*** End of inlined file: juce_Component.cpp ***/
  34116. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34117. BEGIN_JUCE_NAMESPACE
  34118. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34119. void ComponentListener::componentBroughtToFront (Component&) {}
  34120. void ComponentListener::componentVisibilityChanged (Component&) {}
  34121. void ComponentListener::componentChildrenChanged (Component&) {}
  34122. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34123. void ComponentListener::componentNameChanged (Component&) {}
  34124. void ComponentListener::componentBeingDeleted (Component&) {}
  34125. END_JUCE_NAMESPACE
  34126. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34127. /*** Start of inlined file: juce_Desktop.cpp ***/
  34128. BEGIN_JUCE_NAMESPACE
  34129. Desktop::Desktop()
  34130. : mouseClickCounter (0),
  34131. kioskModeComponent (0),
  34132. allowedOrientations (allOrientations)
  34133. {
  34134. createMouseInputSources();
  34135. refreshMonitorSizes();
  34136. }
  34137. Desktop::~Desktop()
  34138. {
  34139. jassert (instance == this);
  34140. instance = 0;
  34141. // doh! If you don't delete all your windows before exiting, you're going to
  34142. // be leaking memory!
  34143. jassert (desktopComponents.size() == 0);
  34144. }
  34145. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34146. {
  34147. if (instance == 0)
  34148. instance = new Desktop();
  34149. return *instance;
  34150. }
  34151. Desktop* Desktop::instance = 0;
  34152. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34153. const bool clipToWorkArea);
  34154. void Desktop::refreshMonitorSizes()
  34155. {
  34156. Array <Rectangle<int> > oldClipped, oldUnclipped;
  34157. oldClipped.swapWithArray (monitorCoordsClipped);
  34158. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  34159. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34160. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34161. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34162. if (oldClipped != monitorCoordsClipped
  34163. || oldUnclipped != monitorCoordsUnclipped)
  34164. {
  34165. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34166. {
  34167. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34168. if (p != 0)
  34169. p->handleScreenSizeChange();
  34170. }
  34171. }
  34172. }
  34173. int Desktop::getNumDisplayMonitors() const throw()
  34174. {
  34175. return monitorCoordsClipped.size();
  34176. }
  34177. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34178. {
  34179. return clippedToWorkArea ? monitorCoordsClipped [index]
  34180. : monitorCoordsUnclipped [index];
  34181. }
  34182. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34183. {
  34184. RectangleList rl;
  34185. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34186. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34187. return rl;
  34188. }
  34189. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34190. {
  34191. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34192. }
  34193. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34194. {
  34195. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34196. double bestDistance = 1.0e10;
  34197. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34198. {
  34199. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34200. if (rect.contains (position))
  34201. return rect;
  34202. const double distance = rect.getCentre().getDistanceFrom (position);
  34203. if (distance < bestDistance)
  34204. {
  34205. bestDistance = distance;
  34206. best = rect;
  34207. }
  34208. }
  34209. return best;
  34210. }
  34211. int Desktop::getNumComponents() const throw()
  34212. {
  34213. return desktopComponents.size();
  34214. }
  34215. Component* Desktop::getComponent (const int index) const throw()
  34216. {
  34217. return desktopComponents [index];
  34218. }
  34219. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34220. {
  34221. for (int i = desktopComponents.size(); --i >= 0;)
  34222. {
  34223. Component* const c = desktopComponents.getUnchecked(i);
  34224. if (c->isVisible())
  34225. {
  34226. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34227. if (c->contains (relative))
  34228. return c->getComponentAt (relative);
  34229. }
  34230. }
  34231. return 0;
  34232. }
  34233. void Desktop::addDesktopComponent (Component* const c)
  34234. {
  34235. jassert (c != 0);
  34236. jassert (! desktopComponents.contains (c));
  34237. desktopComponents.addIfNotAlreadyThere (c);
  34238. }
  34239. void Desktop::removeDesktopComponent (Component* const c)
  34240. {
  34241. desktopComponents.removeValue (c);
  34242. }
  34243. void Desktop::componentBroughtToFront (Component* const c)
  34244. {
  34245. const int index = desktopComponents.indexOf (c);
  34246. jassert (index >= 0);
  34247. if (index >= 0)
  34248. {
  34249. int newIndex = -1;
  34250. if (! c->isAlwaysOnTop())
  34251. {
  34252. newIndex = desktopComponents.size();
  34253. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34254. --newIndex;
  34255. --newIndex;
  34256. }
  34257. desktopComponents.move (index, newIndex);
  34258. }
  34259. }
  34260. const Point<int> Desktop::getMousePosition()
  34261. {
  34262. return getInstance().getMainMouseSource().getScreenPosition();
  34263. }
  34264. const Point<int> Desktop::getLastMouseDownPosition()
  34265. {
  34266. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34267. }
  34268. int Desktop::getMouseButtonClickCounter()
  34269. {
  34270. return getInstance().mouseClickCounter;
  34271. }
  34272. void Desktop::incrementMouseClickCounter() throw()
  34273. {
  34274. ++mouseClickCounter;
  34275. }
  34276. int Desktop::getNumDraggingMouseSources() const throw()
  34277. {
  34278. int num = 0;
  34279. for (int i = mouseSources.size(); --i >= 0;)
  34280. if (mouseSources.getUnchecked(i)->isDragging())
  34281. ++num;
  34282. return num;
  34283. }
  34284. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34285. {
  34286. int num = 0;
  34287. for (int i = mouseSources.size(); --i >= 0;)
  34288. {
  34289. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34290. if (mi->isDragging())
  34291. {
  34292. if (index == num)
  34293. return mi;
  34294. ++num;
  34295. }
  34296. }
  34297. return 0;
  34298. }
  34299. class MouseDragAutoRepeater : public Timer
  34300. {
  34301. public:
  34302. MouseDragAutoRepeater() {}
  34303. void timerCallback()
  34304. {
  34305. Desktop& desktop = Desktop::getInstance();
  34306. int numMiceDown = 0;
  34307. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34308. {
  34309. MouseInputSource* const source = desktop.getMouseSource(i);
  34310. if (source->isDragging())
  34311. {
  34312. source->triggerFakeMove();
  34313. ++numMiceDown;
  34314. }
  34315. }
  34316. if (numMiceDown == 0)
  34317. desktop.beginDragAutoRepeat (0);
  34318. }
  34319. private:
  34320. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34321. };
  34322. void Desktop::beginDragAutoRepeat (const int interval)
  34323. {
  34324. if (interval > 0)
  34325. {
  34326. if (dragRepeater == 0)
  34327. dragRepeater = new MouseDragAutoRepeater();
  34328. if (dragRepeater->getTimerInterval() != interval)
  34329. dragRepeater->startTimer (interval);
  34330. }
  34331. else
  34332. {
  34333. dragRepeater = 0;
  34334. }
  34335. }
  34336. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34337. {
  34338. focusListeners.add (listener);
  34339. }
  34340. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34341. {
  34342. focusListeners.remove (listener);
  34343. }
  34344. void Desktop::triggerFocusCallback()
  34345. {
  34346. triggerAsyncUpdate();
  34347. }
  34348. void Desktop::handleAsyncUpdate()
  34349. {
  34350. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34351. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34352. WeakReference<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34353. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34354. }
  34355. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34356. {
  34357. mouseListeners.add (listener);
  34358. resetTimer();
  34359. }
  34360. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34361. {
  34362. mouseListeners.remove (listener);
  34363. resetTimer();
  34364. }
  34365. void Desktop::timerCallback()
  34366. {
  34367. if (lastFakeMouseMove != getMousePosition())
  34368. sendMouseMove();
  34369. }
  34370. void Desktop::sendMouseMove()
  34371. {
  34372. if (! mouseListeners.isEmpty())
  34373. {
  34374. startTimer (20);
  34375. lastFakeMouseMove = getMousePosition();
  34376. Component* const target = findComponentAt (lastFakeMouseMove);
  34377. if (target != 0)
  34378. {
  34379. Component::BailOutChecker checker (target);
  34380. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34381. const Time now (Time::getCurrentTime());
  34382. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34383. target, target, now, pos, now, 0, false);
  34384. if (me.mods.isAnyMouseButtonDown())
  34385. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34386. else
  34387. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34388. }
  34389. }
  34390. }
  34391. void Desktop::resetTimer()
  34392. {
  34393. if (mouseListeners.size() == 0)
  34394. stopTimer();
  34395. else
  34396. startTimer (100);
  34397. lastFakeMouseMove = getMousePosition();
  34398. }
  34399. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34400. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34401. {
  34402. if (kioskModeComponent != componentToUse)
  34403. {
  34404. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34405. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34406. if (kioskModeComponent != 0)
  34407. {
  34408. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34409. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34410. }
  34411. kioskModeComponent = componentToUse;
  34412. if (kioskModeComponent != 0)
  34413. {
  34414. // Only components that are already on the desktop can be put into kiosk mode!
  34415. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34416. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34417. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34418. }
  34419. }
  34420. }
  34421. void Desktop::setOrientationsEnabled (const int newOrientations)
  34422. {
  34423. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34424. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34425. allowedOrientations = newOrientations;
  34426. }
  34427. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34428. {
  34429. // Make sure you only pass one valid flag in here...
  34430. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34431. return (allowedOrientations & orientation) != 0;
  34432. }
  34433. END_JUCE_NAMESPACE
  34434. /*** End of inlined file: juce_Desktop.cpp ***/
  34435. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34436. BEGIN_JUCE_NAMESPACE
  34437. class ModalComponentManager::ModalItem : public ComponentMovementWatcher
  34438. {
  34439. public:
  34440. ModalItem (Component* const comp, Callback* const callback)
  34441. : ComponentMovementWatcher (comp),
  34442. component (comp), returnValue (0), isActive (true)
  34443. {
  34444. jassert (comp != 0);
  34445. if (callback != 0)
  34446. callbacks.add (callback);
  34447. }
  34448. void componentMovedOrResized (bool, bool) {}
  34449. void componentPeerChanged()
  34450. {
  34451. if (! component->isShowing())
  34452. cancel();
  34453. }
  34454. void componentVisibilityChanged()
  34455. {
  34456. if (! component->isShowing())
  34457. cancel();
  34458. }
  34459. void componentBeingDeleted (Component& comp)
  34460. {
  34461. if (component == &comp || comp.isParentOf (component))
  34462. cancel();
  34463. }
  34464. void cancel()
  34465. {
  34466. if (isActive)
  34467. {
  34468. isActive = false;
  34469. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34470. }
  34471. }
  34472. Component* component;
  34473. OwnedArray<Callback> callbacks;
  34474. int returnValue;
  34475. bool isActive;
  34476. private:
  34477. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34478. };
  34479. ModalComponentManager::ModalComponentManager()
  34480. {
  34481. }
  34482. ModalComponentManager::~ModalComponentManager()
  34483. {
  34484. clearSingletonInstance();
  34485. }
  34486. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34487. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34488. {
  34489. if (component != 0)
  34490. stack.add (new ModalItem (component, callback));
  34491. }
  34492. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34493. {
  34494. if (callback != 0)
  34495. {
  34496. ScopedPointer<Callback> callbackDeleter (callback);
  34497. for (int i = stack.size(); --i >= 0;)
  34498. {
  34499. ModalItem* const item = stack.getUnchecked(i);
  34500. if (item->component == component)
  34501. {
  34502. item->callbacks.add (callback);
  34503. callbackDeleter.release();
  34504. break;
  34505. }
  34506. }
  34507. }
  34508. }
  34509. void ModalComponentManager::endModal (Component* component)
  34510. {
  34511. for (int i = stack.size(); --i >= 0;)
  34512. {
  34513. ModalItem* const item = stack.getUnchecked(i);
  34514. if (item->component == component)
  34515. item->cancel();
  34516. }
  34517. }
  34518. void ModalComponentManager::endModal (Component* component, int returnValue)
  34519. {
  34520. for (int i = stack.size(); --i >= 0;)
  34521. {
  34522. ModalItem* const item = stack.getUnchecked(i);
  34523. if (item->component == component)
  34524. {
  34525. item->returnValue = returnValue;
  34526. item->cancel();
  34527. }
  34528. }
  34529. }
  34530. int ModalComponentManager::getNumModalComponents() const
  34531. {
  34532. int n = 0;
  34533. for (int i = 0; i < stack.size(); ++i)
  34534. if (stack.getUnchecked(i)->isActive)
  34535. ++n;
  34536. return n;
  34537. }
  34538. Component* ModalComponentManager::getModalComponent (const int index) const
  34539. {
  34540. int n = 0;
  34541. for (int i = stack.size(); --i >= 0;)
  34542. {
  34543. const ModalItem* const item = stack.getUnchecked(i);
  34544. if (item->isActive)
  34545. if (n++ == index)
  34546. return item->component;
  34547. }
  34548. return 0;
  34549. }
  34550. bool ModalComponentManager::isModal (Component* const comp) const
  34551. {
  34552. for (int i = stack.size(); --i >= 0;)
  34553. {
  34554. const ModalItem* const item = stack.getUnchecked(i);
  34555. if (item->isActive && item->component == comp)
  34556. return true;
  34557. }
  34558. return false;
  34559. }
  34560. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34561. {
  34562. return comp == getModalComponent (0);
  34563. }
  34564. void ModalComponentManager::handleAsyncUpdate()
  34565. {
  34566. for (int i = stack.size(); --i >= 0;)
  34567. {
  34568. const ModalItem* const item = stack.getUnchecked(i);
  34569. if (! item->isActive)
  34570. {
  34571. for (int j = item->callbacks.size(); --j >= 0;)
  34572. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34573. stack.remove (i);
  34574. }
  34575. }
  34576. }
  34577. void ModalComponentManager::bringModalComponentsToFront()
  34578. {
  34579. ComponentPeer* lastOne = 0;
  34580. for (int i = 0; i < getNumModalComponents(); ++i)
  34581. {
  34582. Component* const c = getModalComponent (i);
  34583. if (c == 0)
  34584. break;
  34585. ComponentPeer* peer = c->getPeer();
  34586. if (peer != 0 && peer != lastOne)
  34587. {
  34588. if (lastOne == 0)
  34589. {
  34590. peer->toFront (true);
  34591. peer->grabFocus();
  34592. }
  34593. else
  34594. peer->toBehind (lastOne);
  34595. lastOne = peer;
  34596. }
  34597. }
  34598. }
  34599. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34600. {
  34601. public:
  34602. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34603. ~ReturnValueRetriever() {}
  34604. void modalStateFinished (int returnValue)
  34605. {
  34606. finished = true;
  34607. value = returnValue;
  34608. }
  34609. private:
  34610. int& value;
  34611. bool& finished;
  34612. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34613. };
  34614. int ModalComponentManager::runEventLoopForCurrentComponent()
  34615. {
  34616. // This can only be run from the message thread!
  34617. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34618. Component* currentlyModal = getModalComponent (0);
  34619. if (currentlyModal == 0)
  34620. return 0;
  34621. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34622. int returnValue = 0;
  34623. bool finished = false;
  34624. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34625. JUCE_TRY
  34626. {
  34627. while (! finished)
  34628. {
  34629. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34630. break;
  34631. }
  34632. }
  34633. JUCE_CATCH_EXCEPTION
  34634. if (prevFocused != 0)
  34635. prevFocused->grabKeyboardFocus();
  34636. return returnValue;
  34637. }
  34638. END_JUCE_NAMESPACE
  34639. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34640. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34641. BEGIN_JUCE_NAMESPACE
  34642. ArrowButton::ArrowButton (const String& name,
  34643. float arrowDirectionInRadians,
  34644. const Colour& arrowColour)
  34645. : Button (name),
  34646. colour (arrowColour)
  34647. {
  34648. path.lineTo (0.0f, 1.0f);
  34649. path.lineTo (1.0f, 0.5f);
  34650. path.closeSubPath();
  34651. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34652. 0.5f, 0.5f));
  34653. setComponentEffect (&shadow);
  34654. buttonStateChanged();
  34655. }
  34656. ArrowButton::~ArrowButton()
  34657. {
  34658. }
  34659. void ArrowButton::paintButton (Graphics& g,
  34660. bool /*isMouseOverButton*/,
  34661. bool /*isButtonDown*/)
  34662. {
  34663. g.setColour (colour);
  34664. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34665. (float) offset,
  34666. (float) (getWidth() - 3),
  34667. (float) (getHeight() - 3),
  34668. false));
  34669. }
  34670. void ArrowButton::buttonStateChanged()
  34671. {
  34672. offset = (isDown()) ? 1 : 0;
  34673. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34674. 0.3f, -1, 0);
  34675. }
  34676. END_JUCE_NAMESPACE
  34677. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34678. /*** Start of inlined file: juce_Button.cpp ***/
  34679. BEGIN_JUCE_NAMESPACE
  34680. class Button::RepeatTimer : public Timer
  34681. {
  34682. public:
  34683. RepeatTimer (Button& owner_) : owner (owner_) {}
  34684. void timerCallback() { owner.repeatTimerCallback(); }
  34685. private:
  34686. Button& owner;
  34687. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34688. };
  34689. Button::Button (const String& name)
  34690. : Component (name),
  34691. text (name),
  34692. buttonPressTime (0),
  34693. lastRepeatTime (0),
  34694. commandManagerToUse (0),
  34695. autoRepeatDelay (-1),
  34696. autoRepeatSpeed (0),
  34697. autoRepeatMinimumDelay (-1),
  34698. radioGroupId (0),
  34699. commandID (0),
  34700. connectedEdgeFlags (0),
  34701. buttonState (buttonNormal),
  34702. lastToggleState (false),
  34703. clickTogglesState (false),
  34704. needsToRelease (false),
  34705. needsRepainting (false),
  34706. isKeyDown (false),
  34707. triggerOnMouseDown (false),
  34708. generateTooltip (false)
  34709. {
  34710. setWantsKeyboardFocus (true);
  34711. isOn.addListener (this);
  34712. }
  34713. Button::~Button()
  34714. {
  34715. isOn.removeListener (this);
  34716. if (commandManagerToUse != 0)
  34717. commandManagerToUse->removeListener (this);
  34718. repeatTimer = 0;
  34719. clearShortcuts();
  34720. }
  34721. void Button::setButtonText (const String& newText)
  34722. {
  34723. if (text != newText)
  34724. {
  34725. text = newText;
  34726. repaint();
  34727. }
  34728. }
  34729. void Button::setTooltip (const String& newTooltip)
  34730. {
  34731. SettableTooltipClient::setTooltip (newTooltip);
  34732. generateTooltip = false;
  34733. }
  34734. const String Button::getTooltip()
  34735. {
  34736. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34737. {
  34738. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34739. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34740. for (int i = 0; i < keyPresses.size(); ++i)
  34741. {
  34742. const String key (keyPresses.getReference(i).getTextDescription());
  34743. tt << " [";
  34744. if (key.length() == 1)
  34745. tt << TRANS("shortcut") << ": '" << key << "']";
  34746. else
  34747. tt << key << ']';
  34748. }
  34749. return tt;
  34750. }
  34751. return SettableTooltipClient::getTooltip();
  34752. }
  34753. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34754. {
  34755. if (connectedEdgeFlags != connectedEdgeFlags_)
  34756. {
  34757. connectedEdgeFlags = connectedEdgeFlags_;
  34758. repaint();
  34759. }
  34760. }
  34761. void Button::setToggleState (const bool shouldBeOn,
  34762. const bool sendChangeNotification)
  34763. {
  34764. if (shouldBeOn != lastToggleState)
  34765. {
  34766. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34767. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34768. lastToggleState = shouldBeOn;
  34769. repaint();
  34770. WeakReference<Component> deletionWatcher (this);
  34771. if (sendChangeNotification)
  34772. {
  34773. sendClickMessage (ModifierKeys());
  34774. if (deletionWatcher == 0)
  34775. return;
  34776. }
  34777. if (lastToggleState)
  34778. {
  34779. turnOffOtherButtonsInGroup (sendChangeNotification);
  34780. if (deletionWatcher == 0)
  34781. return;
  34782. }
  34783. sendStateMessage();
  34784. }
  34785. }
  34786. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34787. {
  34788. clickTogglesState = shouldToggle;
  34789. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34790. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34791. // it is that this button represents, and the button will update its state to reflect this
  34792. // in the applicationCommandListChanged() method.
  34793. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34794. }
  34795. bool Button::getClickingTogglesState() const throw()
  34796. {
  34797. return clickTogglesState;
  34798. }
  34799. void Button::valueChanged (Value& value)
  34800. {
  34801. if (value.refersToSameSourceAs (isOn))
  34802. setToggleState (isOn.getValue(), true);
  34803. }
  34804. void Button::setRadioGroupId (const int newGroupId)
  34805. {
  34806. if (radioGroupId != newGroupId)
  34807. {
  34808. radioGroupId = newGroupId;
  34809. if (lastToggleState)
  34810. turnOffOtherButtonsInGroup (true);
  34811. }
  34812. }
  34813. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34814. {
  34815. Component* const p = getParentComponent();
  34816. if (p != 0 && radioGroupId != 0)
  34817. {
  34818. WeakReference<Component> deletionWatcher (this);
  34819. for (int i = p->getNumChildComponents(); --i >= 0;)
  34820. {
  34821. Component* const c = p->getChildComponent (i);
  34822. if (c != this)
  34823. {
  34824. Button* const b = dynamic_cast <Button*> (c);
  34825. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34826. {
  34827. b->setToggleState (false, sendChangeNotification);
  34828. if (deletionWatcher == 0)
  34829. return;
  34830. }
  34831. }
  34832. }
  34833. }
  34834. }
  34835. void Button::enablementChanged()
  34836. {
  34837. updateState();
  34838. repaint();
  34839. }
  34840. Button::ButtonState Button::updateState()
  34841. {
  34842. return updateState (isMouseOver (true), isMouseButtonDown());
  34843. }
  34844. Button::ButtonState Button::updateState (const bool over, const bool down)
  34845. {
  34846. ButtonState newState = buttonNormal;
  34847. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34848. {
  34849. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34850. newState = buttonDown;
  34851. else if (over)
  34852. newState = buttonOver;
  34853. }
  34854. setState (newState);
  34855. return newState;
  34856. }
  34857. void Button::setState (const ButtonState newState)
  34858. {
  34859. if (buttonState != newState)
  34860. {
  34861. buttonState = newState;
  34862. repaint();
  34863. if (buttonState == buttonDown)
  34864. {
  34865. buttonPressTime = Time::getApproximateMillisecondCounter();
  34866. lastRepeatTime = 0;
  34867. }
  34868. sendStateMessage();
  34869. }
  34870. }
  34871. bool Button::isDown() const throw()
  34872. {
  34873. return buttonState == buttonDown;
  34874. }
  34875. bool Button::isOver() const throw()
  34876. {
  34877. return buttonState != buttonNormal;
  34878. }
  34879. void Button::buttonStateChanged()
  34880. {
  34881. }
  34882. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34883. {
  34884. const uint32 now = Time::getApproximateMillisecondCounter();
  34885. return now > buttonPressTime ? now - buttonPressTime : 0;
  34886. }
  34887. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34888. {
  34889. triggerOnMouseDown = isTriggeredOnMouseDown;
  34890. }
  34891. void Button::clicked()
  34892. {
  34893. }
  34894. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34895. {
  34896. clicked();
  34897. }
  34898. static const int clickMessageId = 0x2f3f4f99;
  34899. void Button::triggerClick()
  34900. {
  34901. postCommandMessage (clickMessageId);
  34902. }
  34903. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34904. {
  34905. if (clickTogglesState)
  34906. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34907. sendClickMessage (modifiers);
  34908. }
  34909. void Button::flashButtonState()
  34910. {
  34911. if (isEnabled())
  34912. {
  34913. needsToRelease = true;
  34914. setState (buttonDown);
  34915. getRepeatTimer().startTimer (100);
  34916. }
  34917. }
  34918. void Button::handleCommandMessage (int commandId)
  34919. {
  34920. if (commandId == clickMessageId)
  34921. {
  34922. if (isEnabled())
  34923. {
  34924. flashButtonState();
  34925. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34926. }
  34927. }
  34928. else
  34929. {
  34930. Component::handleCommandMessage (commandId);
  34931. }
  34932. }
  34933. void Button::addListener (ButtonListener* const newListener)
  34934. {
  34935. buttonListeners.add (newListener);
  34936. }
  34937. void Button::removeListener (ButtonListener* const listener)
  34938. {
  34939. buttonListeners.remove (listener);
  34940. }
  34941. void Button::addButtonListener (ButtonListener* l) { addListener (l); }
  34942. void Button::removeButtonListener (ButtonListener* l) { removeListener (l); }
  34943. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34944. {
  34945. Component::BailOutChecker checker (this);
  34946. if (commandManagerToUse != 0 && commandID != 0)
  34947. {
  34948. ApplicationCommandTarget::InvocationInfo info (commandID);
  34949. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34950. info.originatingComponent = this;
  34951. commandManagerToUse->invoke (info, true);
  34952. }
  34953. clicked (modifiers);
  34954. if (! checker.shouldBailOut())
  34955. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  34956. }
  34957. void Button::sendStateMessage()
  34958. {
  34959. Component::BailOutChecker checker (this);
  34960. buttonStateChanged();
  34961. if (! checker.shouldBailOut())
  34962. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34963. }
  34964. void Button::paint (Graphics& g)
  34965. {
  34966. if (needsToRelease && isEnabled())
  34967. {
  34968. needsToRelease = false;
  34969. needsRepainting = true;
  34970. }
  34971. paintButton (g, isOver(), isDown());
  34972. }
  34973. void Button::mouseEnter (const MouseEvent&)
  34974. {
  34975. updateState (true, false);
  34976. }
  34977. void Button::mouseExit (const MouseEvent&)
  34978. {
  34979. updateState (false, false);
  34980. }
  34981. void Button::mouseDown (const MouseEvent& e)
  34982. {
  34983. updateState (true, true);
  34984. if (isDown())
  34985. {
  34986. if (autoRepeatDelay >= 0)
  34987. getRepeatTimer().startTimer (autoRepeatDelay);
  34988. if (triggerOnMouseDown)
  34989. internalClickCallback (e.mods);
  34990. }
  34991. }
  34992. void Button::mouseUp (const MouseEvent& e)
  34993. {
  34994. const bool wasDown = isDown();
  34995. updateState (isMouseOver(), false);
  34996. if (wasDown && isOver() && ! triggerOnMouseDown)
  34997. internalClickCallback (e.mods);
  34998. }
  34999. void Button::mouseDrag (const MouseEvent&)
  35000. {
  35001. const ButtonState oldState = buttonState;
  35002. updateState (isMouseOver(), true);
  35003. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35004. getRepeatTimer().startTimer (autoRepeatSpeed);
  35005. }
  35006. void Button::focusGained (FocusChangeType)
  35007. {
  35008. updateState();
  35009. repaint();
  35010. }
  35011. void Button::focusLost (FocusChangeType)
  35012. {
  35013. updateState();
  35014. repaint();
  35015. }
  35016. void Button::visibilityChanged()
  35017. {
  35018. needsToRelease = false;
  35019. updateState();
  35020. }
  35021. void Button::parentHierarchyChanged()
  35022. {
  35023. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35024. if (newKeySource != keySource.get())
  35025. {
  35026. if (keySource != 0)
  35027. keySource->removeKeyListener (this);
  35028. keySource = newKeySource;
  35029. if (keySource != 0)
  35030. keySource->addKeyListener (this);
  35031. }
  35032. }
  35033. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35034. const int commandID_,
  35035. const bool generateTooltip_)
  35036. {
  35037. commandID = commandID_;
  35038. generateTooltip = generateTooltip_;
  35039. if (commandManagerToUse != commandManagerToUse_)
  35040. {
  35041. if (commandManagerToUse != 0)
  35042. commandManagerToUse->removeListener (this);
  35043. commandManagerToUse = commandManagerToUse_;
  35044. if (commandManagerToUse != 0)
  35045. commandManagerToUse->addListener (this);
  35046. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35047. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35048. // it is that this button represents, and the button will update its state to reflect this
  35049. // in the applicationCommandListChanged() method.
  35050. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35051. }
  35052. if (commandManagerToUse != 0)
  35053. applicationCommandListChanged();
  35054. else
  35055. setEnabled (true);
  35056. }
  35057. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35058. {
  35059. if (info.commandID == commandID
  35060. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35061. {
  35062. flashButtonState();
  35063. }
  35064. }
  35065. void Button::applicationCommandListChanged()
  35066. {
  35067. if (commandManagerToUse != 0)
  35068. {
  35069. ApplicationCommandInfo info (0);
  35070. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35071. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35072. if (target != 0)
  35073. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35074. }
  35075. }
  35076. void Button::addShortcut (const KeyPress& key)
  35077. {
  35078. if (key.isValid())
  35079. {
  35080. jassert (! isRegisteredForShortcut (key)); // already registered!
  35081. shortcuts.add (key);
  35082. parentHierarchyChanged();
  35083. }
  35084. }
  35085. void Button::clearShortcuts()
  35086. {
  35087. shortcuts.clear();
  35088. parentHierarchyChanged();
  35089. }
  35090. bool Button::isShortcutPressed() const
  35091. {
  35092. if (! isCurrentlyBlockedByAnotherModalComponent())
  35093. {
  35094. for (int i = shortcuts.size(); --i >= 0;)
  35095. if (shortcuts.getReference(i).isCurrentlyDown())
  35096. return true;
  35097. }
  35098. return false;
  35099. }
  35100. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35101. {
  35102. for (int i = shortcuts.size(); --i >= 0;)
  35103. if (key == shortcuts.getReference(i))
  35104. return true;
  35105. return false;
  35106. }
  35107. bool Button::keyStateChanged (const bool, Component*)
  35108. {
  35109. if (! isEnabled())
  35110. return false;
  35111. const bool wasDown = isKeyDown;
  35112. isKeyDown = isShortcutPressed();
  35113. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35114. getRepeatTimer().startTimer (autoRepeatDelay);
  35115. updateState();
  35116. if (isEnabled() && wasDown && ! isKeyDown)
  35117. {
  35118. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35119. // (return immediately - this button may now have been deleted)
  35120. return true;
  35121. }
  35122. return wasDown || isKeyDown;
  35123. }
  35124. bool Button::keyPressed (const KeyPress&, Component*)
  35125. {
  35126. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35127. return isShortcutPressed();
  35128. }
  35129. bool Button::keyPressed (const KeyPress& key)
  35130. {
  35131. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35132. {
  35133. triggerClick();
  35134. return true;
  35135. }
  35136. return false;
  35137. }
  35138. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35139. const int repeatMillisecs,
  35140. const int minimumDelayInMillisecs) throw()
  35141. {
  35142. autoRepeatDelay = initialDelayMillisecs;
  35143. autoRepeatSpeed = repeatMillisecs;
  35144. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35145. }
  35146. void Button::repeatTimerCallback()
  35147. {
  35148. if (needsRepainting)
  35149. {
  35150. getRepeatTimer().stopTimer();
  35151. updateState();
  35152. needsRepainting = false;
  35153. }
  35154. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  35155. {
  35156. int repeatSpeed = autoRepeatSpeed;
  35157. if (autoRepeatMinimumDelay >= 0)
  35158. {
  35159. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35160. timeHeldDown *= timeHeldDown;
  35161. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35162. }
  35163. repeatSpeed = jmax (1, repeatSpeed);
  35164. const uint32 now = Time::getMillisecondCounter();
  35165. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  35166. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  35167. repeatSpeed = jmax (1, repeatSpeed / 2);
  35168. lastRepeatTime = now;
  35169. getRepeatTimer().startTimer (repeatSpeed);
  35170. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35171. }
  35172. else if (! needsToRelease)
  35173. {
  35174. getRepeatTimer().stopTimer();
  35175. }
  35176. }
  35177. Button::RepeatTimer& Button::getRepeatTimer()
  35178. {
  35179. if (repeatTimer == 0)
  35180. repeatTimer = new RepeatTimer (*this);
  35181. return *repeatTimer;
  35182. }
  35183. END_JUCE_NAMESPACE
  35184. /*** End of inlined file: juce_Button.cpp ***/
  35185. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35186. BEGIN_JUCE_NAMESPACE
  35187. DrawableButton::DrawableButton (const String& name,
  35188. const DrawableButton::ButtonStyle buttonStyle)
  35189. : Button (name),
  35190. style (buttonStyle),
  35191. currentImage (0),
  35192. edgeIndent (3)
  35193. {
  35194. if (buttonStyle == ImageOnButtonBackground)
  35195. {
  35196. backgroundOff = Colour (0xffbbbbff);
  35197. backgroundOn = Colour (0xff3333ff);
  35198. }
  35199. else
  35200. {
  35201. backgroundOff = Colours::transparentBlack;
  35202. backgroundOn = Colour (0xaabbbbff);
  35203. }
  35204. }
  35205. DrawableButton::~DrawableButton()
  35206. {
  35207. }
  35208. void DrawableButton::setImages (const Drawable* normal,
  35209. const Drawable* over,
  35210. const Drawable* down,
  35211. const Drawable* disabled,
  35212. const Drawable* normalOn,
  35213. const Drawable* overOn,
  35214. const Drawable* downOn,
  35215. const Drawable* disabledOn)
  35216. {
  35217. jassert (normal != 0); // you really need to give it at least a normal image..
  35218. if (normal != 0) normalImage = normal->createCopy();
  35219. if (over != 0) overImage = over->createCopy();
  35220. if (down != 0) downImage = down->createCopy();
  35221. if (disabled != 0) disabledImage = disabled->createCopy();
  35222. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35223. if (overOn != 0) overImageOn = overOn->createCopy();
  35224. if (downOn != 0) downImageOn = downOn->createCopy();
  35225. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35226. buttonStateChanged();
  35227. }
  35228. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35229. {
  35230. if (style != newStyle)
  35231. {
  35232. style = newStyle;
  35233. buttonStateChanged();
  35234. }
  35235. }
  35236. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35237. const Colour& toggledOnColour)
  35238. {
  35239. if (backgroundOff != toggledOffColour
  35240. || backgroundOn != toggledOnColour)
  35241. {
  35242. backgroundOff = toggledOffColour;
  35243. backgroundOn = toggledOnColour;
  35244. repaint();
  35245. }
  35246. }
  35247. const Colour& DrawableButton::getBackgroundColour() const throw()
  35248. {
  35249. return getToggleState() ? backgroundOn
  35250. : backgroundOff;
  35251. }
  35252. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35253. {
  35254. edgeIndent = numPixelsIndent;
  35255. repaint();
  35256. resized();
  35257. }
  35258. void DrawableButton::resized()
  35259. {
  35260. Button::resized();
  35261. if (currentImage != 0)
  35262. {
  35263. if (style == ImageRaw)
  35264. {
  35265. currentImage->setOriginWithOriginalSize (Point<float>());
  35266. }
  35267. else
  35268. {
  35269. Rectangle<int> imageSpace;
  35270. if (style == ImageOnButtonBackground)
  35271. {
  35272. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35273. }
  35274. else
  35275. {
  35276. const int textH = (style == ImageAboveTextLabel) ? jmin (16, proportionOfHeight (0.25f)) : 0;
  35277. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35278. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35279. imageSpace.setBounds (indentX, indentY,
  35280. getWidth() - indentX * 2,
  35281. getHeight() - indentY * 2 - textH);
  35282. }
  35283. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35284. }
  35285. }
  35286. }
  35287. void DrawableButton::buttonStateChanged()
  35288. {
  35289. repaint();
  35290. Drawable* imageToDraw = 0;
  35291. float opacity = 1.0f;
  35292. if (isEnabled())
  35293. {
  35294. imageToDraw = getCurrentImage();
  35295. }
  35296. else
  35297. {
  35298. imageToDraw = getToggleState() ? disabledImageOn
  35299. : disabledImage;
  35300. if (imageToDraw == 0)
  35301. {
  35302. opacity = 0.4f;
  35303. imageToDraw = getNormalImage();
  35304. }
  35305. }
  35306. if (imageToDraw != currentImage)
  35307. {
  35308. removeChildComponent (currentImage);
  35309. currentImage = imageToDraw;
  35310. if (currentImage != 0)
  35311. {
  35312. addAndMakeVisible (currentImage);
  35313. DrawableButton::resized();
  35314. }
  35315. }
  35316. if (currentImage != 0)
  35317. currentImage->setAlpha (opacity);
  35318. }
  35319. void DrawableButton::paintButton (Graphics& g,
  35320. bool isMouseOverButton,
  35321. bool isButtonDown)
  35322. {
  35323. if (style == ImageOnButtonBackground)
  35324. {
  35325. getLookAndFeel().drawButtonBackground (g, *this,
  35326. getBackgroundColour(),
  35327. isMouseOverButton,
  35328. isButtonDown);
  35329. }
  35330. else
  35331. {
  35332. g.fillAll (getBackgroundColour());
  35333. const int textH = (style == ImageAboveTextLabel)
  35334. ? jmin (16, proportionOfHeight (0.25f))
  35335. : 0;
  35336. if (textH > 0)
  35337. {
  35338. g.setFont ((float) textH);
  35339. g.setColour (findColour (DrawableButton::textColourId)
  35340. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35341. g.drawFittedText (getButtonText(),
  35342. 2, getHeight() - textH - 1,
  35343. getWidth() - 4, textH,
  35344. Justification::centred, 1);
  35345. }
  35346. }
  35347. }
  35348. Drawable* DrawableButton::getCurrentImage() const throw()
  35349. {
  35350. if (isDown())
  35351. return getDownImage();
  35352. if (isOver())
  35353. return getOverImage();
  35354. return getNormalImage();
  35355. }
  35356. Drawable* DrawableButton::getNormalImage() const throw()
  35357. {
  35358. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35359. : normalImage;
  35360. }
  35361. Drawable* DrawableButton::getOverImage() const throw()
  35362. {
  35363. Drawable* d = normalImage;
  35364. if (getToggleState())
  35365. {
  35366. if (overImageOn != 0)
  35367. d = overImageOn;
  35368. else if (normalImageOn != 0)
  35369. d = normalImageOn;
  35370. else if (overImage != 0)
  35371. d = overImage;
  35372. }
  35373. else
  35374. {
  35375. if (overImage != 0)
  35376. d = overImage;
  35377. }
  35378. return d;
  35379. }
  35380. Drawable* DrawableButton::getDownImage() const throw()
  35381. {
  35382. Drawable* d = normalImage;
  35383. if (getToggleState())
  35384. {
  35385. if (downImageOn != 0)
  35386. d = downImageOn;
  35387. else if (overImageOn != 0)
  35388. d = overImageOn;
  35389. else if (normalImageOn != 0)
  35390. d = normalImageOn;
  35391. else if (downImage != 0)
  35392. d = downImage;
  35393. else
  35394. d = getOverImage();
  35395. }
  35396. else
  35397. {
  35398. if (downImage != 0)
  35399. d = downImage;
  35400. else
  35401. d = getOverImage();
  35402. }
  35403. return d;
  35404. }
  35405. END_JUCE_NAMESPACE
  35406. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35407. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35408. BEGIN_JUCE_NAMESPACE
  35409. HyperlinkButton::HyperlinkButton (const String& linkText,
  35410. const URL& linkURL)
  35411. : Button (linkText),
  35412. url (linkURL),
  35413. font (14.0f, Font::underlined),
  35414. resizeFont (true),
  35415. justification (Justification::centred)
  35416. {
  35417. setMouseCursor (MouseCursor::PointingHandCursor);
  35418. setTooltip (linkURL.toString (false));
  35419. }
  35420. HyperlinkButton::~HyperlinkButton()
  35421. {
  35422. }
  35423. void HyperlinkButton::setFont (const Font& newFont,
  35424. const bool resizeToMatchComponentHeight,
  35425. const Justification& justificationType)
  35426. {
  35427. font = newFont;
  35428. resizeFont = resizeToMatchComponentHeight;
  35429. justification = justificationType;
  35430. repaint();
  35431. }
  35432. void HyperlinkButton::setURL (const URL& newURL) throw()
  35433. {
  35434. url = newURL;
  35435. setTooltip (newURL.toString (false));
  35436. }
  35437. const Font HyperlinkButton::getFontToUse() const
  35438. {
  35439. Font f (font);
  35440. if (resizeFont)
  35441. f.setHeight (getHeight() * 0.7f);
  35442. return f;
  35443. }
  35444. void HyperlinkButton::changeWidthToFitText()
  35445. {
  35446. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35447. }
  35448. void HyperlinkButton::colourChanged()
  35449. {
  35450. repaint();
  35451. }
  35452. void HyperlinkButton::clicked()
  35453. {
  35454. if (url.isWellFormed())
  35455. url.launchInDefaultBrowser();
  35456. }
  35457. void HyperlinkButton::paintButton (Graphics& g,
  35458. bool isMouseOverButton,
  35459. bool isButtonDown)
  35460. {
  35461. const Colour textColour (findColour (textColourId));
  35462. if (isEnabled())
  35463. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35464. : textColour);
  35465. else
  35466. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35467. g.setFont (getFontToUse());
  35468. g.drawText (getButtonText(),
  35469. 2, 0, getWidth() - 2, getHeight(),
  35470. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35471. true);
  35472. }
  35473. END_JUCE_NAMESPACE
  35474. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35475. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35476. BEGIN_JUCE_NAMESPACE
  35477. ImageButton::ImageButton (const String& text_)
  35478. : Button (text_),
  35479. scaleImageToFit (true),
  35480. preserveProportions (true),
  35481. alphaThreshold (0),
  35482. imageX (0),
  35483. imageY (0),
  35484. imageW (0),
  35485. imageH (0),
  35486. normalImage (0),
  35487. overImage (0),
  35488. downImage (0)
  35489. {
  35490. }
  35491. ImageButton::~ImageButton()
  35492. {
  35493. }
  35494. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35495. const bool rescaleImagesWhenButtonSizeChanges,
  35496. const bool preserveImageProportions,
  35497. const Image& normalImage_,
  35498. const float imageOpacityWhenNormal,
  35499. const Colour& overlayColourWhenNormal,
  35500. const Image& overImage_,
  35501. const float imageOpacityWhenOver,
  35502. const Colour& overlayColourWhenOver,
  35503. const Image& downImage_,
  35504. const float imageOpacityWhenDown,
  35505. const Colour& overlayColourWhenDown,
  35506. const float hitTestAlphaThreshold)
  35507. {
  35508. normalImage = normalImage_;
  35509. overImage = overImage_;
  35510. downImage = downImage_;
  35511. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35512. {
  35513. imageW = normalImage.getWidth();
  35514. imageH = normalImage.getHeight();
  35515. setSize (imageW, imageH);
  35516. }
  35517. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35518. preserveProportions = preserveImageProportions;
  35519. normalOpacity = imageOpacityWhenNormal;
  35520. normalOverlay = overlayColourWhenNormal;
  35521. overOpacity = imageOpacityWhenOver;
  35522. overOverlay = overlayColourWhenOver;
  35523. downOpacity = imageOpacityWhenDown;
  35524. downOverlay = overlayColourWhenDown;
  35525. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35526. repaint();
  35527. }
  35528. const Image ImageButton::getCurrentImage() const
  35529. {
  35530. if (isDown() || getToggleState())
  35531. return getDownImage();
  35532. if (isOver())
  35533. return getOverImage();
  35534. return getNormalImage();
  35535. }
  35536. const Image ImageButton::getNormalImage() const
  35537. {
  35538. return normalImage;
  35539. }
  35540. const Image ImageButton::getOverImage() const
  35541. {
  35542. return overImage.isValid() ? overImage
  35543. : normalImage;
  35544. }
  35545. const Image ImageButton::getDownImage() const
  35546. {
  35547. return downImage.isValid() ? downImage
  35548. : getOverImage();
  35549. }
  35550. void ImageButton::paintButton (Graphics& g,
  35551. bool isMouseOverButton,
  35552. bool isButtonDown)
  35553. {
  35554. if (! isEnabled())
  35555. {
  35556. isMouseOverButton = false;
  35557. isButtonDown = false;
  35558. }
  35559. Image im (getCurrentImage());
  35560. if (im.isValid())
  35561. {
  35562. const int iw = im.getWidth();
  35563. const int ih = im.getHeight();
  35564. imageW = getWidth();
  35565. imageH = getHeight();
  35566. imageX = (imageW - iw) >> 1;
  35567. imageY = (imageH - ih) >> 1;
  35568. if (scaleImageToFit)
  35569. {
  35570. if (preserveProportions)
  35571. {
  35572. int newW, newH;
  35573. const float imRatio = ih / (float)iw;
  35574. const float destRatio = imageH / (float)imageW;
  35575. if (imRatio > destRatio)
  35576. {
  35577. newW = roundToInt (imageH / imRatio);
  35578. newH = imageH;
  35579. }
  35580. else
  35581. {
  35582. newW = imageW;
  35583. newH = roundToInt (imageW * imRatio);
  35584. }
  35585. imageX = (imageW - newW) / 2;
  35586. imageY = (imageH - newH) / 2;
  35587. imageW = newW;
  35588. imageH = newH;
  35589. }
  35590. else
  35591. {
  35592. imageX = 0;
  35593. imageY = 0;
  35594. }
  35595. }
  35596. if (! scaleImageToFit)
  35597. {
  35598. imageW = iw;
  35599. imageH = ih;
  35600. }
  35601. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35602. isButtonDown ? downOverlay
  35603. : (isMouseOverButton ? overOverlay
  35604. : normalOverlay),
  35605. isButtonDown ? downOpacity
  35606. : (isMouseOverButton ? overOpacity
  35607. : normalOpacity),
  35608. *this);
  35609. }
  35610. }
  35611. bool ImageButton::hitTest (int x, int y)
  35612. {
  35613. if (alphaThreshold == 0)
  35614. return true;
  35615. Image im (getCurrentImage());
  35616. return im.isNull() || (imageW > 0 && imageH > 0
  35617. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35618. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35619. }
  35620. END_JUCE_NAMESPACE
  35621. /*** End of inlined file: juce_ImageButton.cpp ***/
  35622. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35623. BEGIN_JUCE_NAMESPACE
  35624. ShapeButton::ShapeButton (const String& text_,
  35625. const Colour& normalColour_,
  35626. const Colour& overColour_,
  35627. const Colour& downColour_)
  35628. : Button (text_),
  35629. normalColour (normalColour_),
  35630. overColour (overColour_),
  35631. downColour (downColour_),
  35632. maintainShapeProportions (false),
  35633. outlineWidth (0.0f)
  35634. {
  35635. }
  35636. ShapeButton::~ShapeButton()
  35637. {
  35638. }
  35639. void ShapeButton::setColours (const Colour& newNormalColour,
  35640. const Colour& newOverColour,
  35641. const Colour& newDownColour)
  35642. {
  35643. normalColour = newNormalColour;
  35644. overColour = newOverColour;
  35645. downColour = newDownColour;
  35646. }
  35647. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35648. const float newOutlineWidth)
  35649. {
  35650. outlineColour = newOutlineColour;
  35651. outlineWidth = newOutlineWidth;
  35652. }
  35653. void ShapeButton::setShape (const Path& newShape,
  35654. const bool resizeNowToFitThisShape,
  35655. const bool maintainShapeProportions_,
  35656. const bool hasShadow)
  35657. {
  35658. shape = newShape;
  35659. maintainShapeProportions = maintainShapeProportions_;
  35660. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35661. setComponentEffect ((hasShadow) ? &shadow : 0);
  35662. if (resizeNowToFitThisShape)
  35663. {
  35664. Rectangle<float> bounds (shape.getBounds());
  35665. if (hasShadow)
  35666. bounds.expand (4.0f, 4.0f);
  35667. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35668. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35669. 1 + (int) (bounds.getHeight() + outlineWidth));
  35670. }
  35671. }
  35672. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35673. {
  35674. if (! isEnabled())
  35675. {
  35676. isMouseOverButton = false;
  35677. isButtonDown = false;
  35678. }
  35679. g.setColour ((isButtonDown) ? downColour
  35680. : (isMouseOverButton) ? overColour
  35681. : normalColour);
  35682. int w = getWidth();
  35683. int h = getHeight();
  35684. if (getComponentEffect() != 0)
  35685. {
  35686. w -= 4;
  35687. h -= 4;
  35688. }
  35689. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35690. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35691. w - offset - outlineWidth,
  35692. h - offset - outlineWidth,
  35693. maintainShapeProportions));
  35694. g.fillPath (shape, trans);
  35695. if (outlineWidth > 0.0f)
  35696. {
  35697. g.setColour (outlineColour);
  35698. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35699. }
  35700. }
  35701. END_JUCE_NAMESPACE
  35702. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35703. /*** Start of inlined file: juce_TextButton.cpp ***/
  35704. BEGIN_JUCE_NAMESPACE
  35705. TextButton::TextButton (const String& name,
  35706. const String& toolTip)
  35707. : Button (name)
  35708. {
  35709. setTooltip (toolTip);
  35710. }
  35711. TextButton::~TextButton()
  35712. {
  35713. }
  35714. void TextButton::paintButton (Graphics& g,
  35715. bool isMouseOverButton,
  35716. bool isButtonDown)
  35717. {
  35718. getLookAndFeel().drawButtonBackground (g, *this,
  35719. findColour (getToggleState() ? buttonOnColourId
  35720. : buttonColourId),
  35721. isMouseOverButton,
  35722. isButtonDown);
  35723. getLookAndFeel().drawButtonText (g, *this,
  35724. isMouseOverButton,
  35725. isButtonDown);
  35726. }
  35727. void TextButton::colourChanged()
  35728. {
  35729. repaint();
  35730. }
  35731. const Font TextButton::getFont()
  35732. {
  35733. return Font (jmin (15.0f, getHeight() * 0.6f));
  35734. }
  35735. void TextButton::changeWidthToFitText (const int newHeight)
  35736. {
  35737. if (newHeight >= 0)
  35738. setSize (jmax (1, getWidth()), newHeight);
  35739. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35740. getHeight());
  35741. }
  35742. END_JUCE_NAMESPACE
  35743. /*** End of inlined file: juce_TextButton.cpp ***/
  35744. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35745. BEGIN_JUCE_NAMESPACE
  35746. ToggleButton::ToggleButton (const String& buttonText)
  35747. : Button (buttonText)
  35748. {
  35749. setClickingTogglesState (true);
  35750. }
  35751. ToggleButton::~ToggleButton()
  35752. {
  35753. }
  35754. void ToggleButton::paintButton (Graphics& g,
  35755. bool isMouseOverButton,
  35756. bool isButtonDown)
  35757. {
  35758. getLookAndFeel().drawToggleButton (g, *this,
  35759. isMouseOverButton,
  35760. isButtonDown);
  35761. }
  35762. void ToggleButton::changeWidthToFitText()
  35763. {
  35764. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35765. }
  35766. void ToggleButton::colourChanged()
  35767. {
  35768. repaint();
  35769. }
  35770. END_JUCE_NAMESPACE
  35771. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35772. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35773. BEGIN_JUCE_NAMESPACE
  35774. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35775. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35776. : ToolbarItemComponent (itemId_, buttonText, true),
  35777. normalImage (normalImage_),
  35778. toggledOnImage (toggledOnImage_),
  35779. currentImage (0)
  35780. {
  35781. jassert (normalImage_ != 0);
  35782. }
  35783. ToolbarButton::~ToolbarButton()
  35784. {
  35785. }
  35786. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35787. {
  35788. preferredSize = minSize = maxSize = toolbarDepth;
  35789. return true;
  35790. }
  35791. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35792. {
  35793. }
  35794. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35795. {
  35796. buttonStateChanged();
  35797. }
  35798. void ToolbarButton::updateDrawable()
  35799. {
  35800. if (currentImage != 0)
  35801. {
  35802. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35803. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35804. }
  35805. }
  35806. void ToolbarButton::resized()
  35807. {
  35808. ToolbarItemComponent::resized();
  35809. updateDrawable();
  35810. }
  35811. void ToolbarButton::enablementChanged()
  35812. {
  35813. ToolbarItemComponent::enablementChanged();
  35814. updateDrawable();
  35815. }
  35816. void ToolbarButton::buttonStateChanged()
  35817. {
  35818. Drawable* d = normalImage;
  35819. if (getToggleState() && toggledOnImage != 0)
  35820. d = toggledOnImage;
  35821. if (d != currentImage)
  35822. {
  35823. removeChildComponent (currentImage);
  35824. currentImage = d;
  35825. if (d != 0)
  35826. {
  35827. enablementChanged();
  35828. addAndMakeVisible (d);
  35829. updateDrawable();
  35830. }
  35831. }
  35832. }
  35833. END_JUCE_NAMESPACE
  35834. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35835. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35836. BEGIN_JUCE_NAMESPACE
  35837. class CodeDocumentLine
  35838. {
  35839. public:
  35840. CodeDocumentLine (const juce_wchar* const line_,
  35841. const int lineLength_,
  35842. const int numNewLineChars,
  35843. const int lineStartInFile_)
  35844. : line (line_, lineLength_),
  35845. lineStartInFile (lineStartInFile_),
  35846. lineLength (lineLength_),
  35847. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35848. {
  35849. }
  35850. ~CodeDocumentLine()
  35851. {
  35852. }
  35853. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35854. {
  35855. const juce_wchar* const t = text;
  35856. int pos = 0;
  35857. while (t [pos] != 0)
  35858. {
  35859. const int startOfLine = pos;
  35860. int numNewLineChars = 0;
  35861. while (t[pos] != 0)
  35862. {
  35863. if (t[pos] == '\r')
  35864. {
  35865. ++numNewLineChars;
  35866. ++pos;
  35867. if (t[pos] == '\n')
  35868. {
  35869. ++numNewLineChars;
  35870. ++pos;
  35871. }
  35872. break;
  35873. }
  35874. if (t[pos] == '\n')
  35875. {
  35876. ++numNewLineChars;
  35877. ++pos;
  35878. break;
  35879. }
  35880. ++pos;
  35881. }
  35882. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35883. numNewLineChars, startOfLine));
  35884. }
  35885. jassert (pos == text.length());
  35886. }
  35887. bool endsWithLineBreak() const throw()
  35888. {
  35889. return lineLengthWithoutNewLines != lineLength;
  35890. }
  35891. void updateLength() throw()
  35892. {
  35893. lineLengthWithoutNewLines = lineLength = line.length();
  35894. while (lineLengthWithoutNewLines > 0
  35895. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35896. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35897. {
  35898. --lineLengthWithoutNewLines;
  35899. }
  35900. }
  35901. String line;
  35902. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35903. };
  35904. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35905. : document (document_),
  35906. currentLine (document_->lines[0]),
  35907. line (0),
  35908. position (0)
  35909. {
  35910. }
  35911. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35912. : document (other.document),
  35913. currentLine (other.currentLine),
  35914. line (other.line),
  35915. position (other.position)
  35916. {
  35917. }
  35918. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35919. {
  35920. document = other.document;
  35921. currentLine = other.currentLine;
  35922. line = other.line;
  35923. position = other.position;
  35924. return *this;
  35925. }
  35926. CodeDocument::Iterator::~Iterator() throw()
  35927. {
  35928. }
  35929. juce_wchar CodeDocument::Iterator::nextChar()
  35930. {
  35931. if (currentLine == 0)
  35932. return 0;
  35933. jassert (currentLine == document->lines.getUnchecked (line));
  35934. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35935. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35936. {
  35937. ++line;
  35938. currentLine = document->lines [line];
  35939. }
  35940. return result;
  35941. }
  35942. void CodeDocument::Iterator::skip()
  35943. {
  35944. if (currentLine != 0)
  35945. {
  35946. jassert (currentLine == document->lines.getUnchecked (line));
  35947. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35948. {
  35949. ++line;
  35950. currentLine = document->lines [line];
  35951. }
  35952. }
  35953. }
  35954. void CodeDocument::Iterator::skipToEndOfLine()
  35955. {
  35956. if (currentLine != 0)
  35957. {
  35958. jassert (currentLine == document->lines.getUnchecked (line));
  35959. ++line;
  35960. currentLine = document->lines [line];
  35961. if (currentLine != 0)
  35962. position = currentLine->lineStartInFile;
  35963. else
  35964. position = document->getNumCharacters();
  35965. }
  35966. }
  35967. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35968. {
  35969. if (currentLine == 0)
  35970. return 0;
  35971. jassert (currentLine == document->lines.getUnchecked (line));
  35972. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35973. }
  35974. void CodeDocument::Iterator::skipWhitespace()
  35975. {
  35976. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35977. skip();
  35978. }
  35979. bool CodeDocument::Iterator::isEOF() const throw()
  35980. {
  35981. return currentLine == 0;
  35982. }
  35983. CodeDocument::Position::Position() throw()
  35984. : owner (0), characterPos (0), line (0),
  35985. indexInLine (0), positionMaintained (false)
  35986. {
  35987. }
  35988. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35989. const int line_, const int indexInLine_) throw()
  35990. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35991. characterPos (0), line (line_),
  35992. indexInLine (indexInLine_), positionMaintained (false)
  35993. {
  35994. setLineAndIndex (line_, indexInLine_);
  35995. }
  35996. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35997. const int characterPos_) throw()
  35998. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35999. positionMaintained (false)
  36000. {
  36001. setPosition (characterPos_);
  36002. }
  36003. CodeDocument::Position::Position (const Position& other) throw()
  36004. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36005. indexInLine (other.indexInLine), positionMaintained (false)
  36006. {
  36007. jassert (*this == other);
  36008. }
  36009. CodeDocument::Position::~Position()
  36010. {
  36011. setPositionMaintained (false);
  36012. }
  36013. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36014. {
  36015. if (this != &other)
  36016. {
  36017. const bool wasPositionMaintained = positionMaintained;
  36018. if (owner != other.owner)
  36019. setPositionMaintained (false);
  36020. owner = other.owner;
  36021. line = other.line;
  36022. indexInLine = other.indexInLine;
  36023. characterPos = other.characterPos;
  36024. setPositionMaintained (wasPositionMaintained);
  36025. jassert (*this == other);
  36026. }
  36027. return *this;
  36028. }
  36029. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36030. {
  36031. jassert ((characterPos == other.characterPos)
  36032. == (line == other.line && indexInLine == other.indexInLine));
  36033. return characterPos == other.characterPos
  36034. && line == other.line
  36035. && indexInLine == other.indexInLine
  36036. && owner == other.owner;
  36037. }
  36038. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36039. {
  36040. return ! operator== (other);
  36041. }
  36042. void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine)
  36043. {
  36044. jassert (owner != 0);
  36045. if (owner->lines.size() == 0)
  36046. {
  36047. line = 0;
  36048. indexInLine = 0;
  36049. characterPos = 0;
  36050. }
  36051. else
  36052. {
  36053. if (newLineNum >= owner->lines.size())
  36054. {
  36055. line = owner->lines.size() - 1;
  36056. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36057. jassert (l != 0);
  36058. indexInLine = l->lineLengthWithoutNewLines;
  36059. characterPos = l->lineStartInFile + indexInLine;
  36060. }
  36061. else
  36062. {
  36063. line = jmax (0, newLineNum);
  36064. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36065. jassert (l != 0);
  36066. if (l->lineLengthWithoutNewLines > 0)
  36067. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36068. else
  36069. indexInLine = 0;
  36070. characterPos = l->lineStartInFile + indexInLine;
  36071. }
  36072. }
  36073. }
  36074. void CodeDocument::Position::setPosition (const int newPosition)
  36075. {
  36076. jassert (owner != 0);
  36077. line = 0;
  36078. indexInLine = 0;
  36079. characterPos = 0;
  36080. if (newPosition > 0)
  36081. {
  36082. int lineStart = 0;
  36083. int lineEnd = owner->lines.size();
  36084. for (;;)
  36085. {
  36086. if (lineEnd - lineStart < 4)
  36087. {
  36088. for (int i = lineStart; i < lineEnd; ++i)
  36089. {
  36090. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36091. int index = newPosition - l->lineStartInFile;
  36092. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36093. {
  36094. line = i;
  36095. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36096. characterPos = l->lineStartInFile + indexInLine;
  36097. }
  36098. }
  36099. break;
  36100. }
  36101. else
  36102. {
  36103. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36104. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36105. if (newPosition >= mid->lineStartInFile)
  36106. lineStart = midIndex;
  36107. else
  36108. lineEnd = midIndex;
  36109. }
  36110. }
  36111. }
  36112. }
  36113. void CodeDocument::Position::moveBy (int characterDelta)
  36114. {
  36115. jassert (owner != 0);
  36116. if (characterDelta == 1)
  36117. {
  36118. setPosition (getPosition());
  36119. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36120. if (line < owner->lines.size())
  36121. {
  36122. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36123. if (indexInLine + characterDelta < l->lineLength
  36124. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36125. ++characterDelta;
  36126. }
  36127. }
  36128. setPosition (characterPos + characterDelta);
  36129. }
  36130. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36131. {
  36132. CodeDocument::Position p (*this);
  36133. p.moveBy (characterDelta);
  36134. return p;
  36135. }
  36136. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36137. {
  36138. CodeDocument::Position p (*this);
  36139. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36140. return p;
  36141. }
  36142. const juce_wchar CodeDocument::Position::getCharacter() const
  36143. {
  36144. const CodeDocumentLine* const l = owner->lines [line];
  36145. return l == 0 ? 0 : l->line [getIndexInLine()];
  36146. }
  36147. const String CodeDocument::Position::getLineText() const
  36148. {
  36149. const CodeDocumentLine* const l = owner->lines [line];
  36150. return l == 0 ? String::empty : l->line;
  36151. }
  36152. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36153. {
  36154. if (isMaintained != positionMaintained)
  36155. {
  36156. positionMaintained = isMaintained;
  36157. if (owner != 0)
  36158. {
  36159. if (isMaintained)
  36160. {
  36161. jassert (! owner->positionsToMaintain.contains (this));
  36162. owner->positionsToMaintain.add (this);
  36163. }
  36164. else
  36165. {
  36166. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36167. jassert (owner->positionsToMaintain.contains (this));
  36168. owner->positionsToMaintain.removeValue (this);
  36169. }
  36170. }
  36171. }
  36172. }
  36173. CodeDocument::CodeDocument()
  36174. : undoManager (std::numeric_limits<int>::max(), 10000),
  36175. currentActionIndex (0),
  36176. indexOfSavedState (-1),
  36177. maximumLineLength (-1),
  36178. newLineChars ("\r\n")
  36179. {
  36180. }
  36181. CodeDocument::~CodeDocument()
  36182. {
  36183. }
  36184. const String CodeDocument::getAllContent() const
  36185. {
  36186. return getTextBetween (Position (this, 0),
  36187. Position (this, lines.size(), 0));
  36188. }
  36189. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36190. {
  36191. if (end.getPosition() <= start.getPosition())
  36192. return String::empty;
  36193. const int startLine = start.getLineNumber();
  36194. const int endLine = end.getLineNumber();
  36195. if (startLine == endLine)
  36196. {
  36197. CodeDocumentLine* const line = lines [startLine];
  36198. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36199. }
  36200. String result;
  36201. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36202. String::Concatenator concatenator (result);
  36203. const int maxLine = jmin (lines.size() - 1, endLine);
  36204. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36205. {
  36206. const CodeDocumentLine* line = lines.getUnchecked(i);
  36207. int len = line->lineLength;
  36208. if (i == startLine)
  36209. {
  36210. const int index = start.getIndexInLine();
  36211. concatenator.append (line->line.substring (index, len));
  36212. }
  36213. else if (i == endLine)
  36214. {
  36215. len = end.getIndexInLine();
  36216. concatenator.append (line->line.substring (0, len));
  36217. }
  36218. else
  36219. {
  36220. concatenator.append (line->line);
  36221. }
  36222. }
  36223. return result;
  36224. }
  36225. int CodeDocument::getNumCharacters() const throw()
  36226. {
  36227. const CodeDocumentLine* const lastLine = lines.getLast();
  36228. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36229. }
  36230. const String CodeDocument::getLine (const int lineIndex) const throw()
  36231. {
  36232. const CodeDocumentLine* const line = lines [lineIndex];
  36233. return (line == 0) ? String::empty : line->line;
  36234. }
  36235. int CodeDocument::getMaximumLineLength() throw()
  36236. {
  36237. if (maximumLineLength < 0)
  36238. {
  36239. maximumLineLength = 0;
  36240. for (int i = lines.size(); --i >= 0;)
  36241. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36242. }
  36243. return maximumLineLength;
  36244. }
  36245. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36246. {
  36247. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36248. }
  36249. void CodeDocument::insertText (const Position& position, const String& text)
  36250. {
  36251. insert (text, position.getPosition(), true);
  36252. }
  36253. void CodeDocument::replaceAllContent (const String& newContent)
  36254. {
  36255. remove (0, getNumCharacters(), true);
  36256. insert (newContent, 0, true);
  36257. }
  36258. bool CodeDocument::loadFromStream (InputStream& stream)
  36259. {
  36260. replaceAllContent (stream.readEntireStreamAsString());
  36261. setSavePoint();
  36262. clearUndoHistory();
  36263. return true;
  36264. }
  36265. bool CodeDocument::writeToStream (OutputStream& stream)
  36266. {
  36267. for (int i = 0; i < lines.size(); ++i)
  36268. {
  36269. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36270. const char* utf8 = temp.toUTF8();
  36271. if (! stream.write (utf8, (int) strlen (utf8)))
  36272. return false;
  36273. }
  36274. return true;
  36275. }
  36276. void CodeDocument::setNewLineCharacters (const String& newLineChars_) throw()
  36277. {
  36278. jassert (newLineChars_ == "\r\n" || newLineChars_ == "\n" || newLineChars_ == "\r");
  36279. newLineChars = newLineChars_;
  36280. }
  36281. void CodeDocument::newTransaction()
  36282. {
  36283. undoManager.beginNewTransaction (String::empty);
  36284. }
  36285. void CodeDocument::undo()
  36286. {
  36287. newTransaction();
  36288. undoManager.undo();
  36289. }
  36290. void CodeDocument::redo()
  36291. {
  36292. undoManager.redo();
  36293. }
  36294. void CodeDocument::clearUndoHistory()
  36295. {
  36296. undoManager.clearUndoHistory();
  36297. }
  36298. void CodeDocument::setSavePoint() throw()
  36299. {
  36300. indexOfSavedState = currentActionIndex;
  36301. }
  36302. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36303. {
  36304. return currentActionIndex != indexOfSavedState;
  36305. }
  36306. namespace CodeDocumentHelpers
  36307. {
  36308. int getCharacterType (const juce_wchar character) throw()
  36309. {
  36310. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36311. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36312. }
  36313. }
  36314. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36315. {
  36316. Position p (position);
  36317. const int maxDistance = 256;
  36318. int i = 0;
  36319. while (i < maxDistance
  36320. && CharacterFunctions::isWhitespace (p.getCharacter())
  36321. && (i == 0 || (p.getCharacter() != '\n'
  36322. && p.getCharacter() != '\r')))
  36323. {
  36324. ++i;
  36325. p.moveBy (1);
  36326. }
  36327. if (i == 0)
  36328. {
  36329. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36330. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36331. {
  36332. ++i;
  36333. p.moveBy (1);
  36334. }
  36335. while (i < maxDistance
  36336. && CharacterFunctions::isWhitespace (p.getCharacter())
  36337. && (i == 0 || (p.getCharacter() != '\n'
  36338. && p.getCharacter() != '\r')))
  36339. {
  36340. ++i;
  36341. p.moveBy (1);
  36342. }
  36343. }
  36344. return p;
  36345. }
  36346. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36347. {
  36348. Position p (position);
  36349. const int maxDistance = 256;
  36350. int i = 0;
  36351. bool stoppedAtLineStart = false;
  36352. while (i < maxDistance)
  36353. {
  36354. const juce_wchar c = p.movedBy (-1).getCharacter();
  36355. if (c == '\r' || c == '\n')
  36356. {
  36357. stoppedAtLineStart = true;
  36358. if (i > 0)
  36359. break;
  36360. }
  36361. if (! CharacterFunctions::isWhitespace (c))
  36362. break;
  36363. p.moveBy (-1);
  36364. ++i;
  36365. }
  36366. if (i < maxDistance && ! stoppedAtLineStart)
  36367. {
  36368. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36369. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36370. {
  36371. p.moveBy (-1);
  36372. ++i;
  36373. }
  36374. }
  36375. return p;
  36376. }
  36377. void CodeDocument::checkLastLineStatus()
  36378. {
  36379. while (lines.size() > 0
  36380. && lines.getLast()->lineLength == 0
  36381. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36382. {
  36383. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36384. lines.removeLast();
  36385. }
  36386. const CodeDocumentLine* const lastLine = lines.getLast();
  36387. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36388. {
  36389. // check that there's an empty line at the end if the preceding one ends in a newline..
  36390. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36391. }
  36392. }
  36393. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36394. {
  36395. listeners.add (listener);
  36396. }
  36397. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36398. {
  36399. listeners.remove (listener);
  36400. }
  36401. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36402. {
  36403. Position startPos (this, startLine, 0);
  36404. Position endPos (this, endLine, 0);
  36405. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36406. }
  36407. class CodeDocumentInsertAction : public UndoableAction
  36408. {
  36409. public:
  36410. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36411. : owner (owner_),
  36412. text (text_),
  36413. insertPos (insertPos_)
  36414. {
  36415. }
  36416. bool perform()
  36417. {
  36418. owner.currentActionIndex++;
  36419. owner.insert (text, insertPos, false);
  36420. return true;
  36421. }
  36422. bool undo()
  36423. {
  36424. owner.currentActionIndex--;
  36425. owner.remove (insertPos, insertPos + text.length(), false);
  36426. return true;
  36427. }
  36428. int getSizeInUnits() { return text.length() + 32; }
  36429. private:
  36430. CodeDocument& owner;
  36431. const String text;
  36432. int insertPos;
  36433. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36434. };
  36435. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36436. {
  36437. if (text.isEmpty())
  36438. return;
  36439. if (undoable)
  36440. {
  36441. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36442. }
  36443. else
  36444. {
  36445. Position pos (this, insertPos);
  36446. const int firstAffectedLine = pos.getLineNumber();
  36447. int lastAffectedLine = firstAffectedLine + 1;
  36448. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36449. String textInsideOriginalLine (text);
  36450. if (firstLine != 0)
  36451. {
  36452. const int index = pos.getIndexInLine();
  36453. textInsideOriginalLine = firstLine->line.substring (0, index)
  36454. + textInsideOriginalLine
  36455. + firstLine->line.substring (index);
  36456. }
  36457. maximumLineLength = -1;
  36458. Array <CodeDocumentLine*> newLines;
  36459. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36460. jassert (newLines.size() > 0);
  36461. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36462. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36463. lines.set (firstAffectedLine, newFirstLine);
  36464. if (newLines.size() > 1)
  36465. {
  36466. for (int i = 1; i < newLines.size(); ++i)
  36467. {
  36468. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36469. lines.insert (firstAffectedLine + i, l);
  36470. }
  36471. lastAffectedLine = lines.size();
  36472. }
  36473. int i, lineStart = newFirstLine->lineStartInFile;
  36474. for (i = firstAffectedLine; i < lines.size(); ++i)
  36475. {
  36476. CodeDocumentLine* const l = lines.getUnchecked (i);
  36477. l->lineStartInFile = lineStart;
  36478. lineStart += l->lineLength;
  36479. }
  36480. checkLastLineStatus();
  36481. const int newTextLength = text.length();
  36482. for (i = 0; i < positionsToMaintain.size(); ++i)
  36483. {
  36484. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36485. if (p->getPosition() >= insertPos)
  36486. p->setPosition (p->getPosition() + newTextLength);
  36487. }
  36488. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36489. }
  36490. }
  36491. class CodeDocumentDeleteAction : public UndoableAction
  36492. {
  36493. public:
  36494. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36495. : owner (owner_),
  36496. startPos (startPos_),
  36497. endPos (endPos_)
  36498. {
  36499. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36500. CodeDocument::Position (&owner, endPos));
  36501. }
  36502. bool perform()
  36503. {
  36504. owner.currentActionIndex++;
  36505. owner.remove (startPos, endPos, false);
  36506. return true;
  36507. }
  36508. bool undo()
  36509. {
  36510. owner.currentActionIndex--;
  36511. owner.insert (removedText, startPos, false);
  36512. return true;
  36513. }
  36514. int getSizeInUnits() { return removedText.length() + 32; }
  36515. private:
  36516. CodeDocument& owner;
  36517. int startPos, endPos;
  36518. String removedText;
  36519. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36520. };
  36521. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36522. {
  36523. if (endPos <= startPos)
  36524. return;
  36525. if (undoable)
  36526. {
  36527. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36528. }
  36529. else
  36530. {
  36531. Position startPosition (this, startPos);
  36532. Position endPosition (this, endPos);
  36533. maximumLineLength = -1;
  36534. const int firstAffectedLine = startPosition.getLineNumber();
  36535. const int endLine = endPosition.getLineNumber();
  36536. int lastAffectedLine = firstAffectedLine + 1;
  36537. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36538. if (firstAffectedLine == endLine)
  36539. {
  36540. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36541. + firstLine->line.substring (endPosition.getIndexInLine());
  36542. firstLine->updateLength();
  36543. }
  36544. else
  36545. {
  36546. lastAffectedLine = lines.size();
  36547. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36548. jassert (lastLine != 0);
  36549. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36550. + lastLine->line.substring (endPosition.getIndexInLine());
  36551. firstLine->updateLength();
  36552. int numLinesToRemove = endLine - firstAffectedLine;
  36553. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36554. }
  36555. int i;
  36556. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36557. {
  36558. CodeDocumentLine* const l = lines.getUnchecked (i);
  36559. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36560. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36561. }
  36562. checkLastLineStatus();
  36563. const int totalChars = getNumCharacters();
  36564. for (i = 0; i < positionsToMaintain.size(); ++i)
  36565. {
  36566. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36567. if (p->getPosition() > startPosition.getPosition())
  36568. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36569. if (p->getPosition() > totalChars)
  36570. p->setPosition (totalChars);
  36571. }
  36572. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36573. }
  36574. }
  36575. END_JUCE_NAMESPACE
  36576. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36577. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36578. BEGIN_JUCE_NAMESPACE
  36579. class CodeEditorComponent::CaretComponent : public Component,
  36580. public Timer
  36581. {
  36582. public:
  36583. CaretComponent (CodeEditorComponent& owner_)
  36584. : owner (owner_)
  36585. {
  36586. setAlwaysOnTop (true);
  36587. setInterceptsMouseClicks (false, false);
  36588. }
  36589. void paint (Graphics& g)
  36590. {
  36591. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36592. }
  36593. void timerCallback()
  36594. {
  36595. setVisible (shouldBeShown() && ! isVisible());
  36596. }
  36597. void updatePosition()
  36598. {
  36599. startTimer (400);
  36600. setVisible (shouldBeShown());
  36601. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36602. }
  36603. private:
  36604. CodeEditorComponent& owner;
  36605. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36606. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36607. };
  36608. class CodeEditorComponent::CodeEditorLine
  36609. {
  36610. public:
  36611. CodeEditorLine() throw()
  36612. : highlightColumnStart (0), highlightColumnEnd (0)
  36613. {
  36614. }
  36615. bool update (CodeDocument& document, int lineNum,
  36616. CodeDocument::Iterator& source,
  36617. CodeTokeniser* analyser, const int spacesPerTab,
  36618. const CodeDocument::Position& selectionStart,
  36619. const CodeDocument::Position& selectionEnd)
  36620. {
  36621. Array <SyntaxToken> newTokens;
  36622. newTokens.ensureStorageAllocated (8);
  36623. if (analyser == 0)
  36624. {
  36625. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36626. }
  36627. else if (lineNum < document.getNumLines())
  36628. {
  36629. const CodeDocument::Position pos (&document, lineNum, 0);
  36630. createTokens (pos.getPosition(), pos.getLineText(),
  36631. source, analyser, newTokens);
  36632. }
  36633. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36634. int newHighlightStart = 0;
  36635. int newHighlightEnd = 0;
  36636. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36637. {
  36638. const String line (document.getLine (lineNum));
  36639. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36640. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36641. line, spacesPerTab);
  36642. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36643. line, spacesPerTab);
  36644. }
  36645. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36646. {
  36647. highlightColumnStart = newHighlightStart;
  36648. highlightColumnEnd = newHighlightEnd;
  36649. }
  36650. else
  36651. {
  36652. if (tokens.size() == newTokens.size())
  36653. {
  36654. bool allTheSame = true;
  36655. for (int i = newTokens.size(); --i >= 0;)
  36656. {
  36657. if (tokens.getReference(i) != newTokens.getReference(i))
  36658. {
  36659. allTheSame = false;
  36660. break;
  36661. }
  36662. }
  36663. if (allTheSame)
  36664. return false;
  36665. }
  36666. }
  36667. tokens.swapWithArray (newTokens);
  36668. return true;
  36669. }
  36670. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36671. float x, const int y, const int baselineOffset, const int lineHeight,
  36672. const Colour& highlightColour) const
  36673. {
  36674. if (highlightColumnStart < highlightColumnEnd)
  36675. {
  36676. g.setColour (highlightColour);
  36677. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36678. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36679. }
  36680. int lastType = std::numeric_limits<int>::min();
  36681. for (int i = 0; i < tokens.size(); ++i)
  36682. {
  36683. SyntaxToken& token = tokens.getReference(i);
  36684. if (lastType != token.tokenType)
  36685. {
  36686. lastType = token.tokenType;
  36687. g.setColour (owner.getColourForTokenType (lastType));
  36688. }
  36689. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36690. if (i < tokens.size() - 1)
  36691. {
  36692. if (token.width < 0)
  36693. token.width = font.getStringWidthFloat (token.text);
  36694. x += token.width;
  36695. }
  36696. }
  36697. }
  36698. private:
  36699. struct SyntaxToken
  36700. {
  36701. SyntaxToken (const String& text_, const int type) throw()
  36702. : text (text_), tokenType (type), width (-1.0f)
  36703. {
  36704. }
  36705. bool operator!= (const SyntaxToken& other) const throw()
  36706. {
  36707. return text != other.text || tokenType != other.tokenType;
  36708. }
  36709. String text;
  36710. int tokenType;
  36711. float width;
  36712. };
  36713. Array <SyntaxToken> tokens;
  36714. int highlightColumnStart, highlightColumnEnd;
  36715. static void createTokens (int startPosition, const String& lineText,
  36716. CodeDocument::Iterator& source,
  36717. CodeTokeniser* analyser,
  36718. Array <SyntaxToken>& newTokens)
  36719. {
  36720. CodeDocument::Iterator lastIterator (source);
  36721. const int lineLength = lineText.length();
  36722. for (;;)
  36723. {
  36724. int tokenType = analyser->readNextToken (source);
  36725. int tokenStart = lastIterator.getPosition();
  36726. int tokenEnd = source.getPosition();
  36727. if (tokenEnd <= tokenStart)
  36728. break;
  36729. tokenEnd -= startPosition;
  36730. if (tokenEnd > 0)
  36731. {
  36732. tokenStart -= startPosition;
  36733. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36734. tokenType));
  36735. if (tokenEnd >= lineLength)
  36736. break;
  36737. }
  36738. lastIterator = source;
  36739. }
  36740. source = lastIterator;
  36741. }
  36742. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36743. {
  36744. int x = 0;
  36745. for (int i = 0; i < tokens.size(); ++i)
  36746. {
  36747. SyntaxToken& t = tokens.getReference(i);
  36748. for (;;)
  36749. {
  36750. int tabPos = t.text.indexOfChar ('\t');
  36751. if (tabPos < 0)
  36752. break;
  36753. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36754. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36755. }
  36756. x += t.text.length();
  36757. }
  36758. }
  36759. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36760. {
  36761. jassert (index <= line.length());
  36762. int col = 0;
  36763. for (int i = 0; i < index; ++i)
  36764. {
  36765. if (line[i] != '\t')
  36766. ++col;
  36767. else
  36768. col += spacesPerTab - (col % spacesPerTab);
  36769. }
  36770. return col;
  36771. }
  36772. };
  36773. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36774. CodeTokeniser* const codeTokeniser_)
  36775. : document (document_),
  36776. firstLineOnScreen (0),
  36777. gutter (5),
  36778. spacesPerTab (4),
  36779. lineHeight (0),
  36780. linesOnScreen (0),
  36781. columnsOnScreen (0),
  36782. scrollbarThickness (16),
  36783. columnToTryToMaintain (-1),
  36784. useSpacesForTabs (false),
  36785. xOffset (0),
  36786. verticalScrollBar (true),
  36787. horizontalScrollBar (false),
  36788. codeTokeniser (codeTokeniser_)
  36789. {
  36790. caretPos = CodeDocument::Position (&document_, 0, 0);
  36791. caretPos.setPositionMaintained (true);
  36792. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36793. selectionStart.setPositionMaintained (true);
  36794. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36795. selectionEnd.setPositionMaintained (true);
  36796. setOpaque (true);
  36797. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36798. setWantsKeyboardFocus (true);
  36799. addAndMakeVisible (&verticalScrollBar);
  36800. verticalScrollBar.setSingleStepSize (1.0);
  36801. addAndMakeVisible (&horizontalScrollBar);
  36802. horizontalScrollBar.setSingleStepSize (1.0);
  36803. addAndMakeVisible (caret = new CaretComponent (*this));
  36804. Font f (12.0f);
  36805. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36806. setFont (f);
  36807. resetToDefaultColours();
  36808. verticalScrollBar.addListener (this);
  36809. horizontalScrollBar.addListener (this);
  36810. document.addListener (this);
  36811. }
  36812. CodeEditorComponent::~CodeEditorComponent()
  36813. {
  36814. document.removeListener (this);
  36815. }
  36816. void CodeEditorComponent::loadContent (const String& newContent)
  36817. {
  36818. clearCachedIterators (0);
  36819. document.replaceAllContent (newContent);
  36820. document.clearUndoHistory();
  36821. document.setSavePoint();
  36822. caretPos.setPosition (0);
  36823. selectionStart.setPosition (0);
  36824. selectionEnd.setPosition (0);
  36825. scrollToLine (0);
  36826. }
  36827. bool CodeEditorComponent::isTextInputActive() const
  36828. {
  36829. return true;
  36830. }
  36831. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36832. const CodeDocument::Position& affectedTextEnd)
  36833. {
  36834. clearCachedIterators (affectedTextStart.getLineNumber());
  36835. triggerAsyncUpdate();
  36836. caret->updatePosition();
  36837. columnToTryToMaintain = -1;
  36838. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36839. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36840. deselectAll();
  36841. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36842. || caretPos.getPosition() < affectedTextStart.getPosition())
  36843. moveCaretTo (affectedTextStart, false);
  36844. updateScrollBars();
  36845. }
  36846. void CodeEditorComponent::resized()
  36847. {
  36848. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36849. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36850. lines.clear();
  36851. rebuildLineTokens();
  36852. caret->updatePosition();
  36853. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36854. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36855. updateScrollBars();
  36856. }
  36857. void CodeEditorComponent::paint (Graphics& g)
  36858. {
  36859. handleUpdateNowIfNeeded();
  36860. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36861. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36862. g.setFont (font);
  36863. const int baselineOffset = (int) font.getAscent();
  36864. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36865. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36866. const Rectangle<int> clip (g.getClipBounds());
  36867. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36868. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36869. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36870. {
  36871. lines.getUnchecked(j)->draw (*this, g, font,
  36872. (float) (gutter - xOffset * charWidth),
  36873. lineHeight * j, baselineOffset, lineHeight,
  36874. highlightColour);
  36875. }
  36876. }
  36877. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36878. {
  36879. if (scrollbarThickness != thickness)
  36880. {
  36881. scrollbarThickness = thickness;
  36882. resized();
  36883. }
  36884. }
  36885. void CodeEditorComponent::handleAsyncUpdate()
  36886. {
  36887. rebuildLineTokens();
  36888. }
  36889. void CodeEditorComponent::rebuildLineTokens()
  36890. {
  36891. cancelPendingUpdate();
  36892. const int numNeeded = linesOnScreen + 1;
  36893. int minLineToRepaint = numNeeded;
  36894. int maxLineToRepaint = 0;
  36895. if (numNeeded != lines.size())
  36896. {
  36897. lines.clear();
  36898. for (int i = numNeeded; --i >= 0;)
  36899. lines.add (new CodeEditorLine());
  36900. minLineToRepaint = 0;
  36901. maxLineToRepaint = numNeeded;
  36902. }
  36903. jassert (numNeeded == lines.size());
  36904. CodeDocument::Iterator source (&document);
  36905. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36906. for (int i = 0; i < numNeeded; ++i)
  36907. {
  36908. CodeEditorLine* const line = lines.getUnchecked(i);
  36909. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36910. selectionStart, selectionEnd))
  36911. {
  36912. minLineToRepaint = jmin (minLineToRepaint, i);
  36913. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36914. }
  36915. }
  36916. if (minLineToRepaint <= maxLineToRepaint)
  36917. {
  36918. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36919. verticalScrollBar.getX() - gutter,
  36920. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36921. }
  36922. }
  36923. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36924. {
  36925. caretPos = newPos;
  36926. columnToTryToMaintain = -1;
  36927. if (highlighting)
  36928. {
  36929. if (dragType == notDragging)
  36930. {
  36931. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36932. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36933. dragType = draggingSelectionStart;
  36934. else
  36935. dragType = draggingSelectionEnd;
  36936. }
  36937. if (dragType == draggingSelectionStart)
  36938. {
  36939. selectionStart = caretPos;
  36940. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36941. {
  36942. const CodeDocument::Position temp (selectionStart);
  36943. selectionStart = selectionEnd;
  36944. selectionEnd = temp;
  36945. dragType = draggingSelectionEnd;
  36946. }
  36947. }
  36948. else
  36949. {
  36950. selectionEnd = caretPos;
  36951. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36952. {
  36953. const CodeDocument::Position temp (selectionStart);
  36954. selectionStart = selectionEnd;
  36955. selectionEnd = temp;
  36956. dragType = draggingSelectionStart;
  36957. }
  36958. }
  36959. triggerAsyncUpdate();
  36960. }
  36961. else
  36962. {
  36963. deselectAll();
  36964. }
  36965. caret->updatePosition();
  36966. scrollToKeepCaretOnScreen();
  36967. updateScrollBars();
  36968. }
  36969. void CodeEditorComponent::deselectAll()
  36970. {
  36971. if (selectionStart != selectionEnd)
  36972. triggerAsyncUpdate();
  36973. selectionStart = caretPos;
  36974. selectionEnd = caretPos;
  36975. }
  36976. void CodeEditorComponent::updateScrollBars()
  36977. {
  36978. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36979. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  36980. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36981. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  36982. }
  36983. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36984. {
  36985. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36986. newFirstLineOnScreen);
  36987. if (newFirstLineOnScreen != firstLineOnScreen)
  36988. {
  36989. firstLineOnScreen = newFirstLineOnScreen;
  36990. caret->updatePosition();
  36991. updateCachedIterators (firstLineOnScreen);
  36992. triggerAsyncUpdate();
  36993. }
  36994. }
  36995. void CodeEditorComponent::scrollToColumnInternal (double column)
  36996. {
  36997. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36998. if (xOffset != newOffset)
  36999. {
  37000. xOffset = newOffset;
  37001. caret->updatePosition();
  37002. repaint();
  37003. }
  37004. }
  37005. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37006. {
  37007. scrollToLineInternal (newFirstLineOnScreen);
  37008. updateScrollBars();
  37009. }
  37010. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37011. {
  37012. scrollToColumnInternal (newFirstColumnOnScreen);
  37013. updateScrollBars();
  37014. }
  37015. void CodeEditorComponent::scrollBy (int deltaLines)
  37016. {
  37017. scrollToLine (firstLineOnScreen + deltaLines);
  37018. }
  37019. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37020. {
  37021. if (caretPos.getLineNumber() < firstLineOnScreen)
  37022. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37023. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37024. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37025. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37026. if (column >= xOffset + columnsOnScreen - 1)
  37027. scrollToColumn (column + 1 - columnsOnScreen);
  37028. else if (column < xOffset)
  37029. scrollToColumn (column);
  37030. }
  37031. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37032. {
  37033. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37034. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37035. roundToInt (charWidth),
  37036. lineHeight);
  37037. }
  37038. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37039. {
  37040. const int line = y / lineHeight + firstLineOnScreen;
  37041. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37042. const int index = columnToIndex (line, column);
  37043. return CodeDocument::Position (&document, line, index);
  37044. }
  37045. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37046. {
  37047. document.deleteSection (selectionStart, selectionEnd);
  37048. if (newText.isNotEmpty())
  37049. document.insertText (caretPos, newText);
  37050. scrollToKeepCaretOnScreen();
  37051. }
  37052. void CodeEditorComponent::insertTabAtCaret()
  37053. {
  37054. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37055. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37056. {
  37057. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37058. }
  37059. if (useSpacesForTabs)
  37060. {
  37061. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37062. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37063. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37064. }
  37065. else
  37066. {
  37067. insertTextAtCaret ("\t");
  37068. }
  37069. }
  37070. void CodeEditorComponent::cut()
  37071. {
  37072. insertTextAtCaret (String::empty);
  37073. }
  37074. void CodeEditorComponent::copy()
  37075. {
  37076. newTransaction();
  37077. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37078. if (selection.isNotEmpty())
  37079. SystemClipboard::copyTextToClipboard (selection);
  37080. }
  37081. void CodeEditorComponent::copyThenCut()
  37082. {
  37083. copy();
  37084. cut();
  37085. newTransaction();
  37086. }
  37087. void CodeEditorComponent::paste()
  37088. {
  37089. newTransaction();
  37090. const String clip (SystemClipboard::getTextFromClipboard());
  37091. if (clip.isNotEmpty())
  37092. insertTextAtCaret (clip);
  37093. newTransaction();
  37094. }
  37095. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37096. {
  37097. newTransaction();
  37098. if (moveInWholeWordSteps)
  37099. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37100. else
  37101. moveCaretTo (caretPos.movedBy (-1), selecting);
  37102. }
  37103. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37104. {
  37105. newTransaction();
  37106. if (moveInWholeWordSteps)
  37107. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37108. else
  37109. moveCaretTo (caretPos.movedBy (1), selecting);
  37110. }
  37111. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37112. {
  37113. CodeDocument::Position pos (caretPos);
  37114. const int newLineNum = pos.getLineNumber() + delta;
  37115. if (columnToTryToMaintain < 0)
  37116. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37117. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37118. const int colToMaintain = columnToTryToMaintain;
  37119. moveCaretTo (pos, selecting);
  37120. columnToTryToMaintain = colToMaintain;
  37121. }
  37122. void CodeEditorComponent::cursorDown (const bool selecting)
  37123. {
  37124. newTransaction();
  37125. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37126. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37127. else
  37128. moveLineDelta (1, selecting);
  37129. }
  37130. void CodeEditorComponent::cursorUp (const bool selecting)
  37131. {
  37132. newTransaction();
  37133. if (caretPos.getLineNumber() == 0)
  37134. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37135. else
  37136. moveLineDelta (-1, selecting);
  37137. }
  37138. void CodeEditorComponent::pageDown (const bool selecting)
  37139. {
  37140. newTransaction();
  37141. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37142. moveLineDelta (linesOnScreen, selecting);
  37143. }
  37144. void CodeEditorComponent::pageUp (const bool selecting)
  37145. {
  37146. newTransaction();
  37147. scrollBy (-linesOnScreen);
  37148. moveLineDelta (-linesOnScreen, selecting);
  37149. }
  37150. void CodeEditorComponent::scrollUp()
  37151. {
  37152. newTransaction();
  37153. scrollBy (1);
  37154. if (caretPos.getLineNumber() < firstLineOnScreen)
  37155. moveLineDelta (1, false);
  37156. }
  37157. void CodeEditorComponent::scrollDown()
  37158. {
  37159. newTransaction();
  37160. scrollBy (-1);
  37161. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37162. moveLineDelta (-1, false);
  37163. }
  37164. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37165. {
  37166. newTransaction();
  37167. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37168. }
  37169. namespace CodeEditorHelpers
  37170. {
  37171. int findFirstNonWhitespaceChar (const String& line) throw()
  37172. {
  37173. const int len = line.length();
  37174. for (int i = 0; i < len; ++i)
  37175. if (! CharacterFunctions::isWhitespace (line [i]))
  37176. return i;
  37177. return 0;
  37178. }
  37179. }
  37180. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37181. {
  37182. newTransaction();
  37183. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37184. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37185. index = 0;
  37186. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37187. }
  37188. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37189. {
  37190. newTransaction();
  37191. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37192. }
  37193. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37194. {
  37195. newTransaction();
  37196. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37197. }
  37198. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37199. {
  37200. if (moveInWholeWordSteps)
  37201. {
  37202. cut(); // in case something is already highlighted
  37203. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37204. }
  37205. else
  37206. {
  37207. if (selectionStart == selectionEnd)
  37208. selectionStart.moveBy (-1);
  37209. }
  37210. cut();
  37211. }
  37212. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37213. {
  37214. if (moveInWholeWordSteps)
  37215. {
  37216. cut(); // in case something is already highlighted
  37217. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37218. }
  37219. else
  37220. {
  37221. if (selectionStart == selectionEnd)
  37222. selectionEnd.moveBy (1);
  37223. else
  37224. newTransaction();
  37225. }
  37226. cut();
  37227. }
  37228. void CodeEditorComponent::selectAll()
  37229. {
  37230. newTransaction();
  37231. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37232. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37233. }
  37234. void CodeEditorComponent::undo()
  37235. {
  37236. document.undo();
  37237. scrollToKeepCaretOnScreen();
  37238. }
  37239. void CodeEditorComponent::redo()
  37240. {
  37241. document.redo();
  37242. scrollToKeepCaretOnScreen();
  37243. }
  37244. void CodeEditorComponent::newTransaction()
  37245. {
  37246. document.newTransaction();
  37247. startTimer (600);
  37248. }
  37249. void CodeEditorComponent::timerCallback()
  37250. {
  37251. newTransaction();
  37252. }
  37253. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37254. {
  37255. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37256. }
  37257. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37258. {
  37259. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37260. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37261. }
  37262. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37263. {
  37264. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37265. CodeDocument::Position (&document, range.getEnd()));
  37266. }
  37267. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37268. {
  37269. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37270. const bool shiftDown = key.getModifiers().isShiftDown();
  37271. if (key.isKeyCode (KeyPress::leftKey))
  37272. {
  37273. cursorLeft (moveInWholeWordSteps, shiftDown);
  37274. }
  37275. else if (key.isKeyCode (KeyPress::rightKey))
  37276. {
  37277. cursorRight (moveInWholeWordSteps, shiftDown);
  37278. }
  37279. else if (key.isKeyCode (KeyPress::upKey))
  37280. {
  37281. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37282. scrollDown();
  37283. #if JUCE_MAC
  37284. else if (key.getModifiers().isCommandDown())
  37285. goToStartOfDocument (shiftDown);
  37286. #endif
  37287. else
  37288. cursorUp (shiftDown);
  37289. }
  37290. else if (key.isKeyCode (KeyPress::downKey))
  37291. {
  37292. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37293. scrollUp();
  37294. #if JUCE_MAC
  37295. else if (key.getModifiers().isCommandDown())
  37296. goToEndOfDocument (shiftDown);
  37297. #endif
  37298. else
  37299. cursorDown (shiftDown);
  37300. }
  37301. else if (key.isKeyCode (KeyPress::pageDownKey))
  37302. {
  37303. pageDown (shiftDown);
  37304. }
  37305. else if (key.isKeyCode (KeyPress::pageUpKey))
  37306. {
  37307. pageUp (shiftDown);
  37308. }
  37309. else if (key.isKeyCode (KeyPress::homeKey))
  37310. {
  37311. if (moveInWholeWordSteps)
  37312. goToStartOfDocument (shiftDown);
  37313. else
  37314. goToStartOfLine (shiftDown);
  37315. }
  37316. else if (key.isKeyCode (KeyPress::endKey))
  37317. {
  37318. if (moveInWholeWordSteps)
  37319. goToEndOfDocument (shiftDown);
  37320. else
  37321. goToEndOfLine (shiftDown);
  37322. }
  37323. else if (key.isKeyCode (KeyPress::backspaceKey))
  37324. {
  37325. backspace (moveInWholeWordSteps);
  37326. }
  37327. else if (key.isKeyCode (KeyPress::deleteKey))
  37328. {
  37329. deleteForward (moveInWholeWordSteps);
  37330. }
  37331. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37332. {
  37333. copy();
  37334. }
  37335. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37336. {
  37337. copyThenCut();
  37338. }
  37339. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37340. {
  37341. paste();
  37342. }
  37343. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37344. {
  37345. undo();
  37346. }
  37347. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37348. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37349. {
  37350. redo();
  37351. }
  37352. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37353. {
  37354. selectAll();
  37355. }
  37356. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37357. {
  37358. insertTabAtCaret();
  37359. }
  37360. else if (key == KeyPress::returnKey)
  37361. {
  37362. newTransaction();
  37363. insertTextAtCaret (document.getNewLineCharacters());
  37364. }
  37365. else if (key.isKeyCode (KeyPress::escapeKey))
  37366. {
  37367. newTransaction();
  37368. }
  37369. else if (key.getTextCharacter() >= ' ')
  37370. {
  37371. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37372. }
  37373. else
  37374. {
  37375. return false;
  37376. }
  37377. return true;
  37378. }
  37379. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37380. {
  37381. newTransaction();
  37382. dragType = notDragging;
  37383. if (! e.mods.isPopupMenu())
  37384. {
  37385. beginDragAutoRepeat (100);
  37386. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37387. }
  37388. else
  37389. {
  37390. /*PopupMenu m;
  37391. addPopupMenuItems (m, &e);
  37392. const int result = m.show();
  37393. if (result != 0)
  37394. performPopupMenuAction (result);
  37395. */
  37396. }
  37397. }
  37398. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37399. {
  37400. if (! e.mods.isPopupMenu())
  37401. moveCaretTo (getPositionAt (e.x, e.y), true);
  37402. }
  37403. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37404. {
  37405. newTransaction();
  37406. beginDragAutoRepeat (0);
  37407. dragType = notDragging;
  37408. }
  37409. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37410. {
  37411. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37412. CodeDocument::Position tokenEnd (tokenStart);
  37413. if (e.getNumberOfClicks() > 2)
  37414. {
  37415. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37416. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37417. }
  37418. else
  37419. {
  37420. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37421. tokenEnd.moveBy (1);
  37422. tokenStart = tokenEnd;
  37423. while (tokenStart.getIndexInLine() > 0
  37424. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37425. tokenStart.moveBy (-1);
  37426. }
  37427. moveCaretTo (tokenEnd, false);
  37428. moveCaretTo (tokenStart, true);
  37429. }
  37430. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37431. {
  37432. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37433. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37434. {
  37435. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37436. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37437. }
  37438. else
  37439. {
  37440. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37441. }
  37442. }
  37443. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37444. {
  37445. if (scrollBarThatHasMoved == &verticalScrollBar)
  37446. scrollToLineInternal ((int) newRangeStart);
  37447. else
  37448. scrollToColumnInternal (newRangeStart);
  37449. }
  37450. void CodeEditorComponent::focusGained (FocusChangeType)
  37451. {
  37452. caret->updatePosition();
  37453. }
  37454. void CodeEditorComponent::focusLost (FocusChangeType)
  37455. {
  37456. caret->updatePosition();
  37457. }
  37458. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37459. {
  37460. useSpacesForTabs = insertSpaces;
  37461. if (spacesPerTab != numSpaces)
  37462. {
  37463. spacesPerTab = numSpaces;
  37464. triggerAsyncUpdate();
  37465. }
  37466. }
  37467. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37468. {
  37469. const String line (document.getLine (lineNum));
  37470. jassert (index <= line.length());
  37471. int col = 0;
  37472. for (int i = 0; i < index; ++i)
  37473. {
  37474. if (line[i] != '\t')
  37475. ++col;
  37476. else
  37477. col += getTabSize() - (col % getTabSize());
  37478. }
  37479. return col;
  37480. }
  37481. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37482. {
  37483. const String line (document.getLine (lineNum));
  37484. const int lineLength = line.length();
  37485. int i, col = 0;
  37486. for (i = 0; i < lineLength; ++i)
  37487. {
  37488. if (line[i] != '\t')
  37489. ++col;
  37490. else
  37491. col += getTabSize() - (col % getTabSize());
  37492. if (col > column)
  37493. break;
  37494. }
  37495. return i;
  37496. }
  37497. void CodeEditorComponent::setFont (const Font& newFont)
  37498. {
  37499. font = newFont;
  37500. charWidth = font.getStringWidthFloat ("0");
  37501. lineHeight = roundToInt (font.getHeight());
  37502. resized();
  37503. }
  37504. void CodeEditorComponent::resetToDefaultColours()
  37505. {
  37506. coloursForTokenCategories.clear();
  37507. if (codeTokeniser != 0)
  37508. {
  37509. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37510. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37511. }
  37512. }
  37513. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37514. {
  37515. jassert (tokenType < 256);
  37516. while (coloursForTokenCategories.size() < tokenType)
  37517. coloursForTokenCategories.add (Colours::black);
  37518. coloursForTokenCategories.set (tokenType, colour);
  37519. repaint();
  37520. }
  37521. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37522. {
  37523. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37524. return findColour (CodeEditorComponent::defaultTextColourId);
  37525. return coloursForTokenCategories.getReference (tokenType);
  37526. }
  37527. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37528. {
  37529. int i;
  37530. for (i = cachedIterators.size(); --i >= 0;)
  37531. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37532. break;
  37533. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37534. }
  37535. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37536. {
  37537. const int maxNumCachedPositions = 5000;
  37538. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37539. if (cachedIterators.size() == 0)
  37540. cachedIterators.add (new CodeDocument::Iterator (&document));
  37541. if (codeTokeniser == 0)
  37542. return;
  37543. for (;;)
  37544. {
  37545. CodeDocument::Iterator* last = cachedIterators.getLast();
  37546. if (last->getLine() >= maxLineNum)
  37547. break;
  37548. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37549. cachedIterators.add (t);
  37550. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37551. for (;;)
  37552. {
  37553. codeTokeniser->readNextToken (*t);
  37554. if (t->getLine() >= targetLine)
  37555. break;
  37556. if (t->isEOF())
  37557. return;
  37558. }
  37559. }
  37560. }
  37561. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37562. {
  37563. if (codeTokeniser == 0)
  37564. return;
  37565. for (int i = cachedIterators.size(); --i >= 0;)
  37566. {
  37567. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37568. if (t->getPosition() <= position)
  37569. {
  37570. source = *t;
  37571. break;
  37572. }
  37573. }
  37574. while (source.getPosition() < position)
  37575. {
  37576. const CodeDocument::Iterator original (source);
  37577. codeTokeniser->readNextToken (source);
  37578. if (source.getPosition() > position || source.isEOF())
  37579. {
  37580. source = original;
  37581. break;
  37582. }
  37583. }
  37584. }
  37585. END_JUCE_NAMESPACE
  37586. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37587. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37588. BEGIN_JUCE_NAMESPACE
  37589. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37590. {
  37591. }
  37592. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37593. {
  37594. }
  37595. namespace CppTokeniser
  37596. {
  37597. bool isIdentifierStart (const juce_wchar c) throw()
  37598. {
  37599. return CharacterFunctions::isLetter (c)
  37600. || c == '_' || c == '@';
  37601. }
  37602. bool isIdentifierBody (const juce_wchar c) throw()
  37603. {
  37604. return CharacterFunctions::isLetterOrDigit (c)
  37605. || c == '_' || c == '@';
  37606. }
  37607. bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37608. {
  37609. static const juce_wchar* const keywords2Char[] =
  37610. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37611. static const juce_wchar* const keywords3Char[] =
  37612. { 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 };
  37613. static const juce_wchar* const keywords4Char[] =
  37614. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37615. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37616. static const juce_wchar* const keywords5Char[] =
  37617. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37618. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37619. static const juce_wchar* const keywords6Char[] =
  37620. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37621. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37622. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37623. static const juce_wchar* const keywordsOther[] =
  37624. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37625. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37626. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37627. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37628. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37629. const juce_wchar* const* k;
  37630. switch (tokenLength)
  37631. {
  37632. case 2: k = keywords2Char; break;
  37633. case 3: k = keywords3Char; break;
  37634. case 4: k = keywords4Char; break;
  37635. case 5: k = keywords5Char; break;
  37636. case 6: k = keywords6Char; break;
  37637. default:
  37638. if (tokenLength < 2 || tokenLength > 16)
  37639. return false;
  37640. k = keywordsOther;
  37641. break;
  37642. }
  37643. int i = 0;
  37644. while (k[i] != 0)
  37645. {
  37646. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37647. return true;
  37648. ++i;
  37649. }
  37650. return false;
  37651. }
  37652. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37653. {
  37654. int tokenLength = 0;
  37655. juce_wchar possibleIdentifier [19];
  37656. while (isIdentifierBody (source.peekNextChar()))
  37657. {
  37658. const juce_wchar c = source.nextChar();
  37659. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37660. possibleIdentifier [tokenLength] = c;
  37661. ++tokenLength;
  37662. }
  37663. if (tokenLength > 1 && tokenLength <= 16)
  37664. {
  37665. possibleIdentifier [tokenLength] = 0;
  37666. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37667. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37668. }
  37669. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37670. }
  37671. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37672. {
  37673. const juce_wchar c = source.peekNextChar();
  37674. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37675. source.skip();
  37676. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37677. return false;
  37678. return true;
  37679. }
  37680. bool isHexDigit (const juce_wchar c) throw()
  37681. {
  37682. return (c >= '0' && c <= '9')
  37683. || (c >= 'a' && c <= 'f')
  37684. || (c >= 'A' && c <= 'F');
  37685. }
  37686. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37687. {
  37688. if (source.nextChar() != '0')
  37689. return false;
  37690. juce_wchar c = source.nextChar();
  37691. if (c != 'x' && c != 'X')
  37692. return false;
  37693. int numDigits = 0;
  37694. while (isHexDigit (source.peekNextChar()))
  37695. {
  37696. ++numDigits;
  37697. source.skip();
  37698. }
  37699. if (numDigits == 0)
  37700. return false;
  37701. return skipNumberSuffix (source);
  37702. }
  37703. bool isOctalDigit (const juce_wchar c) throw()
  37704. {
  37705. return c >= '0' && c <= '7';
  37706. }
  37707. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37708. {
  37709. if (source.nextChar() != '0')
  37710. return false;
  37711. if (! isOctalDigit (source.nextChar()))
  37712. return false;
  37713. while (isOctalDigit (source.peekNextChar()))
  37714. source.skip();
  37715. return skipNumberSuffix (source);
  37716. }
  37717. bool isDecimalDigit (const juce_wchar c) throw()
  37718. {
  37719. return c >= '0' && c <= '9';
  37720. }
  37721. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37722. {
  37723. int numChars = 0;
  37724. while (isDecimalDigit (source.peekNextChar()))
  37725. {
  37726. ++numChars;
  37727. source.skip();
  37728. }
  37729. if (numChars == 0)
  37730. return false;
  37731. return skipNumberSuffix (source);
  37732. }
  37733. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37734. {
  37735. int numDigits = 0;
  37736. while (isDecimalDigit (source.peekNextChar()))
  37737. {
  37738. source.skip();
  37739. ++numDigits;
  37740. }
  37741. const bool hasPoint = (source.peekNextChar() == '.');
  37742. if (hasPoint)
  37743. {
  37744. source.skip();
  37745. while (isDecimalDigit (source.peekNextChar()))
  37746. {
  37747. source.skip();
  37748. ++numDigits;
  37749. }
  37750. }
  37751. if (numDigits == 0)
  37752. return false;
  37753. juce_wchar c = source.peekNextChar();
  37754. const bool hasExponent = (c == 'e' || c == 'E');
  37755. if (hasExponent)
  37756. {
  37757. source.skip();
  37758. c = source.peekNextChar();
  37759. if (c == '+' || c == '-')
  37760. source.skip();
  37761. int numExpDigits = 0;
  37762. while (isDecimalDigit (source.peekNextChar()))
  37763. {
  37764. source.skip();
  37765. ++numExpDigits;
  37766. }
  37767. if (numExpDigits == 0)
  37768. return false;
  37769. }
  37770. c = source.peekNextChar();
  37771. if (c == 'f' || c == 'F')
  37772. source.skip();
  37773. else if (! (hasExponent || hasPoint))
  37774. return false;
  37775. return true;
  37776. }
  37777. int parseNumber (CodeDocument::Iterator& source)
  37778. {
  37779. const CodeDocument::Iterator original (source);
  37780. if (parseFloatLiteral (source))
  37781. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37782. source = original;
  37783. if (parseHexLiteral (source))
  37784. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37785. source = original;
  37786. if (parseOctalLiteral (source))
  37787. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37788. source = original;
  37789. if (parseDecimalLiteral (source))
  37790. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37791. source = original;
  37792. source.skip();
  37793. return CPlusPlusCodeTokeniser::tokenType_error;
  37794. }
  37795. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37796. {
  37797. const juce_wchar quote = source.nextChar();
  37798. for (;;)
  37799. {
  37800. const juce_wchar c = source.nextChar();
  37801. if (c == quote || c == 0)
  37802. break;
  37803. if (c == '\\')
  37804. source.skip();
  37805. }
  37806. }
  37807. void skipComment (CodeDocument::Iterator& source) throw()
  37808. {
  37809. bool lastWasStar = false;
  37810. for (;;)
  37811. {
  37812. const juce_wchar c = source.nextChar();
  37813. if (c == 0 || (c == '/' && lastWasStar))
  37814. break;
  37815. lastWasStar = (c == '*');
  37816. }
  37817. }
  37818. }
  37819. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37820. {
  37821. int result = tokenType_error;
  37822. source.skipWhitespace();
  37823. juce_wchar firstChar = source.peekNextChar();
  37824. switch (firstChar)
  37825. {
  37826. case 0:
  37827. source.skip();
  37828. break;
  37829. case '0':
  37830. case '1':
  37831. case '2':
  37832. case '3':
  37833. case '4':
  37834. case '5':
  37835. case '6':
  37836. case '7':
  37837. case '8':
  37838. case '9':
  37839. result = CppTokeniser::parseNumber (source);
  37840. break;
  37841. case '.':
  37842. result = CppTokeniser::parseNumber (source);
  37843. if (result == tokenType_error)
  37844. result = tokenType_punctuation;
  37845. break;
  37846. case ',':
  37847. case ';':
  37848. case ':':
  37849. source.skip();
  37850. result = tokenType_punctuation;
  37851. break;
  37852. case '(':
  37853. case ')':
  37854. case '{':
  37855. case '}':
  37856. case '[':
  37857. case ']':
  37858. source.skip();
  37859. result = tokenType_bracket;
  37860. break;
  37861. case '"':
  37862. case '\'':
  37863. CppTokeniser::skipQuotedString (source);
  37864. result = tokenType_stringLiteral;
  37865. break;
  37866. case '+':
  37867. result = tokenType_operator;
  37868. source.skip();
  37869. if (source.peekNextChar() == '+')
  37870. source.skip();
  37871. else if (source.peekNextChar() == '=')
  37872. source.skip();
  37873. break;
  37874. case '-':
  37875. source.skip();
  37876. result = CppTokeniser::parseNumber (source);
  37877. if (result == tokenType_error)
  37878. {
  37879. result = tokenType_operator;
  37880. if (source.peekNextChar() == '-')
  37881. source.skip();
  37882. else if (source.peekNextChar() == '=')
  37883. source.skip();
  37884. }
  37885. break;
  37886. case '*':
  37887. case '%':
  37888. case '=':
  37889. case '!':
  37890. result = tokenType_operator;
  37891. source.skip();
  37892. if (source.peekNextChar() == '=')
  37893. source.skip();
  37894. break;
  37895. case '/':
  37896. result = tokenType_operator;
  37897. source.skip();
  37898. if (source.peekNextChar() == '=')
  37899. {
  37900. source.skip();
  37901. }
  37902. else if (source.peekNextChar() == '/')
  37903. {
  37904. result = tokenType_comment;
  37905. source.skipToEndOfLine();
  37906. }
  37907. else if (source.peekNextChar() == '*')
  37908. {
  37909. source.skip();
  37910. result = tokenType_comment;
  37911. CppTokeniser::skipComment (source);
  37912. }
  37913. break;
  37914. case '?':
  37915. case '~':
  37916. source.skip();
  37917. result = tokenType_operator;
  37918. break;
  37919. case '<':
  37920. source.skip();
  37921. result = tokenType_operator;
  37922. if (source.peekNextChar() == '=')
  37923. {
  37924. source.skip();
  37925. }
  37926. else if (source.peekNextChar() == '<')
  37927. {
  37928. source.skip();
  37929. if (source.peekNextChar() == '=')
  37930. source.skip();
  37931. }
  37932. break;
  37933. case '>':
  37934. source.skip();
  37935. result = tokenType_operator;
  37936. if (source.peekNextChar() == '=')
  37937. {
  37938. source.skip();
  37939. }
  37940. else if (source.peekNextChar() == '<')
  37941. {
  37942. source.skip();
  37943. if (source.peekNextChar() == '=')
  37944. source.skip();
  37945. }
  37946. break;
  37947. case '|':
  37948. source.skip();
  37949. result = tokenType_operator;
  37950. if (source.peekNextChar() == '=')
  37951. {
  37952. source.skip();
  37953. }
  37954. else if (source.peekNextChar() == '|')
  37955. {
  37956. source.skip();
  37957. if (source.peekNextChar() == '=')
  37958. source.skip();
  37959. }
  37960. break;
  37961. case '&':
  37962. source.skip();
  37963. result = tokenType_operator;
  37964. if (source.peekNextChar() == '=')
  37965. {
  37966. source.skip();
  37967. }
  37968. else if (source.peekNextChar() == '&')
  37969. {
  37970. source.skip();
  37971. if (source.peekNextChar() == '=')
  37972. source.skip();
  37973. }
  37974. break;
  37975. case '^':
  37976. source.skip();
  37977. result = tokenType_operator;
  37978. if (source.peekNextChar() == '=')
  37979. {
  37980. source.skip();
  37981. }
  37982. else if (source.peekNextChar() == '^')
  37983. {
  37984. source.skip();
  37985. if (source.peekNextChar() == '=')
  37986. source.skip();
  37987. }
  37988. break;
  37989. case '#':
  37990. result = tokenType_preprocessor;
  37991. source.skipToEndOfLine();
  37992. break;
  37993. default:
  37994. if (CppTokeniser::isIdentifierStart (firstChar))
  37995. result = CppTokeniser::parseIdentifier (source);
  37996. else
  37997. source.skip();
  37998. break;
  37999. }
  38000. return result;
  38001. }
  38002. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38003. {
  38004. const char* const types[] =
  38005. {
  38006. "Error",
  38007. "Comment",
  38008. "C++ keyword",
  38009. "Identifier",
  38010. "Integer literal",
  38011. "Float literal",
  38012. "String literal",
  38013. "Operator",
  38014. "Bracket",
  38015. "Punctuation",
  38016. "Preprocessor line",
  38017. 0
  38018. };
  38019. return StringArray (types);
  38020. }
  38021. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38022. {
  38023. const uint32 colours[] =
  38024. {
  38025. 0xffcc0000, // error
  38026. 0xff00aa00, // comment
  38027. 0xff0000cc, // keyword
  38028. 0xff000000, // identifier
  38029. 0xff880000, // int literal
  38030. 0xff885500, // float literal
  38031. 0xff990099, // string literal
  38032. 0xff225500, // operator
  38033. 0xff000055, // bracket
  38034. 0xff004400, // punctuation
  38035. 0xff660000 // preprocessor
  38036. };
  38037. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38038. return Colour (colours [tokenType]);
  38039. return Colours::black;
  38040. }
  38041. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38042. {
  38043. return CppTokeniser::isReservedKeyword (token, token.length());
  38044. }
  38045. END_JUCE_NAMESPACE
  38046. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38047. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38048. BEGIN_JUCE_NAMESPACE
  38049. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  38050. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  38051. {
  38052. }
  38053. bool ComboBox::ItemInfo::isSeparator() const throw()
  38054. {
  38055. return name.isEmpty();
  38056. }
  38057. bool ComboBox::ItemInfo::isRealItem() const throw()
  38058. {
  38059. return ! (isHeading || name.isEmpty());
  38060. }
  38061. ComboBox::ComboBox (const String& name)
  38062. : Component (name),
  38063. lastCurrentId (0),
  38064. isButtonDown (false),
  38065. separatorPending (false),
  38066. menuActive (false),
  38067. noChoicesMessage (TRANS("(no choices)"))
  38068. {
  38069. setRepaintsOnMouseActivity (true);
  38070. lookAndFeelChanged();
  38071. currentId.addListener (this);
  38072. }
  38073. ComboBox::~ComboBox()
  38074. {
  38075. currentId.removeListener (this);
  38076. if (menuActive)
  38077. PopupMenu::dismissAllActiveMenus();
  38078. label = 0;
  38079. }
  38080. void ComboBox::setEditableText (const bool isEditable)
  38081. {
  38082. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38083. {
  38084. label->setEditable (isEditable, isEditable, false);
  38085. setWantsKeyboardFocus (! isEditable);
  38086. resized();
  38087. }
  38088. }
  38089. bool ComboBox::isTextEditable() const throw()
  38090. {
  38091. return label->isEditable();
  38092. }
  38093. void ComboBox::setJustificationType (const Justification& justification)
  38094. {
  38095. label->setJustificationType (justification);
  38096. }
  38097. const Justification ComboBox::getJustificationType() const throw()
  38098. {
  38099. return label->getJustificationType();
  38100. }
  38101. void ComboBox::setTooltip (const String& newTooltip)
  38102. {
  38103. SettableTooltipClient::setTooltip (newTooltip);
  38104. label->setTooltip (newTooltip);
  38105. }
  38106. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38107. {
  38108. // you can't add empty strings to the list..
  38109. jassert (newItemText.isNotEmpty());
  38110. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38111. jassert (newItemId != 0);
  38112. // you shouldn't use duplicate item IDs!
  38113. jassert (getItemForId (newItemId) == 0);
  38114. if (newItemText.isNotEmpty() && newItemId != 0)
  38115. {
  38116. if (separatorPending)
  38117. {
  38118. separatorPending = false;
  38119. items.add (new ItemInfo (String::empty, 0, false, false));
  38120. }
  38121. items.add (new ItemInfo (newItemText, newItemId, true, false));
  38122. }
  38123. }
  38124. void ComboBox::addSeparator()
  38125. {
  38126. separatorPending = (items.size() > 0);
  38127. }
  38128. void ComboBox::addSectionHeading (const String& headingName)
  38129. {
  38130. // you can't add empty strings to the list..
  38131. jassert (headingName.isNotEmpty());
  38132. if (headingName.isNotEmpty())
  38133. {
  38134. if (separatorPending)
  38135. {
  38136. separatorPending = false;
  38137. items.add (new ItemInfo (String::empty, 0, false, false));
  38138. }
  38139. items.add (new ItemInfo (headingName, 0, true, true));
  38140. }
  38141. }
  38142. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38143. {
  38144. ItemInfo* const item = getItemForId (itemId);
  38145. if (item != 0)
  38146. item->isEnabled = shouldBeEnabled;
  38147. }
  38148. void ComboBox::changeItemText (const int itemId, const String& newText)
  38149. {
  38150. ItemInfo* const item = getItemForId (itemId);
  38151. jassert (item != 0);
  38152. if (item != 0)
  38153. item->name = newText;
  38154. }
  38155. void ComboBox::clear (const bool dontSendChangeMessage)
  38156. {
  38157. items.clear();
  38158. separatorPending = false;
  38159. if (! label->isEditable())
  38160. setSelectedItemIndex (-1, dontSendChangeMessage);
  38161. }
  38162. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38163. {
  38164. if (itemId != 0)
  38165. {
  38166. for (int i = items.size(); --i >= 0;)
  38167. if (items.getUnchecked(i)->itemId == itemId)
  38168. return items.getUnchecked(i);
  38169. }
  38170. return 0;
  38171. }
  38172. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38173. {
  38174. for (int n = 0, i = 0; i < items.size(); ++i)
  38175. {
  38176. ItemInfo* const item = items.getUnchecked(i);
  38177. if (item->isRealItem())
  38178. if (n++ == index)
  38179. return item;
  38180. }
  38181. return 0;
  38182. }
  38183. int ComboBox::getNumItems() const throw()
  38184. {
  38185. int n = 0;
  38186. for (int i = items.size(); --i >= 0;)
  38187. if (items.getUnchecked(i)->isRealItem())
  38188. ++n;
  38189. return n;
  38190. }
  38191. const String ComboBox::getItemText (const int index) const
  38192. {
  38193. const ItemInfo* const item = getItemForIndex (index);
  38194. return item != 0 ? item->name : String::empty;
  38195. }
  38196. int ComboBox::getItemId (const int index) const throw()
  38197. {
  38198. const ItemInfo* const item = getItemForIndex (index);
  38199. return item != 0 ? item->itemId : 0;
  38200. }
  38201. int ComboBox::indexOfItemId (const int itemId) const throw()
  38202. {
  38203. for (int n = 0, i = 0; i < items.size(); ++i)
  38204. {
  38205. const ItemInfo* const item = items.getUnchecked(i);
  38206. if (item->isRealItem())
  38207. {
  38208. if (item->itemId == itemId)
  38209. return n;
  38210. ++n;
  38211. }
  38212. }
  38213. return -1;
  38214. }
  38215. int ComboBox::getSelectedItemIndex() const
  38216. {
  38217. int index = indexOfItemId (currentId.getValue());
  38218. if (getText() != getItemText (index))
  38219. index = -1;
  38220. return index;
  38221. }
  38222. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38223. {
  38224. setSelectedId (getItemId (index), dontSendChangeMessage);
  38225. }
  38226. int ComboBox::getSelectedId() const throw()
  38227. {
  38228. const ItemInfo* const item = getItemForId (currentId.getValue());
  38229. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38230. }
  38231. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38232. {
  38233. const ItemInfo* const item = getItemForId (newItemId);
  38234. const String newItemText (item != 0 ? item->name : String::empty);
  38235. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38236. {
  38237. if (! dontSendChangeMessage)
  38238. triggerAsyncUpdate();
  38239. label->setText (newItemText, false);
  38240. lastCurrentId = newItemId;
  38241. currentId = newItemId;
  38242. repaint(); // for the benefit of the 'none selected' text
  38243. }
  38244. }
  38245. bool ComboBox::selectIfEnabled (const int index)
  38246. {
  38247. const ItemInfo* const item = getItemForIndex (index);
  38248. if (item != 0 && item->isEnabled)
  38249. {
  38250. setSelectedItemIndex (index);
  38251. return true;
  38252. }
  38253. return false;
  38254. }
  38255. void ComboBox::valueChanged (Value&)
  38256. {
  38257. if (lastCurrentId != (int) currentId.getValue())
  38258. setSelectedId (currentId.getValue(), false);
  38259. }
  38260. const String ComboBox::getText() const
  38261. {
  38262. return label->getText();
  38263. }
  38264. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38265. {
  38266. for (int i = items.size(); --i >= 0;)
  38267. {
  38268. const ItemInfo* const item = items.getUnchecked(i);
  38269. if (item->isRealItem()
  38270. && item->name == newText)
  38271. {
  38272. setSelectedId (item->itemId, dontSendChangeMessage);
  38273. return;
  38274. }
  38275. }
  38276. lastCurrentId = 0;
  38277. currentId = 0;
  38278. if (label->getText() != newText)
  38279. {
  38280. label->setText (newText, false);
  38281. if (! dontSendChangeMessage)
  38282. triggerAsyncUpdate();
  38283. }
  38284. repaint();
  38285. }
  38286. void ComboBox::showEditor()
  38287. {
  38288. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38289. label->showEditor();
  38290. }
  38291. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38292. {
  38293. if (textWhenNothingSelected != newMessage)
  38294. {
  38295. textWhenNothingSelected = newMessage;
  38296. repaint();
  38297. }
  38298. }
  38299. const String ComboBox::getTextWhenNothingSelected() const
  38300. {
  38301. return textWhenNothingSelected;
  38302. }
  38303. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38304. {
  38305. noChoicesMessage = newMessage;
  38306. }
  38307. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38308. {
  38309. return noChoicesMessage;
  38310. }
  38311. void ComboBox::paint (Graphics& g)
  38312. {
  38313. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38314. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38315. *this);
  38316. if (textWhenNothingSelected.isNotEmpty()
  38317. && label->getText().isEmpty()
  38318. && ! label->isBeingEdited())
  38319. {
  38320. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38321. g.setFont (label->getFont());
  38322. g.drawFittedText (textWhenNothingSelected,
  38323. label->getX() + 2, label->getY() + 1,
  38324. label->getWidth() - 4, label->getHeight() - 2,
  38325. label->getJustificationType(),
  38326. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38327. }
  38328. }
  38329. void ComboBox::resized()
  38330. {
  38331. if (getHeight() > 0 && getWidth() > 0)
  38332. getLookAndFeel().positionComboBoxText (*this, *label);
  38333. }
  38334. void ComboBox::enablementChanged()
  38335. {
  38336. repaint();
  38337. }
  38338. void ComboBox::lookAndFeelChanged()
  38339. {
  38340. repaint();
  38341. {
  38342. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38343. jassert (newLabel != 0);
  38344. if (label != 0)
  38345. {
  38346. newLabel->setEditable (label->isEditable());
  38347. newLabel->setJustificationType (label->getJustificationType());
  38348. newLabel->setTooltip (label->getTooltip());
  38349. newLabel->setText (label->getText(), false);
  38350. }
  38351. label = newLabel;
  38352. }
  38353. addAndMakeVisible (label);
  38354. label->addListener (this);
  38355. label->addMouseListener (this, false);
  38356. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38357. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38358. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38359. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38360. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38361. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38362. resized();
  38363. }
  38364. void ComboBox::colourChanged()
  38365. {
  38366. lookAndFeelChanged();
  38367. }
  38368. bool ComboBox::keyPressed (const KeyPress& key)
  38369. {
  38370. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38371. {
  38372. int index = getSelectedItemIndex() - 1;
  38373. while (index >= 0 && ! selectIfEnabled (index))
  38374. --index;
  38375. return true;
  38376. }
  38377. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38378. {
  38379. int index = getSelectedItemIndex() + 1;
  38380. while (index < getNumItems() && ! selectIfEnabled (index))
  38381. ++index;
  38382. return true;
  38383. }
  38384. else if (key.isKeyCode (KeyPress::returnKey))
  38385. {
  38386. showPopup();
  38387. return true;
  38388. }
  38389. return false;
  38390. }
  38391. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38392. {
  38393. // only forward key events that aren't used by this component
  38394. return isKeyDown
  38395. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38396. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38397. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38398. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38399. }
  38400. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38401. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38402. void ComboBox::labelTextChanged (Label*)
  38403. {
  38404. triggerAsyncUpdate();
  38405. }
  38406. class ComboBox::Callback : public ModalComponentManager::Callback
  38407. {
  38408. public:
  38409. Callback (ComboBox* const box_)
  38410. : box (box_)
  38411. {
  38412. }
  38413. void modalStateFinished (int returnValue)
  38414. {
  38415. if (box != 0)
  38416. {
  38417. box->menuActive = false;
  38418. if (returnValue != 0)
  38419. box->setSelectedId (returnValue);
  38420. }
  38421. }
  38422. private:
  38423. Component::SafePointer<ComboBox> box;
  38424. JUCE_DECLARE_NON_COPYABLE (Callback);
  38425. };
  38426. void ComboBox::showPopup()
  38427. {
  38428. if (! menuActive)
  38429. {
  38430. const int selectedId = getSelectedId();
  38431. PopupMenu menu;
  38432. menu.setLookAndFeel (&getLookAndFeel());
  38433. for (int i = 0; i < items.size(); ++i)
  38434. {
  38435. const ItemInfo* const item = items.getUnchecked(i);
  38436. if (item->isSeparator())
  38437. menu.addSeparator();
  38438. else if (item->isHeading)
  38439. menu.addSectionHeader (item->name);
  38440. else
  38441. menu.addItem (item->itemId, item->name,
  38442. item->isEnabled, item->itemId == selectedId);
  38443. }
  38444. if (items.size() == 0)
  38445. menu.addItem (1, noChoicesMessage, false);
  38446. menuActive = true;
  38447. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38448. new Callback (this));
  38449. }
  38450. }
  38451. void ComboBox::mouseDown (const MouseEvent& e)
  38452. {
  38453. beginDragAutoRepeat (300);
  38454. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38455. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38456. showPopup();
  38457. }
  38458. void ComboBox::mouseDrag (const MouseEvent& e)
  38459. {
  38460. beginDragAutoRepeat (50);
  38461. if (isButtonDown && ! e.mouseWasClicked())
  38462. showPopup();
  38463. }
  38464. void ComboBox::mouseUp (const MouseEvent& e2)
  38465. {
  38466. if (isButtonDown)
  38467. {
  38468. isButtonDown = false;
  38469. repaint();
  38470. const MouseEvent e (e2.getEventRelativeTo (this));
  38471. if (reallyContains (e.getPosition(), true)
  38472. && (e2.eventComponent == this || ! label->isEditable()))
  38473. {
  38474. showPopup();
  38475. }
  38476. }
  38477. }
  38478. void ComboBox::addListener (ComboBoxListener* const listener)
  38479. {
  38480. listeners.add (listener);
  38481. }
  38482. void ComboBox::removeListener (ComboBoxListener* const listener)
  38483. {
  38484. listeners.remove (listener);
  38485. }
  38486. void ComboBox::handleAsyncUpdate()
  38487. {
  38488. Component::BailOutChecker checker (this);
  38489. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38490. }
  38491. END_JUCE_NAMESPACE
  38492. /*** End of inlined file: juce_ComboBox.cpp ***/
  38493. /*** Start of inlined file: juce_Label.cpp ***/
  38494. BEGIN_JUCE_NAMESPACE
  38495. Label::Label (const String& componentName,
  38496. const String& labelText)
  38497. : Component (componentName),
  38498. textValue (labelText),
  38499. lastTextValue (labelText),
  38500. font (15.0f),
  38501. justification (Justification::centredLeft),
  38502. ownerComponent (0),
  38503. horizontalBorderSize (5),
  38504. verticalBorderSize (1),
  38505. minimumHorizontalScale (0.7f),
  38506. editSingleClick (false),
  38507. editDoubleClick (false),
  38508. lossOfFocusDiscardsChanges (false)
  38509. {
  38510. setColour (TextEditor::textColourId, Colours::black);
  38511. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38512. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38513. textValue.addListener (this);
  38514. }
  38515. Label::~Label()
  38516. {
  38517. textValue.removeListener (this);
  38518. if (ownerComponent != 0)
  38519. ownerComponent->removeComponentListener (this);
  38520. editor = 0;
  38521. }
  38522. void Label::setText (const String& newText,
  38523. const bool broadcastChangeMessage)
  38524. {
  38525. hideEditor (true);
  38526. if (lastTextValue != newText)
  38527. {
  38528. lastTextValue = newText;
  38529. textValue = newText;
  38530. repaint();
  38531. textWasChanged();
  38532. if (ownerComponent != 0)
  38533. componentMovedOrResized (*ownerComponent, true, true);
  38534. if (broadcastChangeMessage)
  38535. callChangeListeners();
  38536. }
  38537. }
  38538. const String Label::getText (const bool returnActiveEditorContents) const
  38539. {
  38540. return (returnActiveEditorContents && isBeingEdited())
  38541. ? editor->getText()
  38542. : textValue.toString();
  38543. }
  38544. void Label::valueChanged (Value&)
  38545. {
  38546. if (lastTextValue != textValue.toString())
  38547. setText (textValue.toString(), true);
  38548. }
  38549. void Label::setFont (const Font& newFont)
  38550. {
  38551. if (font != newFont)
  38552. {
  38553. font = newFont;
  38554. repaint();
  38555. }
  38556. }
  38557. const Font& Label::getFont() const throw()
  38558. {
  38559. return font;
  38560. }
  38561. void Label::setEditable (const bool editOnSingleClick,
  38562. const bool editOnDoubleClick,
  38563. const bool lossOfFocusDiscardsChanges_)
  38564. {
  38565. editSingleClick = editOnSingleClick;
  38566. editDoubleClick = editOnDoubleClick;
  38567. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38568. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38569. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38570. }
  38571. void Label::setJustificationType (const Justification& newJustification)
  38572. {
  38573. if (justification != newJustification)
  38574. {
  38575. justification = newJustification;
  38576. repaint();
  38577. }
  38578. }
  38579. void Label::setBorderSize (int h, int v)
  38580. {
  38581. if (horizontalBorderSize != h || verticalBorderSize != v)
  38582. {
  38583. horizontalBorderSize = h;
  38584. verticalBorderSize = v;
  38585. repaint();
  38586. }
  38587. }
  38588. Component* Label::getAttachedComponent() const
  38589. {
  38590. return static_cast<Component*> (ownerComponent);
  38591. }
  38592. void Label::attachToComponent (Component* owner,
  38593. const bool onLeft)
  38594. {
  38595. if (ownerComponent != 0)
  38596. ownerComponent->removeComponentListener (this);
  38597. ownerComponent = owner;
  38598. leftOfOwnerComp = onLeft;
  38599. if (ownerComponent != 0)
  38600. {
  38601. setVisible (owner->isVisible());
  38602. ownerComponent->addComponentListener (this);
  38603. componentParentHierarchyChanged (*ownerComponent);
  38604. componentMovedOrResized (*ownerComponent, true, true);
  38605. }
  38606. }
  38607. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38608. {
  38609. if (leftOfOwnerComp)
  38610. {
  38611. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38612. component.getHeight());
  38613. setTopRightPosition (component.getX(), component.getY());
  38614. }
  38615. else
  38616. {
  38617. setSize (component.getWidth(),
  38618. 8 + roundToInt (getFont().getHeight()));
  38619. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38620. }
  38621. }
  38622. void Label::componentParentHierarchyChanged (Component& component)
  38623. {
  38624. if (component.getParentComponent() != 0)
  38625. component.getParentComponent()->addChildComponent (this);
  38626. }
  38627. void Label::componentVisibilityChanged (Component& component)
  38628. {
  38629. setVisible (component.isVisible());
  38630. }
  38631. void Label::textWasEdited()
  38632. {
  38633. }
  38634. void Label::textWasChanged()
  38635. {
  38636. }
  38637. void Label::showEditor()
  38638. {
  38639. if (editor == 0)
  38640. {
  38641. addAndMakeVisible (editor = createEditorComponent());
  38642. editor->setText (getText(), false);
  38643. editor->addListener (this);
  38644. editor->grabKeyboardFocus();
  38645. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38646. editor->addListener (this);
  38647. resized();
  38648. repaint();
  38649. editorShown (editor);
  38650. enterModalState (false);
  38651. editor->grabKeyboardFocus();
  38652. }
  38653. }
  38654. void Label::editorShown (TextEditor* /*editorComponent*/)
  38655. {
  38656. }
  38657. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38658. {
  38659. }
  38660. bool Label::updateFromTextEditorContents()
  38661. {
  38662. jassert (editor != 0);
  38663. const String newText (editor->getText());
  38664. if (textValue.toString() != newText)
  38665. {
  38666. lastTextValue = newText;
  38667. textValue = newText;
  38668. repaint();
  38669. textWasChanged();
  38670. if (ownerComponent != 0)
  38671. componentMovedOrResized (*ownerComponent, true, true);
  38672. return true;
  38673. }
  38674. return false;
  38675. }
  38676. void Label::hideEditor (const bool discardCurrentEditorContents)
  38677. {
  38678. if (editor != 0)
  38679. {
  38680. WeakReference<Component> deletionChecker (this);
  38681. editorAboutToBeHidden (editor);
  38682. const bool changed = (! discardCurrentEditorContents)
  38683. && updateFromTextEditorContents();
  38684. editor = 0;
  38685. repaint();
  38686. if (changed)
  38687. textWasEdited();
  38688. if (deletionChecker != 0)
  38689. exitModalState (0);
  38690. if (changed && deletionChecker != 0)
  38691. callChangeListeners();
  38692. }
  38693. }
  38694. void Label::inputAttemptWhenModal()
  38695. {
  38696. if (editor != 0)
  38697. {
  38698. if (lossOfFocusDiscardsChanges)
  38699. textEditorEscapeKeyPressed (*editor);
  38700. else
  38701. textEditorReturnKeyPressed (*editor);
  38702. }
  38703. }
  38704. bool Label::isBeingEdited() const throw()
  38705. {
  38706. return editor != 0;
  38707. }
  38708. TextEditor* Label::createEditorComponent()
  38709. {
  38710. TextEditor* const ed = new TextEditor (getName());
  38711. ed->setFont (font);
  38712. // copy these colours from our own settings..
  38713. const int cols[] = { TextEditor::backgroundColourId,
  38714. TextEditor::textColourId,
  38715. TextEditor::highlightColourId,
  38716. TextEditor::highlightedTextColourId,
  38717. TextEditor::caretColourId,
  38718. TextEditor::outlineColourId,
  38719. TextEditor::focusedOutlineColourId,
  38720. TextEditor::shadowColourId };
  38721. for (int i = 0; i < numElementsInArray (cols); ++i)
  38722. ed->setColour (cols[i], findColour (cols[i]));
  38723. return ed;
  38724. }
  38725. void Label::paint (Graphics& g)
  38726. {
  38727. getLookAndFeel().drawLabel (g, *this);
  38728. }
  38729. void Label::mouseUp (const MouseEvent& e)
  38730. {
  38731. if (editSingleClick
  38732. && e.mouseWasClicked()
  38733. && contains (e.getPosition())
  38734. && ! e.mods.isPopupMenu())
  38735. {
  38736. showEditor();
  38737. }
  38738. }
  38739. void Label::mouseDoubleClick (const MouseEvent& e)
  38740. {
  38741. if (editDoubleClick && ! e.mods.isPopupMenu())
  38742. showEditor();
  38743. }
  38744. void Label::resized()
  38745. {
  38746. if (editor != 0)
  38747. editor->setBoundsInset (BorderSize<int> (0));
  38748. }
  38749. void Label::focusGained (FocusChangeType cause)
  38750. {
  38751. if (editSingleClick && cause == focusChangedByTabKey)
  38752. showEditor();
  38753. }
  38754. void Label::enablementChanged()
  38755. {
  38756. repaint();
  38757. }
  38758. void Label::colourChanged()
  38759. {
  38760. repaint();
  38761. }
  38762. void Label::setMinimumHorizontalScale (const float newScale)
  38763. {
  38764. if (minimumHorizontalScale != newScale)
  38765. {
  38766. minimumHorizontalScale = newScale;
  38767. repaint();
  38768. }
  38769. }
  38770. // We'll use a custom focus traverser here to make sure focus goes from the
  38771. // text editor to another component rather than back to the label itself.
  38772. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38773. {
  38774. public:
  38775. LabelKeyboardFocusTraverser() {}
  38776. Component* getNextComponent (Component* current)
  38777. {
  38778. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38779. ? current->getParentComponent() : current);
  38780. }
  38781. Component* getPreviousComponent (Component* current)
  38782. {
  38783. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38784. ? current->getParentComponent() : current);
  38785. }
  38786. };
  38787. KeyboardFocusTraverser* Label::createFocusTraverser()
  38788. {
  38789. return new LabelKeyboardFocusTraverser();
  38790. }
  38791. void Label::addListener (LabelListener* const listener)
  38792. {
  38793. listeners.add (listener);
  38794. }
  38795. void Label::removeListener (LabelListener* const listener)
  38796. {
  38797. listeners.remove (listener);
  38798. }
  38799. void Label::callChangeListeners()
  38800. {
  38801. Component::BailOutChecker checker (this);
  38802. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38803. }
  38804. void Label::textEditorTextChanged (TextEditor& ed)
  38805. {
  38806. if (editor != 0)
  38807. {
  38808. jassert (&ed == editor);
  38809. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38810. {
  38811. if (lossOfFocusDiscardsChanges)
  38812. textEditorEscapeKeyPressed (ed);
  38813. else
  38814. textEditorReturnKeyPressed (ed);
  38815. }
  38816. }
  38817. }
  38818. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38819. {
  38820. if (editor != 0)
  38821. {
  38822. jassert (&ed == editor);
  38823. (void) ed;
  38824. const bool changed = updateFromTextEditorContents();
  38825. hideEditor (true);
  38826. if (changed)
  38827. {
  38828. WeakReference<Component> deletionChecker (this);
  38829. textWasEdited();
  38830. if (deletionChecker != 0)
  38831. callChangeListeners();
  38832. }
  38833. }
  38834. }
  38835. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38836. {
  38837. if (editor != 0)
  38838. {
  38839. jassert (&ed == editor);
  38840. (void) ed;
  38841. editor->setText (textValue.toString(), false);
  38842. hideEditor (true);
  38843. }
  38844. }
  38845. void Label::textEditorFocusLost (TextEditor& ed)
  38846. {
  38847. textEditorTextChanged (ed);
  38848. }
  38849. END_JUCE_NAMESPACE
  38850. /*** End of inlined file: juce_Label.cpp ***/
  38851. /*** Start of inlined file: juce_ListBox.cpp ***/
  38852. BEGIN_JUCE_NAMESPACE
  38853. class ListBoxRowComponent : public Component,
  38854. public TooltipClient
  38855. {
  38856. public:
  38857. ListBoxRowComponent (ListBox& owner_)
  38858. : owner (owner_), row (-1),
  38859. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38860. {
  38861. }
  38862. void paint (Graphics& g)
  38863. {
  38864. if (owner.getModel() != 0)
  38865. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38866. }
  38867. void update (const int row_, const bool selected_)
  38868. {
  38869. if (row != row_ || selected != selected_)
  38870. {
  38871. repaint();
  38872. row = row_;
  38873. selected = selected_;
  38874. }
  38875. if (owner.getModel() != 0)
  38876. {
  38877. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  38878. if (customComponent != 0)
  38879. {
  38880. addAndMakeVisible (customComponent);
  38881. customComponent->setBounds (getLocalBounds());
  38882. }
  38883. }
  38884. }
  38885. void mouseDown (const MouseEvent& e)
  38886. {
  38887. isDragging = false;
  38888. selectRowOnMouseUp = false;
  38889. if (isEnabled())
  38890. {
  38891. if (! selected)
  38892. {
  38893. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  38894. if (owner.getModel() != 0)
  38895. owner.getModel()->listBoxItemClicked (row, e);
  38896. }
  38897. else
  38898. {
  38899. selectRowOnMouseUp = true;
  38900. }
  38901. }
  38902. }
  38903. void mouseUp (const MouseEvent& e)
  38904. {
  38905. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38906. {
  38907. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  38908. if (owner.getModel() != 0)
  38909. owner.getModel()->listBoxItemClicked (row, e);
  38910. }
  38911. }
  38912. void mouseDoubleClick (const MouseEvent& e)
  38913. {
  38914. if (owner.getModel() != 0 && isEnabled())
  38915. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38916. }
  38917. void mouseDrag (const MouseEvent& e)
  38918. {
  38919. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38920. {
  38921. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38922. if (selectedRows.size() > 0)
  38923. {
  38924. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38925. if (dragDescription.isNotEmpty())
  38926. {
  38927. isDragging = true;
  38928. owner.startDragAndDrop (e, dragDescription);
  38929. }
  38930. }
  38931. }
  38932. }
  38933. void resized()
  38934. {
  38935. if (customComponent != 0)
  38936. customComponent->setBounds (getLocalBounds());
  38937. }
  38938. const String getTooltip()
  38939. {
  38940. if (owner.getModel() != 0)
  38941. return owner.getModel()->getTooltipForRow (row);
  38942. return String::empty;
  38943. }
  38944. ScopedPointer<Component> customComponent;
  38945. private:
  38946. ListBox& owner;
  38947. int row;
  38948. bool selected, isDragging, selectRowOnMouseUp;
  38949. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  38950. };
  38951. class ListViewport : public Viewport
  38952. {
  38953. public:
  38954. ListViewport (ListBox& owner_)
  38955. : owner (owner_)
  38956. {
  38957. setWantsKeyboardFocus (false);
  38958. Component* const content = new Component();
  38959. setViewedComponent (content);
  38960. content->addMouseListener (this, false);
  38961. content->setWantsKeyboardFocus (false);
  38962. }
  38963. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38964. {
  38965. return rows [row % jmax (1, rows.size())];
  38966. }
  38967. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  38968. {
  38969. return (row >= firstIndex && row < firstIndex + rows.size())
  38970. ? getComponentForRow (row) : 0;
  38971. }
  38972. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38973. {
  38974. const int index = getIndexOfChildComponent (rowComponent);
  38975. const int num = rows.size();
  38976. for (int i = num; --i >= 0;)
  38977. if (((firstIndex + i) % jmax (1, num)) == index)
  38978. return firstIndex + i;
  38979. return -1;
  38980. }
  38981. void visibleAreaChanged (const Rectangle<int>&)
  38982. {
  38983. updateVisibleArea (true);
  38984. if (owner.getModel() != 0)
  38985. owner.getModel()->listWasScrolled();
  38986. }
  38987. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38988. {
  38989. hasUpdated = false;
  38990. const int newX = getViewedComponent()->getX();
  38991. int newY = getViewedComponent()->getY();
  38992. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38993. const int newH = owner.totalItems * owner.getRowHeight();
  38994. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38995. newY = getMaximumVisibleHeight() - newH;
  38996. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38997. if (makeSureItUpdatesContent && ! hasUpdated)
  38998. updateContents();
  38999. }
  39000. void updateContents()
  39001. {
  39002. hasUpdated = true;
  39003. const int rowHeight = owner.getRowHeight();
  39004. if (rowHeight > 0)
  39005. {
  39006. const int y = getViewPositionY();
  39007. const int w = getViewedComponent()->getWidth();
  39008. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39009. rows.removeRange (numNeeded, rows.size());
  39010. while (numNeeded > rows.size())
  39011. {
  39012. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  39013. rows.add (newRow);
  39014. getViewedComponent()->addAndMakeVisible (newRow);
  39015. }
  39016. firstIndex = y / rowHeight;
  39017. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39018. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39019. for (int i = 0; i < numNeeded; ++i)
  39020. {
  39021. const int row = i + firstIndex;
  39022. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39023. if (rowComp != 0)
  39024. {
  39025. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39026. rowComp->update (row, owner.isRowSelected (row));
  39027. }
  39028. }
  39029. }
  39030. if (owner.headerComponent != 0)
  39031. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39032. owner.outlineThickness,
  39033. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39034. getViewedComponent()->getWidth()),
  39035. owner.headerComponent->getHeight());
  39036. }
  39037. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39038. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39039. {
  39040. hasUpdated = false;
  39041. if (row < firstWholeIndex && ! dontScroll)
  39042. {
  39043. setViewPosition (getViewPositionX(), row * rowHeight);
  39044. }
  39045. else if (row >= lastWholeIndex && ! dontScroll)
  39046. {
  39047. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39048. if (row >= lastRowSelected + rowsOnScreen
  39049. && rowsOnScreen < totalItems - 1
  39050. && ! isMouseClick)
  39051. {
  39052. setViewPosition (getViewPositionX(),
  39053. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39054. }
  39055. else
  39056. {
  39057. setViewPosition (getViewPositionX(),
  39058. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39059. }
  39060. }
  39061. if (! hasUpdated)
  39062. updateContents();
  39063. }
  39064. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39065. {
  39066. if (row < firstWholeIndex)
  39067. {
  39068. setViewPosition (getViewPositionX(), row * rowHeight);
  39069. }
  39070. else if (row >= lastWholeIndex)
  39071. {
  39072. setViewPosition (getViewPositionX(),
  39073. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39074. }
  39075. }
  39076. void paint (Graphics& g)
  39077. {
  39078. if (isOpaque())
  39079. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39080. }
  39081. bool keyPressed (const KeyPress& key)
  39082. {
  39083. if (key.isKeyCode (KeyPress::upKey)
  39084. || key.isKeyCode (KeyPress::downKey)
  39085. || key.isKeyCode (KeyPress::pageUpKey)
  39086. || key.isKeyCode (KeyPress::pageDownKey)
  39087. || key.isKeyCode (KeyPress::homeKey)
  39088. || key.isKeyCode (KeyPress::endKey))
  39089. {
  39090. // we want to avoid these keypresses going to the viewport, and instead allow
  39091. // them to pass up to our listbox..
  39092. return false;
  39093. }
  39094. return Viewport::keyPressed (key);
  39095. }
  39096. private:
  39097. ListBox& owner;
  39098. OwnedArray<ListBoxRowComponent> rows;
  39099. int firstIndex, firstWholeIndex, lastWholeIndex;
  39100. bool hasUpdated;
  39101. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  39102. };
  39103. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39104. : Component (name),
  39105. model (model_),
  39106. totalItems (0),
  39107. rowHeight (22),
  39108. minimumRowWidth (0),
  39109. outlineThickness (0),
  39110. lastRowSelected (-1),
  39111. mouseMoveSelects (false),
  39112. multipleSelection (false),
  39113. hasDoneInitialUpdate (false)
  39114. {
  39115. addAndMakeVisible (viewport = new ListViewport (*this));
  39116. setWantsKeyboardFocus (true);
  39117. colourChanged();
  39118. }
  39119. ListBox::~ListBox()
  39120. {
  39121. headerComponent = 0;
  39122. viewport = 0;
  39123. }
  39124. void ListBox::setModel (ListBoxModel* const newModel)
  39125. {
  39126. if (model != newModel)
  39127. {
  39128. model = newModel;
  39129. repaint();
  39130. updateContent();
  39131. }
  39132. }
  39133. void ListBox::setMultipleSelectionEnabled (bool b)
  39134. {
  39135. multipleSelection = b;
  39136. }
  39137. void ListBox::setMouseMoveSelectsRows (bool b)
  39138. {
  39139. mouseMoveSelects = b;
  39140. if (b)
  39141. addMouseListener (this, true);
  39142. }
  39143. void ListBox::paint (Graphics& g)
  39144. {
  39145. if (! hasDoneInitialUpdate)
  39146. updateContent();
  39147. g.fillAll (findColour (backgroundColourId));
  39148. }
  39149. void ListBox::paintOverChildren (Graphics& g)
  39150. {
  39151. if (outlineThickness > 0)
  39152. {
  39153. g.setColour (findColour (outlineColourId));
  39154. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39155. }
  39156. }
  39157. void ListBox::resized()
  39158. {
  39159. viewport->setBoundsInset (BorderSize<int> (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39160. outlineThickness, outlineThickness, outlineThickness));
  39161. viewport->setSingleStepSizes (20, getRowHeight());
  39162. viewport->updateVisibleArea (false);
  39163. }
  39164. void ListBox::visibilityChanged()
  39165. {
  39166. viewport->updateVisibleArea (true);
  39167. }
  39168. Viewport* ListBox::getViewport() const throw()
  39169. {
  39170. return viewport;
  39171. }
  39172. void ListBox::updateContent()
  39173. {
  39174. hasDoneInitialUpdate = true;
  39175. totalItems = (model != 0) ? model->getNumRows() : 0;
  39176. bool selectionChanged = false;
  39177. if (selected [selected.size() - 1] >= totalItems)
  39178. {
  39179. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39180. lastRowSelected = getSelectedRow (0);
  39181. selectionChanged = true;
  39182. }
  39183. viewport->updateVisibleArea (isVisible());
  39184. viewport->resized();
  39185. if (selectionChanged && model != 0)
  39186. model->selectedRowsChanged (lastRowSelected);
  39187. }
  39188. void ListBox::selectRow (const int row,
  39189. bool dontScroll,
  39190. bool deselectOthersFirst)
  39191. {
  39192. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39193. }
  39194. void ListBox::selectRowInternal (const int row,
  39195. bool dontScroll,
  39196. bool deselectOthersFirst,
  39197. bool isMouseClick)
  39198. {
  39199. if (! multipleSelection)
  39200. deselectOthersFirst = true;
  39201. if ((! isRowSelected (row))
  39202. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39203. {
  39204. if (isPositiveAndBelow (row, totalItems))
  39205. {
  39206. if (deselectOthersFirst)
  39207. selected.clear();
  39208. selected.addRange (Range<int> (row, row + 1));
  39209. if (getHeight() == 0 || getWidth() == 0)
  39210. dontScroll = true;
  39211. viewport->selectRow (row, getRowHeight(), dontScroll,
  39212. lastRowSelected, totalItems, isMouseClick);
  39213. lastRowSelected = row;
  39214. model->selectedRowsChanged (row);
  39215. }
  39216. else
  39217. {
  39218. if (deselectOthersFirst)
  39219. deselectAllRows();
  39220. }
  39221. }
  39222. }
  39223. void ListBox::deselectRow (const int row)
  39224. {
  39225. if (selected.contains (row))
  39226. {
  39227. selected.removeRange (Range <int> (row, row + 1));
  39228. if (row == lastRowSelected)
  39229. lastRowSelected = getSelectedRow (0);
  39230. viewport->updateContents();
  39231. model->selectedRowsChanged (lastRowSelected);
  39232. }
  39233. }
  39234. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39235. const bool sendNotificationEventToModel)
  39236. {
  39237. selected = setOfRowsToBeSelected;
  39238. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39239. if (! isRowSelected (lastRowSelected))
  39240. lastRowSelected = getSelectedRow (0);
  39241. viewport->updateContents();
  39242. if ((model != 0) && sendNotificationEventToModel)
  39243. model->selectedRowsChanged (lastRowSelected);
  39244. }
  39245. const SparseSet<int> ListBox::getSelectedRows() const
  39246. {
  39247. return selected;
  39248. }
  39249. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39250. {
  39251. if (multipleSelection && (firstRow != lastRow))
  39252. {
  39253. const int numRows = totalItems - 1;
  39254. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39255. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39256. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39257. jmax (firstRow, lastRow) + 1));
  39258. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39259. }
  39260. selectRowInternal (lastRow, false, false, true);
  39261. }
  39262. void ListBox::flipRowSelection (const int row)
  39263. {
  39264. if (isRowSelected (row))
  39265. deselectRow (row);
  39266. else
  39267. selectRowInternal (row, false, false, true);
  39268. }
  39269. void ListBox::deselectAllRows()
  39270. {
  39271. if (! selected.isEmpty())
  39272. {
  39273. selected.clear();
  39274. lastRowSelected = -1;
  39275. viewport->updateContents();
  39276. if (model != 0)
  39277. model->selectedRowsChanged (lastRowSelected);
  39278. }
  39279. }
  39280. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39281. const ModifierKeys& mods,
  39282. const bool isMouseUpEvent)
  39283. {
  39284. if (multipleSelection && mods.isCommandDown())
  39285. {
  39286. flipRowSelection (row);
  39287. }
  39288. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39289. {
  39290. selectRangeOfRows (lastRowSelected, row);
  39291. }
  39292. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39293. {
  39294. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  39295. }
  39296. }
  39297. int ListBox::getNumSelectedRows() const
  39298. {
  39299. return selected.size();
  39300. }
  39301. int ListBox::getSelectedRow (const int index) const
  39302. {
  39303. return (isPositiveAndBelow (index, selected.size()))
  39304. ? selected [index] : -1;
  39305. }
  39306. bool ListBox::isRowSelected (const int row) const
  39307. {
  39308. return selected.contains (row);
  39309. }
  39310. int ListBox::getLastRowSelected() const
  39311. {
  39312. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39313. }
  39314. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39315. {
  39316. if (isPositiveAndBelow (x, getWidth()))
  39317. {
  39318. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39319. if (isPositiveAndBelow (row, totalItems))
  39320. return row;
  39321. }
  39322. return -1;
  39323. }
  39324. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39325. {
  39326. if (isPositiveAndBelow (x, getWidth()))
  39327. {
  39328. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39329. return jlimit (0, totalItems, row);
  39330. }
  39331. return -1;
  39332. }
  39333. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39334. {
  39335. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39336. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39337. }
  39338. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39339. {
  39340. return viewport->getRowNumberOfComponent (rowComponent);
  39341. }
  39342. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39343. const bool relativeToComponentTopLeft) const throw()
  39344. {
  39345. int y = viewport->getY() + rowHeight * rowNumber;
  39346. if (relativeToComponentTopLeft)
  39347. y -= viewport->getViewPositionY();
  39348. return Rectangle<int> (viewport->getX(), y,
  39349. viewport->getViewedComponent()->getWidth(), rowHeight);
  39350. }
  39351. void ListBox::setVerticalPosition (const double proportion)
  39352. {
  39353. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39354. viewport->setViewPosition (viewport->getViewPositionX(),
  39355. jmax (0, roundToInt (proportion * offscreen)));
  39356. }
  39357. double ListBox::getVerticalPosition() const
  39358. {
  39359. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39360. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39361. : 0;
  39362. }
  39363. int ListBox::getVisibleRowWidth() const throw()
  39364. {
  39365. return viewport->getViewWidth();
  39366. }
  39367. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39368. {
  39369. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39370. }
  39371. bool ListBox::keyPressed (const KeyPress& key)
  39372. {
  39373. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39374. const bool multiple = multipleSelection
  39375. && (lastRowSelected >= 0)
  39376. && (key.getModifiers().isShiftDown()
  39377. || key.getModifiers().isCtrlDown()
  39378. || key.getModifiers().isCommandDown());
  39379. if (key.isKeyCode (KeyPress::upKey))
  39380. {
  39381. if (multiple)
  39382. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39383. else
  39384. selectRow (jmax (0, lastRowSelected - 1));
  39385. }
  39386. else if (key.isKeyCode (KeyPress::returnKey)
  39387. && isRowSelected (lastRowSelected))
  39388. {
  39389. if (model != 0)
  39390. model->returnKeyPressed (lastRowSelected);
  39391. }
  39392. else if (key.isKeyCode (KeyPress::pageUpKey))
  39393. {
  39394. if (multiple)
  39395. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39396. else
  39397. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39398. }
  39399. else if (key.isKeyCode (KeyPress::pageDownKey))
  39400. {
  39401. if (multiple)
  39402. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39403. else
  39404. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39405. }
  39406. else if (key.isKeyCode (KeyPress::homeKey))
  39407. {
  39408. if (multiple && key.getModifiers().isShiftDown())
  39409. selectRangeOfRows (lastRowSelected, 0);
  39410. else
  39411. selectRow (0);
  39412. }
  39413. else if (key.isKeyCode (KeyPress::endKey))
  39414. {
  39415. if (multiple && key.getModifiers().isShiftDown())
  39416. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39417. else
  39418. selectRow (totalItems - 1);
  39419. }
  39420. else if (key.isKeyCode (KeyPress::downKey))
  39421. {
  39422. if (multiple)
  39423. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39424. else
  39425. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39426. }
  39427. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39428. && isRowSelected (lastRowSelected))
  39429. {
  39430. if (model != 0)
  39431. model->deleteKeyPressed (lastRowSelected);
  39432. }
  39433. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39434. {
  39435. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39436. }
  39437. else
  39438. {
  39439. return false;
  39440. }
  39441. return true;
  39442. }
  39443. bool ListBox::keyStateChanged (const bool isKeyDown)
  39444. {
  39445. return isKeyDown
  39446. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39447. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39448. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39449. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39450. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39451. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39452. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39453. }
  39454. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39455. {
  39456. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39457. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39458. }
  39459. void ListBox::mouseMove (const MouseEvent& e)
  39460. {
  39461. if (mouseMoveSelects)
  39462. {
  39463. const MouseEvent e2 (e.getEventRelativeTo (this));
  39464. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39465. }
  39466. }
  39467. void ListBox::mouseExit (const MouseEvent& e)
  39468. {
  39469. mouseMove (e);
  39470. }
  39471. void ListBox::mouseUp (const MouseEvent& e)
  39472. {
  39473. if (e.mouseWasClicked() && model != 0)
  39474. model->backgroundClicked();
  39475. }
  39476. void ListBox::setRowHeight (const int newHeight)
  39477. {
  39478. rowHeight = jmax (1, newHeight);
  39479. viewport->setSingleStepSizes (20, rowHeight);
  39480. updateContent();
  39481. }
  39482. int ListBox::getNumRowsOnScreen() const throw()
  39483. {
  39484. return viewport->getMaximumVisibleHeight() / rowHeight;
  39485. }
  39486. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39487. {
  39488. minimumRowWidth = newMinimumWidth;
  39489. updateContent();
  39490. }
  39491. int ListBox::getVisibleContentWidth() const throw()
  39492. {
  39493. return viewport->getMaximumVisibleWidth();
  39494. }
  39495. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39496. {
  39497. return viewport->getVerticalScrollBar();
  39498. }
  39499. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39500. {
  39501. return viewport->getHorizontalScrollBar();
  39502. }
  39503. void ListBox::colourChanged()
  39504. {
  39505. setOpaque (findColour (backgroundColourId).isOpaque());
  39506. viewport->setOpaque (isOpaque());
  39507. repaint();
  39508. }
  39509. void ListBox::setOutlineThickness (const int outlineThickness_)
  39510. {
  39511. outlineThickness = outlineThickness_;
  39512. resized();
  39513. }
  39514. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39515. {
  39516. if (headerComponent != newHeaderComponent)
  39517. {
  39518. headerComponent = newHeaderComponent;
  39519. addAndMakeVisible (newHeaderComponent);
  39520. ListBox::resized();
  39521. }
  39522. }
  39523. void ListBox::repaintRow (const int rowNumber) throw()
  39524. {
  39525. repaint (getRowPosition (rowNumber, true));
  39526. }
  39527. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39528. {
  39529. Rectangle<int> imageArea;
  39530. const int firstRow = getRowContainingPosition (0, 0);
  39531. int i;
  39532. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39533. {
  39534. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39535. if (rowComp != 0 && isRowSelected (firstRow + i))
  39536. {
  39537. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39538. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39539. imageArea = imageArea.getUnion (rowRect);
  39540. }
  39541. }
  39542. imageArea = imageArea.getIntersection (getLocalBounds());
  39543. imageX = imageArea.getX();
  39544. imageY = imageArea.getY();
  39545. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39546. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39547. {
  39548. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39549. if (rowComp != 0 && isRowSelected (firstRow + i))
  39550. {
  39551. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39552. Graphics g (snapshot);
  39553. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39554. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39555. rowComp->paintEntireComponent (g, false);
  39556. }
  39557. }
  39558. return snapshot;
  39559. }
  39560. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39561. {
  39562. DragAndDropContainer* const dragContainer
  39563. = DragAndDropContainer::findParentDragContainerFor (this);
  39564. if (dragContainer != 0)
  39565. {
  39566. int x, y;
  39567. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39568. dragImage.multiplyAllAlphas (0.6f);
  39569. MouseEvent e2 (e.getEventRelativeTo (this));
  39570. const Point<int> p (x - e2.x, y - e2.y);
  39571. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39572. }
  39573. else
  39574. {
  39575. // to be able to do a drag-and-drop operation, the listbox needs to
  39576. // be inside a component which is also a DragAndDropContainer.
  39577. jassertfalse;
  39578. }
  39579. }
  39580. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39581. {
  39582. (void) existingComponentToUpdate;
  39583. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39584. return 0;
  39585. }
  39586. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39587. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39588. void ListBoxModel::backgroundClicked() {}
  39589. void ListBoxModel::selectedRowsChanged (int) {}
  39590. void ListBoxModel::deleteKeyPressed (int) {}
  39591. void ListBoxModel::returnKeyPressed (int) {}
  39592. void ListBoxModel::listWasScrolled() {}
  39593. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39594. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39595. END_JUCE_NAMESPACE
  39596. /*** End of inlined file: juce_ListBox.cpp ***/
  39597. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39598. BEGIN_JUCE_NAMESPACE
  39599. ProgressBar::ProgressBar (double& progress_)
  39600. : progress (progress_),
  39601. displayPercentage (true),
  39602. lastCallbackTime (0)
  39603. {
  39604. currentValue = jlimit (0.0, 1.0, progress);
  39605. }
  39606. ProgressBar::~ProgressBar()
  39607. {
  39608. }
  39609. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39610. {
  39611. displayPercentage = shouldDisplayPercentage;
  39612. repaint();
  39613. }
  39614. void ProgressBar::setTextToDisplay (const String& text)
  39615. {
  39616. displayPercentage = false;
  39617. displayedMessage = text;
  39618. }
  39619. void ProgressBar::lookAndFeelChanged()
  39620. {
  39621. setOpaque (findColour (backgroundColourId).isOpaque());
  39622. }
  39623. void ProgressBar::colourChanged()
  39624. {
  39625. lookAndFeelChanged();
  39626. }
  39627. void ProgressBar::paint (Graphics& g)
  39628. {
  39629. String text;
  39630. if (displayPercentage)
  39631. {
  39632. if (currentValue >= 0 && currentValue <= 1.0)
  39633. text << roundToInt (currentValue * 100.0) << '%';
  39634. }
  39635. else
  39636. {
  39637. text = displayedMessage;
  39638. }
  39639. getLookAndFeel().drawProgressBar (g, *this,
  39640. getWidth(), getHeight(),
  39641. currentValue, text);
  39642. }
  39643. void ProgressBar::visibilityChanged()
  39644. {
  39645. if (isVisible())
  39646. startTimer (30);
  39647. else
  39648. stopTimer();
  39649. }
  39650. void ProgressBar::timerCallback()
  39651. {
  39652. double newProgress = progress;
  39653. const uint32 now = Time::getMillisecondCounter();
  39654. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39655. lastCallbackTime = now;
  39656. if (currentValue != newProgress
  39657. || newProgress < 0 || newProgress >= 1.0
  39658. || currentMessage != displayedMessage)
  39659. {
  39660. if (currentValue < newProgress
  39661. && newProgress >= 0 && newProgress < 1.0
  39662. && currentValue >= 0 && currentValue < 1.0)
  39663. {
  39664. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39665. newProgress);
  39666. }
  39667. currentValue = newProgress;
  39668. currentMessage = displayedMessage;
  39669. repaint();
  39670. }
  39671. }
  39672. END_JUCE_NAMESPACE
  39673. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39674. /*** Start of inlined file: juce_Slider.cpp ***/
  39675. BEGIN_JUCE_NAMESPACE
  39676. class SliderPopupDisplayComponent : public BubbleComponent
  39677. {
  39678. public:
  39679. SliderPopupDisplayComponent (Slider* const owner_)
  39680. : owner (owner_),
  39681. font (15.0f, Font::bold)
  39682. {
  39683. setAlwaysOnTop (true);
  39684. }
  39685. ~SliderPopupDisplayComponent()
  39686. {
  39687. }
  39688. void paintContent (Graphics& g, int w, int h)
  39689. {
  39690. g.setFont (font);
  39691. g.setColour (Colours::black);
  39692. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39693. }
  39694. void getContentSize (int& w, int& h)
  39695. {
  39696. w = font.getStringWidth (text) + 18;
  39697. h = (int) (font.getHeight() * 1.6f);
  39698. }
  39699. void updatePosition (const String& newText)
  39700. {
  39701. if (text != newText)
  39702. {
  39703. text = newText;
  39704. repaint();
  39705. }
  39706. BubbleComponent::setPosition (owner);
  39707. }
  39708. private:
  39709. Slider* owner;
  39710. Font font;
  39711. String text;
  39712. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39713. };
  39714. Slider::Slider (const String& name)
  39715. : Component (name),
  39716. lastCurrentValue (0),
  39717. lastValueMin (0),
  39718. lastValueMax (0),
  39719. minimum (0),
  39720. maximum (10),
  39721. interval (0),
  39722. skewFactor (1.0),
  39723. velocityModeSensitivity (1.0),
  39724. velocityModeOffset (0.0),
  39725. velocityModeThreshold (1),
  39726. rotaryStart (float_Pi * 1.2f),
  39727. rotaryEnd (float_Pi * 2.8f),
  39728. numDecimalPlaces (7),
  39729. sliderRegionStart (0),
  39730. sliderRegionSize (1),
  39731. sliderBeingDragged (-1),
  39732. pixelsForFullDragExtent (250),
  39733. style (LinearHorizontal),
  39734. textBoxPos (TextBoxLeft),
  39735. textBoxWidth (80),
  39736. textBoxHeight (20),
  39737. incDecButtonMode (incDecButtonsNotDraggable),
  39738. editableText (true),
  39739. doubleClickToValue (false),
  39740. isVelocityBased (false),
  39741. userKeyOverridesVelocity (true),
  39742. rotaryStop (true),
  39743. incDecButtonsSideBySide (false),
  39744. sendChangeOnlyOnRelease (false),
  39745. popupDisplayEnabled (false),
  39746. menuEnabled (false),
  39747. menuShown (false),
  39748. scrollWheelEnabled (true),
  39749. snapsToMousePos (true),
  39750. popupDisplay (0),
  39751. parentForPopupDisplay (0)
  39752. {
  39753. setWantsKeyboardFocus (false);
  39754. setRepaintsOnMouseActivity (true);
  39755. lookAndFeelChanged();
  39756. updateText();
  39757. currentValue.addListener (this);
  39758. valueMin.addListener (this);
  39759. valueMax.addListener (this);
  39760. }
  39761. Slider::~Slider()
  39762. {
  39763. currentValue.removeListener (this);
  39764. valueMin.removeListener (this);
  39765. valueMax.removeListener (this);
  39766. popupDisplay = 0;
  39767. }
  39768. void Slider::handleAsyncUpdate()
  39769. {
  39770. cancelPendingUpdate();
  39771. Component::BailOutChecker checker (this);
  39772. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39773. }
  39774. void Slider::sendDragStart()
  39775. {
  39776. startedDragging();
  39777. Component::BailOutChecker checker (this);
  39778. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39779. }
  39780. void Slider::sendDragEnd()
  39781. {
  39782. stoppedDragging();
  39783. sliderBeingDragged = -1;
  39784. Component::BailOutChecker checker (this);
  39785. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39786. }
  39787. void Slider::addListener (SliderListener* const listener)
  39788. {
  39789. listeners.add (listener);
  39790. }
  39791. void Slider::removeListener (SliderListener* const listener)
  39792. {
  39793. listeners.remove (listener);
  39794. }
  39795. void Slider::setSliderStyle (const SliderStyle newStyle)
  39796. {
  39797. if (style != newStyle)
  39798. {
  39799. style = newStyle;
  39800. repaint();
  39801. lookAndFeelChanged();
  39802. }
  39803. }
  39804. void Slider::setRotaryParameters (const float startAngleRadians,
  39805. const float endAngleRadians,
  39806. const bool stopAtEnd)
  39807. {
  39808. // make sure the values are sensible..
  39809. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39810. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39811. jassert (rotaryStart < rotaryEnd);
  39812. rotaryStart = startAngleRadians;
  39813. rotaryEnd = endAngleRadians;
  39814. rotaryStop = stopAtEnd;
  39815. }
  39816. void Slider::setVelocityBasedMode (const bool velBased)
  39817. {
  39818. isVelocityBased = velBased;
  39819. }
  39820. void Slider::setVelocityModeParameters (const double sensitivity,
  39821. const int threshold,
  39822. const double offset,
  39823. const bool userCanPressKeyToSwapMode)
  39824. {
  39825. jassert (threshold >= 0);
  39826. jassert (sensitivity > 0);
  39827. jassert (offset >= 0);
  39828. velocityModeSensitivity = sensitivity;
  39829. velocityModeOffset = offset;
  39830. velocityModeThreshold = threshold;
  39831. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39832. }
  39833. void Slider::setSkewFactor (const double factor)
  39834. {
  39835. skewFactor = factor;
  39836. }
  39837. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39838. {
  39839. if (maximum > minimum)
  39840. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39841. / (maximum - minimum));
  39842. }
  39843. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39844. {
  39845. jassert (distanceForFullScaleDrag > 0);
  39846. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39847. }
  39848. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39849. {
  39850. if (incDecButtonMode != mode)
  39851. {
  39852. incDecButtonMode = mode;
  39853. lookAndFeelChanged();
  39854. }
  39855. }
  39856. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39857. const bool isReadOnly,
  39858. const int textEntryBoxWidth,
  39859. const int textEntryBoxHeight)
  39860. {
  39861. if (textBoxPos != newPosition
  39862. || editableText != (! isReadOnly)
  39863. || textBoxWidth != textEntryBoxWidth
  39864. || textBoxHeight != textEntryBoxHeight)
  39865. {
  39866. textBoxPos = newPosition;
  39867. editableText = ! isReadOnly;
  39868. textBoxWidth = textEntryBoxWidth;
  39869. textBoxHeight = textEntryBoxHeight;
  39870. repaint();
  39871. lookAndFeelChanged();
  39872. }
  39873. }
  39874. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39875. {
  39876. editableText = shouldBeEditable;
  39877. if (valueBox != 0)
  39878. valueBox->setEditable (shouldBeEditable && isEnabled());
  39879. }
  39880. void Slider::showTextBox()
  39881. {
  39882. jassert (editableText); // this should probably be avoided in read-only sliders.
  39883. if (valueBox != 0)
  39884. valueBox->showEditor();
  39885. }
  39886. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39887. {
  39888. if (valueBox != 0)
  39889. {
  39890. valueBox->hideEditor (discardCurrentEditorContents);
  39891. if (discardCurrentEditorContents)
  39892. updateText();
  39893. }
  39894. }
  39895. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39896. {
  39897. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39898. }
  39899. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39900. {
  39901. snapsToMousePos = shouldSnapToMouse;
  39902. }
  39903. void Slider::setPopupDisplayEnabled (const bool enabled,
  39904. Component* const parentComponentToUse)
  39905. {
  39906. popupDisplayEnabled = enabled;
  39907. parentForPopupDisplay = parentComponentToUse;
  39908. }
  39909. void Slider::colourChanged()
  39910. {
  39911. lookAndFeelChanged();
  39912. }
  39913. void Slider::lookAndFeelChanged()
  39914. {
  39915. LookAndFeel& lf = getLookAndFeel();
  39916. if (textBoxPos != NoTextBox)
  39917. {
  39918. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39919. : getTextFromValue (currentValue.getValue()));
  39920. valueBox = 0;
  39921. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39922. valueBox->setWantsKeyboardFocus (false);
  39923. valueBox->setText (previousTextBoxContent, false);
  39924. valueBox->setEditable (editableText && isEnabled());
  39925. valueBox->addListener (this);
  39926. if (style == LinearBar)
  39927. valueBox->addMouseListener (this, false);
  39928. valueBox->setTooltip (getTooltip());
  39929. }
  39930. else
  39931. {
  39932. valueBox = 0;
  39933. }
  39934. if (style == IncDecButtons)
  39935. {
  39936. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39937. incButton->addListener (this);
  39938. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39939. decButton->addListener (this);
  39940. if (incDecButtonMode != incDecButtonsNotDraggable)
  39941. {
  39942. incButton->addMouseListener (this, false);
  39943. decButton->addMouseListener (this, false);
  39944. }
  39945. else
  39946. {
  39947. incButton->setRepeatSpeed (300, 100, 20);
  39948. incButton->addMouseListener (decButton, false);
  39949. decButton->setRepeatSpeed (300, 100, 20);
  39950. decButton->addMouseListener (incButton, false);
  39951. }
  39952. incButton->setTooltip (getTooltip());
  39953. decButton->setTooltip (getTooltip());
  39954. }
  39955. else
  39956. {
  39957. incButton = 0;
  39958. decButton = 0;
  39959. }
  39960. setComponentEffect (lf.getSliderEffect());
  39961. resized();
  39962. repaint();
  39963. }
  39964. void Slider::setRange (const double newMin,
  39965. const double newMax,
  39966. const double newInt)
  39967. {
  39968. if (minimum != newMin
  39969. || maximum != newMax
  39970. || interval != newInt)
  39971. {
  39972. minimum = newMin;
  39973. maximum = newMax;
  39974. interval = newInt;
  39975. // figure out the number of DPs needed to display all values at this
  39976. // interval setting.
  39977. numDecimalPlaces = 7;
  39978. if (newInt != 0)
  39979. {
  39980. int v = abs ((int) (newInt * 10000000));
  39981. while ((v % 10) == 0)
  39982. {
  39983. --numDecimalPlaces;
  39984. v /= 10;
  39985. }
  39986. }
  39987. // keep the current values inside the new range..
  39988. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39989. {
  39990. setValue (getValue(), false, false);
  39991. }
  39992. else
  39993. {
  39994. setMinValue (getMinValue(), false, false);
  39995. setMaxValue (getMaxValue(), false, false);
  39996. }
  39997. updateText();
  39998. }
  39999. }
  40000. void Slider::triggerChangeMessage (const bool synchronous)
  40001. {
  40002. if (synchronous)
  40003. handleAsyncUpdate();
  40004. else
  40005. triggerAsyncUpdate();
  40006. valueChanged();
  40007. }
  40008. void Slider::valueChanged (Value& value)
  40009. {
  40010. if (value.refersToSameSourceAs (currentValue))
  40011. {
  40012. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40013. setValue (currentValue.getValue(), false, false);
  40014. }
  40015. else if (value.refersToSameSourceAs (valueMin))
  40016. setMinValue (valueMin.getValue(), false, false, true);
  40017. else if (value.refersToSameSourceAs (valueMax))
  40018. setMaxValue (valueMax.getValue(), false, false, true);
  40019. }
  40020. double Slider::getValue() const
  40021. {
  40022. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40023. // methods to get the two values.
  40024. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40025. return currentValue.getValue();
  40026. }
  40027. void Slider::setValue (double newValue,
  40028. const bool sendUpdateMessage,
  40029. const bool sendMessageSynchronously)
  40030. {
  40031. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40032. // methods to set the two values.
  40033. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40034. newValue = constrainedValue (newValue);
  40035. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40036. {
  40037. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40038. newValue = jlimit ((double) valueMin.getValue(),
  40039. (double) valueMax.getValue(),
  40040. newValue);
  40041. }
  40042. if (newValue != lastCurrentValue)
  40043. {
  40044. if (valueBox != 0)
  40045. valueBox->hideEditor (true);
  40046. lastCurrentValue = newValue;
  40047. currentValue = newValue;
  40048. updateText();
  40049. repaint();
  40050. if (popupDisplay != 0)
  40051. {
  40052. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40053. ->updatePosition (getTextFromValue (newValue));
  40054. popupDisplay->repaint();
  40055. }
  40056. if (sendUpdateMessage)
  40057. triggerChangeMessage (sendMessageSynchronously);
  40058. }
  40059. }
  40060. double Slider::getMinValue() const
  40061. {
  40062. // The minimum value only applies to sliders that are in two- or three-value mode.
  40063. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40064. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40065. return valueMin.getValue();
  40066. }
  40067. double Slider::getMaxValue() const
  40068. {
  40069. // The maximum value only applies to sliders that are in two- or three-value mode.
  40070. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40071. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40072. return valueMax.getValue();
  40073. }
  40074. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40075. {
  40076. // The minimum value only applies to sliders that are in two- or three-value mode.
  40077. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40078. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40079. newValue = constrainedValue (newValue);
  40080. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40081. {
  40082. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40083. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40084. newValue = jmin ((double) valueMax.getValue(), newValue);
  40085. }
  40086. else
  40087. {
  40088. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40089. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40090. newValue = jmin (lastCurrentValue, newValue);
  40091. }
  40092. if (lastValueMin != newValue)
  40093. {
  40094. lastValueMin = newValue;
  40095. valueMin = newValue;
  40096. repaint();
  40097. if (popupDisplay != 0)
  40098. {
  40099. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40100. ->updatePosition (getTextFromValue (newValue));
  40101. popupDisplay->repaint();
  40102. }
  40103. if (sendUpdateMessage)
  40104. triggerChangeMessage (sendMessageSynchronously);
  40105. }
  40106. }
  40107. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40108. {
  40109. // The maximum value only applies to sliders that are in two- or three-value mode.
  40110. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40111. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40112. newValue = constrainedValue (newValue);
  40113. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40114. {
  40115. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40116. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40117. newValue = jmax ((double) valueMin.getValue(), newValue);
  40118. }
  40119. else
  40120. {
  40121. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40122. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40123. newValue = jmax (lastCurrentValue, newValue);
  40124. }
  40125. if (lastValueMax != newValue)
  40126. {
  40127. lastValueMax = newValue;
  40128. valueMax = newValue;
  40129. repaint();
  40130. if (popupDisplay != 0)
  40131. {
  40132. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40133. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40134. popupDisplay->repaint();
  40135. }
  40136. if (sendUpdateMessage)
  40137. triggerChangeMessage (sendMessageSynchronously);
  40138. }
  40139. }
  40140. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40141. const double valueToSetOnDoubleClick)
  40142. {
  40143. doubleClickToValue = isDoubleClickEnabled;
  40144. doubleClickReturnValue = valueToSetOnDoubleClick;
  40145. }
  40146. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40147. {
  40148. isEnabled_ = doubleClickToValue;
  40149. return doubleClickReturnValue;
  40150. }
  40151. void Slider::updateText()
  40152. {
  40153. if (valueBox != 0)
  40154. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40155. }
  40156. void Slider::setTextValueSuffix (const String& suffix)
  40157. {
  40158. if (textSuffix != suffix)
  40159. {
  40160. textSuffix = suffix;
  40161. updateText();
  40162. }
  40163. }
  40164. const String Slider::getTextValueSuffix() const
  40165. {
  40166. return textSuffix;
  40167. }
  40168. const String Slider::getTextFromValue (double v)
  40169. {
  40170. if (getNumDecimalPlacesToDisplay() > 0)
  40171. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40172. else
  40173. return String (roundToInt (v)) + getTextValueSuffix();
  40174. }
  40175. double Slider::getValueFromText (const String& text)
  40176. {
  40177. String t (text.trimStart());
  40178. if (t.endsWith (textSuffix))
  40179. t = t.substring (0, t.length() - textSuffix.length());
  40180. while (t.startsWithChar ('+'))
  40181. t = t.substring (1).trimStart();
  40182. return t.initialSectionContainingOnly ("0123456789.,-")
  40183. .getDoubleValue();
  40184. }
  40185. double Slider::proportionOfLengthToValue (double proportion)
  40186. {
  40187. if (skewFactor != 1.0 && proportion > 0.0)
  40188. proportion = exp (log (proportion) / skewFactor);
  40189. return minimum + (maximum - minimum) * proportion;
  40190. }
  40191. double Slider::valueToProportionOfLength (double value)
  40192. {
  40193. const double n = (value - minimum) / (maximum - minimum);
  40194. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40195. }
  40196. double Slider::snapValue (double attemptedValue, const bool)
  40197. {
  40198. return attemptedValue;
  40199. }
  40200. void Slider::startedDragging()
  40201. {
  40202. }
  40203. void Slider::stoppedDragging()
  40204. {
  40205. }
  40206. void Slider::valueChanged()
  40207. {
  40208. }
  40209. void Slider::enablementChanged()
  40210. {
  40211. repaint();
  40212. }
  40213. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40214. {
  40215. menuEnabled = menuEnabled_;
  40216. }
  40217. void Slider::setScrollWheelEnabled (const bool enabled)
  40218. {
  40219. scrollWheelEnabled = enabled;
  40220. }
  40221. void Slider::labelTextChanged (Label* label)
  40222. {
  40223. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40224. if (newValue != (double) currentValue.getValue())
  40225. {
  40226. sendDragStart();
  40227. setValue (newValue, true, true);
  40228. sendDragEnd();
  40229. }
  40230. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40231. }
  40232. void Slider::buttonClicked (Button* button)
  40233. {
  40234. if (style == IncDecButtons)
  40235. {
  40236. sendDragStart();
  40237. if (button == incButton)
  40238. setValue (snapValue (getValue() + interval, false), true, true);
  40239. else if (button == decButton)
  40240. setValue (snapValue (getValue() - interval, false), true, true);
  40241. sendDragEnd();
  40242. }
  40243. }
  40244. double Slider::constrainedValue (double value) const
  40245. {
  40246. if (interval > 0)
  40247. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40248. if (value <= minimum || maximum <= minimum)
  40249. value = minimum;
  40250. else if (value >= maximum)
  40251. value = maximum;
  40252. return value;
  40253. }
  40254. float Slider::getLinearSliderPos (const double value)
  40255. {
  40256. double sliderPosProportional;
  40257. if (maximum > minimum)
  40258. {
  40259. if (value < minimum)
  40260. {
  40261. sliderPosProportional = 0.0;
  40262. }
  40263. else if (value > maximum)
  40264. {
  40265. sliderPosProportional = 1.0;
  40266. }
  40267. else
  40268. {
  40269. sliderPosProportional = valueToProportionOfLength (value);
  40270. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40271. }
  40272. }
  40273. else
  40274. {
  40275. sliderPosProportional = 0.5;
  40276. }
  40277. if (isVertical() || style == IncDecButtons)
  40278. sliderPosProportional = 1.0 - sliderPosProportional;
  40279. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40280. }
  40281. bool Slider::isHorizontal() const
  40282. {
  40283. return style == LinearHorizontal
  40284. || style == LinearBar
  40285. || style == TwoValueHorizontal
  40286. || style == ThreeValueHorizontal;
  40287. }
  40288. bool Slider::isVertical() const
  40289. {
  40290. return style == LinearVertical
  40291. || style == TwoValueVertical
  40292. || style == ThreeValueVertical;
  40293. }
  40294. bool Slider::incDecDragDirectionIsHorizontal() const
  40295. {
  40296. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40297. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40298. }
  40299. float Slider::getPositionOfValue (const double value)
  40300. {
  40301. if (isHorizontal() || isVertical())
  40302. {
  40303. return getLinearSliderPos (value);
  40304. }
  40305. else
  40306. {
  40307. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40308. return 0.0f;
  40309. }
  40310. }
  40311. void Slider::paint (Graphics& g)
  40312. {
  40313. if (style != IncDecButtons)
  40314. {
  40315. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40316. {
  40317. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40318. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40319. getLookAndFeel().drawRotarySlider (g,
  40320. sliderRect.getX(),
  40321. sliderRect.getY(),
  40322. sliderRect.getWidth(),
  40323. sliderRect.getHeight(),
  40324. sliderPos,
  40325. rotaryStart, rotaryEnd,
  40326. *this);
  40327. }
  40328. else
  40329. {
  40330. getLookAndFeel().drawLinearSlider (g,
  40331. sliderRect.getX(),
  40332. sliderRect.getY(),
  40333. sliderRect.getWidth(),
  40334. sliderRect.getHeight(),
  40335. getLinearSliderPos (lastCurrentValue),
  40336. getLinearSliderPos (lastValueMin),
  40337. getLinearSliderPos (lastValueMax),
  40338. style,
  40339. *this);
  40340. }
  40341. if (style == LinearBar && valueBox == 0)
  40342. {
  40343. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40344. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40345. }
  40346. }
  40347. }
  40348. void Slider::resized()
  40349. {
  40350. int minXSpace = 0;
  40351. int minYSpace = 0;
  40352. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40353. minXSpace = 30;
  40354. else
  40355. minYSpace = 15;
  40356. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40357. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40358. if (style == LinearBar)
  40359. {
  40360. if (valueBox != 0)
  40361. valueBox->setBounds (getLocalBounds());
  40362. }
  40363. else
  40364. {
  40365. if (textBoxPos == NoTextBox)
  40366. {
  40367. sliderRect = getLocalBounds();
  40368. }
  40369. else if (textBoxPos == TextBoxLeft)
  40370. {
  40371. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40372. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40373. }
  40374. else if (textBoxPos == TextBoxRight)
  40375. {
  40376. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40377. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40378. }
  40379. else if (textBoxPos == TextBoxAbove)
  40380. {
  40381. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40382. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40383. }
  40384. else if (textBoxPos == TextBoxBelow)
  40385. {
  40386. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40387. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40388. }
  40389. }
  40390. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40391. if (style == LinearBar)
  40392. {
  40393. const int barIndent = 1;
  40394. sliderRegionStart = barIndent;
  40395. sliderRegionSize = getWidth() - barIndent * 2;
  40396. sliderRect.setBounds (sliderRegionStart, barIndent,
  40397. sliderRegionSize, getHeight() - barIndent * 2);
  40398. }
  40399. else if (isHorizontal())
  40400. {
  40401. sliderRegionStart = sliderRect.getX() + indent;
  40402. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40403. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40404. sliderRegionSize, sliderRect.getHeight());
  40405. }
  40406. else if (isVertical())
  40407. {
  40408. sliderRegionStart = sliderRect.getY() + indent;
  40409. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40410. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40411. sliderRect.getWidth(), sliderRegionSize);
  40412. }
  40413. else
  40414. {
  40415. sliderRegionStart = 0;
  40416. sliderRegionSize = 100;
  40417. }
  40418. if (style == IncDecButtons)
  40419. {
  40420. Rectangle<int> buttonRect (sliderRect);
  40421. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40422. buttonRect.expand (-2, 0);
  40423. else
  40424. buttonRect.expand (0, -2);
  40425. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40426. if (incDecButtonsSideBySide)
  40427. {
  40428. decButton->setBounds (buttonRect.getX(),
  40429. buttonRect.getY(),
  40430. buttonRect.getWidth() / 2,
  40431. buttonRect.getHeight());
  40432. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40433. incButton->setBounds (buttonRect.getCentreX(),
  40434. buttonRect.getY(),
  40435. buttonRect.getWidth() / 2,
  40436. buttonRect.getHeight());
  40437. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40438. }
  40439. else
  40440. {
  40441. incButton->setBounds (buttonRect.getX(),
  40442. buttonRect.getY(),
  40443. buttonRect.getWidth(),
  40444. buttonRect.getHeight() / 2);
  40445. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40446. decButton->setBounds (buttonRect.getX(),
  40447. buttonRect.getCentreY(),
  40448. buttonRect.getWidth(),
  40449. buttonRect.getHeight() / 2);
  40450. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40451. }
  40452. }
  40453. }
  40454. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40455. {
  40456. repaint();
  40457. }
  40458. void Slider::mouseDown (const MouseEvent& e)
  40459. {
  40460. mouseWasHidden = false;
  40461. incDecDragged = false;
  40462. mouseXWhenLastDragged = e.x;
  40463. mouseYWhenLastDragged = e.y;
  40464. mouseDragStartX = e.getMouseDownX();
  40465. mouseDragStartY = e.getMouseDownY();
  40466. if (isEnabled())
  40467. {
  40468. if (e.mods.isPopupMenu() && menuEnabled)
  40469. {
  40470. menuShown = true;
  40471. PopupMenu m;
  40472. m.setLookAndFeel (&getLookAndFeel());
  40473. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40474. m.addSeparator();
  40475. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40476. {
  40477. PopupMenu rotaryMenu;
  40478. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40479. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40480. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40481. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40482. }
  40483. const int r = m.show();
  40484. if (r == 1)
  40485. {
  40486. setVelocityBasedMode (! isVelocityBased);
  40487. }
  40488. else if (r == 2)
  40489. {
  40490. setSliderStyle (Rotary);
  40491. }
  40492. else if (r == 3)
  40493. {
  40494. setSliderStyle (RotaryHorizontalDrag);
  40495. }
  40496. else if (r == 4)
  40497. {
  40498. setSliderStyle (RotaryVerticalDrag);
  40499. }
  40500. }
  40501. else if (maximum > minimum)
  40502. {
  40503. menuShown = false;
  40504. if (valueBox != 0)
  40505. valueBox->hideEditor (true);
  40506. sliderBeingDragged = 0;
  40507. if (style == TwoValueHorizontal
  40508. || style == TwoValueVertical
  40509. || style == ThreeValueHorizontal
  40510. || style == ThreeValueVertical)
  40511. {
  40512. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40513. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40514. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40515. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40516. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40517. {
  40518. if (maxPosDistance <= minPosDistance)
  40519. sliderBeingDragged = 2;
  40520. else
  40521. sliderBeingDragged = 1;
  40522. }
  40523. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40524. {
  40525. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40526. sliderBeingDragged = 1;
  40527. else if (normalPosDistance >= maxPosDistance)
  40528. sliderBeingDragged = 2;
  40529. }
  40530. }
  40531. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40532. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40533. * valueToProportionOfLength (currentValue.getValue());
  40534. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40535. : ((sliderBeingDragged == 1) ? valueMin
  40536. : currentValue)).getValue();
  40537. valueOnMouseDown = valueWhenLastDragged;
  40538. if (popupDisplayEnabled)
  40539. {
  40540. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40541. popupDisplay = popup;
  40542. if (parentForPopupDisplay != 0)
  40543. {
  40544. parentForPopupDisplay->addChildComponent (popup);
  40545. }
  40546. else
  40547. {
  40548. popup->addToDesktop (0);
  40549. }
  40550. popup->setVisible (true);
  40551. }
  40552. sendDragStart();
  40553. mouseDrag (e);
  40554. }
  40555. }
  40556. }
  40557. void Slider::mouseUp (const MouseEvent&)
  40558. {
  40559. if (isEnabled()
  40560. && (! menuShown)
  40561. && (maximum > minimum)
  40562. && (style != IncDecButtons || incDecDragged))
  40563. {
  40564. restoreMouseIfHidden();
  40565. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40566. triggerChangeMessage (false);
  40567. sendDragEnd();
  40568. popupDisplay = 0;
  40569. if (style == IncDecButtons)
  40570. {
  40571. incButton->setState (Button::buttonNormal);
  40572. decButton->setState (Button::buttonNormal);
  40573. }
  40574. }
  40575. }
  40576. void Slider::restoreMouseIfHidden()
  40577. {
  40578. if (mouseWasHidden)
  40579. {
  40580. mouseWasHidden = false;
  40581. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40582. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40583. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40584. : ((sliderBeingDragged == 1) ? getMinValue()
  40585. : (double) currentValue.getValue());
  40586. Point<int> mousePos;
  40587. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40588. {
  40589. mousePos = Desktop::getLastMouseDownPosition();
  40590. if (style == RotaryHorizontalDrag)
  40591. {
  40592. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40593. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40594. }
  40595. else
  40596. {
  40597. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40598. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40599. }
  40600. }
  40601. else
  40602. {
  40603. const int pixelPos = (int) getLinearSliderPos (pos);
  40604. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40605. isVertical() ? pixelPos : (getHeight() / 2)));
  40606. }
  40607. Desktop::setMousePosition (mousePos);
  40608. }
  40609. }
  40610. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40611. {
  40612. if (isEnabled()
  40613. && style != IncDecButtons
  40614. && style != Rotary
  40615. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40616. {
  40617. restoreMouseIfHidden();
  40618. }
  40619. }
  40620. namespace SliderHelpers
  40621. {
  40622. double smallestAngleBetween (double a1, double a2) throw()
  40623. {
  40624. return jmin (std::abs (a1 - a2),
  40625. std::abs (a1 + double_Pi * 2.0 - a2),
  40626. std::abs (a2 + double_Pi * 2.0 - a1));
  40627. }
  40628. }
  40629. void Slider::mouseDrag (const MouseEvent& e)
  40630. {
  40631. if (isEnabled()
  40632. && (! menuShown)
  40633. && (maximum > minimum))
  40634. {
  40635. if (style == Rotary)
  40636. {
  40637. int dx = e.x - sliderRect.getCentreX();
  40638. int dy = e.y - sliderRect.getCentreY();
  40639. if (dx * dx + dy * dy > 25)
  40640. {
  40641. double angle = std::atan2 ((double) dx, (double) -dy);
  40642. while (angle < 0.0)
  40643. angle += double_Pi * 2.0;
  40644. if (rotaryStop && ! e.mouseWasClicked())
  40645. {
  40646. if (std::abs (angle - lastAngle) > double_Pi)
  40647. {
  40648. if (angle >= lastAngle)
  40649. angle -= double_Pi * 2.0;
  40650. else
  40651. angle += double_Pi * 2.0;
  40652. }
  40653. if (angle >= lastAngle)
  40654. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40655. else
  40656. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40657. }
  40658. else
  40659. {
  40660. while (angle < rotaryStart)
  40661. angle += double_Pi * 2.0;
  40662. if (angle > rotaryEnd)
  40663. {
  40664. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40665. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40666. angle = rotaryStart;
  40667. else
  40668. angle = rotaryEnd;
  40669. }
  40670. }
  40671. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40672. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40673. lastAngle = angle;
  40674. }
  40675. }
  40676. else
  40677. {
  40678. if (style == LinearBar && e.mouseWasClicked()
  40679. && valueBox != 0 && valueBox->isEditable())
  40680. return;
  40681. if (style == IncDecButtons && ! incDecDragged)
  40682. {
  40683. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40684. return;
  40685. incDecDragged = true;
  40686. mouseDragStartX = e.x;
  40687. mouseDragStartY = e.y;
  40688. }
  40689. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40690. : false))
  40691. || ((maximum - minimum) / sliderRegionSize < interval))
  40692. {
  40693. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40694. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40695. if (style == RotaryHorizontalDrag
  40696. || style == RotaryVerticalDrag
  40697. || style == IncDecButtons
  40698. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40699. && ! snapsToMousePos))
  40700. {
  40701. const int mouseDiff = (style == RotaryHorizontalDrag
  40702. || style == LinearHorizontal
  40703. || style == LinearBar
  40704. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40705. ? e.x - mouseDragStartX
  40706. : mouseDragStartY - e.y;
  40707. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40708. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40709. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40710. if (style == IncDecButtons)
  40711. {
  40712. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40713. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40714. }
  40715. }
  40716. else
  40717. {
  40718. if (isVertical())
  40719. scaledMousePos = 1.0 - scaledMousePos;
  40720. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40721. }
  40722. }
  40723. else
  40724. {
  40725. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40726. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40727. ? e.x - mouseXWhenLastDragged
  40728. : e.y - mouseYWhenLastDragged;
  40729. const double maxSpeed = jmax (200, sliderRegionSize);
  40730. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40731. if (speed != 0)
  40732. {
  40733. speed = 0.2 * velocityModeSensitivity
  40734. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40735. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40736. / maxSpeed))));
  40737. if (mouseDiff < 0)
  40738. speed = -speed;
  40739. if (isVertical() || style == RotaryVerticalDrag
  40740. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40741. speed = -speed;
  40742. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40743. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40744. e.source.enableUnboundedMouseMovement (true, false);
  40745. mouseWasHidden = true;
  40746. }
  40747. }
  40748. }
  40749. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40750. if (sliderBeingDragged == 0)
  40751. {
  40752. setValue (snapValue (valueWhenLastDragged, true),
  40753. ! sendChangeOnlyOnRelease, true);
  40754. }
  40755. else if (sliderBeingDragged == 1)
  40756. {
  40757. setMinValue (snapValue (valueWhenLastDragged, true),
  40758. ! sendChangeOnlyOnRelease, false, true);
  40759. if (e.mods.isShiftDown())
  40760. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40761. else
  40762. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40763. }
  40764. else
  40765. {
  40766. jassert (sliderBeingDragged == 2);
  40767. setMaxValue (snapValue (valueWhenLastDragged, true),
  40768. ! sendChangeOnlyOnRelease, false, true);
  40769. if (e.mods.isShiftDown())
  40770. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40771. else
  40772. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40773. }
  40774. mouseXWhenLastDragged = e.x;
  40775. mouseYWhenLastDragged = e.y;
  40776. }
  40777. }
  40778. void Slider::mouseDoubleClick (const MouseEvent&)
  40779. {
  40780. if (doubleClickToValue
  40781. && isEnabled()
  40782. && style != IncDecButtons
  40783. && minimum <= doubleClickReturnValue
  40784. && maximum >= doubleClickReturnValue)
  40785. {
  40786. sendDragStart();
  40787. setValue (doubleClickReturnValue, true, true);
  40788. sendDragEnd();
  40789. }
  40790. }
  40791. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40792. {
  40793. if (scrollWheelEnabled && isEnabled()
  40794. && style != TwoValueHorizontal
  40795. && style != TwoValueVertical)
  40796. {
  40797. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40798. {
  40799. if (valueBox != 0)
  40800. valueBox->hideEditor (false);
  40801. const double value = (double) currentValue.getValue();
  40802. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40803. const double currentPos = valueToProportionOfLength (value);
  40804. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40805. double delta = (newValue != value)
  40806. ? jmax (std::abs (newValue - value), interval) : 0;
  40807. if (value > newValue)
  40808. delta = -delta;
  40809. sendDragStart();
  40810. setValue (snapValue (value + delta, false), true, true);
  40811. sendDragEnd();
  40812. }
  40813. }
  40814. else
  40815. {
  40816. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40817. }
  40818. }
  40819. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40820. {
  40821. }
  40822. void SliderListener::sliderDragEnded (Slider*)
  40823. {
  40824. }
  40825. END_JUCE_NAMESPACE
  40826. /*** End of inlined file: juce_Slider.cpp ***/
  40827. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40828. BEGIN_JUCE_NAMESPACE
  40829. class DragOverlayComp : public Component
  40830. {
  40831. public:
  40832. DragOverlayComp (const Image& image_)
  40833. : image (image_)
  40834. {
  40835. image.duplicateIfShared();
  40836. image.multiplyAllAlphas (0.8f);
  40837. setAlwaysOnTop (true);
  40838. }
  40839. void paint (Graphics& g)
  40840. {
  40841. g.drawImageAt (image, 0, 0);
  40842. }
  40843. private:
  40844. Image image;
  40845. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40846. };
  40847. TableHeaderComponent::TableHeaderComponent()
  40848. : columnsChanged (false),
  40849. columnsResized (false),
  40850. sortChanged (false),
  40851. menuActive (true),
  40852. stretchToFit (false),
  40853. columnIdBeingResized (0),
  40854. columnIdBeingDragged (0),
  40855. columnIdUnderMouse (0),
  40856. lastDeliberateWidth (0)
  40857. {
  40858. }
  40859. TableHeaderComponent::~TableHeaderComponent()
  40860. {
  40861. dragOverlayComp = 0;
  40862. }
  40863. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40864. {
  40865. menuActive = hasMenu;
  40866. }
  40867. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40868. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40869. {
  40870. if (onlyCountVisibleColumns)
  40871. {
  40872. int num = 0;
  40873. for (int i = columns.size(); --i >= 0;)
  40874. if (columns.getUnchecked(i)->isVisible())
  40875. ++num;
  40876. return num;
  40877. }
  40878. else
  40879. {
  40880. return columns.size();
  40881. }
  40882. }
  40883. const String TableHeaderComponent::getColumnName (const int columnId) const
  40884. {
  40885. const ColumnInfo* const ci = getInfoForId (columnId);
  40886. return ci != 0 ? ci->name : String::empty;
  40887. }
  40888. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40889. {
  40890. ColumnInfo* const ci = getInfoForId (columnId);
  40891. if (ci != 0 && ci->name != newName)
  40892. {
  40893. ci->name = newName;
  40894. sendColumnsChanged();
  40895. }
  40896. }
  40897. void TableHeaderComponent::addColumn (const String& columnName,
  40898. const int columnId,
  40899. const int width,
  40900. const int minimumWidth,
  40901. const int maximumWidth,
  40902. const int propertyFlags,
  40903. const int insertIndex)
  40904. {
  40905. // can't have a duplicate or null ID!
  40906. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40907. jassert (width > 0);
  40908. ColumnInfo* const ci = new ColumnInfo();
  40909. ci->name = columnName;
  40910. ci->id = columnId;
  40911. ci->width = width;
  40912. ci->lastDeliberateWidth = width;
  40913. ci->minimumWidth = minimumWidth;
  40914. ci->maximumWidth = maximumWidth;
  40915. if (ci->maximumWidth < 0)
  40916. ci->maximumWidth = std::numeric_limits<int>::max();
  40917. jassert (ci->maximumWidth >= ci->minimumWidth);
  40918. ci->propertyFlags = propertyFlags;
  40919. columns.insert (insertIndex, ci);
  40920. sendColumnsChanged();
  40921. }
  40922. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40923. {
  40924. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40925. if (index >= 0)
  40926. {
  40927. columns.remove (index);
  40928. sortChanged = true;
  40929. sendColumnsChanged();
  40930. }
  40931. }
  40932. void TableHeaderComponent::removeAllColumns()
  40933. {
  40934. if (columns.size() > 0)
  40935. {
  40936. columns.clear();
  40937. sendColumnsChanged();
  40938. }
  40939. }
  40940. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40941. {
  40942. const int currentIndex = getIndexOfColumnId (columnId, false);
  40943. newIndex = visibleIndexToTotalIndex (newIndex);
  40944. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40945. {
  40946. columns.move (currentIndex, newIndex);
  40947. sendColumnsChanged();
  40948. }
  40949. }
  40950. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40951. {
  40952. const ColumnInfo* const ci = getInfoForId (columnId);
  40953. return ci != 0 ? ci->width : 0;
  40954. }
  40955. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40956. {
  40957. ColumnInfo* const ci = getInfoForId (columnId);
  40958. if (ci != 0 && ci->width != newWidth)
  40959. {
  40960. const int numColumns = getNumColumns (true);
  40961. ci->lastDeliberateWidth = ci->width
  40962. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40963. if (stretchToFit)
  40964. {
  40965. const int index = getIndexOfColumnId (columnId, true) + 1;
  40966. if (isPositiveAndBelow (index, numColumns))
  40967. {
  40968. const int x = getColumnPosition (index).getX();
  40969. if (lastDeliberateWidth == 0)
  40970. lastDeliberateWidth = getTotalWidth();
  40971. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40972. }
  40973. }
  40974. repaint();
  40975. columnsResized = true;
  40976. triggerAsyncUpdate();
  40977. }
  40978. }
  40979. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40980. {
  40981. int n = 0;
  40982. for (int i = 0; i < columns.size(); ++i)
  40983. {
  40984. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40985. {
  40986. if (columns.getUnchecked(i)->id == columnId)
  40987. return n;
  40988. ++n;
  40989. }
  40990. }
  40991. return -1;
  40992. }
  40993. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40994. {
  40995. if (onlyCountVisibleColumns)
  40996. index = visibleIndexToTotalIndex (index);
  40997. const ColumnInfo* const ci = columns [index];
  40998. return (ci != 0) ? ci->id : 0;
  40999. }
  41000. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41001. {
  41002. int x = 0, width = 0, n = 0;
  41003. for (int i = 0; i < columns.size(); ++i)
  41004. {
  41005. x += width;
  41006. if (columns.getUnchecked(i)->isVisible())
  41007. {
  41008. width = columns.getUnchecked(i)->width;
  41009. if (n++ == index)
  41010. break;
  41011. }
  41012. else
  41013. {
  41014. width = 0;
  41015. }
  41016. }
  41017. return Rectangle<int> (x, 0, width, getHeight());
  41018. }
  41019. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41020. {
  41021. if (xToFind >= 0)
  41022. {
  41023. int x = 0;
  41024. for (int i = 0; i < columns.size(); ++i)
  41025. {
  41026. const ColumnInfo* const ci = columns.getUnchecked(i);
  41027. if (ci->isVisible())
  41028. {
  41029. x += ci->width;
  41030. if (xToFind < x)
  41031. return ci->id;
  41032. }
  41033. }
  41034. }
  41035. return 0;
  41036. }
  41037. int TableHeaderComponent::getTotalWidth() const
  41038. {
  41039. int w = 0;
  41040. for (int i = columns.size(); --i >= 0;)
  41041. if (columns.getUnchecked(i)->isVisible())
  41042. w += columns.getUnchecked(i)->width;
  41043. return w;
  41044. }
  41045. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41046. {
  41047. stretchToFit = shouldStretchToFit;
  41048. lastDeliberateWidth = getTotalWidth();
  41049. resized();
  41050. }
  41051. bool TableHeaderComponent::isStretchToFitActive() const
  41052. {
  41053. return stretchToFit;
  41054. }
  41055. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41056. {
  41057. if (stretchToFit && getWidth() > 0
  41058. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41059. {
  41060. lastDeliberateWidth = targetTotalWidth;
  41061. resizeColumnsToFit (0, targetTotalWidth);
  41062. }
  41063. }
  41064. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41065. {
  41066. targetTotalWidth = jmax (targetTotalWidth, 0);
  41067. StretchableObjectResizer sor;
  41068. int i;
  41069. for (i = firstColumnIndex; i < columns.size(); ++i)
  41070. {
  41071. ColumnInfo* const ci = columns.getUnchecked(i);
  41072. if (ci->isVisible())
  41073. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41074. }
  41075. sor.resizeToFit (targetTotalWidth);
  41076. int visIndex = 0;
  41077. for (i = firstColumnIndex; i < columns.size(); ++i)
  41078. {
  41079. ColumnInfo* const ci = columns.getUnchecked(i);
  41080. if (ci->isVisible())
  41081. {
  41082. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41083. (int) std::floor (sor.getItemSize (visIndex++)));
  41084. if (newWidth != ci->width)
  41085. {
  41086. ci->width = newWidth;
  41087. repaint();
  41088. columnsResized = true;
  41089. triggerAsyncUpdate();
  41090. }
  41091. }
  41092. }
  41093. }
  41094. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41095. {
  41096. ColumnInfo* const ci = getInfoForId (columnId);
  41097. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41098. {
  41099. if (shouldBeVisible)
  41100. ci->propertyFlags |= visible;
  41101. else
  41102. ci->propertyFlags &= ~visible;
  41103. sendColumnsChanged();
  41104. resized();
  41105. }
  41106. }
  41107. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41108. {
  41109. const ColumnInfo* const ci = getInfoForId (columnId);
  41110. return ci != 0 && ci->isVisible();
  41111. }
  41112. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41113. {
  41114. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41115. {
  41116. for (int i = columns.size(); --i >= 0;)
  41117. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41118. ColumnInfo* const ci = getInfoForId (columnId);
  41119. if (ci != 0)
  41120. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41121. reSortTable();
  41122. }
  41123. }
  41124. int TableHeaderComponent::getSortColumnId() const
  41125. {
  41126. for (int i = columns.size(); --i >= 0;)
  41127. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41128. return columns.getUnchecked(i)->id;
  41129. return 0;
  41130. }
  41131. bool TableHeaderComponent::isSortedForwards() const
  41132. {
  41133. for (int i = columns.size(); --i >= 0;)
  41134. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41135. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41136. return true;
  41137. }
  41138. void TableHeaderComponent::reSortTable()
  41139. {
  41140. sortChanged = true;
  41141. repaint();
  41142. triggerAsyncUpdate();
  41143. }
  41144. const String TableHeaderComponent::toString() const
  41145. {
  41146. String s;
  41147. XmlElement doc ("TABLELAYOUT");
  41148. doc.setAttribute ("sortedCol", getSortColumnId());
  41149. doc.setAttribute ("sortForwards", isSortedForwards());
  41150. for (int i = 0; i < columns.size(); ++i)
  41151. {
  41152. const ColumnInfo* const ci = columns.getUnchecked (i);
  41153. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41154. e->setAttribute ("id", ci->id);
  41155. e->setAttribute ("visible", ci->isVisible());
  41156. e->setAttribute ("width", ci->width);
  41157. }
  41158. return doc.createDocument (String::empty, true, false);
  41159. }
  41160. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41161. {
  41162. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41163. int index = 0;
  41164. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41165. {
  41166. forEachXmlChildElement (*storedXml, col)
  41167. {
  41168. const int tabId = col->getIntAttribute ("id");
  41169. ColumnInfo* const ci = getInfoForId (tabId);
  41170. if (ci != 0)
  41171. {
  41172. columns.move (columns.indexOf (ci), index);
  41173. ci->width = col->getIntAttribute ("width");
  41174. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41175. }
  41176. ++index;
  41177. }
  41178. columnsResized = true;
  41179. sendColumnsChanged();
  41180. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41181. storedXml->getBoolAttribute ("sortForwards", true));
  41182. }
  41183. }
  41184. void TableHeaderComponent::addListener (Listener* const newListener)
  41185. {
  41186. listeners.addIfNotAlreadyThere (newListener);
  41187. }
  41188. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41189. {
  41190. listeners.removeValue (listenerToRemove);
  41191. }
  41192. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41193. {
  41194. const ColumnInfo* const ci = getInfoForId (columnId);
  41195. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41196. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41197. }
  41198. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41199. {
  41200. for (int i = 0; i < columns.size(); ++i)
  41201. {
  41202. const ColumnInfo* const ci = columns.getUnchecked(i);
  41203. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41204. menu.addItem (ci->id, ci->name,
  41205. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41206. isColumnVisible (ci->id));
  41207. }
  41208. }
  41209. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41210. {
  41211. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41212. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41213. }
  41214. void TableHeaderComponent::paint (Graphics& g)
  41215. {
  41216. LookAndFeel& lf = getLookAndFeel();
  41217. lf.drawTableHeaderBackground (g, *this);
  41218. const Rectangle<int> clip (g.getClipBounds());
  41219. int x = 0;
  41220. for (int i = 0; i < columns.size(); ++i)
  41221. {
  41222. const ColumnInfo* const ci = columns.getUnchecked(i);
  41223. if (ci->isVisible())
  41224. {
  41225. if (x + ci->width > clip.getX()
  41226. && (ci->id != columnIdBeingDragged
  41227. || dragOverlayComp == 0
  41228. || ! dragOverlayComp->isVisible()))
  41229. {
  41230. Graphics::ScopedSaveState ss (g);
  41231. g.setOrigin (x, 0);
  41232. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41233. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41234. ci->id == columnIdUnderMouse,
  41235. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41236. ci->propertyFlags);
  41237. }
  41238. x += ci->width;
  41239. if (x >= clip.getRight())
  41240. break;
  41241. }
  41242. }
  41243. }
  41244. void TableHeaderComponent::resized()
  41245. {
  41246. }
  41247. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41248. {
  41249. updateColumnUnderMouse (e.x, e.y);
  41250. }
  41251. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41252. {
  41253. updateColumnUnderMouse (e.x, e.y);
  41254. }
  41255. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41256. {
  41257. updateColumnUnderMouse (e.x, e.y);
  41258. }
  41259. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41260. {
  41261. repaint();
  41262. columnIdBeingResized = 0;
  41263. columnIdBeingDragged = 0;
  41264. if (columnIdUnderMouse != 0)
  41265. {
  41266. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41267. if (e.mods.isPopupMenu())
  41268. columnClicked (columnIdUnderMouse, e.mods);
  41269. }
  41270. if (menuActive && e.mods.isPopupMenu())
  41271. showColumnChooserMenu (columnIdUnderMouse);
  41272. }
  41273. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41274. {
  41275. if (columnIdBeingResized == 0
  41276. && columnIdBeingDragged == 0
  41277. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41278. {
  41279. dragOverlayComp = 0;
  41280. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41281. if (columnIdBeingResized != 0)
  41282. {
  41283. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41284. initialColumnWidth = ci->width;
  41285. }
  41286. else
  41287. {
  41288. beginDrag (e);
  41289. }
  41290. }
  41291. if (columnIdBeingResized != 0)
  41292. {
  41293. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41294. if (ci != 0)
  41295. {
  41296. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41297. initialColumnWidth + e.getDistanceFromDragStartX());
  41298. if (stretchToFit)
  41299. {
  41300. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41301. int minWidthOnRight = 0;
  41302. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41303. if (columns.getUnchecked (i)->isVisible())
  41304. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41305. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41306. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41307. }
  41308. setColumnWidth (columnIdBeingResized, w);
  41309. }
  41310. }
  41311. else if (columnIdBeingDragged != 0)
  41312. {
  41313. if (e.y >= -50 && e.y < getHeight() + 50)
  41314. {
  41315. if (dragOverlayComp != 0)
  41316. {
  41317. dragOverlayComp->setVisible (true);
  41318. dragOverlayComp->setBounds (jlimit (0,
  41319. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41320. e.x - draggingColumnOffset),
  41321. 0,
  41322. dragOverlayComp->getWidth(),
  41323. getHeight());
  41324. for (int i = columns.size(); --i >= 0;)
  41325. {
  41326. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41327. int newIndex = currentIndex;
  41328. if (newIndex > 0)
  41329. {
  41330. // if the previous column isn't draggable, we can't move our column
  41331. // past it, because that'd change the undraggable column's position..
  41332. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41333. if ((previous->propertyFlags & draggable) != 0)
  41334. {
  41335. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41336. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41337. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41338. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41339. {
  41340. --newIndex;
  41341. }
  41342. }
  41343. }
  41344. if (newIndex < columns.size() - 1)
  41345. {
  41346. // if the next column isn't draggable, we can't move our column
  41347. // past it, because that'd change the undraggable column's position..
  41348. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41349. if ((nextCol->propertyFlags & draggable) != 0)
  41350. {
  41351. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41352. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41353. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41354. > abs (dragOverlayComp->getRight() - rightOfNext))
  41355. {
  41356. ++newIndex;
  41357. }
  41358. }
  41359. }
  41360. if (newIndex != currentIndex)
  41361. moveColumn (columnIdBeingDragged, newIndex);
  41362. else
  41363. break;
  41364. }
  41365. }
  41366. }
  41367. else
  41368. {
  41369. endDrag (draggingColumnOriginalIndex);
  41370. }
  41371. }
  41372. }
  41373. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41374. {
  41375. if (columnIdBeingDragged == 0)
  41376. {
  41377. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41378. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41379. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41380. {
  41381. columnIdBeingDragged = 0;
  41382. }
  41383. else
  41384. {
  41385. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41386. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41387. const int temp = columnIdBeingDragged;
  41388. columnIdBeingDragged = 0;
  41389. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41390. columnIdBeingDragged = temp;
  41391. dragOverlayComp->setBounds (columnRect);
  41392. for (int i = listeners.size(); --i >= 0;)
  41393. {
  41394. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41395. i = jmin (i, listeners.size() - 1);
  41396. }
  41397. }
  41398. }
  41399. }
  41400. void TableHeaderComponent::endDrag (const int finalIndex)
  41401. {
  41402. if (columnIdBeingDragged != 0)
  41403. {
  41404. moveColumn (columnIdBeingDragged, finalIndex);
  41405. columnIdBeingDragged = 0;
  41406. repaint();
  41407. for (int i = listeners.size(); --i >= 0;)
  41408. {
  41409. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41410. i = jmin (i, listeners.size() - 1);
  41411. }
  41412. }
  41413. }
  41414. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41415. {
  41416. mouseDrag (e);
  41417. for (int i = columns.size(); --i >= 0;)
  41418. if (columns.getUnchecked (i)->isVisible())
  41419. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41420. columnIdBeingResized = 0;
  41421. repaint();
  41422. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41423. updateColumnUnderMouse (e.x, e.y);
  41424. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41425. columnClicked (columnIdUnderMouse, e.mods);
  41426. dragOverlayComp = 0;
  41427. }
  41428. const MouseCursor TableHeaderComponent::getMouseCursor()
  41429. {
  41430. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41431. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41432. return Component::getMouseCursor();
  41433. }
  41434. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41435. {
  41436. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41437. }
  41438. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41439. {
  41440. for (int i = columns.size(); --i >= 0;)
  41441. if (columns.getUnchecked(i)->id == id)
  41442. return columns.getUnchecked(i);
  41443. return 0;
  41444. }
  41445. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41446. {
  41447. int n = 0;
  41448. for (int i = 0; i < columns.size(); ++i)
  41449. {
  41450. if (columns.getUnchecked(i)->isVisible())
  41451. {
  41452. if (n == visibleIndex)
  41453. return i;
  41454. ++n;
  41455. }
  41456. }
  41457. return -1;
  41458. }
  41459. void TableHeaderComponent::sendColumnsChanged()
  41460. {
  41461. if (stretchToFit && lastDeliberateWidth > 0)
  41462. resizeAllColumnsToFit (lastDeliberateWidth);
  41463. repaint();
  41464. columnsChanged = true;
  41465. triggerAsyncUpdate();
  41466. }
  41467. void TableHeaderComponent::handleAsyncUpdate()
  41468. {
  41469. const bool changed = columnsChanged || sortChanged;
  41470. const bool sized = columnsResized || changed;
  41471. const bool sorted = sortChanged;
  41472. columnsChanged = false;
  41473. columnsResized = false;
  41474. sortChanged = false;
  41475. if (sorted)
  41476. {
  41477. for (int i = listeners.size(); --i >= 0;)
  41478. {
  41479. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41480. i = jmin (i, listeners.size() - 1);
  41481. }
  41482. }
  41483. if (changed)
  41484. {
  41485. for (int i = listeners.size(); --i >= 0;)
  41486. {
  41487. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41488. i = jmin (i, listeners.size() - 1);
  41489. }
  41490. }
  41491. if (sized)
  41492. {
  41493. for (int i = listeners.size(); --i >= 0;)
  41494. {
  41495. listeners.getUnchecked(i)->tableColumnsResized (this);
  41496. i = jmin (i, listeners.size() - 1);
  41497. }
  41498. }
  41499. }
  41500. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41501. {
  41502. if (isPositiveAndBelow (mouseX, getWidth()))
  41503. {
  41504. const int draggableDistance = 3;
  41505. int x = 0;
  41506. for (int i = 0; i < columns.size(); ++i)
  41507. {
  41508. const ColumnInfo* const ci = columns.getUnchecked(i);
  41509. if (ci->isVisible())
  41510. {
  41511. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41512. && (ci->propertyFlags & resizable) != 0)
  41513. return ci->id;
  41514. x += ci->width;
  41515. }
  41516. }
  41517. }
  41518. return 0;
  41519. }
  41520. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41521. {
  41522. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41523. ? getColumnIdAtX (x) : 0;
  41524. if (newCol != columnIdUnderMouse)
  41525. {
  41526. columnIdUnderMouse = newCol;
  41527. repaint();
  41528. }
  41529. }
  41530. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41531. {
  41532. PopupMenu m;
  41533. addMenuItems (m, columnIdClicked);
  41534. if (m.getNumItems() > 0)
  41535. {
  41536. m.setLookAndFeel (&getLookAndFeel());
  41537. const int result = m.show();
  41538. if (result != 0)
  41539. reactToMenuItem (result, columnIdClicked);
  41540. }
  41541. }
  41542. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41543. {
  41544. }
  41545. END_JUCE_NAMESPACE
  41546. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41547. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41548. BEGIN_JUCE_NAMESPACE
  41549. class TableListRowComp : public Component,
  41550. public TooltipClient
  41551. {
  41552. public:
  41553. TableListRowComp (TableListBox& owner_)
  41554. : owner (owner_), row (-1), isSelected (false)
  41555. {
  41556. }
  41557. void paint (Graphics& g)
  41558. {
  41559. TableListBoxModel* const model = owner.getModel();
  41560. if (model != 0)
  41561. {
  41562. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41563. const TableHeaderComponent& header = owner.getHeader();
  41564. const int numColumns = header.getNumColumns (true);
  41565. for (int i = 0; i < numColumns; ++i)
  41566. {
  41567. if (columnComponents[i] == 0)
  41568. {
  41569. const int columnId = header.getColumnIdOfIndex (i, true);
  41570. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41571. Graphics::ScopedSaveState ss (g);
  41572. g.reduceClipRegion (columnRect);
  41573. g.setOrigin (columnRect.getX(), 0);
  41574. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41575. }
  41576. }
  41577. }
  41578. }
  41579. void update (const int newRow, const bool isNowSelected)
  41580. {
  41581. jassert (newRow >= 0);
  41582. if (newRow != row || isNowSelected != isSelected)
  41583. {
  41584. row = newRow;
  41585. isSelected = isNowSelected;
  41586. repaint();
  41587. }
  41588. TableListBoxModel* const model = owner.getModel();
  41589. if (model != 0 && row < owner.getNumRows())
  41590. {
  41591. const Identifier columnProperty ("_tableColumnId");
  41592. const int numColumns = owner.getHeader().getNumColumns (true);
  41593. for (int i = 0; i < numColumns; ++i)
  41594. {
  41595. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41596. Component* comp = columnComponents[i];
  41597. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41598. {
  41599. columnComponents.set (i, 0);
  41600. comp = 0;
  41601. }
  41602. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41603. columnComponents.set (i, comp, false);
  41604. if (comp != 0)
  41605. {
  41606. comp->getProperties().set (columnProperty, columnId);
  41607. addAndMakeVisible (comp);
  41608. resizeCustomComp (i);
  41609. }
  41610. }
  41611. columnComponents.removeRange (numColumns, columnComponents.size());
  41612. }
  41613. else
  41614. {
  41615. columnComponents.clear();
  41616. }
  41617. }
  41618. void resized()
  41619. {
  41620. for (int i = columnComponents.size(); --i >= 0;)
  41621. resizeCustomComp (i);
  41622. }
  41623. void resizeCustomComp (const int index)
  41624. {
  41625. Component* const c = columnComponents.getUnchecked (index);
  41626. if (c != 0)
  41627. c->setBounds (owner.getHeader().getColumnPosition (index)
  41628. .withY (0).withHeight (getHeight()));
  41629. }
  41630. void mouseDown (const MouseEvent& e)
  41631. {
  41632. isDragging = false;
  41633. selectRowOnMouseUp = false;
  41634. if (isEnabled())
  41635. {
  41636. if (! isSelected)
  41637. {
  41638. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  41639. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41640. if (columnId != 0 && owner.getModel() != 0)
  41641. owner.getModel()->cellClicked (row, columnId, e);
  41642. }
  41643. else
  41644. {
  41645. selectRowOnMouseUp = true;
  41646. }
  41647. }
  41648. }
  41649. void mouseDrag (const MouseEvent& e)
  41650. {
  41651. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41652. {
  41653. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41654. if (selectedRows.size() > 0)
  41655. {
  41656. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41657. if (dragDescription.isNotEmpty())
  41658. {
  41659. isDragging = true;
  41660. owner.startDragAndDrop (e, dragDescription);
  41661. }
  41662. }
  41663. }
  41664. }
  41665. void mouseUp (const MouseEvent& e)
  41666. {
  41667. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41668. {
  41669. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  41670. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41671. if (columnId != 0 && owner.getModel() != 0)
  41672. owner.getModel()->cellClicked (row, columnId, e);
  41673. }
  41674. }
  41675. void mouseDoubleClick (const MouseEvent& e)
  41676. {
  41677. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41678. if (columnId != 0 && owner.getModel() != 0)
  41679. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41680. }
  41681. const String getTooltip()
  41682. {
  41683. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41684. if (columnId != 0 && owner.getModel() != 0)
  41685. return owner.getModel()->getCellTooltip (row, columnId);
  41686. return String::empty;
  41687. }
  41688. Component* findChildComponentForColumn (const int columnId) const
  41689. {
  41690. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41691. }
  41692. private:
  41693. TableListBox& owner;
  41694. OwnedArray<Component> columnComponents;
  41695. int row;
  41696. bool isSelected, isDragging, selectRowOnMouseUp;
  41697. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41698. };
  41699. class TableListBoxHeader : public TableHeaderComponent
  41700. {
  41701. public:
  41702. TableListBoxHeader (TableListBox& owner_)
  41703. : owner (owner_)
  41704. {
  41705. }
  41706. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41707. {
  41708. if (owner.isAutoSizeMenuOptionShown())
  41709. {
  41710. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41711. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41712. menu.addSeparator();
  41713. }
  41714. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41715. }
  41716. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41717. {
  41718. switch (menuReturnId)
  41719. {
  41720. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41721. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41722. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41723. }
  41724. }
  41725. private:
  41726. TableListBox& owner;
  41727. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41728. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41729. };
  41730. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41731. : ListBox (name, 0),
  41732. model (model_),
  41733. autoSizeOptionsShown (true)
  41734. {
  41735. ListBox::model = this;
  41736. header = new TableListBoxHeader (*this);
  41737. header->setSize (100, 28);
  41738. header->addListener (this);
  41739. setHeaderComponent (header);
  41740. }
  41741. TableListBox::~TableListBox()
  41742. {
  41743. header = 0;
  41744. }
  41745. void TableListBox::setModel (TableListBoxModel* const newModel)
  41746. {
  41747. if (model != newModel)
  41748. {
  41749. model = newModel;
  41750. updateContent();
  41751. }
  41752. }
  41753. int TableListBox::getHeaderHeight() const
  41754. {
  41755. return header->getHeight();
  41756. }
  41757. void TableListBox::setHeaderHeight (const int newHeight)
  41758. {
  41759. header->setSize (header->getWidth(), newHeight);
  41760. resized();
  41761. }
  41762. void TableListBox::autoSizeColumn (const int columnId)
  41763. {
  41764. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41765. if (width > 0)
  41766. header->setColumnWidth (columnId, width);
  41767. }
  41768. void TableListBox::autoSizeAllColumns()
  41769. {
  41770. for (int i = 0; i < header->getNumColumns (true); ++i)
  41771. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41772. }
  41773. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41774. {
  41775. autoSizeOptionsShown = shouldBeShown;
  41776. }
  41777. bool TableListBox::isAutoSizeMenuOptionShown() const
  41778. {
  41779. return autoSizeOptionsShown;
  41780. }
  41781. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41782. const bool relativeToComponentTopLeft) const
  41783. {
  41784. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41785. if (relativeToComponentTopLeft)
  41786. headerCell.translate (header->getX(), 0);
  41787. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41788. .withX (headerCell.getX())
  41789. .withWidth (headerCell.getWidth());
  41790. }
  41791. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41792. {
  41793. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41794. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41795. }
  41796. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41797. {
  41798. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41799. if (scrollbar != 0)
  41800. {
  41801. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41802. double x = scrollbar->getCurrentRangeStart();
  41803. const double w = scrollbar->getCurrentRangeSize();
  41804. if (pos.getX() < x)
  41805. x = pos.getX();
  41806. else if (pos.getRight() > x + w)
  41807. x += jmax (0.0, pos.getRight() - (x + w));
  41808. scrollbar->setCurrentRangeStart (x);
  41809. }
  41810. }
  41811. int TableListBox::getNumRows()
  41812. {
  41813. return model != 0 ? model->getNumRows() : 0;
  41814. }
  41815. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41816. {
  41817. }
  41818. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41819. {
  41820. if (existingComponentToUpdate == 0)
  41821. existingComponentToUpdate = new TableListRowComp (*this);
  41822. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41823. return existingComponentToUpdate;
  41824. }
  41825. void TableListBox::selectedRowsChanged (int row)
  41826. {
  41827. if (model != 0)
  41828. model->selectedRowsChanged (row);
  41829. }
  41830. void TableListBox::deleteKeyPressed (int row)
  41831. {
  41832. if (model != 0)
  41833. model->deleteKeyPressed (row);
  41834. }
  41835. void TableListBox::returnKeyPressed (int row)
  41836. {
  41837. if (model != 0)
  41838. model->returnKeyPressed (row);
  41839. }
  41840. void TableListBox::backgroundClicked()
  41841. {
  41842. if (model != 0)
  41843. model->backgroundClicked();
  41844. }
  41845. void TableListBox::listWasScrolled()
  41846. {
  41847. if (model != 0)
  41848. model->listWasScrolled();
  41849. }
  41850. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41851. {
  41852. setMinimumContentWidth (header->getTotalWidth());
  41853. repaint();
  41854. updateColumnComponents();
  41855. }
  41856. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41857. {
  41858. setMinimumContentWidth (header->getTotalWidth());
  41859. repaint();
  41860. updateColumnComponents();
  41861. }
  41862. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41863. {
  41864. if (model != 0)
  41865. model->sortOrderChanged (header->getSortColumnId(),
  41866. header->isSortedForwards());
  41867. }
  41868. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41869. {
  41870. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41871. repaint();
  41872. }
  41873. void TableListBox::resized()
  41874. {
  41875. ListBox::resized();
  41876. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41877. setMinimumContentWidth (header->getTotalWidth());
  41878. }
  41879. void TableListBox::updateColumnComponents() const
  41880. {
  41881. const int firstRow = getRowContainingPosition (0, 0);
  41882. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41883. {
  41884. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41885. if (rowComp != 0)
  41886. rowComp->resized();
  41887. }
  41888. }
  41889. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  41890. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  41891. void TableListBoxModel::backgroundClicked() {}
  41892. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  41893. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  41894. void TableListBoxModel::selectedRowsChanged (int) {}
  41895. void TableListBoxModel::deleteKeyPressed (int) {}
  41896. void TableListBoxModel::returnKeyPressed (int) {}
  41897. void TableListBoxModel::listWasScrolled() {}
  41898. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  41899. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  41900. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41901. {
  41902. (void) existingComponentToUpdate;
  41903. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41904. return 0;
  41905. }
  41906. END_JUCE_NAMESPACE
  41907. /*** End of inlined file: juce_TableListBox.cpp ***/
  41908. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41909. BEGIN_JUCE_NAMESPACE
  41910. // a word or space that can't be broken down any further
  41911. struct TextAtom
  41912. {
  41913. String atomText;
  41914. float width;
  41915. int numChars;
  41916. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41917. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41918. const String getText (const juce_wchar passwordCharacter) const
  41919. {
  41920. if (passwordCharacter == 0)
  41921. return atomText;
  41922. else
  41923. return String::repeatedString (String::charToString (passwordCharacter),
  41924. atomText.length());
  41925. }
  41926. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41927. {
  41928. if (passwordCharacter == 0)
  41929. return atomText.substring (0, numChars);
  41930. else if (isNewLine())
  41931. return String::empty;
  41932. else
  41933. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41934. }
  41935. };
  41936. // a run of text with a single font and colour
  41937. class TextEditor::UniformTextSection
  41938. {
  41939. public:
  41940. UniformTextSection (const String& text,
  41941. const Font& font_,
  41942. const Colour& colour_,
  41943. const juce_wchar passwordCharacter)
  41944. : font (font_),
  41945. colour (colour_)
  41946. {
  41947. initialiseAtoms (text, passwordCharacter);
  41948. }
  41949. UniformTextSection (const UniformTextSection& other)
  41950. : font (other.font),
  41951. colour (other.colour)
  41952. {
  41953. atoms.ensureStorageAllocated (other.atoms.size());
  41954. for (int i = 0; i < other.atoms.size(); ++i)
  41955. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41956. }
  41957. ~UniformTextSection()
  41958. {
  41959. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41960. }
  41961. void clear()
  41962. {
  41963. for (int i = atoms.size(); --i >= 0;)
  41964. delete getAtom(i);
  41965. atoms.clear();
  41966. }
  41967. int getNumAtoms() const
  41968. {
  41969. return atoms.size();
  41970. }
  41971. TextAtom* getAtom (const int index) const throw()
  41972. {
  41973. return atoms.getUnchecked (index);
  41974. }
  41975. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41976. {
  41977. if (other.atoms.size() > 0)
  41978. {
  41979. TextAtom* const lastAtom = atoms.getLast();
  41980. int i = 0;
  41981. if (lastAtom != 0)
  41982. {
  41983. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41984. {
  41985. TextAtom* const first = other.getAtom(0);
  41986. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41987. {
  41988. lastAtom->atomText += first->atomText;
  41989. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41990. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41991. delete first;
  41992. ++i;
  41993. }
  41994. }
  41995. }
  41996. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41997. while (i < other.atoms.size())
  41998. {
  41999. atoms.add (other.getAtom(i));
  42000. ++i;
  42001. }
  42002. }
  42003. }
  42004. UniformTextSection* split (const int indexToBreakAt,
  42005. const juce_wchar passwordCharacter)
  42006. {
  42007. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42008. font, colour,
  42009. passwordCharacter);
  42010. int index = 0;
  42011. for (int i = 0; i < atoms.size(); ++i)
  42012. {
  42013. TextAtom* const atom = getAtom(i);
  42014. const int nextIndex = index + atom->numChars;
  42015. if (index == indexToBreakAt)
  42016. {
  42017. int j;
  42018. for (j = i; j < atoms.size(); ++j)
  42019. section2->atoms.add (getAtom (j));
  42020. for (j = atoms.size(); --j >= i;)
  42021. atoms.remove (j);
  42022. break;
  42023. }
  42024. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42025. {
  42026. TextAtom* const secondAtom = new TextAtom();
  42027. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42028. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42029. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42030. section2->atoms.add (secondAtom);
  42031. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42032. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42033. atom->numChars = (uint16) (indexToBreakAt - index);
  42034. int j;
  42035. for (j = i + 1; j < atoms.size(); ++j)
  42036. section2->atoms.add (getAtom (j));
  42037. for (j = atoms.size(); --j > i;)
  42038. atoms.remove (j);
  42039. break;
  42040. }
  42041. index = nextIndex;
  42042. }
  42043. return section2;
  42044. }
  42045. void appendAllText (String::Concatenator& concatenator) const
  42046. {
  42047. for (int i = 0; i < atoms.size(); ++i)
  42048. concatenator.append (getAtom(i)->atomText);
  42049. }
  42050. void appendSubstring (String::Concatenator& concatenator,
  42051. const Range<int>& range) const
  42052. {
  42053. int index = 0;
  42054. for (int i = 0; i < atoms.size(); ++i)
  42055. {
  42056. const TextAtom* const atom = getAtom (i);
  42057. const int nextIndex = index + atom->numChars;
  42058. if (range.getStart() < nextIndex)
  42059. {
  42060. if (range.getEnd() <= index)
  42061. break;
  42062. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42063. if (! r.isEmpty())
  42064. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42065. }
  42066. index = nextIndex;
  42067. }
  42068. }
  42069. int getTotalLength() const
  42070. {
  42071. int total = 0;
  42072. for (int i = atoms.size(); --i >= 0;)
  42073. total += getAtom(i)->numChars;
  42074. return total;
  42075. }
  42076. void setFont (const Font& newFont,
  42077. const juce_wchar passwordCharacter)
  42078. {
  42079. if (font != newFont)
  42080. {
  42081. font = newFont;
  42082. for (int i = atoms.size(); --i >= 0;)
  42083. {
  42084. TextAtom* const atom = atoms.getUnchecked(i);
  42085. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42086. }
  42087. }
  42088. }
  42089. Font font;
  42090. Colour colour;
  42091. private:
  42092. Array <TextAtom*> atoms;
  42093. void initialiseAtoms (const String& textToParse,
  42094. const juce_wchar passwordCharacter)
  42095. {
  42096. int i = 0;
  42097. const int len = textToParse.length();
  42098. const juce_wchar* const text = textToParse;
  42099. while (i < len)
  42100. {
  42101. int start = i;
  42102. // create a whitespace atom unless it starts with non-ws
  42103. if (CharacterFunctions::isWhitespace (text[i])
  42104. && text[i] != '\r'
  42105. && text[i] != '\n')
  42106. {
  42107. while (i < len
  42108. && CharacterFunctions::isWhitespace (text[i])
  42109. && text[i] != '\r'
  42110. && text[i] != '\n')
  42111. {
  42112. ++i;
  42113. }
  42114. }
  42115. else
  42116. {
  42117. if (text[i] == '\r')
  42118. {
  42119. ++i;
  42120. if ((i < len) && (text[i] == '\n'))
  42121. {
  42122. ++start;
  42123. ++i;
  42124. }
  42125. }
  42126. else if (text[i] == '\n')
  42127. {
  42128. ++i;
  42129. }
  42130. else
  42131. {
  42132. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42133. ++i;
  42134. }
  42135. }
  42136. TextAtom* const atom = new TextAtom();
  42137. atom->atomText = String (text + start, i - start);
  42138. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42139. atom->numChars = (uint16) (i - start);
  42140. atoms.add (atom);
  42141. }
  42142. }
  42143. UniformTextSection& operator= (const UniformTextSection& other);
  42144. JUCE_LEAK_DETECTOR (UniformTextSection);
  42145. };
  42146. class TextEditor::Iterator
  42147. {
  42148. public:
  42149. Iterator (const Array <UniformTextSection*>& sections_,
  42150. const float wordWrapWidth_,
  42151. const juce_wchar passwordCharacter_)
  42152. : indexInText (0),
  42153. lineY (0),
  42154. lineHeight (0),
  42155. maxDescent (0),
  42156. atomX (0),
  42157. atomRight (0),
  42158. atom (0),
  42159. currentSection (0),
  42160. sections (sections_),
  42161. sectionIndex (0),
  42162. atomIndex (0),
  42163. wordWrapWidth (wordWrapWidth_),
  42164. passwordCharacter (passwordCharacter_)
  42165. {
  42166. jassert (wordWrapWidth_ > 0);
  42167. if (sections.size() > 0)
  42168. {
  42169. currentSection = sections.getUnchecked (sectionIndex);
  42170. if (currentSection != 0)
  42171. beginNewLine();
  42172. }
  42173. }
  42174. Iterator (const Iterator& other)
  42175. : indexInText (other.indexInText),
  42176. lineY (other.lineY),
  42177. lineHeight (other.lineHeight),
  42178. maxDescent (other.maxDescent),
  42179. atomX (other.atomX),
  42180. atomRight (other.atomRight),
  42181. atom (other.atom),
  42182. currentSection (other.currentSection),
  42183. sections (other.sections),
  42184. sectionIndex (other.sectionIndex),
  42185. atomIndex (other.atomIndex),
  42186. wordWrapWidth (other.wordWrapWidth),
  42187. passwordCharacter (other.passwordCharacter),
  42188. tempAtom (other.tempAtom)
  42189. {
  42190. }
  42191. bool next()
  42192. {
  42193. if (atom == &tempAtom)
  42194. {
  42195. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42196. if (numRemaining > 0)
  42197. {
  42198. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42199. atomX = 0;
  42200. if (tempAtom.numChars > 0)
  42201. lineY += lineHeight;
  42202. indexInText += tempAtom.numChars;
  42203. GlyphArrangement g;
  42204. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42205. int split;
  42206. for (split = 0; split < g.getNumGlyphs(); ++split)
  42207. if (shouldWrap (g.getGlyph (split).getRight()))
  42208. break;
  42209. if (split > 0 && split <= numRemaining)
  42210. {
  42211. tempAtom.numChars = (uint16) split;
  42212. tempAtom.width = g.getGlyph (split - 1).getRight();
  42213. atomRight = atomX + tempAtom.width;
  42214. return true;
  42215. }
  42216. }
  42217. }
  42218. bool forceNewLine = false;
  42219. if (sectionIndex >= sections.size())
  42220. {
  42221. moveToEndOfLastAtom();
  42222. return false;
  42223. }
  42224. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42225. {
  42226. if (atomIndex >= currentSection->getNumAtoms())
  42227. {
  42228. if (++sectionIndex >= sections.size())
  42229. {
  42230. moveToEndOfLastAtom();
  42231. return false;
  42232. }
  42233. atomIndex = 0;
  42234. currentSection = sections.getUnchecked (sectionIndex);
  42235. }
  42236. else
  42237. {
  42238. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42239. if (! lastAtom->isWhitespace())
  42240. {
  42241. // handle the case where the last atom in a section is actually part of the same
  42242. // word as the first atom of the next section...
  42243. float right = atomRight + lastAtom->width;
  42244. float lineHeight2 = lineHeight;
  42245. float maxDescent2 = maxDescent;
  42246. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42247. {
  42248. const UniformTextSection* const s = sections.getUnchecked (section);
  42249. if (s->getNumAtoms() == 0)
  42250. break;
  42251. const TextAtom* const nextAtom = s->getAtom (0);
  42252. if (nextAtom->isWhitespace())
  42253. break;
  42254. right += nextAtom->width;
  42255. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42256. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42257. if (shouldWrap (right))
  42258. {
  42259. lineHeight = lineHeight2;
  42260. maxDescent = maxDescent2;
  42261. forceNewLine = true;
  42262. break;
  42263. }
  42264. if (s->getNumAtoms() > 1)
  42265. break;
  42266. }
  42267. }
  42268. }
  42269. }
  42270. if (atom != 0)
  42271. {
  42272. atomX = atomRight;
  42273. indexInText += atom->numChars;
  42274. if (atom->isNewLine())
  42275. beginNewLine();
  42276. }
  42277. atom = currentSection->getAtom (atomIndex);
  42278. atomRight = atomX + atom->width;
  42279. ++atomIndex;
  42280. if (shouldWrap (atomRight) || forceNewLine)
  42281. {
  42282. if (atom->isWhitespace())
  42283. {
  42284. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42285. atomRight = jmin (atomRight, wordWrapWidth);
  42286. }
  42287. else
  42288. {
  42289. atomRight = atom->width;
  42290. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42291. {
  42292. tempAtom = *atom;
  42293. tempAtom.width = 0;
  42294. tempAtom.numChars = 0;
  42295. atom = &tempAtom;
  42296. if (atomX > 0)
  42297. beginNewLine();
  42298. return next();
  42299. }
  42300. beginNewLine();
  42301. return true;
  42302. }
  42303. }
  42304. return true;
  42305. }
  42306. void beginNewLine()
  42307. {
  42308. atomX = 0;
  42309. lineY += lineHeight;
  42310. int tempSectionIndex = sectionIndex;
  42311. int tempAtomIndex = atomIndex;
  42312. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42313. lineHeight = section->font.getHeight();
  42314. maxDescent = section->font.getDescent();
  42315. float x = (atom != 0) ? atom->width : 0;
  42316. while (! shouldWrap (x))
  42317. {
  42318. if (tempSectionIndex >= sections.size())
  42319. break;
  42320. bool checkSize = false;
  42321. if (tempAtomIndex >= section->getNumAtoms())
  42322. {
  42323. if (++tempSectionIndex >= sections.size())
  42324. break;
  42325. tempAtomIndex = 0;
  42326. section = sections.getUnchecked (tempSectionIndex);
  42327. checkSize = true;
  42328. }
  42329. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42330. if (nextAtom == 0)
  42331. break;
  42332. x += nextAtom->width;
  42333. if (shouldWrap (x) || nextAtom->isNewLine())
  42334. break;
  42335. if (checkSize)
  42336. {
  42337. lineHeight = jmax (lineHeight, section->font.getHeight());
  42338. maxDescent = jmax (maxDescent, section->font.getDescent());
  42339. }
  42340. ++tempAtomIndex;
  42341. }
  42342. }
  42343. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42344. {
  42345. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42346. {
  42347. if (lastSection != currentSection)
  42348. {
  42349. lastSection = currentSection;
  42350. g.setColour (currentSection->colour);
  42351. g.setFont (currentSection->font);
  42352. }
  42353. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42354. GlyphArrangement ga;
  42355. ga.addLineOfText (currentSection->font,
  42356. atom->getTrimmedText (passwordCharacter),
  42357. atomX,
  42358. (float) roundToInt (lineY + lineHeight - maxDescent));
  42359. ga.draw (g);
  42360. }
  42361. }
  42362. void drawSelection (Graphics& g,
  42363. const Range<int>& selection) const
  42364. {
  42365. const int startX = roundToInt (indexToX (selection.getStart()));
  42366. const int endX = roundToInt (indexToX (selection.getEnd()));
  42367. const int y = roundToInt (lineY);
  42368. const int nextY = roundToInt (lineY + lineHeight);
  42369. g.fillRect (startX, y, endX - startX, nextY - y);
  42370. }
  42371. void drawSelectedText (Graphics& g,
  42372. const Range<int>& selection,
  42373. const Colour& selectedTextColour) const
  42374. {
  42375. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42376. {
  42377. GlyphArrangement ga;
  42378. ga.addLineOfText (currentSection->font,
  42379. atom->getTrimmedText (passwordCharacter),
  42380. atomX,
  42381. (float) roundToInt (lineY + lineHeight - maxDescent));
  42382. if (selection.getEnd() < indexInText + atom->numChars)
  42383. {
  42384. GlyphArrangement ga2 (ga);
  42385. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42386. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42387. g.setColour (currentSection->colour);
  42388. ga2.draw (g);
  42389. }
  42390. if (selection.getStart() > indexInText)
  42391. {
  42392. GlyphArrangement ga2 (ga);
  42393. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42394. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42395. g.setColour (currentSection->colour);
  42396. ga2.draw (g);
  42397. }
  42398. g.setColour (selectedTextColour);
  42399. ga.draw (g);
  42400. }
  42401. }
  42402. float indexToX (const int indexToFind) const
  42403. {
  42404. if (indexToFind <= indexInText)
  42405. return atomX;
  42406. if (indexToFind >= indexInText + atom->numChars)
  42407. return atomRight;
  42408. GlyphArrangement g;
  42409. g.addLineOfText (currentSection->font,
  42410. atom->getText (passwordCharacter),
  42411. atomX, 0.0f);
  42412. if (indexToFind - indexInText >= g.getNumGlyphs())
  42413. return atomRight;
  42414. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42415. }
  42416. int xToIndex (const float xToFind) const
  42417. {
  42418. if (xToFind <= atomX || atom->isNewLine())
  42419. return indexInText;
  42420. if (xToFind >= atomRight)
  42421. return indexInText + atom->numChars;
  42422. GlyphArrangement g;
  42423. g.addLineOfText (currentSection->font,
  42424. atom->getText (passwordCharacter),
  42425. atomX, 0.0f);
  42426. int j;
  42427. for (j = 0; j < g.getNumGlyphs(); ++j)
  42428. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42429. break;
  42430. return indexInText + j;
  42431. }
  42432. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42433. {
  42434. while (next())
  42435. {
  42436. if (indexInText + atom->numChars > index)
  42437. {
  42438. cx = indexToX (index);
  42439. cy = lineY;
  42440. lineHeight_ = lineHeight;
  42441. return true;
  42442. }
  42443. }
  42444. cx = atomX;
  42445. cy = lineY;
  42446. lineHeight_ = lineHeight;
  42447. return false;
  42448. }
  42449. int indexInText;
  42450. float lineY, lineHeight, maxDescent;
  42451. float atomX, atomRight;
  42452. const TextAtom* atom;
  42453. const UniformTextSection* currentSection;
  42454. private:
  42455. const Array <UniformTextSection*>& sections;
  42456. int sectionIndex, atomIndex;
  42457. const float wordWrapWidth;
  42458. const juce_wchar passwordCharacter;
  42459. TextAtom tempAtom;
  42460. Iterator& operator= (const Iterator&);
  42461. void moveToEndOfLastAtom()
  42462. {
  42463. if (atom != 0)
  42464. {
  42465. atomX = atomRight;
  42466. if (atom->isNewLine())
  42467. {
  42468. atomX = 0.0f;
  42469. lineY += lineHeight;
  42470. }
  42471. }
  42472. }
  42473. bool shouldWrap (const float x) const
  42474. {
  42475. return (x - 0.0001f) >= wordWrapWidth;
  42476. }
  42477. JUCE_LEAK_DETECTOR (Iterator);
  42478. };
  42479. class TextEditor::InsertAction : public UndoableAction
  42480. {
  42481. public:
  42482. InsertAction (TextEditor& owner_,
  42483. const String& text_,
  42484. const int insertIndex_,
  42485. const Font& font_,
  42486. const Colour& colour_,
  42487. const int oldCaretPos_,
  42488. const int newCaretPos_)
  42489. : owner (owner_),
  42490. text (text_),
  42491. insertIndex (insertIndex_),
  42492. oldCaretPos (oldCaretPos_),
  42493. newCaretPos (newCaretPos_),
  42494. font (font_),
  42495. colour (colour_)
  42496. {
  42497. }
  42498. bool perform()
  42499. {
  42500. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42501. return true;
  42502. }
  42503. bool undo()
  42504. {
  42505. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42506. return true;
  42507. }
  42508. int getSizeInUnits()
  42509. {
  42510. return text.length() + 16;
  42511. }
  42512. private:
  42513. TextEditor& owner;
  42514. const String text;
  42515. const int insertIndex, oldCaretPos, newCaretPos;
  42516. const Font font;
  42517. const Colour colour;
  42518. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42519. };
  42520. class TextEditor::RemoveAction : public UndoableAction
  42521. {
  42522. public:
  42523. RemoveAction (TextEditor& owner_,
  42524. const Range<int> range_,
  42525. const int oldCaretPos_,
  42526. const int newCaretPos_,
  42527. const Array <UniformTextSection*>& removedSections_)
  42528. : owner (owner_),
  42529. range (range_),
  42530. oldCaretPos (oldCaretPos_),
  42531. newCaretPos (newCaretPos_),
  42532. removedSections (removedSections_)
  42533. {
  42534. }
  42535. ~RemoveAction()
  42536. {
  42537. for (int i = removedSections.size(); --i >= 0;)
  42538. {
  42539. UniformTextSection* const section = removedSections.getUnchecked (i);
  42540. section->clear();
  42541. delete section;
  42542. }
  42543. }
  42544. bool perform()
  42545. {
  42546. owner.remove (range, 0, newCaretPos);
  42547. return true;
  42548. }
  42549. bool undo()
  42550. {
  42551. owner.reinsert (range.getStart(), removedSections);
  42552. owner.moveCursorTo (oldCaretPos, false);
  42553. return true;
  42554. }
  42555. int getSizeInUnits()
  42556. {
  42557. int n = 0;
  42558. for (int i = removedSections.size(); --i >= 0;)
  42559. n += removedSections.getUnchecked (i)->getTotalLength();
  42560. return n + 16;
  42561. }
  42562. private:
  42563. TextEditor& owner;
  42564. const Range<int> range;
  42565. const int oldCaretPos, newCaretPos;
  42566. Array <UniformTextSection*> removedSections;
  42567. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42568. };
  42569. class TextEditor::TextHolderComponent : public Component,
  42570. public Timer,
  42571. public ValueListener
  42572. {
  42573. public:
  42574. TextHolderComponent (TextEditor& owner_)
  42575. : owner (owner_)
  42576. {
  42577. setWantsKeyboardFocus (false);
  42578. setInterceptsMouseClicks (false, true);
  42579. owner.getTextValue().addListener (this);
  42580. }
  42581. ~TextHolderComponent()
  42582. {
  42583. owner.getTextValue().removeListener (this);
  42584. }
  42585. void paint (Graphics& g)
  42586. {
  42587. owner.drawContent (g);
  42588. }
  42589. void timerCallback()
  42590. {
  42591. owner.timerCallbackInt();
  42592. }
  42593. const MouseCursor getMouseCursor()
  42594. {
  42595. return owner.getMouseCursor();
  42596. }
  42597. void valueChanged (Value&)
  42598. {
  42599. owner.textWasChangedByValue();
  42600. }
  42601. private:
  42602. TextEditor& owner;
  42603. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42604. };
  42605. class TextEditorViewport : public Viewport
  42606. {
  42607. public:
  42608. TextEditorViewport (TextEditor& owner_)
  42609. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42610. {
  42611. }
  42612. void visibleAreaChanged (const Rectangle<int>&)
  42613. {
  42614. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42615. // appear and disappear, causing the wrap width to change.
  42616. {
  42617. const float wordWrapWidth = owner.getWordWrapWidth();
  42618. if (wordWrapWidth != lastWordWrapWidth)
  42619. {
  42620. lastWordWrapWidth = wordWrapWidth;
  42621. rentrant = true;
  42622. owner.updateTextHolderSize();
  42623. rentrant = false;
  42624. }
  42625. }
  42626. }
  42627. private:
  42628. TextEditor& owner;
  42629. float lastWordWrapWidth;
  42630. bool rentrant;
  42631. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42632. };
  42633. namespace TextEditorDefs
  42634. {
  42635. const int flashSpeedIntervalMs = 380;
  42636. const int textChangeMessageId = 0x10003001;
  42637. const int returnKeyMessageId = 0x10003002;
  42638. const int escapeKeyMessageId = 0x10003003;
  42639. const int focusLossMessageId = 0x10003004;
  42640. const int maxActionsPerTransaction = 100;
  42641. int getCharacterCategory (const juce_wchar character)
  42642. {
  42643. return CharacterFunctions::isLetterOrDigit (character)
  42644. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42645. }
  42646. }
  42647. TextEditor::TextEditor (const String& name,
  42648. const juce_wchar passwordCharacter_)
  42649. : Component (name),
  42650. borderSize (1, 1, 1, 3),
  42651. readOnly (false),
  42652. multiline (false),
  42653. wordWrap (false),
  42654. returnKeyStartsNewLine (false),
  42655. caretVisible (true),
  42656. popupMenuEnabled (true),
  42657. selectAllTextWhenFocused (false),
  42658. scrollbarVisible (true),
  42659. wasFocused (false),
  42660. caretFlashState (true),
  42661. keepCursorOnScreen (true),
  42662. tabKeyUsed (false),
  42663. menuActive (false),
  42664. valueTextNeedsUpdating (false),
  42665. cursorX (0),
  42666. cursorY (0),
  42667. cursorHeight (0),
  42668. maxTextLength (0),
  42669. leftIndent (4),
  42670. topIndent (4),
  42671. lastTransactionTime (0),
  42672. currentFont (14.0f),
  42673. totalNumChars (0),
  42674. caretPosition (0),
  42675. passwordCharacter (passwordCharacter_),
  42676. dragType (notDragging)
  42677. {
  42678. setOpaque (true);
  42679. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  42680. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42681. viewport->setWantsKeyboardFocus (false);
  42682. viewport->setScrollBarsShown (false, false);
  42683. setMouseCursor (MouseCursor::IBeamCursor);
  42684. setWantsKeyboardFocus (true);
  42685. }
  42686. TextEditor::~TextEditor()
  42687. {
  42688. textValue.referTo (Value());
  42689. clearInternal (0);
  42690. viewport = 0;
  42691. textHolder = 0;
  42692. }
  42693. void TextEditor::newTransaction()
  42694. {
  42695. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42696. undoManager.beginNewTransaction();
  42697. }
  42698. void TextEditor::doUndoRedo (const bool isRedo)
  42699. {
  42700. if (! isReadOnly())
  42701. {
  42702. if (isRedo ? undoManager.redo()
  42703. : undoManager.undo())
  42704. {
  42705. scrollToMakeSureCursorIsVisible();
  42706. repaint();
  42707. textChanged();
  42708. }
  42709. }
  42710. }
  42711. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42712. const bool shouldWordWrap)
  42713. {
  42714. if (multiline != shouldBeMultiLine
  42715. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42716. {
  42717. multiline = shouldBeMultiLine;
  42718. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42719. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42720. scrollbarVisible && multiline);
  42721. viewport->setViewPosition (0, 0);
  42722. resized();
  42723. scrollToMakeSureCursorIsVisible();
  42724. }
  42725. }
  42726. bool TextEditor::isMultiLine() const
  42727. {
  42728. return multiline;
  42729. }
  42730. void TextEditor::setScrollbarsShown (bool shown)
  42731. {
  42732. if (scrollbarVisible != shown)
  42733. {
  42734. scrollbarVisible = shown;
  42735. shown = shown && isMultiLine();
  42736. viewport->setScrollBarsShown (shown, shown);
  42737. }
  42738. }
  42739. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42740. {
  42741. if (readOnly != shouldBeReadOnly)
  42742. {
  42743. readOnly = shouldBeReadOnly;
  42744. enablementChanged();
  42745. }
  42746. }
  42747. bool TextEditor::isReadOnly() const
  42748. {
  42749. return readOnly || ! isEnabled();
  42750. }
  42751. bool TextEditor::isTextInputActive() const
  42752. {
  42753. return ! isReadOnly();
  42754. }
  42755. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42756. {
  42757. returnKeyStartsNewLine = shouldStartNewLine;
  42758. }
  42759. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42760. {
  42761. tabKeyUsed = shouldTabKeyBeUsed;
  42762. }
  42763. void TextEditor::setPopupMenuEnabled (const bool b)
  42764. {
  42765. popupMenuEnabled = b;
  42766. }
  42767. void TextEditor::setSelectAllWhenFocused (const bool b)
  42768. {
  42769. selectAllTextWhenFocused = b;
  42770. }
  42771. const Font TextEditor::getFont() const
  42772. {
  42773. return currentFont;
  42774. }
  42775. void TextEditor::setFont (const Font& newFont)
  42776. {
  42777. currentFont = newFont;
  42778. scrollToMakeSureCursorIsVisible();
  42779. }
  42780. void TextEditor::applyFontToAllText (const Font& newFont)
  42781. {
  42782. currentFont = newFont;
  42783. const Colour overallColour (findColour (textColourId));
  42784. for (int i = sections.size(); --i >= 0;)
  42785. {
  42786. UniformTextSection* const uts = sections.getUnchecked (i);
  42787. uts->setFont (newFont, passwordCharacter);
  42788. uts->colour = overallColour;
  42789. }
  42790. coalesceSimilarSections();
  42791. updateTextHolderSize();
  42792. scrollToMakeSureCursorIsVisible();
  42793. repaint();
  42794. }
  42795. void TextEditor::colourChanged()
  42796. {
  42797. setOpaque (findColour (backgroundColourId).isOpaque());
  42798. repaint();
  42799. }
  42800. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42801. {
  42802. caretVisible = shouldCaretBeVisible;
  42803. if (shouldCaretBeVisible)
  42804. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42805. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42806. : MouseCursor::NormalCursor);
  42807. }
  42808. void TextEditor::setInputRestrictions (const int maxLen,
  42809. const String& chars)
  42810. {
  42811. maxTextLength = jmax (0, maxLen);
  42812. allowedCharacters = chars;
  42813. }
  42814. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42815. {
  42816. textToShowWhenEmpty = text;
  42817. colourForTextWhenEmpty = colourToUse;
  42818. }
  42819. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42820. {
  42821. if (passwordCharacter != newPasswordCharacter)
  42822. {
  42823. passwordCharacter = newPasswordCharacter;
  42824. resized();
  42825. repaint();
  42826. }
  42827. }
  42828. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42829. {
  42830. viewport->setScrollBarThickness (newThicknessPixels);
  42831. }
  42832. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42833. {
  42834. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42835. }
  42836. void TextEditor::clear()
  42837. {
  42838. clearInternal (0);
  42839. updateTextHolderSize();
  42840. undoManager.clearUndoHistory();
  42841. }
  42842. void TextEditor::setText (const String& newText,
  42843. const bool sendTextChangeMessage)
  42844. {
  42845. const int newLength = newText.length();
  42846. if (newLength != getTotalNumChars() || getText() != newText)
  42847. {
  42848. const int oldCursorPos = caretPosition;
  42849. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42850. clearInternal (0);
  42851. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42852. // if you're adding text with line-feeds to a single-line text editor, it
  42853. // ain't gonna look right!
  42854. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42855. if (cursorWasAtEnd && ! isMultiLine())
  42856. moveCursorTo (getTotalNumChars(), false);
  42857. else
  42858. moveCursorTo (oldCursorPos, false);
  42859. if (sendTextChangeMessage)
  42860. textChanged();
  42861. updateTextHolderSize();
  42862. scrollToMakeSureCursorIsVisible();
  42863. undoManager.clearUndoHistory();
  42864. repaint();
  42865. }
  42866. }
  42867. Value& TextEditor::getTextValue()
  42868. {
  42869. if (valueTextNeedsUpdating)
  42870. {
  42871. valueTextNeedsUpdating = false;
  42872. textValue = getText();
  42873. }
  42874. return textValue;
  42875. }
  42876. void TextEditor::textWasChangedByValue()
  42877. {
  42878. if (textValue.getValueSource().getReferenceCount() > 1)
  42879. setText (textValue.getValue());
  42880. }
  42881. void TextEditor::textChanged()
  42882. {
  42883. updateTextHolderSize();
  42884. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42885. if (textValue.getValueSource().getReferenceCount() > 1)
  42886. {
  42887. valueTextNeedsUpdating = false;
  42888. textValue = getText();
  42889. }
  42890. }
  42891. void TextEditor::returnPressed()
  42892. {
  42893. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42894. }
  42895. void TextEditor::escapePressed()
  42896. {
  42897. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42898. }
  42899. void TextEditor::addListener (TextEditorListener* const newListener)
  42900. {
  42901. listeners.add (newListener);
  42902. }
  42903. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42904. {
  42905. listeners.remove (listenerToRemove);
  42906. }
  42907. void TextEditor::timerCallbackInt()
  42908. {
  42909. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42910. if (caretFlashState != newState)
  42911. {
  42912. caretFlashState = newState;
  42913. if (caretFlashState)
  42914. wasFocused = true;
  42915. if (caretVisible
  42916. && hasKeyboardFocus (false)
  42917. && ! isReadOnly())
  42918. {
  42919. repaintCaret();
  42920. }
  42921. }
  42922. const unsigned int now = Time::getApproximateMillisecondCounter();
  42923. if (now > lastTransactionTime + 200)
  42924. newTransaction();
  42925. }
  42926. void TextEditor::repaintCaret()
  42927. {
  42928. if (! findColour (caretColourId).isTransparent())
  42929. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42930. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42931. 4,
  42932. roundToInt (cursorHeight) + 2);
  42933. }
  42934. void TextEditor::repaintText (const Range<int>& range)
  42935. {
  42936. if (! range.isEmpty())
  42937. {
  42938. float x = 0, y = 0, lh = currentFont.getHeight();
  42939. const float wordWrapWidth = getWordWrapWidth();
  42940. if (wordWrapWidth > 0)
  42941. {
  42942. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42943. i.getCharPosition (range.getStart(), x, y, lh);
  42944. const int y1 = (int) y;
  42945. int y2;
  42946. if (range.getEnd() >= getTotalNumChars())
  42947. {
  42948. y2 = textHolder->getHeight();
  42949. }
  42950. else
  42951. {
  42952. i.getCharPosition (range.getEnd(), x, y, lh);
  42953. y2 = (int) (y + lh * 2.0f);
  42954. }
  42955. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42956. }
  42957. }
  42958. }
  42959. void TextEditor::moveCaret (int newCaretPos)
  42960. {
  42961. if (newCaretPos < 0)
  42962. newCaretPos = 0;
  42963. else if (newCaretPos > getTotalNumChars())
  42964. newCaretPos = getTotalNumChars();
  42965. if (newCaretPos != getCaretPosition())
  42966. {
  42967. repaintCaret();
  42968. caretFlashState = true;
  42969. caretPosition = newCaretPos;
  42970. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42971. scrollToMakeSureCursorIsVisible();
  42972. repaintCaret();
  42973. }
  42974. }
  42975. void TextEditor::setCaretPosition (const int newIndex)
  42976. {
  42977. moveCursorTo (newIndex, false);
  42978. }
  42979. int TextEditor::getCaretPosition() const
  42980. {
  42981. return caretPosition;
  42982. }
  42983. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42984. const int desiredCaretY)
  42985. {
  42986. updateCaretPosition();
  42987. int vx = roundToInt (cursorX) - desiredCaretX;
  42988. int vy = roundToInt (cursorY) - desiredCaretY;
  42989. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42990. {
  42991. vx += desiredCaretX - proportionOfWidth (0.2f);
  42992. }
  42993. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42994. {
  42995. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42996. }
  42997. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42998. if (! isMultiLine())
  42999. {
  43000. vy = viewport->getViewPositionY();
  43001. }
  43002. else
  43003. {
  43004. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43005. const int curH = roundToInt (cursorHeight);
  43006. if (desiredCaretY < 0)
  43007. {
  43008. vy = jmax (0, desiredCaretY + vy);
  43009. }
  43010. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43011. {
  43012. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43013. }
  43014. }
  43015. viewport->setViewPosition (vx, vy);
  43016. }
  43017. const Rectangle<int> TextEditor::getCaretRectangle()
  43018. {
  43019. updateCaretPosition();
  43020. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43021. roundToInt (cursorY) - viewport->getY(),
  43022. 1, roundToInt (cursorHeight));
  43023. }
  43024. float TextEditor::getWordWrapWidth() const
  43025. {
  43026. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43027. : 1.0e10f;
  43028. }
  43029. void TextEditor::updateTextHolderSize()
  43030. {
  43031. const float wordWrapWidth = getWordWrapWidth();
  43032. if (wordWrapWidth > 0)
  43033. {
  43034. float maxWidth = 0.0f;
  43035. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43036. while (i.next())
  43037. maxWidth = jmax (maxWidth, i.atomRight);
  43038. const int w = leftIndent + roundToInt (maxWidth);
  43039. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43040. currentFont.getHeight()));
  43041. textHolder->setSize (w + 1, h + 1);
  43042. }
  43043. }
  43044. int TextEditor::getTextWidth() const
  43045. {
  43046. return textHolder->getWidth();
  43047. }
  43048. int TextEditor::getTextHeight() const
  43049. {
  43050. return textHolder->getHeight();
  43051. }
  43052. void TextEditor::setIndents (const int newLeftIndent,
  43053. const int newTopIndent)
  43054. {
  43055. leftIndent = newLeftIndent;
  43056. topIndent = newTopIndent;
  43057. }
  43058. void TextEditor::setBorder (const BorderSize<int>& border)
  43059. {
  43060. borderSize = border;
  43061. resized();
  43062. }
  43063. const BorderSize<int> TextEditor::getBorder() const
  43064. {
  43065. return borderSize;
  43066. }
  43067. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43068. {
  43069. keepCursorOnScreen = shouldScrollToShowCursor;
  43070. }
  43071. void TextEditor::updateCaretPosition()
  43072. {
  43073. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43074. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43075. }
  43076. void TextEditor::scrollToMakeSureCursorIsVisible()
  43077. {
  43078. updateCaretPosition();
  43079. if (keepCursorOnScreen)
  43080. {
  43081. int x = viewport->getViewPositionX();
  43082. int y = viewport->getViewPositionY();
  43083. const int relativeCursorX = roundToInt (cursorX) - x;
  43084. const int relativeCursorY = roundToInt (cursorY) - y;
  43085. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43086. {
  43087. x += relativeCursorX - proportionOfWidth (0.2f);
  43088. }
  43089. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43090. {
  43091. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43092. }
  43093. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43094. if (! isMultiLine())
  43095. {
  43096. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43097. }
  43098. else
  43099. {
  43100. const int curH = roundToInt (cursorHeight);
  43101. if (relativeCursorY < 0)
  43102. {
  43103. y = jmax (0, relativeCursorY + y);
  43104. }
  43105. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43106. {
  43107. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43108. }
  43109. }
  43110. viewport->setViewPosition (x, y);
  43111. }
  43112. }
  43113. void TextEditor::moveCursorTo (const int newPosition,
  43114. const bool isSelecting)
  43115. {
  43116. if (isSelecting)
  43117. {
  43118. moveCaret (newPosition);
  43119. const Range<int> oldSelection (selection);
  43120. if (dragType == notDragging)
  43121. {
  43122. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43123. dragType = draggingSelectionStart;
  43124. else
  43125. dragType = draggingSelectionEnd;
  43126. }
  43127. if (dragType == draggingSelectionStart)
  43128. {
  43129. if (getCaretPosition() >= selection.getEnd())
  43130. dragType = draggingSelectionEnd;
  43131. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43132. }
  43133. else
  43134. {
  43135. if (getCaretPosition() < selection.getStart())
  43136. dragType = draggingSelectionStart;
  43137. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43138. }
  43139. repaintText (selection.getUnionWith (oldSelection));
  43140. }
  43141. else
  43142. {
  43143. dragType = notDragging;
  43144. repaintText (selection);
  43145. moveCaret (newPosition);
  43146. selection = Range<int>::emptyRange (getCaretPosition());
  43147. }
  43148. }
  43149. int TextEditor::getTextIndexAt (const int x,
  43150. const int y)
  43151. {
  43152. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43153. (float) (y + viewport->getViewPositionY() - topIndent));
  43154. }
  43155. void TextEditor::insertTextAtCaret (const String& newText_)
  43156. {
  43157. String newText (newText_);
  43158. if (allowedCharacters.isNotEmpty())
  43159. newText = newText.retainCharacters (allowedCharacters);
  43160. if (! isMultiLine())
  43161. newText = newText.replaceCharacters ("\r\n", " ");
  43162. else
  43163. newText = newText.replace ("\r\n", "\n");
  43164. const int newCaretPos = selection.getStart() + newText.length();
  43165. const int insertIndex = selection.getStart();
  43166. remove (selection, getUndoManager(),
  43167. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43168. if (maxTextLength > 0)
  43169. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43170. if (newText.isNotEmpty())
  43171. insert (newText,
  43172. insertIndex,
  43173. currentFont,
  43174. findColour (textColourId),
  43175. getUndoManager(),
  43176. newCaretPos);
  43177. textChanged();
  43178. }
  43179. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43180. {
  43181. moveCursorTo (newSelection.getStart(), false);
  43182. moveCursorTo (newSelection.getEnd(), true);
  43183. }
  43184. void TextEditor::copy()
  43185. {
  43186. if (passwordCharacter == 0)
  43187. {
  43188. const String selectedText (getHighlightedText());
  43189. if (selectedText.isNotEmpty())
  43190. SystemClipboard::copyTextToClipboard (selectedText);
  43191. }
  43192. }
  43193. void TextEditor::paste()
  43194. {
  43195. if (! isReadOnly())
  43196. {
  43197. const String clip (SystemClipboard::getTextFromClipboard());
  43198. if (clip.isNotEmpty())
  43199. insertTextAtCaret (clip);
  43200. }
  43201. }
  43202. void TextEditor::cut()
  43203. {
  43204. if (! isReadOnly())
  43205. {
  43206. moveCaret (selection.getEnd());
  43207. insertTextAtCaret (String::empty);
  43208. }
  43209. }
  43210. void TextEditor::drawContent (Graphics& g)
  43211. {
  43212. const float wordWrapWidth = getWordWrapWidth();
  43213. if (wordWrapWidth > 0)
  43214. {
  43215. g.setOrigin (leftIndent, topIndent);
  43216. const Rectangle<int> clip (g.getClipBounds());
  43217. Colour selectedTextColour;
  43218. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43219. while (i.lineY + 200.0 < clip.getY() && i.next())
  43220. {}
  43221. if (! selection.isEmpty())
  43222. {
  43223. g.setColour (findColour (highlightColourId)
  43224. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43225. selectedTextColour = findColour (highlightedTextColourId);
  43226. Iterator i2 (i);
  43227. while (i2.next() && i2.lineY < clip.getBottom())
  43228. {
  43229. if (i2.lineY + i2.lineHeight >= clip.getY()
  43230. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43231. {
  43232. i2.drawSelection (g, selection);
  43233. }
  43234. }
  43235. }
  43236. const UniformTextSection* lastSection = 0;
  43237. while (i.next() && i.lineY < clip.getBottom())
  43238. {
  43239. if (i.lineY + i.lineHeight >= clip.getY())
  43240. {
  43241. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43242. {
  43243. i.drawSelectedText (g, selection, selectedTextColour);
  43244. lastSection = 0;
  43245. }
  43246. else
  43247. {
  43248. i.draw (g, lastSection);
  43249. }
  43250. }
  43251. }
  43252. }
  43253. }
  43254. void TextEditor::paint (Graphics& g)
  43255. {
  43256. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43257. }
  43258. void TextEditor::paintOverChildren (Graphics& g)
  43259. {
  43260. if (caretFlashState
  43261. && hasKeyboardFocus (false)
  43262. && caretVisible
  43263. && ! isReadOnly())
  43264. {
  43265. g.setColour (findColour (caretColourId));
  43266. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43267. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43268. 2.0f, cursorHeight);
  43269. }
  43270. if (textToShowWhenEmpty.isNotEmpty()
  43271. && (! hasKeyboardFocus (false))
  43272. && getTotalNumChars() == 0)
  43273. {
  43274. g.setColour (colourForTextWhenEmpty);
  43275. g.setFont (getFont());
  43276. if (isMultiLine())
  43277. {
  43278. g.drawText (textToShowWhenEmpty,
  43279. 0, 0, getWidth(), getHeight(),
  43280. Justification::centred, true);
  43281. }
  43282. else
  43283. {
  43284. g.drawText (textToShowWhenEmpty,
  43285. leftIndent, topIndent,
  43286. viewport->getWidth() - leftIndent,
  43287. viewport->getHeight() - topIndent,
  43288. Justification::centredLeft, true);
  43289. }
  43290. }
  43291. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43292. }
  43293. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43294. {
  43295. public:
  43296. TextEditorMenuPerformer (TextEditor* const editor_)
  43297. : editor (editor_)
  43298. {
  43299. }
  43300. void modalStateFinished (int returnValue)
  43301. {
  43302. if (editor != 0 && returnValue != 0)
  43303. editor->performPopupMenuAction (returnValue);
  43304. }
  43305. private:
  43306. Component::SafePointer<TextEditor> editor;
  43307. JUCE_DECLARE_NON_COPYABLE (TextEditorMenuPerformer);
  43308. };
  43309. void TextEditor::mouseDown (const MouseEvent& e)
  43310. {
  43311. beginDragAutoRepeat (100);
  43312. newTransaction();
  43313. if (wasFocused || ! selectAllTextWhenFocused)
  43314. {
  43315. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43316. {
  43317. moveCursorTo (getTextIndexAt (e.x, e.y),
  43318. e.mods.isShiftDown());
  43319. }
  43320. else
  43321. {
  43322. PopupMenu m;
  43323. m.setLookAndFeel (&getLookAndFeel());
  43324. addPopupMenuItems (m, &e);
  43325. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43326. }
  43327. }
  43328. }
  43329. void TextEditor::mouseDrag (const MouseEvent& e)
  43330. {
  43331. if (wasFocused || ! selectAllTextWhenFocused)
  43332. {
  43333. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43334. {
  43335. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43336. }
  43337. }
  43338. }
  43339. void TextEditor::mouseUp (const MouseEvent& e)
  43340. {
  43341. newTransaction();
  43342. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43343. if (wasFocused || ! selectAllTextWhenFocused)
  43344. {
  43345. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43346. {
  43347. moveCaret (getTextIndexAt (e.x, e.y));
  43348. }
  43349. }
  43350. wasFocused = true;
  43351. }
  43352. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43353. {
  43354. int tokenEnd = getTextIndexAt (e.x, e.y);
  43355. int tokenStart = tokenEnd;
  43356. if (e.getNumberOfClicks() > 3)
  43357. {
  43358. tokenStart = 0;
  43359. tokenEnd = getTotalNumChars();
  43360. }
  43361. else
  43362. {
  43363. const String t (getText());
  43364. const int totalLength = getTotalNumChars();
  43365. while (tokenEnd < totalLength)
  43366. {
  43367. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43368. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43369. ++tokenEnd;
  43370. else
  43371. break;
  43372. }
  43373. tokenStart = tokenEnd;
  43374. while (tokenStart > 0)
  43375. {
  43376. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43377. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43378. --tokenStart;
  43379. else
  43380. break;
  43381. }
  43382. if (e.getNumberOfClicks() > 2)
  43383. {
  43384. while (tokenEnd < totalLength)
  43385. {
  43386. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43387. ++tokenEnd;
  43388. else
  43389. break;
  43390. }
  43391. while (tokenStart > 0)
  43392. {
  43393. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43394. --tokenStart;
  43395. else
  43396. break;
  43397. }
  43398. }
  43399. }
  43400. moveCursorTo (tokenEnd, false);
  43401. moveCursorTo (tokenStart, true);
  43402. }
  43403. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43404. {
  43405. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43406. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43407. }
  43408. bool TextEditor::keyPressed (const KeyPress& key)
  43409. {
  43410. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43411. return false;
  43412. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43413. if (key.isKeyCode (KeyPress::leftKey)
  43414. || key.isKeyCode (KeyPress::upKey))
  43415. {
  43416. newTransaction();
  43417. int newPos;
  43418. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43419. newPos = indexAtPosition (cursorX, cursorY - 1);
  43420. else if (moveInWholeWordSteps)
  43421. newPos = findWordBreakBefore (getCaretPosition());
  43422. else
  43423. newPos = getCaretPosition() - 1;
  43424. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43425. }
  43426. else if (key.isKeyCode (KeyPress::rightKey)
  43427. || key.isKeyCode (KeyPress::downKey))
  43428. {
  43429. newTransaction();
  43430. int newPos;
  43431. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43432. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43433. else if (moveInWholeWordSteps)
  43434. newPos = findWordBreakAfter (getCaretPosition());
  43435. else
  43436. newPos = getCaretPosition() + 1;
  43437. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43438. }
  43439. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43440. {
  43441. newTransaction();
  43442. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43443. key.getModifiers().isShiftDown());
  43444. }
  43445. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43446. {
  43447. newTransaction();
  43448. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43449. key.getModifiers().isShiftDown());
  43450. }
  43451. else if (key.isKeyCode (KeyPress::homeKey))
  43452. {
  43453. newTransaction();
  43454. if (isMultiLine() && ! moveInWholeWordSteps)
  43455. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43456. key.getModifiers().isShiftDown());
  43457. else
  43458. moveCursorTo (0, key.getModifiers().isShiftDown());
  43459. }
  43460. else if (key.isKeyCode (KeyPress::endKey))
  43461. {
  43462. newTransaction();
  43463. if (isMultiLine() && ! moveInWholeWordSteps)
  43464. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43465. key.getModifiers().isShiftDown());
  43466. else
  43467. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43468. }
  43469. else if (key.isKeyCode (KeyPress::backspaceKey))
  43470. {
  43471. if (moveInWholeWordSteps)
  43472. {
  43473. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43474. }
  43475. else
  43476. {
  43477. if (selection.isEmpty() && selection.getStart() > 0)
  43478. selection.setStart (selection.getEnd() - 1);
  43479. }
  43480. cut();
  43481. }
  43482. else if (key.isKeyCode (KeyPress::deleteKey))
  43483. {
  43484. if (key.getModifiers().isShiftDown())
  43485. copy();
  43486. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43487. selection.setEnd (selection.getStart() + 1);
  43488. cut();
  43489. }
  43490. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43491. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43492. {
  43493. newTransaction();
  43494. copy();
  43495. }
  43496. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43497. {
  43498. newTransaction();
  43499. copy();
  43500. cut();
  43501. }
  43502. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43503. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43504. {
  43505. newTransaction();
  43506. paste();
  43507. }
  43508. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43509. {
  43510. newTransaction();
  43511. doUndoRedo (false);
  43512. }
  43513. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43514. {
  43515. newTransaction();
  43516. doUndoRedo (true);
  43517. }
  43518. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43519. {
  43520. newTransaction();
  43521. moveCursorTo (getTotalNumChars(), false);
  43522. moveCursorTo (0, true);
  43523. }
  43524. else if (key == KeyPress::returnKey)
  43525. {
  43526. newTransaction();
  43527. if (returnKeyStartsNewLine)
  43528. insertTextAtCaret ("\n");
  43529. else
  43530. returnPressed();
  43531. }
  43532. else if (key.isKeyCode (KeyPress::escapeKey))
  43533. {
  43534. newTransaction();
  43535. moveCursorTo (getCaretPosition(), false);
  43536. escapePressed();
  43537. }
  43538. else if (key.getTextCharacter() >= ' '
  43539. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43540. {
  43541. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43542. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43543. }
  43544. else
  43545. {
  43546. return false;
  43547. }
  43548. return true;
  43549. }
  43550. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43551. {
  43552. if (! isKeyDown)
  43553. return false;
  43554. #if JUCE_WINDOWS
  43555. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43556. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43557. #endif
  43558. // (overridden to avoid forwarding key events to the parent)
  43559. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43560. }
  43561. const int baseMenuItemID = 0x7fff0000;
  43562. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43563. {
  43564. const bool writable = ! isReadOnly();
  43565. if (passwordCharacter == 0)
  43566. {
  43567. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43568. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43569. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43570. }
  43571. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43572. m.addSeparator();
  43573. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43574. m.addSeparator();
  43575. if (getUndoManager() != 0)
  43576. {
  43577. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43578. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43579. }
  43580. }
  43581. void TextEditor::performPopupMenuAction (const int menuItemID)
  43582. {
  43583. switch (menuItemID)
  43584. {
  43585. case baseMenuItemID + 1:
  43586. copy();
  43587. cut();
  43588. break;
  43589. case baseMenuItemID + 2:
  43590. copy();
  43591. break;
  43592. case baseMenuItemID + 3:
  43593. paste();
  43594. break;
  43595. case baseMenuItemID + 4:
  43596. cut();
  43597. break;
  43598. case baseMenuItemID + 5:
  43599. moveCursorTo (getTotalNumChars(), false);
  43600. moveCursorTo (0, true);
  43601. break;
  43602. case baseMenuItemID + 6:
  43603. doUndoRedo (false);
  43604. break;
  43605. case baseMenuItemID + 7:
  43606. doUndoRedo (true);
  43607. break;
  43608. default:
  43609. break;
  43610. }
  43611. }
  43612. void TextEditor::focusGained (FocusChangeType)
  43613. {
  43614. newTransaction();
  43615. caretFlashState = true;
  43616. if (selectAllTextWhenFocused)
  43617. {
  43618. moveCursorTo (0, false);
  43619. moveCursorTo (getTotalNumChars(), true);
  43620. }
  43621. repaint();
  43622. if (caretVisible)
  43623. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43624. ComponentPeer* const peer = getPeer();
  43625. if (peer != 0 && ! isReadOnly())
  43626. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43627. }
  43628. void TextEditor::focusLost (FocusChangeType)
  43629. {
  43630. newTransaction();
  43631. wasFocused = false;
  43632. textHolder->stopTimer();
  43633. caretFlashState = false;
  43634. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43635. repaint();
  43636. }
  43637. void TextEditor::resized()
  43638. {
  43639. viewport->setBoundsInset (borderSize);
  43640. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43641. updateTextHolderSize();
  43642. if (! isMultiLine())
  43643. {
  43644. scrollToMakeSureCursorIsVisible();
  43645. }
  43646. else
  43647. {
  43648. updateCaretPosition();
  43649. }
  43650. }
  43651. void TextEditor::handleCommandMessage (const int commandId)
  43652. {
  43653. Component::BailOutChecker checker (this);
  43654. switch (commandId)
  43655. {
  43656. case TextEditorDefs::textChangeMessageId:
  43657. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43658. break;
  43659. case TextEditorDefs::returnKeyMessageId:
  43660. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43661. break;
  43662. case TextEditorDefs::escapeKeyMessageId:
  43663. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43664. break;
  43665. case TextEditorDefs::focusLossMessageId:
  43666. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43667. break;
  43668. default:
  43669. jassertfalse;
  43670. break;
  43671. }
  43672. }
  43673. void TextEditor::enablementChanged()
  43674. {
  43675. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43676. : MouseCursor::IBeamCursor);
  43677. repaint();
  43678. }
  43679. UndoManager* TextEditor::getUndoManager() throw()
  43680. {
  43681. return isReadOnly() ? 0 : &undoManager;
  43682. }
  43683. void TextEditor::clearInternal (UndoManager* const um)
  43684. {
  43685. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43686. }
  43687. void TextEditor::insert (const String& text,
  43688. const int insertIndex,
  43689. const Font& font,
  43690. const Colour& colour,
  43691. UndoManager* const um,
  43692. const int caretPositionToMoveTo)
  43693. {
  43694. if (text.isNotEmpty())
  43695. {
  43696. if (um != 0)
  43697. {
  43698. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43699. newTransaction();
  43700. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43701. caretPosition, caretPositionToMoveTo));
  43702. }
  43703. else
  43704. {
  43705. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43706. // a line gets moved due to word wrap
  43707. int index = 0;
  43708. int nextIndex = 0;
  43709. for (int i = 0; i < sections.size(); ++i)
  43710. {
  43711. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43712. if (insertIndex == index)
  43713. {
  43714. sections.insert (i, new UniformTextSection (text,
  43715. font, colour,
  43716. passwordCharacter));
  43717. break;
  43718. }
  43719. else if (insertIndex > index && insertIndex < nextIndex)
  43720. {
  43721. splitSection (i, insertIndex - index);
  43722. sections.insert (i + 1, new UniformTextSection (text,
  43723. font, colour,
  43724. passwordCharacter));
  43725. break;
  43726. }
  43727. index = nextIndex;
  43728. }
  43729. if (nextIndex == insertIndex)
  43730. sections.add (new UniformTextSection (text,
  43731. font, colour,
  43732. passwordCharacter));
  43733. coalesceSimilarSections();
  43734. totalNumChars = -1;
  43735. valueTextNeedsUpdating = true;
  43736. moveCursorTo (caretPositionToMoveTo, false);
  43737. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43738. }
  43739. }
  43740. }
  43741. void TextEditor::reinsert (const int insertIndex,
  43742. const Array <UniformTextSection*>& sectionsToInsert)
  43743. {
  43744. int index = 0;
  43745. int nextIndex = 0;
  43746. for (int i = 0; i < sections.size(); ++i)
  43747. {
  43748. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43749. if (insertIndex == index)
  43750. {
  43751. for (int j = sectionsToInsert.size(); --j >= 0;)
  43752. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43753. break;
  43754. }
  43755. else if (insertIndex > index && insertIndex < nextIndex)
  43756. {
  43757. splitSection (i, insertIndex - index);
  43758. for (int j = sectionsToInsert.size(); --j >= 0;)
  43759. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43760. break;
  43761. }
  43762. index = nextIndex;
  43763. }
  43764. if (nextIndex == insertIndex)
  43765. {
  43766. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43767. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43768. }
  43769. coalesceSimilarSections();
  43770. totalNumChars = -1;
  43771. valueTextNeedsUpdating = true;
  43772. }
  43773. void TextEditor::remove (const Range<int>& range,
  43774. UndoManager* const um,
  43775. const int caretPositionToMoveTo)
  43776. {
  43777. if (! range.isEmpty())
  43778. {
  43779. int index = 0;
  43780. for (int i = 0; i < sections.size(); ++i)
  43781. {
  43782. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43783. if (range.getStart() > index && range.getStart() < nextIndex)
  43784. {
  43785. splitSection (i, range.getStart() - index);
  43786. --i;
  43787. }
  43788. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43789. {
  43790. splitSection (i, range.getEnd() - index);
  43791. --i;
  43792. }
  43793. else
  43794. {
  43795. index = nextIndex;
  43796. if (index > range.getEnd())
  43797. break;
  43798. }
  43799. }
  43800. index = 0;
  43801. if (um != 0)
  43802. {
  43803. Array <UniformTextSection*> removedSections;
  43804. for (int i = 0; i < sections.size(); ++i)
  43805. {
  43806. if (range.getEnd() <= range.getStart())
  43807. break;
  43808. UniformTextSection* const section = sections.getUnchecked (i);
  43809. const int nextIndex = index + section->getTotalLength();
  43810. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43811. removedSections.add (new UniformTextSection (*section));
  43812. index = nextIndex;
  43813. }
  43814. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43815. newTransaction();
  43816. um->perform (new RemoveAction (*this, range, caretPosition,
  43817. caretPositionToMoveTo, removedSections));
  43818. }
  43819. else
  43820. {
  43821. Range<int> remainingRange (range);
  43822. for (int i = 0; i < sections.size(); ++i)
  43823. {
  43824. UniformTextSection* const section = sections.getUnchecked (i);
  43825. const int nextIndex = index + section->getTotalLength();
  43826. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43827. {
  43828. sections.remove(i);
  43829. section->clear();
  43830. delete section;
  43831. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43832. if (remainingRange.isEmpty())
  43833. break;
  43834. --i;
  43835. }
  43836. else
  43837. {
  43838. index = nextIndex;
  43839. }
  43840. }
  43841. coalesceSimilarSections();
  43842. totalNumChars = -1;
  43843. valueTextNeedsUpdating = true;
  43844. moveCursorTo (caretPositionToMoveTo, false);
  43845. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43846. }
  43847. }
  43848. }
  43849. const String TextEditor::getText() const
  43850. {
  43851. String t;
  43852. t.preallocateStorage (getTotalNumChars());
  43853. String::Concatenator concatenator (t);
  43854. for (int i = 0; i < sections.size(); ++i)
  43855. sections.getUnchecked (i)->appendAllText (concatenator);
  43856. return t;
  43857. }
  43858. const String TextEditor::getTextInRange (const Range<int>& range) const
  43859. {
  43860. String t;
  43861. if (! range.isEmpty())
  43862. {
  43863. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43864. String::Concatenator concatenator (t);
  43865. int index = 0;
  43866. for (int i = 0; i < sections.size(); ++i)
  43867. {
  43868. const UniformTextSection* const s = sections.getUnchecked (i);
  43869. const int nextIndex = index + s->getTotalLength();
  43870. if (range.getStart() < nextIndex)
  43871. {
  43872. if (range.getEnd() <= index)
  43873. break;
  43874. s->appendSubstring (concatenator, range - index);
  43875. }
  43876. index = nextIndex;
  43877. }
  43878. }
  43879. return t;
  43880. }
  43881. const String TextEditor::getHighlightedText() const
  43882. {
  43883. return getTextInRange (selection);
  43884. }
  43885. int TextEditor::getTotalNumChars() const
  43886. {
  43887. if (totalNumChars < 0)
  43888. {
  43889. totalNumChars = 0;
  43890. for (int i = sections.size(); --i >= 0;)
  43891. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43892. }
  43893. return totalNumChars;
  43894. }
  43895. bool TextEditor::isEmpty() const
  43896. {
  43897. return getTotalNumChars() == 0;
  43898. }
  43899. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43900. {
  43901. const float wordWrapWidth = getWordWrapWidth();
  43902. if (wordWrapWidth > 0 && sections.size() > 0)
  43903. {
  43904. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43905. i.getCharPosition (index, cx, cy, lineHeight);
  43906. }
  43907. else
  43908. {
  43909. cx = cy = 0;
  43910. lineHeight = currentFont.getHeight();
  43911. }
  43912. }
  43913. int TextEditor::indexAtPosition (const float x, const float y)
  43914. {
  43915. const float wordWrapWidth = getWordWrapWidth();
  43916. if (wordWrapWidth > 0)
  43917. {
  43918. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43919. while (i.next())
  43920. {
  43921. if (i.lineY + i.lineHeight > y)
  43922. {
  43923. if (i.lineY > y)
  43924. return jmax (0, i.indexInText - 1);
  43925. if (i.atomX >= x)
  43926. return i.indexInText;
  43927. if (x < i.atomRight)
  43928. return i.xToIndex (x);
  43929. }
  43930. }
  43931. }
  43932. return getTotalNumChars();
  43933. }
  43934. int TextEditor::findWordBreakAfter (const int position) const
  43935. {
  43936. const String t (getTextInRange (Range<int> (position, position + 512)));
  43937. const int totalLength = t.length();
  43938. int i = 0;
  43939. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43940. ++i;
  43941. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  43942. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  43943. ++i;
  43944. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43945. ++i;
  43946. return position + i;
  43947. }
  43948. int TextEditor::findWordBreakBefore (const int position) const
  43949. {
  43950. if (position <= 0)
  43951. return 0;
  43952. const int startOfBuffer = jmax (0, position - 512);
  43953. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43954. int i = position - startOfBuffer;
  43955. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43956. --i;
  43957. if (i > 0)
  43958. {
  43959. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  43960. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  43961. --i;
  43962. }
  43963. jassert (startOfBuffer + i >= 0);
  43964. return startOfBuffer + i;
  43965. }
  43966. void TextEditor::splitSection (const int sectionIndex,
  43967. const int charToSplitAt)
  43968. {
  43969. jassert (sections[sectionIndex] != 0);
  43970. sections.insert (sectionIndex + 1,
  43971. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43972. }
  43973. void TextEditor::coalesceSimilarSections()
  43974. {
  43975. for (int i = 0; i < sections.size() - 1; ++i)
  43976. {
  43977. UniformTextSection* const s1 = sections.getUnchecked (i);
  43978. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43979. if (s1->font == s2->font
  43980. && s1->colour == s2->colour)
  43981. {
  43982. s1->append (*s2, passwordCharacter);
  43983. sections.remove (i + 1);
  43984. delete s2;
  43985. --i;
  43986. }
  43987. }
  43988. }
  43989. END_JUCE_NAMESPACE
  43990. /*** End of inlined file: juce_TextEditor.cpp ***/
  43991. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43992. BEGIN_JUCE_NAMESPACE
  43993. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43994. class ToolbarSpacerComp : public ToolbarItemComponent
  43995. {
  43996. public:
  43997. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43998. : ToolbarItemComponent (itemId_, String::empty, false),
  43999. fixedSize (fixedSize_),
  44000. drawBar (drawBar_)
  44001. {
  44002. }
  44003. ~ToolbarSpacerComp()
  44004. {
  44005. }
  44006. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44007. int& preferredSize, int& minSize, int& maxSize)
  44008. {
  44009. if (fixedSize <= 0)
  44010. {
  44011. preferredSize = toolbarThickness * 2;
  44012. minSize = 4;
  44013. maxSize = 32768;
  44014. }
  44015. else
  44016. {
  44017. maxSize = roundToInt (toolbarThickness * fixedSize);
  44018. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44019. preferredSize = maxSize;
  44020. if (getEditingMode() == editableOnPalette)
  44021. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44022. }
  44023. return true;
  44024. }
  44025. void paintButtonArea (Graphics&, int, int, bool, bool)
  44026. {
  44027. }
  44028. void contentAreaChanged (const Rectangle<int>&)
  44029. {
  44030. }
  44031. int getResizeOrder() const throw()
  44032. {
  44033. return fixedSize <= 0 ? 0 : 1;
  44034. }
  44035. void paint (Graphics& g)
  44036. {
  44037. const int w = getWidth();
  44038. const int h = getHeight();
  44039. if (drawBar)
  44040. {
  44041. g.setColour (findColour (Toolbar::separatorColourId, true));
  44042. const float thickness = 0.2f;
  44043. if (isToolbarVertical())
  44044. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44045. else
  44046. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44047. }
  44048. if (getEditingMode() != normalMode && ! drawBar)
  44049. {
  44050. g.setColour (findColour (Toolbar::separatorColourId, true));
  44051. const int indentX = jmin (2, (w - 3) / 2);
  44052. const int indentY = jmin (2, (h - 3) / 2);
  44053. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44054. if (fixedSize <= 0)
  44055. {
  44056. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44057. if (isToolbarVertical())
  44058. {
  44059. x1 = w * 0.5f;
  44060. y1 = h * 0.4f;
  44061. x2 = x1;
  44062. y2 = indentX * 2.0f;
  44063. x3 = x1;
  44064. y3 = h * 0.6f;
  44065. x4 = x1;
  44066. y4 = h - y2;
  44067. hw = w * 0.15f;
  44068. hl = w * 0.2f;
  44069. }
  44070. else
  44071. {
  44072. x1 = w * 0.4f;
  44073. y1 = h * 0.5f;
  44074. x2 = indentX * 2.0f;
  44075. y2 = y1;
  44076. x3 = w * 0.6f;
  44077. y3 = y1;
  44078. x4 = w - x2;
  44079. y4 = y1;
  44080. hw = h * 0.15f;
  44081. hl = h * 0.2f;
  44082. }
  44083. Path p;
  44084. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44085. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44086. g.fillPath (p);
  44087. }
  44088. }
  44089. }
  44090. private:
  44091. const float fixedSize;
  44092. const bool drawBar;
  44093. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  44094. };
  44095. class Toolbar::MissingItemsComponent : public PopupMenu::CustomComponent
  44096. {
  44097. public:
  44098. MissingItemsComponent (Toolbar& owner_, const int height_)
  44099. : PopupMenu::CustomComponent (true),
  44100. owner (&owner_),
  44101. height (height_)
  44102. {
  44103. for (int i = owner_.items.size(); --i >= 0;)
  44104. {
  44105. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44106. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44107. {
  44108. oldIndexes.insert (0, i);
  44109. addAndMakeVisible (tc, 0);
  44110. }
  44111. }
  44112. layout (400);
  44113. }
  44114. ~MissingItemsComponent()
  44115. {
  44116. if (owner != 0)
  44117. {
  44118. for (int i = 0; i < getNumChildComponents(); ++i)
  44119. {
  44120. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44121. if (tc != 0)
  44122. {
  44123. tc->setVisible (false);
  44124. const int index = oldIndexes.remove (i);
  44125. owner->addChildComponent (tc, index);
  44126. --i;
  44127. }
  44128. }
  44129. owner->resized();
  44130. }
  44131. }
  44132. void layout (const int preferredWidth)
  44133. {
  44134. const int indent = 8;
  44135. int x = indent;
  44136. int y = indent;
  44137. int maxX = 0;
  44138. for (int i = 0; i < getNumChildComponents(); ++i)
  44139. {
  44140. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44141. if (tc != 0)
  44142. {
  44143. int preferredSize = 1, minSize = 1, maxSize = 1;
  44144. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44145. {
  44146. if (x + preferredSize > preferredWidth && x > indent)
  44147. {
  44148. x = indent;
  44149. y += height;
  44150. }
  44151. tc->setBounds (x, y, preferredSize, height);
  44152. x += preferredSize;
  44153. maxX = jmax (maxX, x);
  44154. }
  44155. }
  44156. }
  44157. setSize (maxX + 8, y + height + 8);
  44158. }
  44159. void getIdealSize (int& idealWidth, int& idealHeight)
  44160. {
  44161. idealWidth = getWidth();
  44162. idealHeight = getHeight();
  44163. }
  44164. private:
  44165. Component::SafePointer<Toolbar> owner;
  44166. const int height;
  44167. Array <int> oldIndexes;
  44168. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44169. };
  44170. Toolbar::Toolbar()
  44171. : vertical (false),
  44172. isEditingActive (false),
  44173. toolbarStyle (Toolbar::iconsOnly)
  44174. {
  44175. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44176. missingItemsButton->setAlwaysOnTop (true);
  44177. missingItemsButton->addListener (this);
  44178. }
  44179. Toolbar::~Toolbar()
  44180. {
  44181. items.clear();
  44182. }
  44183. void Toolbar::setVertical (const bool shouldBeVertical)
  44184. {
  44185. if (vertical != shouldBeVertical)
  44186. {
  44187. vertical = shouldBeVertical;
  44188. resized();
  44189. }
  44190. }
  44191. void Toolbar::clear()
  44192. {
  44193. items.clear();
  44194. resized();
  44195. }
  44196. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44197. {
  44198. if (itemId == ToolbarItemFactory::separatorBarId)
  44199. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44200. else if (itemId == ToolbarItemFactory::spacerId)
  44201. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44202. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44203. return new ToolbarSpacerComp (itemId, 0, false);
  44204. return factory.createItem (itemId);
  44205. }
  44206. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44207. const int itemId,
  44208. const int insertIndex)
  44209. {
  44210. // An ID can't be zero - this might indicate a mistake somewhere?
  44211. jassert (itemId != 0);
  44212. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44213. if (tc != 0)
  44214. {
  44215. #if JUCE_DEBUG
  44216. Array <int> allowedIds;
  44217. factory.getAllToolbarItemIds (allowedIds);
  44218. // If your factory can create an item for a given ID, it must also return
  44219. // that ID from its getAllToolbarItemIds() method!
  44220. jassert (allowedIds.contains (itemId));
  44221. #endif
  44222. items.insert (insertIndex, tc);
  44223. addAndMakeVisible (tc, insertIndex);
  44224. }
  44225. }
  44226. void Toolbar::addItem (ToolbarItemFactory& factory,
  44227. const int itemId,
  44228. const int insertIndex)
  44229. {
  44230. addItemInternal (factory, itemId, insertIndex);
  44231. resized();
  44232. }
  44233. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44234. {
  44235. Array <int> ids;
  44236. factoryToUse.getDefaultItemSet (ids);
  44237. clear();
  44238. for (int i = 0; i < ids.size(); ++i)
  44239. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44240. resized();
  44241. }
  44242. void Toolbar::removeToolbarItem (const int itemIndex)
  44243. {
  44244. items.remove (itemIndex);
  44245. resized();
  44246. }
  44247. int Toolbar::getNumItems() const throw()
  44248. {
  44249. return items.size();
  44250. }
  44251. int Toolbar::getItemId (const int itemIndex) const throw()
  44252. {
  44253. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44254. return tc != 0 ? tc->getItemId() : 0;
  44255. }
  44256. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44257. {
  44258. return items [itemIndex];
  44259. }
  44260. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44261. {
  44262. for (;;)
  44263. {
  44264. index += delta;
  44265. ToolbarItemComponent* const tc = getItemComponent (index);
  44266. if (tc == 0)
  44267. break;
  44268. if (tc->isActive)
  44269. return tc;
  44270. }
  44271. return 0;
  44272. }
  44273. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44274. {
  44275. if (toolbarStyle != newStyle)
  44276. {
  44277. toolbarStyle = newStyle;
  44278. updateAllItemPositions (false);
  44279. }
  44280. }
  44281. const String Toolbar::toString() const
  44282. {
  44283. String s ("TB:");
  44284. for (int i = 0; i < getNumItems(); ++i)
  44285. s << getItemId(i) << ' ';
  44286. return s.trimEnd();
  44287. }
  44288. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44289. const String& savedVersion)
  44290. {
  44291. if (! savedVersion.startsWith ("TB:"))
  44292. return false;
  44293. StringArray tokens;
  44294. tokens.addTokens (savedVersion.substring (3), false);
  44295. clear();
  44296. for (int i = 0; i < tokens.size(); ++i)
  44297. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44298. resized();
  44299. return true;
  44300. }
  44301. void Toolbar::paint (Graphics& g)
  44302. {
  44303. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44304. }
  44305. int Toolbar::getThickness() const throw()
  44306. {
  44307. return vertical ? getWidth() : getHeight();
  44308. }
  44309. int Toolbar::getLength() const throw()
  44310. {
  44311. return vertical ? getHeight() : getWidth();
  44312. }
  44313. void Toolbar::setEditingActive (const bool active)
  44314. {
  44315. if (isEditingActive != active)
  44316. {
  44317. isEditingActive = active;
  44318. updateAllItemPositions (false);
  44319. }
  44320. }
  44321. void Toolbar::resized()
  44322. {
  44323. updateAllItemPositions (false);
  44324. }
  44325. void Toolbar::updateAllItemPositions (const bool animate)
  44326. {
  44327. if (getWidth() > 0 && getHeight() > 0)
  44328. {
  44329. StretchableObjectResizer resizer;
  44330. int i;
  44331. for (i = 0; i < items.size(); ++i)
  44332. {
  44333. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44334. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44335. : ToolbarItemComponent::normalMode);
  44336. tc->setStyle (toolbarStyle);
  44337. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44338. int preferredSize = 1, minSize = 1, maxSize = 1;
  44339. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44340. preferredSize, minSize, maxSize))
  44341. {
  44342. tc->isActive = true;
  44343. resizer.addItem (preferredSize, minSize, maxSize,
  44344. spacer != 0 ? spacer->getResizeOrder() : 2);
  44345. }
  44346. else
  44347. {
  44348. tc->isActive = false;
  44349. tc->setVisible (false);
  44350. }
  44351. }
  44352. resizer.resizeToFit (getLength());
  44353. int totalLength = 0;
  44354. for (i = 0; i < resizer.getNumItems(); ++i)
  44355. totalLength += (int) resizer.getItemSize (i);
  44356. const bool itemsOffTheEnd = totalLength > getLength();
  44357. const int extrasButtonSize = getThickness() / 2;
  44358. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44359. missingItemsButton->setVisible (itemsOffTheEnd);
  44360. missingItemsButton->setEnabled (! isEditingActive);
  44361. if (vertical)
  44362. missingItemsButton->setCentrePosition (getWidth() / 2,
  44363. getHeight() - 4 - extrasButtonSize / 2);
  44364. else
  44365. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44366. getHeight() / 2);
  44367. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44368. : missingItemsButton->getX()) - 4
  44369. : getLength();
  44370. int pos = 0, activeIndex = 0;
  44371. for (i = 0; i < items.size(); ++i)
  44372. {
  44373. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44374. if (tc->isActive)
  44375. {
  44376. const int size = (int) resizer.getItemSize (activeIndex++);
  44377. Rectangle<int> newBounds;
  44378. if (vertical)
  44379. newBounds.setBounds (0, pos, getWidth(), size);
  44380. else
  44381. newBounds.setBounds (pos, 0, size, getHeight());
  44382. if (animate)
  44383. {
  44384. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44385. }
  44386. else
  44387. {
  44388. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44389. tc->setBounds (newBounds);
  44390. }
  44391. pos += size;
  44392. tc->setVisible (pos <= maxLength
  44393. && ((! tc->isBeingDragged)
  44394. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44395. }
  44396. }
  44397. }
  44398. }
  44399. void Toolbar::buttonClicked (Button*)
  44400. {
  44401. jassert (missingItemsButton->isShowing());
  44402. if (missingItemsButton->isShowing())
  44403. {
  44404. PopupMenu m;
  44405. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44406. m.showAt (missingItemsButton);
  44407. }
  44408. }
  44409. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44410. Component* /*sourceComponent*/)
  44411. {
  44412. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44413. }
  44414. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44415. {
  44416. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44417. if (tc != 0)
  44418. {
  44419. if (! items.contains (tc))
  44420. {
  44421. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44422. {
  44423. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44424. if (palette != 0)
  44425. palette->replaceComponent (tc);
  44426. }
  44427. else
  44428. {
  44429. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44430. }
  44431. items.add (tc);
  44432. addChildComponent (tc);
  44433. updateAllItemPositions (true);
  44434. }
  44435. for (int i = getNumItems(); --i >= 0;)
  44436. {
  44437. const int currentIndex = items.indexOf (tc);
  44438. int newIndex = currentIndex;
  44439. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44440. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44441. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44442. .getComponentDestination (getChildComponent (newIndex)));
  44443. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44444. if (prev != 0)
  44445. {
  44446. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44447. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44448. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44449. {
  44450. newIndex = getIndexOfChildComponent (prev);
  44451. }
  44452. }
  44453. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44454. if (next != 0)
  44455. {
  44456. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44457. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44458. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44459. {
  44460. newIndex = getIndexOfChildComponent (next) + 1;
  44461. }
  44462. }
  44463. if (newIndex == currentIndex)
  44464. break;
  44465. items.removeObject (tc, false);
  44466. removeChildComponent (tc);
  44467. addChildComponent (tc, newIndex);
  44468. items.insert (newIndex, tc);
  44469. updateAllItemPositions (true);
  44470. }
  44471. }
  44472. }
  44473. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44474. {
  44475. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44476. if (tc != 0 && isParentOf (tc))
  44477. {
  44478. items.removeObject (tc, false);
  44479. removeChildComponent (tc);
  44480. updateAllItemPositions (true);
  44481. }
  44482. }
  44483. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44484. {
  44485. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44486. if (tc != 0)
  44487. tc->setState (Button::buttonNormal);
  44488. }
  44489. void Toolbar::mouseDown (const MouseEvent&)
  44490. {
  44491. }
  44492. class ToolbarCustomisationDialog : public DialogWindow
  44493. {
  44494. public:
  44495. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44496. Toolbar* const toolbar_,
  44497. const int optionFlags)
  44498. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44499. toolbar (toolbar_)
  44500. {
  44501. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44502. setResizable (true, true);
  44503. setResizeLimits (400, 300, 1500, 1000);
  44504. positionNearBar();
  44505. }
  44506. ~ToolbarCustomisationDialog()
  44507. {
  44508. setContentComponent (0, true);
  44509. }
  44510. void closeButtonPressed()
  44511. {
  44512. setVisible (false);
  44513. }
  44514. bool canModalEventBeSentToComponent (const Component* comp)
  44515. {
  44516. return toolbar->isParentOf (comp);
  44517. }
  44518. void positionNearBar()
  44519. {
  44520. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44521. const int tbx = toolbar->getScreenX();
  44522. const int tby = toolbar->getScreenY();
  44523. const int gap = 8;
  44524. int x, y;
  44525. if (toolbar->isVertical())
  44526. {
  44527. y = tby;
  44528. if (tbx > screenSize.getCentreX())
  44529. x = tbx - getWidth() - gap;
  44530. else
  44531. x = tbx + toolbar->getWidth() + gap;
  44532. }
  44533. else
  44534. {
  44535. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44536. if (tby > screenSize.getCentreY())
  44537. y = tby - getHeight() - gap;
  44538. else
  44539. y = tby + toolbar->getHeight() + gap;
  44540. }
  44541. setTopLeftPosition (x, y);
  44542. }
  44543. private:
  44544. Toolbar* const toolbar;
  44545. class CustomiserPanel : public Component,
  44546. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44547. private ButtonListener
  44548. {
  44549. public:
  44550. CustomiserPanel (ToolbarItemFactory& factory_,
  44551. Toolbar* const toolbar_,
  44552. const int optionFlags)
  44553. : factory (factory_),
  44554. toolbar (toolbar_),
  44555. palette (factory_, toolbar_),
  44556. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44557. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44558. defaultButton (TRANS ("Restore to default set of items"))
  44559. {
  44560. addAndMakeVisible (&palette);
  44561. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44562. | Toolbar::allowIconsWithTextChoice
  44563. | Toolbar::allowTextOnlyChoice)) != 0)
  44564. {
  44565. addAndMakeVisible (&styleBox);
  44566. styleBox.setEditableText (false);
  44567. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44568. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44569. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44570. int selectedStyle = 0;
  44571. switch (toolbar_->getStyle())
  44572. {
  44573. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44574. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44575. case Toolbar::textOnly: selectedStyle = 3; break;
  44576. }
  44577. styleBox.setSelectedId (selectedStyle);
  44578. styleBox.addListener (this);
  44579. }
  44580. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44581. {
  44582. addAndMakeVisible (&defaultButton);
  44583. defaultButton.addListener (this);
  44584. }
  44585. addAndMakeVisible (&instructions);
  44586. instructions.setFont (Font (13.0f));
  44587. setSize (500, 300);
  44588. }
  44589. void comboBoxChanged (ComboBox*)
  44590. {
  44591. switch (styleBox.getSelectedId())
  44592. {
  44593. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44594. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44595. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44596. }
  44597. palette.resized(); // to make it update the styles
  44598. }
  44599. void buttonClicked (Button*)
  44600. {
  44601. toolbar->addDefaultItems (factory);
  44602. }
  44603. void paint (Graphics& g)
  44604. {
  44605. Colour background;
  44606. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44607. if (dw != 0)
  44608. background = dw->getBackgroundColour();
  44609. g.setColour (background.contrasting().withAlpha (0.3f));
  44610. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44611. }
  44612. void resized()
  44613. {
  44614. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44615. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44616. defaultButton.changeWidthToFitText (22);
  44617. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44618. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44619. }
  44620. private:
  44621. ToolbarItemFactory& factory;
  44622. Toolbar* const toolbar;
  44623. ToolbarItemPalette palette;
  44624. Label instructions;
  44625. ComboBox styleBox;
  44626. TextButton defaultButton;
  44627. };
  44628. };
  44629. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44630. {
  44631. setEditingActive (true);
  44632. #if JUCE_DEBUG
  44633. WeakReference<Component> checker (this);
  44634. #endif
  44635. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44636. dw.runModalLoop();
  44637. #if JUCE_DEBUG
  44638. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44639. #endif
  44640. setEditingActive (false);
  44641. }
  44642. END_JUCE_NAMESPACE
  44643. /*** End of inlined file: juce_Toolbar.cpp ***/
  44644. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44645. BEGIN_JUCE_NAMESPACE
  44646. ToolbarItemFactory::ToolbarItemFactory()
  44647. {
  44648. }
  44649. ToolbarItemFactory::~ToolbarItemFactory()
  44650. {
  44651. }
  44652. class ItemDragAndDropOverlayComponent : public Component
  44653. {
  44654. public:
  44655. ItemDragAndDropOverlayComponent()
  44656. : isDragging (false)
  44657. {
  44658. setAlwaysOnTop (true);
  44659. setRepaintsOnMouseActivity (true);
  44660. setMouseCursor (MouseCursor::DraggingHandCursor);
  44661. }
  44662. void paint (Graphics& g)
  44663. {
  44664. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44665. if (isMouseOverOrDragging()
  44666. && tc != 0
  44667. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44668. {
  44669. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44670. g.drawRect (0, 0, getWidth(), getHeight(),
  44671. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44672. }
  44673. }
  44674. void mouseDown (const MouseEvent& e)
  44675. {
  44676. isDragging = false;
  44677. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44678. if (tc != 0)
  44679. {
  44680. tc->dragOffsetX = e.x;
  44681. tc->dragOffsetY = e.y;
  44682. }
  44683. }
  44684. void mouseDrag (const MouseEvent& e)
  44685. {
  44686. if (! (isDragging || e.mouseWasClicked()))
  44687. {
  44688. isDragging = true;
  44689. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44690. if (dnd != 0)
  44691. {
  44692. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44693. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44694. if (tc != 0)
  44695. {
  44696. tc->isBeingDragged = true;
  44697. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44698. tc->setVisible (false);
  44699. }
  44700. }
  44701. }
  44702. }
  44703. void mouseUp (const MouseEvent&)
  44704. {
  44705. isDragging = false;
  44706. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44707. if (tc != 0)
  44708. {
  44709. tc->isBeingDragged = false;
  44710. Toolbar* const tb = tc->getToolbar();
  44711. if (tb != 0)
  44712. tb->updateAllItemPositions (true);
  44713. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44714. delete tc;
  44715. }
  44716. }
  44717. void parentSizeChanged()
  44718. {
  44719. setBounds (0, 0, getParentWidth(), getParentHeight());
  44720. }
  44721. private:
  44722. bool isDragging;
  44723. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44724. };
  44725. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44726. const String& labelText,
  44727. const bool isBeingUsedAsAButton_)
  44728. : Button (labelText),
  44729. itemId (itemId_),
  44730. mode (normalMode),
  44731. toolbarStyle (Toolbar::iconsOnly),
  44732. dragOffsetX (0),
  44733. dragOffsetY (0),
  44734. isActive (true),
  44735. isBeingDragged (false),
  44736. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44737. {
  44738. // Your item ID can't be 0!
  44739. jassert (itemId_ != 0);
  44740. }
  44741. ToolbarItemComponent::~ToolbarItemComponent()
  44742. {
  44743. overlayComp = 0;
  44744. }
  44745. Toolbar* ToolbarItemComponent::getToolbar() const
  44746. {
  44747. return dynamic_cast <Toolbar*> (getParentComponent());
  44748. }
  44749. bool ToolbarItemComponent::isToolbarVertical() const
  44750. {
  44751. const Toolbar* const t = getToolbar();
  44752. return t != 0 && t->isVertical();
  44753. }
  44754. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44755. {
  44756. if (toolbarStyle != newStyle)
  44757. {
  44758. toolbarStyle = newStyle;
  44759. repaint();
  44760. resized();
  44761. }
  44762. }
  44763. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44764. {
  44765. if (isBeingUsedAsAButton)
  44766. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44767. over, down, *this);
  44768. if (toolbarStyle != Toolbar::iconsOnly)
  44769. {
  44770. const int indent = contentArea.getX();
  44771. int y = indent;
  44772. int h = getHeight() - indent * 2;
  44773. if (toolbarStyle == Toolbar::iconsWithText)
  44774. {
  44775. y = contentArea.getBottom() + indent / 2;
  44776. h -= contentArea.getHeight();
  44777. }
  44778. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44779. getButtonText(), *this);
  44780. }
  44781. if (! contentArea.isEmpty())
  44782. {
  44783. Graphics::ScopedSaveState ss (g);
  44784. g.reduceClipRegion (contentArea);
  44785. g.setOrigin (contentArea.getX(), contentArea.getY());
  44786. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44787. }
  44788. }
  44789. void ToolbarItemComponent::resized()
  44790. {
  44791. if (toolbarStyle != Toolbar::textOnly)
  44792. {
  44793. const int indent = jmin (proportionOfWidth (0.08f),
  44794. proportionOfHeight (0.08f));
  44795. contentArea = Rectangle<int> (indent, indent,
  44796. getWidth() - indent * 2,
  44797. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44798. : (getHeight() - indent * 2));
  44799. }
  44800. else
  44801. {
  44802. contentArea = Rectangle<int>();
  44803. }
  44804. contentAreaChanged (contentArea);
  44805. }
  44806. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44807. {
  44808. if (mode != newMode)
  44809. {
  44810. mode = newMode;
  44811. repaint();
  44812. if (mode == normalMode)
  44813. {
  44814. overlayComp = 0;
  44815. }
  44816. else if (overlayComp == 0)
  44817. {
  44818. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44819. overlayComp->parentSizeChanged();
  44820. }
  44821. resized();
  44822. }
  44823. }
  44824. END_JUCE_NAMESPACE
  44825. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44826. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44827. BEGIN_JUCE_NAMESPACE
  44828. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44829. Toolbar* const toolbar_)
  44830. : factory (factory_),
  44831. toolbar (toolbar_)
  44832. {
  44833. Component* const itemHolder = new Component();
  44834. viewport.setViewedComponent (itemHolder);
  44835. Array <int> allIds;
  44836. factory.getAllToolbarItemIds (allIds);
  44837. for (int i = 0; i < allIds.size(); ++i)
  44838. addComponent (allIds.getUnchecked (i), -1);
  44839. addAndMakeVisible (&viewport);
  44840. }
  44841. ToolbarItemPalette::~ToolbarItemPalette()
  44842. {
  44843. }
  44844. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44845. {
  44846. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  44847. jassert (tc != 0);
  44848. if (tc != 0)
  44849. {
  44850. items.insert (index, tc);
  44851. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  44852. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44853. }
  44854. }
  44855. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44856. {
  44857. const int index = items.indexOf (comp);
  44858. jassert (index >= 0);
  44859. items.removeObject (comp, false);
  44860. addComponent (comp->getItemId(), index);
  44861. resized();
  44862. }
  44863. void ToolbarItemPalette::resized()
  44864. {
  44865. viewport.setBoundsInset (BorderSize<int> (1));
  44866. Component* const itemHolder = viewport.getViewedComponent();
  44867. const int indent = 8;
  44868. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  44869. const int height = toolbar->getThickness();
  44870. int x = indent;
  44871. int y = indent;
  44872. int maxX = 0;
  44873. for (int i = 0; i < items.size(); ++i)
  44874. {
  44875. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44876. tc->setStyle (toolbar->getStyle());
  44877. int preferredSize = 1, minSize = 1, maxSize = 1;
  44878. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44879. {
  44880. if (x + preferredSize > preferredWidth && x > indent)
  44881. {
  44882. x = indent;
  44883. y += height;
  44884. }
  44885. tc->setBounds (x, y, preferredSize, height);
  44886. x += preferredSize + 8;
  44887. maxX = jmax (maxX, x);
  44888. }
  44889. }
  44890. itemHolder->setSize (maxX, y + height + 8);
  44891. }
  44892. END_JUCE_NAMESPACE
  44893. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44894. /*** Start of inlined file: juce_TreeView.cpp ***/
  44895. BEGIN_JUCE_NAMESPACE
  44896. class TreeViewContentComponent : public Component,
  44897. public TooltipClient
  44898. {
  44899. public:
  44900. TreeViewContentComponent (TreeView& owner_)
  44901. : owner (owner_),
  44902. buttonUnderMouse (0),
  44903. isDragging (false)
  44904. {
  44905. }
  44906. void mouseDown (const MouseEvent& e)
  44907. {
  44908. updateButtonUnderMouse (e);
  44909. isDragging = false;
  44910. needSelectionOnMouseUp = false;
  44911. Rectangle<int> pos;
  44912. TreeViewItem* const item = findItemAt (e.y, pos);
  44913. if (item == 0)
  44914. return;
  44915. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44916. // as selection clicks)
  44917. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44918. {
  44919. if (e.x >= pos.getX() - owner.getIndentSize())
  44920. item->setOpen (! item->isOpen());
  44921. // (clicks to the left of an open/close button are ignored)
  44922. }
  44923. else
  44924. {
  44925. // mouse-down inside the body of the item..
  44926. if (! owner.isMultiSelectEnabled())
  44927. item->setSelected (true, true);
  44928. else if (item->isSelected())
  44929. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44930. else
  44931. selectBasedOnModifiers (item, e.mods);
  44932. if (e.x >= pos.getX())
  44933. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44934. }
  44935. }
  44936. void mouseUp (const MouseEvent& e)
  44937. {
  44938. updateButtonUnderMouse (e);
  44939. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44940. {
  44941. Rectangle<int> pos;
  44942. TreeViewItem* const item = findItemAt (e.y, pos);
  44943. if (item != 0)
  44944. selectBasedOnModifiers (item, e.mods);
  44945. }
  44946. }
  44947. void mouseDoubleClick (const MouseEvent& e)
  44948. {
  44949. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44950. {
  44951. Rectangle<int> pos;
  44952. TreeViewItem* const item = findItemAt (e.y, pos);
  44953. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44954. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44955. }
  44956. }
  44957. void mouseDrag (const MouseEvent& e)
  44958. {
  44959. if (isEnabled()
  44960. && ! (isDragging || e.mouseWasClicked()
  44961. || e.getDistanceFromDragStart() < 5
  44962. || e.mods.isPopupMenu()))
  44963. {
  44964. isDragging = true;
  44965. Rectangle<int> pos;
  44966. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44967. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44968. {
  44969. const String dragDescription (item->getDragSourceDescription());
  44970. if (dragDescription.isNotEmpty())
  44971. {
  44972. DragAndDropContainer* const dragContainer
  44973. = DragAndDropContainer::findParentDragContainerFor (this);
  44974. if (dragContainer != 0)
  44975. {
  44976. pos.setSize (pos.getWidth(), item->itemHeight);
  44977. Image dragImage (Component::createComponentSnapshot (pos, true));
  44978. dragImage.multiplyAllAlphas (0.6f);
  44979. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44980. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44981. }
  44982. else
  44983. {
  44984. // to be able to do a drag-and-drop operation, the treeview needs to
  44985. // be inside a component which is also a DragAndDropContainer.
  44986. jassertfalse;
  44987. }
  44988. }
  44989. }
  44990. }
  44991. }
  44992. void mouseMove (const MouseEvent& e)
  44993. {
  44994. updateButtonUnderMouse (e);
  44995. }
  44996. void mouseExit (const MouseEvent& e)
  44997. {
  44998. updateButtonUnderMouse (e);
  44999. }
  45000. void paint (Graphics& g)
  45001. {
  45002. if (owner.rootItem != 0)
  45003. {
  45004. owner.handleAsyncUpdate();
  45005. if (! owner.rootItemVisible)
  45006. g.setOrigin (0, -owner.rootItem->itemHeight);
  45007. owner.rootItem->paintRecursively (g, getWidth());
  45008. }
  45009. }
  45010. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45011. {
  45012. if (owner.rootItem != 0)
  45013. {
  45014. owner.handleAsyncUpdate();
  45015. if (! owner.rootItemVisible)
  45016. y += owner.rootItem->itemHeight;
  45017. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45018. if (ti != 0)
  45019. itemPosition = ti->getItemPosition (false);
  45020. return ti;
  45021. }
  45022. return 0;
  45023. }
  45024. void updateComponents()
  45025. {
  45026. const int visibleTop = -getY();
  45027. const int visibleBottom = visibleTop + getParentHeight();
  45028. {
  45029. for (int i = items.size(); --i >= 0;)
  45030. items.getUnchecked(i)->shouldKeep = false;
  45031. }
  45032. {
  45033. TreeViewItem* item = owner.rootItem;
  45034. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45035. while (item != 0 && y < visibleBottom)
  45036. {
  45037. y += item->itemHeight;
  45038. if (y >= visibleTop)
  45039. {
  45040. RowItem* const ri = findItem (item->uid);
  45041. if (ri != 0)
  45042. {
  45043. ri->shouldKeep = true;
  45044. }
  45045. else
  45046. {
  45047. Component* const comp = item->createItemComponent();
  45048. if (comp != 0)
  45049. {
  45050. items.add (new RowItem (item, comp, item->uid));
  45051. addAndMakeVisible (comp);
  45052. }
  45053. }
  45054. }
  45055. item = item->getNextVisibleItem (true);
  45056. }
  45057. }
  45058. for (int i = items.size(); --i >= 0;)
  45059. {
  45060. RowItem* const ri = items.getUnchecked(i);
  45061. bool keep = false;
  45062. if (isParentOf (ri->component))
  45063. {
  45064. if (ri->shouldKeep)
  45065. {
  45066. Rectangle<int> pos (ri->item->getItemPosition (false));
  45067. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45068. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45069. {
  45070. keep = true;
  45071. ri->component->setBounds (pos);
  45072. }
  45073. }
  45074. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45075. {
  45076. keep = true;
  45077. ri->component->setSize (0, 0);
  45078. }
  45079. }
  45080. if (! keep)
  45081. items.remove (i);
  45082. }
  45083. }
  45084. void updateButtonUnderMouse (const MouseEvent& e)
  45085. {
  45086. TreeViewItem* newItem = 0;
  45087. if (owner.openCloseButtonsVisible)
  45088. {
  45089. Rectangle<int> pos;
  45090. TreeViewItem* item = findItemAt (e.y, pos);
  45091. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45092. {
  45093. newItem = item;
  45094. if (! newItem->mightContainSubItems())
  45095. newItem = 0;
  45096. }
  45097. }
  45098. if (buttonUnderMouse != newItem)
  45099. {
  45100. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45101. {
  45102. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45103. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45104. }
  45105. buttonUnderMouse = newItem;
  45106. if (buttonUnderMouse != 0)
  45107. {
  45108. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45109. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45110. }
  45111. }
  45112. }
  45113. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45114. {
  45115. return item == buttonUnderMouse;
  45116. }
  45117. void resized()
  45118. {
  45119. owner.itemsChanged();
  45120. }
  45121. const String getTooltip()
  45122. {
  45123. Rectangle<int> pos;
  45124. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45125. if (item != 0)
  45126. return item->getTooltip();
  45127. return owner.getTooltip();
  45128. }
  45129. private:
  45130. TreeView& owner;
  45131. struct RowItem
  45132. {
  45133. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45134. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45135. {
  45136. }
  45137. ~RowItem()
  45138. {
  45139. delete component.get();
  45140. }
  45141. WeakReference<Component> component;
  45142. TreeViewItem* item;
  45143. int uid;
  45144. bool shouldKeep;
  45145. };
  45146. OwnedArray <RowItem> items;
  45147. TreeViewItem* buttonUnderMouse;
  45148. bool isDragging, needSelectionOnMouseUp;
  45149. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45150. {
  45151. TreeViewItem* firstSelected = 0;
  45152. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45153. {
  45154. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45155. jassert (lastSelected != 0);
  45156. int rowStart = firstSelected->getRowNumberInTree();
  45157. int rowEnd = lastSelected->getRowNumberInTree();
  45158. if (rowStart > rowEnd)
  45159. swapVariables (rowStart, rowEnd);
  45160. int ourRow = item->getRowNumberInTree();
  45161. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45162. if (ourRow > otherEnd)
  45163. swapVariables (ourRow, otherEnd);
  45164. for (int i = ourRow; i <= otherEnd; ++i)
  45165. owner.getItemOnRow (i)->setSelected (true, false);
  45166. }
  45167. else
  45168. {
  45169. const bool cmd = modifiers.isCommandDown();
  45170. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45171. }
  45172. }
  45173. bool containsItem (TreeViewItem* const item) const throw()
  45174. {
  45175. for (int i = items.size(); --i >= 0;)
  45176. if (items.getUnchecked(i)->item == item)
  45177. return true;
  45178. return false;
  45179. }
  45180. RowItem* findItem (const int uid) const throw()
  45181. {
  45182. for (int i = items.size(); --i >= 0;)
  45183. {
  45184. RowItem* const ri = items.getUnchecked(i);
  45185. if (ri->uid == uid)
  45186. return ri;
  45187. }
  45188. return 0;
  45189. }
  45190. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45191. {
  45192. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45193. {
  45194. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45195. if (source->isDragging())
  45196. {
  45197. Component* const underMouse = source->getComponentUnderMouse();
  45198. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45199. return true;
  45200. }
  45201. }
  45202. return false;
  45203. }
  45204. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45205. };
  45206. class TreeView::TreeViewport : public Viewport
  45207. {
  45208. public:
  45209. TreeViewport() throw() : lastX (-1) {}
  45210. void updateComponents (const bool triggerResize = false)
  45211. {
  45212. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45213. if (tvc != 0)
  45214. {
  45215. if (triggerResize)
  45216. tvc->resized();
  45217. else
  45218. tvc->updateComponents();
  45219. }
  45220. repaint();
  45221. }
  45222. void visibleAreaChanged (const Rectangle<int>& newVisibleArea)
  45223. {
  45224. const bool hasScrolledSideways = (newVisibleArea.getX() != lastX);
  45225. lastX = newVisibleArea.getX();
  45226. updateComponents (hasScrolledSideways);
  45227. }
  45228. private:
  45229. int lastX;
  45230. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45231. };
  45232. TreeView::TreeView (const String& componentName)
  45233. : Component (componentName),
  45234. rootItem (0),
  45235. indentSize (24),
  45236. defaultOpenness (false),
  45237. needsRecalculating (true),
  45238. rootItemVisible (true),
  45239. multiSelectEnabled (false),
  45240. openCloseButtonsVisible (true)
  45241. {
  45242. addAndMakeVisible (viewport = new TreeViewport());
  45243. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45244. viewport->setWantsKeyboardFocus (false);
  45245. setWantsKeyboardFocus (true);
  45246. }
  45247. TreeView::~TreeView()
  45248. {
  45249. if (rootItem != 0)
  45250. rootItem->setOwnerView (0);
  45251. }
  45252. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45253. {
  45254. if (rootItem != newRootItem)
  45255. {
  45256. if (newRootItem != 0)
  45257. {
  45258. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45259. if (newRootItem->ownerView != 0)
  45260. newRootItem->ownerView->setRootItem (0);
  45261. }
  45262. if (rootItem != 0)
  45263. rootItem->setOwnerView (0);
  45264. rootItem = newRootItem;
  45265. if (newRootItem != 0)
  45266. newRootItem->setOwnerView (this);
  45267. needsRecalculating = true;
  45268. handleAsyncUpdate();
  45269. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45270. {
  45271. rootItem->setOpen (false); // force a re-open
  45272. rootItem->setOpen (true);
  45273. }
  45274. }
  45275. }
  45276. void TreeView::deleteRootItem()
  45277. {
  45278. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45279. setRootItem (0);
  45280. }
  45281. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45282. {
  45283. rootItemVisible = shouldBeVisible;
  45284. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45285. {
  45286. rootItem->setOpen (false); // force a re-open
  45287. rootItem->setOpen (true);
  45288. }
  45289. itemsChanged();
  45290. }
  45291. void TreeView::colourChanged()
  45292. {
  45293. setOpaque (findColour (backgroundColourId).isOpaque());
  45294. repaint();
  45295. }
  45296. void TreeView::setIndentSize (const int newIndentSize)
  45297. {
  45298. if (indentSize != newIndentSize)
  45299. {
  45300. indentSize = newIndentSize;
  45301. resized();
  45302. }
  45303. }
  45304. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45305. {
  45306. if (defaultOpenness != isOpenByDefault)
  45307. {
  45308. defaultOpenness = isOpenByDefault;
  45309. itemsChanged();
  45310. }
  45311. }
  45312. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45313. {
  45314. multiSelectEnabled = canMultiSelect;
  45315. }
  45316. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45317. {
  45318. if (openCloseButtonsVisible != shouldBeVisible)
  45319. {
  45320. openCloseButtonsVisible = shouldBeVisible;
  45321. itemsChanged();
  45322. }
  45323. }
  45324. Viewport* TreeView::getViewport() const throw()
  45325. {
  45326. return viewport;
  45327. }
  45328. void TreeView::clearSelectedItems()
  45329. {
  45330. if (rootItem != 0)
  45331. rootItem->deselectAllRecursively();
  45332. }
  45333. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45334. {
  45335. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45336. }
  45337. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45338. {
  45339. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45340. }
  45341. int TreeView::getNumRowsInTree() const
  45342. {
  45343. if (rootItem != 0)
  45344. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45345. return 0;
  45346. }
  45347. TreeViewItem* TreeView::getItemOnRow (int index) const
  45348. {
  45349. if (! rootItemVisible)
  45350. ++index;
  45351. if (rootItem != 0 && index >= 0)
  45352. return rootItem->getItemOnRow (index);
  45353. return 0;
  45354. }
  45355. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45356. {
  45357. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45358. Rectangle<int> pos;
  45359. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45360. }
  45361. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45362. {
  45363. if (rootItem == 0)
  45364. return 0;
  45365. return rootItem->findItemFromIdentifierString (identifierString);
  45366. }
  45367. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45368. {
  45369. XmlElement* e = 0;
  45370. if (rootItem != 0)
  45371. {
  45372. e = rootItem->getOpennessState();
  45373. if (e != 0 && alsoIncludeScrollPosition)
  45374. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45375. }
  45376. return e;
  45377. }
  45378. void TreeView::restoreOpennessState (const XmlElement& newState)
  45379. {
  45380. if (rootItem != 0)
  45381. {
  45382. rootItem->restoreOpennessState (newState);
  45383. if (newState.hasAttribute ("scrollPos"))
  45384. viewport->setViewPosition (viewport->getViewPositionX(),
  45385. newState.getIntAttribute ("scrollPos"));
  45386. }
  45387. }
  45388. void TreeView::paint (Graphics& g)
  45389. {
  45390. g.fillAll (findColour (backgroundColourId));
  45391. }
  45392. void TreeView::resized()
  45393. {
  45394. viewport->setBounds (getLocalBounds());
  45395. itemsChanged();
  45396. handleAsyncUpdate();
  45397. }
  45398. void TreeView::enablementChanged()
  45399. {
  45400. repaint();
  45401. }
  45402. void TreeView::moveSelectedRow (int delta)
  45403. {
  45404. if (delta == 0)
  45405. return;
  45406. int rowSelected = 0;
  45407. TreeViewItem* const firstSelected = getSelectedItem (0);
  45408. if (firstSelected != 0)
  45409. rowSelected = firstSelected->getRowNumberInTree();
  45410. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45411. for (;;)
  45412. {
  45413. TreeViewItem* item = getItemOnRow (rowSelected);
  45414. if (item != 0)
  45415. {
  45416. if (! item->canBeSelected())
  45417. {
  45418. // if the row we want to highlight doesn't allow it, try skipping
  45419. // to the next item..
  45420. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45421. rowSelected + (delta < 0 ? -1 : 1));
  45422. if (rowSelected != nextRowToTry)
  45423. {
  45424. rowSelected = nextRowToTry;
  45425. continue;
  45426. }
  45427. else
  45428. {
  45429. break;
  45430. }
  45431. }
  45432. item->setSelected (true, true);
  45433. scrollToKeepItemVisible (item);
  45434. }
  45435. break;
  45436. }
  45437. }
  45438. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45439. {
  45440. if (item != 0 && item->ownerView == this)
  45441. {
  45442. handleAsyncUpdate();
  45443. item = item->getDeepestOpenParentItem();
  45444. int y = item->y;
  45445. int viewTop = viewport->getViewPositionY();
  45446. if (y < viewTop)
  45447. {
  45448. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45449. }
  45450. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45451. {
  45452. viewport->setViewPosition (viewport->getViewPositionX(),
  45453. (y + item->itemHeight) - viewport->getViewHeight());
  45454. }
  45455. }
  45456. }
  45457. bool TreeView::keyPressed (const KeyPress& key)
  45458. {
  45459. if (key.isKeyCode (KeyPress::upKey))
  45460. {
  45461. moveSelectedRow (-1);
  45462. }
  45463. else if (key.isKeyCode (KeyPress::downKey))
  45464. {
  45465. moveSelectedRow (1);
  45466. }
  45467. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45468. {
  45469. if (rootItem != 0)
  45470. {
  45471. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45472. if (key.isKeyCode (KeyPress::pageUpKey))
  45473. rowsOnScreen = -rowsOnScreen;
  45474. moveSelectedRow (rowsOnScreen);
  45475. }
  45476. }
  45477. else if (key.isKeyCode (KeyPress::homeKey))
  45478. {
  45479. moveSelectedRow (-0x3fffffff);
  45480. }
  45481. else if (key.isKeyCode (KeyPress::endKey))
  45482. {
  45483. moveSelectedRow (0x3fffffff);
  45484. }
  45485. else if (key.isKeyCode (KeyPress::returnKey))
  45486. {
  45487. TreeViewItem* const firstSelected = getSelectedItem (0);
  45488. if (firstSelected != 0)
  45489. firstSelected->setOpen (! firstSelected->isOpen());
  45490. }
  45491. else if (key.isKeyCode (KeyPress::leftKey))
  45492. {
  45493. TreeViewItem* const firstSelected = getSelectedItem (0);
  45494. if (firstSelected != 0)
  45495. {
  45496. if (firstSelected->isOpen())
  45497. {
  45498. firstSelected->setOpen (false);
  45499. }
  45500. else
  45501. {
  45502. TreeViewItem* parent = firstSelected->parentItem;
  45503. if ((! rootItemVisible) && parent == rootItem)
  45504. parent = 0;
  45505. if (parent != 0)
  45506. {
  45507. parent->setSelected (true, true);
  45508. scrollToKeepItemVisible (parent);
  45509. }
  45510. }
  45511. }
  45512. }
  45513. else if (key.isKeyCode (KeyPress::rightKey))
  45514. {
  45515. TreeViewItem* const firstSelected = getSelectedItem (0);
  45516. if (firstSelected != 0)
  45517. {
  45518. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45519. moveSelectedRow (1);
  45520. else
  45521. firstSelected->setOpen (true);
  45522. }
  45523. }
  45524. else
  45525. {
  45526. return false;
  45527. }
  45528. return true;
  45529. }
  45530. void TreeView::itemsChanged() throw()
  45531. {
  45532. needsRecalculating = true;
  45533. repaint();
  45534. triggerAsyncUpdate();
  45535. }
  45536. void TreeView::handleAsyncUpdate()
  45537. {
  45538. if (needsRecalculating)
  45539. {
  45540. needsRecalculating = false;
  45541. const ScopedLock sl (nodeAlterationLock);
  45542. if (rootItem != 0)
  45543. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45544. viewport->updateComponents();
  45545. if (rootItem != 0)
  45546. {
  45547. viewport->getViewedComponent()
  45548. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45549. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45550. }
  45551. else
  45552. {
  45553. viewport->getViewedComponent()->setSize (0, 0);
  45554. }
  45555. }
  45556. }
  45557. class TreeView::InsertPointHighlight : public Component
  45558. {
  45559. public:
  45560. InsertPointHighlight()
  45561. : lastItem (0)
  45562. {
  45563. setSize (100, 12);
  45564. setAlwaysOnTop (true);
  45565. setInterceptsMouseClicks (false, false);
  45566. }
  45567. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45568. {
  45569. lastItem = item;
  45570. lastIndex = insertIndex;
  45571. const int offset = getHeight() / 2;
  45572. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45573. }
  45574. void paint (Graphics& g)
  45575. {
  45576. Path p;
  45577. const float h = (float) getHeight();
  45578. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45579. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45580. p.lineTo ((float) getWidth(), h / 2.0f);
  45581. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45582. g.strokePath (p, PathStrokeType (2.0f));
  45583. }
  45584. TreeViewItem* lastItem;
  45585. int lastIndex;
  45586. private:
  45587. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45588. };
  45589. class TreeView::TargetGroupHighlight : public Component
  45590. {
  45591. public:
  45592. TargetGroupHighlight()
  45593. {
  45594. setAlwaysOnTop (true);
  45595. setInterceptsMouseClicks (false, false);
  45596. }
  45597. void setTargetPosition (TreeViewItem* const item) throw()
  45598. {
  45599. Rectangle<int> r (item->getItemPosition (true));
  45600. r.setHeight (item->getItemHeight());
  45601. setBounds (r);
  45602. }
  45603. void paint (Graphics& g)
  45604. {
  45605. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45606. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45607. }
  45608. private:
  45609. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45610. };
  45611. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45612. {
  45613. beginDragAutoRepeat (100);
  45614. if (dragInsertPointHighlight == 0)
  45615. {
  45616. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45617. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45618. }
  45619. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45620. dragTargetGroupHighlight->setTargetPosition (item);
  45621. }
  45622. void TreeView::hideDragHighlight() throw()
  45623. {
  45624. dragInsertPointHighlight = 0;
  45625. dragTargetGroupHighlight = 0;
  45626. }
  45627. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45628. const StringArray& files, const String& sourceDescription,
  45629. Component* sourceComponent) const throw()
  45630. {
  45631. insertIndex = 0;
  45632. TreeViewItem* item = getItemAt (y);
  45633. if (item == 0)
  45634. return 0;
  45635. Rectangle<int> itemPos (item->getItemPosition (true));
  45636. insertIndex = item->getIndexInParent();
  45637. const int oldY = y;
  45638. y = itemPos.getY();
  45639. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45640. {
  45641. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45642. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45643. {
  45644. // Check if we're trying to drag into an empty group item..
  45645. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45646. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45647. {
  45648. insertIndex = 0;
  45649. x = itemPos.getX() + getIndentSize();
  45650. y = itemPos.getBottom();
  45651. return item;
  45652. }
  45653. }
  45654. }
  45655. if (oldY > itemPos.getCentreY())
  45656. {
  45657. y += item->getItemHeight();
  45658. while (item->isLastOfSiblings() && item->parentItem != 0
  45659. && item->parentItem->parentItem != 0)
  45660. {
  45661. if (x > itemPos.getX())
  45662. break;
  45663. item = item->parentItem;
  45664. itemPos = item->getItemPosition (true);
  45665. insertIndex = item->getIndexInParent();
  45666. }
  45667. ++insertIndex;
  45668. }
  45669. x = itemPos.getX();
  45670. return item->parentItem;
  45671. }
  45672. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45673. {
  45674. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45675. int insertIndex;
  45676. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45677. if (item != 0)
  45678. {
  45679. if (scrolled || dragInsertPointHighlight == 0
  45680. || dragInsertPointHighlight->lastItem != item
  45681. || dragInsertPointHighlight->lastIndex != insertIndex)
  45682. {
  45683. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45684. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45685. showDragHighlight (item, insertIndex, x, y);
  45686. else
  45687. hideDragHighlight();
  45688. }
  45689. }
  45690. else
  45691. {
  45692. hideDragHighlight();
  45693. }
  45694. }
  45695. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45696. {
  45697. hideDragHighlight();
  45698. int insertIndex;
  45699. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45700. if (item != 0)
  45701. {
  45702. if (files.size() > 0)
  45703. {
  45704. if (item->isInterestedInFileDrag (files))
  45705. item->filesDropped (files, insertIndex);
  45706. }
  45707. else
  45708. {
  45709. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45710. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45711. }
  45712. }
  45713. }
  45714. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45715. {
  45716. return true;
  45717. }
  45718. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45719. {
  45720. fileDragMove (files, x, y);
  45721. }
  45722. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45723. {
  45724. handleDrag (files, String::empty, 0, x, y);
  45725. }
  45726. void TreeView::fileDragExit (const StringArray&)
  45727. {
  45728. hideDragHighlight();
  45729. }
  45730. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45731. {
  45732. handleDrop (files, String::empty, 0, x, y);
  45733. }
  45734. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45735. {
  45736. return true;
  45737. }
  45738. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45739. {
  45740. itemDragMove (sourceDescription, sourceComponent, x, y);
  45741. }
  45742. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45743. {
  45744. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45745. }
  45746. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45747. {
  45748. hideDragHighlight();
  45749. }
  45750. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45751. {
  45752. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45753. }
  45754. enum TreeViewOpenness
  45755. {
  45756. opennessDefault = 0,
  45757. opennessClosed = 1,
  45758. opennessOpen = 2
  45759. };
  45760. TreeViewItem::TreeViewItem()
  45761. : ownerView (0),
  45762. parentItem (0),
  45763. y (0),
  45764. itemHeight (0),
  45765. totalHeight (0),
  45766. selected (false),
  45767. redrawNeeded (true),
  45768. drawLinesInside (true),
  45769. drawsInLeftMargin (false),
  45770. openness (opennessDefault)
  45771. {
  45772. static int nextUID = 0;
  45773. uid = nextUID++;
  45774. }
  45775. TreeViewItem::~TreeViewItem()
  45776. {
  45777. }
  45778. const String TreeViewItem::getUniqueName() const
  45779. {
  45780. return String::empty;
  45781. }
  45782. void TreeViewItem::itemOpennessChanged (bool)
  45783. {
  45784. }
  45785. int TreeViewItem::getNumSubItems() const throw()
  45786. {
  45787. return subItems.size();
  45788. }
  45789. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45790. {
  45791. return subItems [index];
  45792. }
  45793. void TreeViewItem::clearSubItems()
  45794. {
  45795. if (subItems.size() > 0)
  45796. {
  45797. if (ownerView != 0)
  45798. {
  45799. const ScopedLock sl (ownerView->nodeAlterationLock);
  45800. subItems.clear();
  45801. treeHasChanged();
  45802. }
  45803. else
  45804. {
  45805. subItems.clear();
  45806. }
  45807. }
  45808. }
  45809. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45810. {
  45811. if (newItem != 0)
  45812. {
  45813. newItem->parentItem = this;
  45814. newItem->setOwnerView (ownerView);
  45815. newItem->y = 0;
  45816. newItem->itemHeight = newItem->getItemHeight();
  45817. newItem->totalHeight = 0;
  45818. newItem->itemWidth = newItem->getItemWidth();
  45819. newItem->totalWidth = 0;
  45820. if (ownerView != 0)
  45821. {
  45822. const ScopedLock sl (ownerView->nodeAlterationLock);
  45823. subItems.insert (insertPosition, newItem);
  45824. treeHasChanged();
  45825. if (newItem->isOpen())
  45826. newItem->itemOpennessChanged (true);
  45827. }
  45828. else
  45829. {
  45830. subItems.insert (insertPosition, newItem);
  45831. if (newItem->isOpen())
  45832. newItem->itemOpennessChanged (true);
  45833. }
  45834. }
  45835. }
  45836. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45837. {
  45838. if (ownerView != 0)
  45839. {
  45840. const ScopedLock sl (ownerView->nodeAlterationLock);
  45841. if (isPositiveAndBelow (index, subItems.size()))
  45842. {
  45843. subItems.remove (index, deleteItem);
  45844. treeHasChanged();
  45845. }
  45846. }
  45847. else
  45848. {
  45849. subItems.remove (index, deleteItem);
  45850. }
  45851. }
  45852. bool TreeViewItem::isOpen() const throw()
  45853. {
  45854. if (openness == opennessDefault)
  45855. return ownerView != 0 && ownerView->defaultOpenness;
  45856. else
  45857. return openness == opennessOpen;
  45858. }
  45859. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45860. {
  45861. if (isOpen() != shouldBeOpen)
  45862. {
  45863. openness = shouldBeOpen ? opennessOpen
  45864. : opennessClosed;
  45865. treeHasChanged();
  45866. itemOpennessChanged (isOpen());
  45867. }
  45868. }
  45869. bool TreeViewItem::isSelected() const throw()
  45870. {
  45871. return selected;
  45872. }
  45873. void TreeViewItem::deselectAllRecursively()
  45874. {
  45875. setSelected (false, false);
  45876. for (int i = 0; i < subItems.size(); ++i)
  45877. subItems.getUnchecked(i)->deselectAllRecursively();
  45878. }
  45879. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45880. const bool deselectOtherItemsFirst)
  45881. {
  45882. if (shouldBeSelected && ! canBeSelected())
  45883. return;
  45884. if (deselectOtherItemsFirst)
  45885. getTopLevelItem()->deselectAllRecursively();
  45886. if (shouldBeSelected != selected)
  45887. {
  45888. selected = shouldBeSelected;
  45889. if (ownerView != 0)
  45890. ownerView->repaint();
  45891. itemSelectionChanged (shouldBeSelected);
  45892. }
  45893. }
  45894. void TreeViewItem::paintItem (Graphics&, int, int)
  45895. {
  45896. }
  45897. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45898. {
  45899. ownerView->getLookAndFeel()
  45900. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45901. }
  45902. void TreeViewItem::itemClicked (const MouseEvent&)
  45903. {
  45904. }
  45905. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45906. {
  45907. if (mightContainSubItems())
  45908. setOpen (! isOpen());
  45909. }
  45910. void TreeViewItem::itemSelectionChanged (bool)
  45911. {
  45912. }
  45913. const String TreeViewItem::getTooltip()
  45914. {
  45915. return String::empty;
  45916. }
  45917. const String TreeViewItem::getDragSourceDescription()
  45918. {
  45919. return String::empty;
  45920. }
  45921. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45922. {
  45923. return false;
  45924. }
  45925. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45926. {
  45927. }
  45928. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45929. {
  45930. return false;
  45931. }
  45932. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45933. {
  45934. }
  45935. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45936. {
  45937. const int indentX = getIndentX();
  45938. int width = itemWidth;
  45939. if (ownerView != 0 && width < 0)
  45940. width = ownerView->viewport->getViewWidth() - indentX;
  45941. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45942. if (relativeToTreeViewTopLeft)
  45943. r -= ownerView->viewport->getViewPosition();
  45944. return r;
  45945. }
  45946. void TreeViewItem::treeHasChanged() const throw()
  45947. {
  45948. if (ownerView != 0)
  45949. ownerView->itemsChanged();
  45950. }
  45951. void TreeViewItem::repaintItem() const
  45952. {
  45953. if (ownerView != 0 && areAllParentsOpen())
  45954. {
  45955. Rectangle<int> r (getItemPosition (true));
  45956. r.setLeft (0);
  45957. ownerView->viewport->repaint (r);
  45958. }
  45959. }
  45960. bool TreeViewItem::areAllParentsOpen() const throw()
  45961. {
  45962. return parentItem == 0
  45963. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45964. }
  45965. void TreeViewItem::updatePositions (int newY)
  45966. {
  45967. y = newY;
  45968. itemHeight = getItemHeight();
  45969. totalHeight = itemHeight;
  45970. itemWidth = getItemWidth();
  45971. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45972. if (isOpen())
  45973. {
  45974. newY += totalHeight;
  45975. for (int i = 0; i < subItems.size(); ++i)
  45976. {
  45977. TreeViewItem* const ti = subItems.getUnchecked(i);
  45978. ti->updatePositions (newY);
  45979. newY += ti->totalHeight;
  45980. totalHeight += ti->totalHeight;
  45981. totalWidth = jmax (totalWidth, ti->totalWidth);
  45982. }
  45983. }
  45984. }
  45985. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45986. {
  45987. TreeViewItem* result = this;
  45988. TreeViewItem* item = this;
  45989. while (item->parentItem != 0)
  45990. {
  45991. item = item->parentItem;
  45992. if (! item->isOpen())
  45993. result = item;
  45994. }
  45995. return result;
  45996. }
  45997. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45998. {
  45999. ownerView = newOwner;
  46000. for (int i = subItems.size(); --i >= 0;)
  46001. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46002. }
  46003. int TreeViewItem::getIndentX() const throw()
  46004. {
  46005. const int indentWidth = ownerView->getIndentSize();
  46006. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46007. if (! ownerView->openCloseButtonsVisible)
  46008. x -= indentWidth;
  46009. TreeViewItem* p = parentItem;
  46010. while (p != 0)
  46011. {
  46012. x += indentWidth;
  46013. p = p->parentItem;
  46014. }
  46015. return x;
  46016. }
  46017. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46018. {
  46019. drawsInLeftMargin = canDrawInLeftMargin;
  46020. }
  46021. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46022. {
  46023. jassert (ownerView != 0);
  46024. if (ownerView == 0)
  46025. return;
  46026. const int indent = getIndentX();
  46027. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46028. {
  46029. Graphics::ScopedSaveState ss (g);
  46030. g.setOrigin (indent, 0);
  46031. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46032. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46033. paintItem (g, itemW, itemHeight);
  46034. }
  46035. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46036. const float halfH = itemHeight * 0.5f;
  46037. int depth = 0;
  46038. TreeViewItem* p = parentItem;
  46039. while (p != 0)
  46040. {
  46041. ++depth;
  46042. p = p->parentItem;
  46043. }
  46044. if (! ownerView->rootItemVisible)
  46045. --depth;
  46046. const int indentWidth = ownerView->getIndentSize();
  46047. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46048. {
  46049. float x = (depth + 0.5f) * indentWidth;
  46050. if (depth >= 0)
  46051. {
  46052. if (parentItem != 0 && parentItem->drawLinesInside)
  46053. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46054. if ((parentItem != 0 && parentItem->drawLinesInside)
  46055. || (parentItem == 0 && drawLinesInside))
  46056. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46057. }
  46058. p = parentItem;
  46059. int d = depth;
  46060. while (p != 0 && --d >= 0)
  46061. {
  46062. x -= (float) indentWidth;
  46063. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46064. && ! p->isLastOfSiblings())
  46065. {
  46066. g.drawLine (x, 0, x, (float) itemHeight);
  46067. }
  46068. p = p->parentItem;
  46069. }
  46070. if (mightContainSubItems())
  46071. {
  46072. Graphics::ScopedSaveState ss (g);
  46073. g.setOrigin (depth * indentWidth, 0);
  46074. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46075. paintOpenCloseButton (g, indentWidth, itemHeight,
  46076. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46077. ->isMouseOverButton (this));
  46078. }
  46079. }
  46080. if (isOpen())
  46081. {
  46082. const Rectangle<int> clip (g.getClipBounds());
  46083. for (int i = 0; i < subItems.size(); ++i)
  46084. {
  46085. TreeViewItem* const ti = subItems.getUnchecked(i);
  46086. const int relY = ti->y - y;
  46087. if (relY >= clip.getBottom())
  46088. break;
  46089. if (relY + ti->totalHeight >= clip.getY())
  46090. {
  46091. Graphics::ScopedSaveState ss (g);
  46092. g.setOrigin (0, relY);
  46093. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46094. ti->paintRecursively (g, width);
  46095. }
  46096. }
  46097. }
  46098. }
  46099. bool TreeViewItem::isLastOfSiblings() const throw()
  46100. {
  46101. return parentItem == 0
  46102. || parentItem->subItems.getLast() == this;
  46103. }
  46104. int TreeViewItem::getIndexInParent() const throw()
  46105. {
  46106. return parentItem == 0 ? 0
  46107. : parentItem->subItems.indexOf (this);
  46108. }
  46109. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46110. {
  46111. return parentItem == 0 ? this
  46112. : parentItem->getTopLevelItem();
  46113. }
  46114. int TreeViewItem::getNumRows() const throw()
  46115. {
  46116. int num = 1;
  46117. if (isOpen())
  46118. {
  46119. for (int i = subItems.size(); --i >= 0;)
  46120. num += subItems.getUnchecked(i)->getNumRows();
  46121. }
  46122. return num;
  46123. }
  46124. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46125. {
  46126. if (index == 0)
  46127. return this;
  46128. if (index > 0 && isOpen())
  46129. {
  46130. --index;
  46131. for (int i = 0; i < subItems.size(); ++i)
  46132. {
  46133. TreeViewItem* const item = subItems.getUnchecked(i);
  46134. if (index == 0)
  46135. return item;
  46136. const int numRows = item->getNumRows();
  46137. if (numRows > index)
  46138. return item->getItemOnRow (index);
  46139. index -= numRows;
  46140. }
  46141. }
  46142. return 0;
  46143. }
  46144. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46145. {
  46146. if (isPositiveAndBelow (targetY, totalHeight))
  46147. {
  46148. const int h = itemHeight;
  46149. if (targetY < h)
  46150. return this;
  46151. if (isOpen())
  46152. {
  46153. targetY -= h;
  46154. for (int i = 0; i < subItems.size(); ++i)
  46155. {
  46156. TreeViewItem* const ti = subItems.getUnchecked(i);
  46157. if (targetY < ti->totalHeight)
  46158. return ti->findItemRecursively (targetY);
  46159. targetY -= ti->totalHeight;
  46160. }
  46161. }
  46162. }
  46163. return 0;
  46164. }
  46165. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  46166. {
  46167. int total = isSelected() ? 1 : 0;
  46168. if (depth != 0)
  46169. for (int i = subItems.size(); --i >= 0;)
  46170. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  46171. return total;
  46172. }
  46173. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46174. {
  46175. if (isSelected())
  46176. {
  46177. if (index == 0)
  46178. return this;
  46179. --index;
  46180. }
  46181. if (index >= 0)
  46182. {
  46183. for (int i = 0; i < subItems.size(); ++i)
  46184. {
  46185. TreeViewItem* const item = subItems.getUnchecked(i);
  46186. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46187. if (found != 0)
  46188. return found;
  46189. index -= item->countSelectedItemsRecursively (-1);
  46190. }
  46191. }
  46192. return 0;
  46193. }
  46194. int TreeViewItem::getRowNumberInTree() const throw()
  46195. {
  46196. if (parentItem != 0 && ownerView != 0)
  46197. {
  46198. int n = 1 + parentItem->getRowNumberInTree();
  46199. int ourIndex = parentItem->subItems.indexOf (this);
  46200. jassert (ourIndex >= 0);
  46201. while (--ourIndex >= 0)
  46202. n += parentItem->subItems [ourIndex]->getNumRows();
  46203. if (parentItem->parentItem == 0
  46204. && ! ownerView->rootItemVisible)
  46205. --n;
  46206. return n;
  46207. }
  46208. else
  46209. {
  46210. return 0;
  46211. }
  46212. }
  46213. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46214. {
  46215. drawLinesInside = drawLines;
  46216. }
  46217. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46218. {
  46219. if (recurse && isOpen() && subItems.size() > 0)
  46220. return subItems [0];
  46221. if (parentItem != 0)
  46222. {
  46223. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46224. if (nextIndex >= parentItem->subItems.size())
  46225. return parentItem->getNextVisibleItem (false);
  46226. return parentItem->subItems [nextIndex];
  46227. }
  46228. return 0;
  46229. }
  46230. const String TreeViewItem::getItemIdentifierString() const
  46231. {
  46232. String s;
  46233. if (parentItem != 0)
  46234. s = parentItem->getItemIdentifierString();
  46235. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46236. }
  46237. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46238. {
  46239. const String thisId (getUniqueName());
  46240. if (thisId == identifierString)
  46241. return this;
  46242. if (identifierString.startsWith (thisId + "/"))
  46243. {
  46244. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46245. bool wasOpen = isOpen();
  46246. setOpen (true);
  46247. for (int i = subItems.size(); --i >= 0;)
  46248. {
  46249. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46250. if (item != 0)
  46251. return item;
  46252. }
  46253. setOpen (wasOpen);
  46254. }
  46255. return 0;
  46256. }
  46257. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46258. {
  46259. if (e.hasTagName ("CLOSED"))
  46260. {
  46261. setOpen (false);
  46262. }
  46263. else if (e.hasTagName ("OPEN"))
  46264. {
  46265. setOpen (true);
  46266. forEachXmlChildElement (e, n)
  46267. {
  46268. const String id (n->getStringAttribute ("id"));
  46269. for (int i = 0; i < subItems.size(); ++i)
  46270. {
  46271. TreeViewItem* const ti = subItems.getUnchecked(i);
  46272. if (ti->getUniqueName() == id)
  46273. {
  46274. ti->restoreOpennessState (*n);
  46275. break;
  46276. }
  46277. }
  46278. }
  46279. }
  46280. }
  46281. XmlElement* TreeViewItem::getOpennessState() const throw()
  46282. {
  46283. const String name (getUniqueName());
  46284. if (name.isNotEmpty())
  46285. {
  46286. XmlElement* e;
  46287. if (isOpen())
  46288. {
  46289. e = new XmlElement ("OPEN");
  46290. for (int i = 0; i < subItems.size(); ++i)
  46291. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46292. }
  46293. else
  46294. {
  46295. e = new XmlElement ("CLOSED");
  46296. }
  46297. e->setAttribute ("id", name);
  46298. return e;
  46299. }
  46300. else
  46301. {
  46302. // trying to save the openness for an element that has no name - this won't
  46303. // work because it needs the names to identify what to open.
  46304. jassertfalse;
  46305. }
  46306. return 0;
  46307. }
  46308. END_JUCE_NAMESPACE
  46309. /*** End of inlined file: juce_TreeView.cpp ***/
  46310. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46311. BEGIN_JUCE_NAMESPACE
  46312. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46313. : fileList (listToShow)
  46314. {
  46315. }
  46316. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46317. {
  46318. }
  46319. FileBrowserListener::~FileBrowserListener()
  46320. {
  46321. }
  46322. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46323. {
  46324. listeners.add (listener);
  46325. }
  46326. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46327. {
  46328. listeners.remove (listener);
  46329. }
  46330. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46331. {
  46332. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46333. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46334. }
  46335. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46336. {
  46337. if (fileList.getDirectory().exists())
  46338. {
  46339. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46340. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46341. }
  46342. }
  46343. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46344. {
  46345. if (fileList.getDirectory().exists())
  46346. {
  46347. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46348. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46349. }
  46350. }
  46351. END_JUCE_NAMESPACE
  46352. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46353. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46354. BEGIN_JUCE_NAMESPACE
  46355. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46356. TimeSliceThread& thread_)
  46357. : fileFilter (fileFilter_),
  46358. thread (thread_),
  46359. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46360. fileFindHandle (0),
  46361. shouldStop (true)
  46362. {
  46363. }
  46364. DirectoryContentsList::~DirectoryContentsList()
  46365. {
  46366. clear();
  46367. }
  46368. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46369. {
  46370. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46371. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46372. }
  46373. bool DirectoryContentsList::ignoresHiddenFiles() const
  46374. {
  46375. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46376. }
  46377. const File& DirectoryContentsList::getDirectory() const
  46378. {
  46379. return root;
  46380. }
  46381. void DirectoryContentsList::setDirectory (const File& directory,
  46382. const bool includeDirectories,
  46383. const bool includeFiles)
  46384. {
  46385. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46386. if (directory != root)
  46387. {
  46388. clear();
  46389. root = directory;
  46390. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46391. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46392. }
  46393. int newFlags = fileTypeFlags;
  46394. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46395. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46396. setTypeFlags (newFlags);
  46397. }
  46398. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46399. {
  46400. if (fileTypeFlags != newFlags)
  46401. {
  46402. fileTypeFlags = newFlags;
  46403. refresh();
  46404. }
  46405. }
  46406. void DirectoryContentsList::clear()
  46407. {
  46408. shouldStop = true;
  46409. thread.removeTimeSliceClient (this);
  46410. fileFindHandle = 0;
  46411. if (files.size() > 0)
  46412. {
  46413. files.clear();
  46414. changed();
  46415. }
  46416. }
  46417. void DirectoryContentsList::refresh()
  46418. {
  46419. clear();
  46420. if (root.isDirectory())
  46421. {
  46422. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46423. shouldStop = false;
  46424. thread.addTimeSliceClient (this);
  46425. }
  46426. }
  46427. int DirectoryContentsList::getNumFiles() const
  46428. {
  46429. return files.size();
  46430. }
  46431. bool DirectoryContentsList::getFileInfo (const int index,
  46432. FileInfo& result) const
  46433. {
  46434. const ScopedLock sl (fileListLock);
  46435. const FileInfo* const info = files [index];
  46436. if (info != 0)
  46437. {
  46438. result = *info;
  46439. return true;
  46440. }
  46441. return false;
  46442. }
  46443. const File DirectoryContentsList::getFile (const int index) const
  46444. {
  46445. const ScopedLock sl (fileListLock);
  46446. const FileInfo* const info = files [index];
  46447. if (info != 0)
  46448. return root.getChildFile (info->filename);
  46449. return File::nonexistent;
  46450. }
  46451. bool DirectoryContentsList::isStillLoading() const
  46452. {
  46453. return fileFindHandle != 0;
  46454. }
  46455. void DirectoryContentsList::changed()
  46456. {
  46457. sendChangeMessage();
  46458. }
  46459. bool DirectoryContentsList::useTimeSlice()
  46460. {
  46461. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46462. bool hasChanged = false;
  46463. for (int i = 100; --i >= 0;)
  46464. {
  46465. if (! checkNextFile (hasChanged))
  46466. {
  46467. if (hasChanged)
  46468. changed();
  46469. return false;
  46470. }
  46471. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46472. break;
  46473. }
  46474. if (hasChanged)
  46475. changed();
  46476. return true;
  46477. }
  46478. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46479. {
  46480. if (fileFindHandle != 0)
  46481. {
  46482. bool fileFoundIsDir, isHidden, isReadOnly;
  46483. int64 fileSize;
  46484. Time modTime, creationTime;
  46485. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46486. &modTime, &creationTime, &isReadOnly))
  46487. {
  46488. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46489. fileSize, modTime, creationTime, isReadOnly))
  46490. {
  46491. hasChanged = true;
  46492. }
  46493. return true;
  46494. }
  46495. else
  46496. {
  46497. fileFindHandle = 0;
  46498. }
  46499. }
  46500. return false;
  46501. }
  46502. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46503. const DirectoryContentsList::FileInfo* const second)
  46504. {
  46505. #if JUCE_WINDOWS
  46506. if (first->isDirectory != second->isDirectory)
  46507. return first->isDirectory ? -1 : 1;
  46508. #endif
  46509. return first->filename.compareIgnoreCase (second->filename);
  46510. }
  46511. bool DirectoryContentsList::addFile (const File& file,
  46512. const bool isDir,
  46513. const int64 fileSize,
  46514. const Time& modTime,
  46515. const Time& creationTime,
  46516. const bool isReadOnly)
  46517. {
  46518. if (fileFilter == 0
  46519. || ((! isDir) && fileFilter->isFileSuitable (file))
  46520. || (isDir && fileFilter->isDirectorySuitable (file)))
  46521. {
  46522. ScopedPointer <FileInfo> info (new FileInfo());
  46523. info->filename = file.getFileName();
  46524. info->fileSize = fileSize;
  46525. info->modificationTime = modTime;
  46526. info->creationTime = creationTime;
  46527. info->isDirectory = isDir;
  46528. info->isReadOnly = isReadOnly;
  46529. const ScopedLock sl (fileListLock);
  46530. for (int i = files.size(); --i >= 0;)
  46531. if (files.getUnchecked(i)->filename == info->filename)
  46532. return false;
  46533. files.addSorted (*this, info.release());
  46534. return true;
  46535. }
  46536. return false;
  46537. }
  46538. END_JUCE_NAMESPACE
  46539. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46540. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46541. BEGIN_JUCE_NAMESPACE
  46542. FileBrowserComponent::FileBrowserComponent (int flags_,
  46543. const File& initialFileOrDirectory,
  46544. const FileFilter* fileFilter_,
  46545. FilePreviewComponent* previewComp_)
  46546. : FileFilter (String::empty),
  46547. fileFilter (fileFilter_),
  46548. flags (flags_),
  46549. previewComp (previewComp_),
  46550. currentPathBox ("path"),
  46551. fileLabel ("f", TRANS ("file:")),
  46552. thread ("Juce FileBrowser")
  46553. {
  46554. // You need to specify one or other of the open/save flags..
  46555. jassert ((flags & (saveMode | openMode)) != 0);
  46556. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46557. // You need to specify at least one of these flags..
  46558. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46559. String filename;
  46560. if (initialFileOrDirectory == File::nonexistent)
  46561. {
  46562. currentRoot = File::getCurrentWorkingDirectory();
  46563. }
  46564. else if (initialFileOrDirectory.isDirectory())
  46565. {
  46566. currentRoot = initialFileOrDirectory;
  46567. }
  46568. else
  46569. {
  46570. chosenFiles.add (initialFileOrDirectory);
  46571. currentRoot = initialFileOrDirectory.getParentDirectory();
  46572. filename = initialFileOrDirectory.getFileName();
  46573. }
  46574. fileList = new DirectoryContentsList (this, thread);
  46575. if ((flags & useTreeView) != 0)
  46576. {
  46577. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46578. fileListComponent = tree;
  46579. if ((flags & canSelectMultipleItems) != 0)
  46580. tree->setMultiSelectEnabled (true);
  46581. addAndMakeVisible (tree);
  46582. }
  46583. else
  46584. {
  46585. FileListComponent* const list = new FileListComponent (*fileList);
  46586. fileListComponent = list;
  46587. list->setOutlineThickness (1);
  46588. if ((flags & canSelectMultipleItems) != 0)
  46589. list->setMultipleSelectionEnabled (true);
  46590. addAndMakeVisible (list);
  46591. }
  46592. fileListComponent->addListener (this);
  46593. addAndMakeVisible (&currentPathBox);
  46594. currentPathBox.setEditableText (true);
  46595. StringArray rootNames, rootPaths;
  46596. getRoots (rootNames, rootPaths);
  46597. for (int i = 0; i < rootNames.size(); ++i)
  46598. {
  46599. if (rootNames[i].isEmpty())
  46600. currentPathBox.addSeparator();
  46601. else
  46602. currentPathBox.addItem (rootNames[i], i + 1);
  46603. }
  46604. currentPathBox.addSeparator();
  46605. currentPathBox.addListener (this);
  46606. addAndMakeVisible (&filenameBox);
  46607. filenameBox.setMultiLine (false);
  46608. filenameBox.setSelectAllWhenFocused (true);
  46609. filenameBox.setText (filename, false);
  46610. filenameBox.addListener (this);
  46611. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46612. addAndMakeVisible (&fileLabel);
  46613. fileLabel.attachToComponent (&filenameBox, true);
  46614. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46615. goUpButton->addListener (this);
  46616. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46617. if (previewComp != 0)
  46618. addAndMakeVisible (previewComp);
  46619. setRoot (currentRoot);
  46620. thread.startThread (4);
  46621. }
  46622. FileBrowserComponent::~FileBrowserComponent()
  46623. {
  46624. fileListComponent = 0;
  46625. fileList = 0;
  46626. thread.stopThread (10000);
  46627. }
  46628. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46629. {
  46630. listeners.add (newListener);
  46631. }
  46632. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46633. {
  46634. listeners.remove (listener);
  46635. }
  46636. bool FileBrowserComponent::isSaveMode() const throw()
  46637. {
  46638. return (flags & saveMode) != 0;
  46639. }
  46640. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46641. {
  46642. if (chosenFiles.size() == 0 && currentFileIsValid())
  46643. return 1;
  46644. return chosenFiles.size();
  46645. }
  46646. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46647. {
  46648. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46649. return currentRoot;
  46650. if (! filenameBox.isReadOnly())
  46651. return currentRoot.getChildFile (filenameBox.getText());
  46652. return chosenFiles[index];
  46653. }
  46654. bool FileBrowserComponent::currentFileIsValid() const
  46655. {
  46656. if (isSaveMode())
  46657. return ! getSelectedFile (0).isDirectory();
  46658. else
  46659. return getSelectedFile (0).exists();
  46660. }
  46661. const File FileBrowserComponent::getHighlightedFile() const throw()
  46662. {
  46663. return fileListComponent->getSelectedFile (0);
  46664. }
  46665. void FileBrowserComponent::deselectAllFiles()
  46666. {
  46667. fileListComponent->deselectAllFiles();
  46668. }
  46669. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46670. {
  46671. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46672. }
  46673. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46674. {
  46675. return true;
  46676. }
  46677. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46678. {
  46679. if (f.isDirectory())
  46680. return (flags & canSelectDirectories) != 0
  46681. && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46682. return (flags & canSelectFiles) != 0 && f.exists()
  46683. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46684. }
  46685. const File FileBrowserComponent::getRoot() const
  46686. {
  46687. return currentRoot;
  46688. }
  46689. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46690. {
  46691. if (currentRoot != newRootDirectory)
  46692. {
  46693. fileListComponent->scrollToTop();
  46694. String path (newRootDirectory.getFullPathName());
  46695. if (path.isEmpty())
  46696. path = File::separatorString;
  46697. StringArray rootNames, rootPaths;
  46698. getRoots (rootNames, rootPaths);
  46699. if (! rootPaths.contains (path, true))
  46700. {
  46701. bool alreadyListed = false;
  46702. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46703. {
  46704. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46705. {
  46706. alreadyListed = true;
  46707. break;
  46708. }
  46709. }
  46710. if (! alreadyListed)
  46711. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46712. }
  46713. }
  46714. currentRoot = newRootDirectory;
  46715. fileList->setDirectory (currentRoot, true, true);
  46716. String currentRootName (currentRoot.getFullPathName());
  46717. if (currentRootName.isEmpty())
  46718. currentRootName = File::separatorString;
  46719. currentPathBox.setText (currentRootName, true);
  46720. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46721. && currentRoot.getParentDirectory() != currentRoot);
  46722. }
  46723. void FileBrowserComponent::goUp()
  46724. {
  46725. setRoot (getRoot().getParentDirectory());
  46726. }
  46727. void FileBrowserComponent::refresh()
  46728. {
  46729. fileList->refresh();
  46730. }
  46731. void FileBrowserComponent::setFileFilter (const FileFilter* const newFileFilter)
  46732. {
  46733. if (fileFilter != newFileFilter)
  46734. {
  46735. fileFilter = newFileFilter;
  46736. refresh();
  46737. }
  46738. }
  46739. const String FileBrowserComponent::getActionVerb() const
  46740. {
  46741. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46742. }
  46743. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46744. {
  46745. return previewComp;
  46746. }
  46747. void FileBrowserComponent::resized()
  46748. {
  46749. getLookAndFeel()
  46750. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46751. &currentPathBox, &filenameBox, goUpButton);
  46752. }
  46753. void FileBrowserComponent::sendListenerChangeMessage()
  46754. {
  46755. Component::BailOutChecker checker (this);
  46756. if (previewComp != 0)
  46757. previewComp->selectedFileChanged (getSelectedFile (0));
  46758. // You shouldn't delete the browser when the file gets changed!
  46759. jassert (! checker.shouldBailOut());
  46760. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46761. }
  46762. void FileBrowserComponent::selectionChanged()
  46763. {
  46764. StringArray newFilenames;
  46765. bool resetChosenFiles = true;
  46766. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46767. {
  46768. const File f (fileListComponent->getSelectedFile (i));
  46769. if (isFileOrDirSuitable (f))
  46770. {
  46771. if (resetChosenFiles)
  46772. {
  46773. chosenFiles.clear();
  46774. resetChosenFiles = false;
  46775. }
  46776. chosenFiles.add (f);
  46777. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46778. }
  46779. }
  46780. if (newFilenames.size() > 0)
  46781. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46782. sendListenerChangeMessage();
  46783. }
  46784. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46785. {
  46786. Component::BailOutChecker checker (this);
  46787. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46788. }
  46789. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46790. {
  46791. if (f.isDirectory())
  46792. {
  46793. setRoot (f);
  46794. if ((flags & canSelectDirectories) != 0)
  46795. filenameBox.setText (String::empty);
  46796. }
  46797. else
  46798. {
  46799. Component::BailOutChecker checker (this);
  46800. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46801. }
  46802. }
  46803. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46804. {
  46805. (void) key;
  46806. #if JUCE_LINUX || JUCE_WINDOWS
  46807. if (key.getModifiers().isCommandDown()
  46808. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46809. {
  46810. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46811. fileList->refresh();
  46812. return true;
  46813. }
  46814. #endif
  46815. return false;
  46816. }
  46817. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46818. {
  46819. sendListenerChangeMessage();
  46820. }
  46821. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46822. {
  46823. if (filenameBox.getText().containsChar (File::separator))
  46824. {
  46825. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46826. if (f.isDirectory())
  46827. {
  46828. setRoot (f);
  46829. chosenFiles.clear();
  46830. filenameBox.setText (String::empty);
  46831. }
  46832. else
  46833. {
  46834. setRoot (f.getParentDirectory());
  46835. chosenFiles.clear();
  46836. chosenFiles.add (f);
  46837. filenameBox.setText (f.getFileName());
  46838. }
  46839. }
  46840. else
  46841. {
  46842. fileDoubleClicked (getSelectedFile (0));
  46843. }
  46844. }
  46845. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46846. {
  46847. }
  46848. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46849. {
  46850. if (! isSaveMode())
  46851. selectionChanged();
  46852. }
  46853. void FileBrowserComponent::buttonClicked (Button*)
  46854. {
  46855. goUp();
  46856. }
  46857. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46858. {
  46859. const String newText (currentPathBox.getText().trim().unquoted());
  46860. if (newText.isNotEmpty())
  46861. {
  46862. const int index = currentPathBox.getSelectedId() - 1;
  46863. StringArray rootNames, rootPaths;
  46864. getRoots (rootNames, rootPaths);
  46865. if (rootPaths [index].isNotEmpty())
  46866. {
  46867. setRoot (File (rootPaths [index]));
  46868. }
  46869. else
  46870. {
  46871. File f (newText);
  46872. for (;;)
  46873. {
  46874. if (f.isDirectory())
  46875. {
  46876. setRoot (f);
  46877. break;
  46878. }
  46879. if (f.getParentDirectory() == f)
  46880. break;
  46881. f = f.getParentDirectory();
  46882. }
  46883. }
  46884. }
  46885. }
  46886. void FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46887. {
  46888. #if JUCE_WINDOWS
  46889. Array<File> roots;
  46890. File::findFileSystemRoots (roots);
  46891. rootPaths.clear();
  46892. for (int i = 0; i < roots.size(); ++i)
  46893. {
  46894. const File& drive = roots.getReference(i);
  46895. String name (drive.getFullPathName());
  46896. rootPaths.add (name);
  46897. if (drive.isOnHardDisk())
  46898. {
  46899. String volume (drive.getVolumeLabel());
  46900. if (volume.isEmpty())
  46901. volume = TRANS("Hard Drive");
  46902. name << " [" << volume << ']';
  46903. }
  46904. else if (drive.isOnCDRomDrive())
  46905. {
  46906. name << TRANS(" [CD/DVD drive]");
  46907. }
  46908. rootNames.add (name);
  46909. }
  46910. rootPaths.add (String::empty);
  46911. rootNames.add (String::empty);
  46912. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46913. rootNames.add ("Documents");
  46914. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46915. rootNames.add ("Desktop");
  46916. #endif
  46917. #if JUCE_MAC
  46918. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46919. rootNames.add ("Home folder");
  46920. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46921. rootNames.add ("Documents");
  46922. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46923. rootNames.add ("Desktop");
  46924. rootPaths.add (String::empty);
  46925. rootNames.add (String::empty);
  46926. Array <File> volumes;
  46927. File vol ("/Volumes");
  46928. vol.findChildFiles (volumes, File::findDirectories, false);
  46929. for (int i = 0; i < volumes.size(); ++i)
  46930. {
  46931. const File& volume = volumes.getReference(i);
  46932. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46933. {
  46934. rootPaths.add (volume.getFullPathName());
  46935. rootNames.add (volume.getFileName());
  46936. }
  46937. }
  46938. #endif
  46939. #if JUCE_LINUX
  46940. rootPaths.add ("/");
  46941. rootNames.add ("/");
  46942. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46943. rootNames.add ("Home folder");
  46944. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46945. rootNames.add ("Desktop");
  46946. #endif
  46947. }
  46948. END_JUCE_NAMESPACE
  46949. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46950. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46951. BEGIN_JUCE_NAMESPACE
  46952. FileChooser::FileChooser (const String& chooserBoxTitle,
  46953. const File& currentFileOrDirectory,
  46954. const String& fileFilters,
  46955. const bool useNativeDialogBox_)
  46956. : title (chooserBoxTitle),
  46957. filters (fileFilters),
  46958. startingFile (currentFileOrDirectory),
  46959. useNativeDialogBox (useNativeDialogBox_)
  46960. {
  46961. #if JUCE_LINUX
  46962. useNativeDialogBox = false;
  46963. #endif
  46964. if (! fileFilters.containsNonWhitespaceChars())
  46965. filters = "*";
  46966. }
  46967. FileChooser::~FileChooser()
  46968. {
  46969. }
  46970. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46971. {
  46972. return showDialog (false, true, false, false, false, previewComponent);
  46973. }
  46974. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46975. {
  46976. return showDialog (false, true, false, false, true, previewComponent);
  46977. }
  46978. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46979. {
  46980. return showDialog (true, true, false, false, true, previewComponent);
  46981. }
  46982. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46983. {
  46984. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46985. }
  46986. bool FileChooser::browseForDirectory()
  46987. {
  46988. return showDialog (true, false, false, false, false, 0);
  46989. }
  46990. const File FileChooser::getResult() const
  46991. {
  46992. // if you've used a multiple-file select, you should use the getResults() method
  46993. // to retrieve all the files that were chosen.
  46994. jassert (results.size() <= 1);
  46995. return results.getFirst();
  46996. }
  46997. const Array<File>& FileChooser::getResults() const
  46998. {
  46999. return results;
  47000. }
  47001. bool FileChooser::showDialog (const bool selectsDirectories,
  47002. const bool selectsFiles,
  47003. const bool isSave,
  47004. const bool warnAboutOverwritingExistingFiles,
  47005. const bool selectMultipleFiles,
  47006. FilePreviewComponent* const previewComponent)
  47007. {
  47008. WeakReference<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47009. results.clear();
  47010. // the preview component needs to be the right size before you pass it in here..
  47011. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47012. && previewComponent->getHeight() > 10));
  47013. #if JUCE_WINDOWS
  47014. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47015. #elif JUCE_MAC
  47016. if (useNativeDialogBox && (previewComponent == 0))
  47017. #else
  47018. if (false)
  47019. #endif
  47020. {
  47021. showPlatformDialog (results, title, startingFile, filters,
  47022. selectsDirectories, selectsFiles, isSave,
  47023. warnAboutOverwritingExistingFiles,
  47024. selectMultipleFiles,
  47025. previewComponent);
  47026. }
  47027. else
  47028. {
  47029. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47030. selectsDirectories ? "*" : String::empty,
  47031. String::empty);
  47032. int flags = isSave ? FileBrowserComponent::saveMode
  47033. : FileBrowserComponent::openMode;
  47034. if (selectsFiles)
  47035. flags |= FileBrowserComponent::canSelectFiles;
  47036. if (selectsDirectories)
  47037. {
  47038. flags |= FileBrowserComponent::canSelectDirectories;
  47039. if (! isSave)
  47040. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47041. }
  47042. if (selectMultipleFiles)
  47043. flags |= FileBrowserComponent::canSelectMultipleItems;
  47044. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47045. FileChooserDialogBox box (title, String::empty,
  47046. browserComponent,
  47047. warnAboutOverwritingExistingFiles,
  47048. browserComponent.findColour (AlertWindow::backgroundColourId));
  47049. if (box.show())
  47050. {
  47051. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47052. results.add (browserComponent.getSelectedFile (i));
  47053. }
  47054. }
  47055. if (previouslyFocused != 0)
  47056. previouslyFocused->grabKeyboardFocus();
  47057. return results.size() > 0;
  47058. }
  47059. FilePreviewComponent::FilePreviewComponent()
  47060. {
  47061. }
  47062. FilePreviewComponent::~FilePreviewComponent()
  47063. {
  47064. }
  47065. END_JUCE_NAMESPACE
  47066. /*** End of inlined file: juce_FileChooser.cpp ***/
  47067. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47068. BEGIN_JUCE_NAMESPACE
  47069. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47070. const String& instructions,
  47071. FileBrowserComponent& chooserComponent,
  47072. const bool warnAboutOverwritingExistingFiles_,
  47073. const Colour& backgroundColour)
  47074. : ResizableWindow (name, backgroundColour, true),
  47075. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47076. {
  47077. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47078. setResizable (true, true);
  47079. setResizeLimits (300, 300, 1200, 1000);
  47080. content->okButton.addListener (this);
  47081. content->cancelButton.addListener (this);
  47082. content->newFolderButton.addListener (this);
  47083. content->chooserComponent.addListener (this);
  47084. selectionChanged();
  47085. }
  47086. FileChooserDialogBox::~FileChooserDialogBox()
  47087. {
  47088. content->chooserComponent.removeListener (this);
  47089. }
  47090. bool FileChooserDialogBox::show (int w, int h)
  47091. {
  47092. return showAt (-1, -1, w, h);
  47093. }
  47094. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47095. {
  47096. if (w <= 0)
  47097. {
  47098. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47099. if (previewComp != 0)
  47100. w = 400 + previewComp->getWidth();
  47101. else
  47102. w = 600;
  47103. }
  47104. if (h <= 0)
  47105. h = 500;
  47106. if (x < 0 || y < 0)
  47107. centreWithSize (w, h);
  47108. else
  47109. setBounds (x, y, w, h);
  47110. const bool ok = (runModalLoop() != 0);
  47111. setVisible (false);
  47112. return ok;
  47113. }
  47114. void FileChooserDialogBox::buttonClicked (Button* button)
  47115. {
  47116. if (button == &(content->okButton))
  47117. {
  47118. okButtonPressed();
  47119. }
  47120. else if (button == &(content->cancelButton))
  47121. {
  47122. closeButtonPressed();
  47123. }
  47124. else if (button == &(content->newFolderButton))
  47125. {
  47126. createNewFolder();
  47127. }
  47128. }
  47129. void FileChooserDialogBox::closeButtonPressed()
  47130. {
  47131. setVisible (false);
  47132. }
  47133. void FileChooserDialogBox::selectionChanged()
  47134. {
  47135. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47136. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  47137. && content->chooserComponent.getRoot().isDirectory());
  47138. }
  47139. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47140. {
  47141. }
  47142. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47143. {
  47144. selectionChanged();
  47145. content->okButton.triggerClick();
  47146. }
  47147. void FileChooserDialogBox::okButtonPressed()
  47148. {
  47149. if ((! (warnAboutOverwritingExistingFiles
  47150. && content->chooserComponent.isSaveMode()
  47151. && content->chooserComponent.getSelectedFile(0).exists()))
  47152. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47153. TRANS("File already exists"),
  47154. TRANS("There's already a file called:")
  47155. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47156. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47157. TRANS("overwrite"),
  47158. TRANS("cancel")))
  47159. {
  47160. exitModalState (1);
  47161. }
  47162. }
  47163. void FileChooserDialogBox::createNewFolder()
  47164. {
  47165. File parent (content->chooserComponent.getRoot());
  47166. if (parent.isDirectory())
  47167. {
  47168. AlertWindow aw (TRANS("New Folder"),
  47169. TRANS("Please enter the name for the folder"),
  47170. AlertWindow::NoIcon, this);
  47171. aw.addTextEditor ("name", String::empty, String::empty, false);
  47172. aw.addButton (TRANS("ok"), 1, KeyPress::returnKey);
  47173. aw.addButton (TRANS("cancel"), KeyPress::escapeKey);
  47174. if (aw.runModalLoop() != 0)
  47175. {
  47176. aw.setVisible (false);
  47177. const String name (File::createLegalFileName (aw.getTextEditorContents ("name")));
  47178. if (! name.isEmpty())
  47179. {
  47180. if (! parent.getChildFile (name).createDirectory())
  47181. {
  47182. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  47183. TRANS ("New Folder"),
  47184. TRANS ("Couldn't create the folder!"));
  47185. }
  47186. content->chooserComponent.refresh();
  47187. }
  47188. }
  47189. }
  47190. }
  47191. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47192. : Component (name), instructions (instructions_),
  47193. chooserComponent (chooserComponent_),
  47194. okButton (chooserComponent_.getActionVerb()),
  47195. cancelButton (TRANS ("Cancel")),
  47196. newFolderButton (TRANS ("New Folder"))
  47197. {
  47198. addAndMakeVisible (&chooserComponent);
  47199. addAndMakeVisible (&okButton);
  47200. okButton.addShortcut (KeyPress::returnKey);
  47201. addAndMakeVisible (&cancelButton);
  47202. cancelButton.addShortcut (KeyPress::escapeKey);
  47203. addChildComponent (&newFolderButton);
  47204. setInterceptsMouseClicks (false, true);
  47205. }
  47206. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47207. {
  47208. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47209. text.draw (g);
  47210. }
  47211. void FileChooserDialogBox::ContentComponent::resized()
  47212. {
  47213. const int buttonHeight = 26;
  47214. Rectangle<int> area (getLocalBounds());
  47215. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47216. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47217. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47218. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47219. Rectangle<int> buttonArea (area.reduced (16, 10));
  47220. okButton.changeWidthToFitText (buttonHeight);
  47221. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47222. buttonArea.removeFromRight (16);
  47223. cancelButton.changeWidthToFitText (buttonHeight);
  47224. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47225. newFolderButton.changeWidthToFitText (buttonHeight);
  47226. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47227. }
  47228. END_JUCE_NAMESPACE
  47229. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47230. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47231. BEGIN_JUCE_NAMESPACE
  47232. FileFilter::FileFilter (const String& filterDescription)
  47233. : description (filterDescription)
  47234. {
  47235. }
  47236. FileFilter::~FileFilter()
  47237. {
  47238. }
  47239. const String& FileFilter::getDescription() const throw()
  47240. {
  47241. return description;
  47242. }
  47243. END_JUCE_NAMESPACE
  47244. /*** End of inlined file: juce_FileFilter.cpp ***/
  47245. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47246. BEGIN_JUCE_NAMESPACE
  47247. const Image juce_createIconForFile (const File& file);
  47248. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47249. : ListBox (String::empty, 0),
  47250. DirectoryContentsDisplayComponent (listToShow)
  47251. {
  47252. setModel (this);
  47253. fileList.addChangeListener (this);
  47254. }
  47255. FileListComponent::~FileListComponent()
  47256. {
  47257. fileList.removeChangeListener (this);
  47258. }
  47259. int FileListComponent::getNumSelectedFiles() const
  47260. {
  47261. return getNumSelectedRows();
  47262. }
  47263. const File FileListComponent::getSelectedFile (int index) const
  47264. {
  47265. return fileList.getFile (getSelectedRow (index));
  47266. }
  47267. void FileListComponent::deselectAllFiles()
  47268. {
  47269. deselectAllRows();
  47270. }
  47271. void FileListComponent::scrollToTop()
  47272. {
  47273. getVerticalScrollBar()->setCurrentRangeStart (0);
  47274. }
  47275. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47276. {
  47277. updateContent();
  47278. if (lastDirectory != fileList.getDirectory())
  47279. {
  47280. lastDirectory = fileList.getDirectory();
  47281. deselectAllRows();
  47282. }
  47283. }
  47284. class FileListItemComponent : public Component,
  47285. public TimeSliceClient,
  47286. public AsyncUpdater
  47287. {
  47288. public:
  47289. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47290. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47291. {
  47292. }
  47293. ~FileListItemComponent()
  47294. {
  47295. thread.removeTimeSliceClient (this);
  47296. }
  47297. void paint (Graphics& g)
  47298. {
  47299. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47300. file.getFileName(),
  47301. &icon, fileSize, modTime,
  47302. isDirectory, highlighted,
  47303. index, owner);
  47304. }
  47305. void mouseDown (const MouseEvent& e)
  47306. {
  47307. owner.selectRowsBasedOnModifierKeys (index, e.mods, false);
  47308. owner.sendMouseClickMessage (file, e);
  47309. }
  47310. void mouseDoubleClick (const MouseEvent&)
  47311. {
  47312. owner.sendDoubleClickMessage (file);
  47313. }
  47314. void update (const File& root,
  47315. const DirectoryContentsList::FileInfo* const fileInfo,
  47316. const int index_,
  47317. const bool highlighted_)
  47318. {
  47319. thread.removeTimeSliceClient (this);
  47320. if (highlighted_ != highlighted || index_ != index)
  47321. {
  47322. index = index_;
  47323. highlighted = highlighted_;
  47324. repaint();
  47325. }
  47326. File newFile;
  47327. String newFileSize, newModTime;
  47328. if (fileInfo != 0)
  47329. {
  47330. newFile = root.getChildFile (fileInfo->filename);
  47331. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47332. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47333. }
  47334. if (newFile != file
  47335. || fileSize != newFileSize
  47336. || modTime != newModTime)
  47337. {
  47338. file = newFile;
  47339. fileSize = newFileSize;
  47340. modTime = newModTime;
  47341. icon = Image::null;
  47342. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47343. repaint();
  47344. }
  47345. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47346. {
  47347. updateIcon (true);
  47348. if (! icon.isValid())
  47349. thread.addTimeSliceClient (this);
  47350. }
  47351. }
  47352. bool useTimeSlice()
  47353. {
  47354. updateIcon (false);
  47355. return false;
  47356. }
  47357. void handleAsyncUpdate()
  47358. {
  47359. repaint();
  47360. }
  47361. private:
  47362. FileListComponent& owner;
  47363. TimeSliceThread& thread;
  47364. File file;
  47365. String fileSize, modTime;
  47366. Image icon;
  47367. int index;
  47368. bool highlighted, isDirectory;
  47369. void updateIcon (const bool onlyUpdateIfCached)
  47370. {
  47371. if (icon.isNull())
  47372. {
  47373. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47374. Image im (ImageCache::getFromHashCode (hashCode));
  47375. if (im.isNull() && ! onlyUpdateIfCached)
  47376. {
  47377. im = juce_createIconForFile (file);
  47378. if (im.isValid())
  47379. ImageCache::addImageToCache (im, hashCode);
  47380. }
  47381. if (im.isValid())
  47382. {
  47383. icon = im;
  47384. triggerAsyncUpdate();
  47385. }
  47386. }
  47387. }
  47388. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47389. };
  47390. int FileListComponent::getNumRows()
  47391. {
  47392. return fileList.getNumFiles();
  47393. }
  47394. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47395. {
  47396. }
  47397. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47398. {
  47399. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47400. if (comp == 0)
  47401. {
  47402. delete existingComponentToUpdate;
  47403. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47404. }
  47405. DirectoryContentsList::FileInfo fileInfo;
  47406. if (fileList.getFileInfo (row, fileInfo))
  47407. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47408. else
  47409. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47410. return comp;
  47411. }
  47412. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47413. {
  47414. sendSelectionChangeMessage();
  47415. }
  47416. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47417. {
  47418. }
  47419. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47420. {
  47421. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47422. }
  47423. END_JUCE_NAMESPACE
  47424. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47425. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47426. BEGIN_JUCE_NAMESPACE
  47427. FilenameComponent::FilenameComponent (const String& name,
  47428. const File& currentFile,
  47429. const bool canEditFilename,
  47430. const bool isDirectory,
  47431. const bool isForSaving,
  47432. const String& fileBrowserWildcard,
  47433. const String& enforcedSuffix_,
  47434. const String& textWhenNothingSelected)
  47435. : Component (name),
  47436. maxRecentFiles (30),
  47437. isDir (isDirectory),
  47438. isSaving (isForSaving),
  47439. isFileDragOver (false),
  47440. wildcard (fileBrowserWildcard),
  47441. enforcedSuffix (enforcedSuffix_)
  47442. {
  47443. addAndMakeVisible (&filenameBox);
  47444. filenameBox.setEditableText (canEditFilename);
  47445. filenameBox.addListener (this);
  47446. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47447. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47448. setBrowseButtonText ("...");
  47449. setCurrentFile (currentFile, true);
  47450. }
  47451. FilenameComponent::~FilenameComponent()
  47452. {
  47453. }
  47454. void FilenameComponent::paintOverChildren (Graphics& g)
  47455. {
  47456. if (isFileDragOver)
  47457. {
  47458. g.setColour (Colours::red.withAlpha (0.2f));
  47459. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47460. }
  47461. }
  47462. void FilenameComponent::resized()
  47463. {
  47464. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47465. }
  47466. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47467. {
  47468. browseButtonText = newBrowseButtonText;
  47469. lookAndFeelChanged();
  47470. }
  47471. void FilenameComponent::lookAndFeelChanged()
  47472. {
  47473. browseButton = 0;
  47474. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47475. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47476. resized();
  47477. browseButton->addListener (this);
  47478. }
  47479. void FilenameComponent::setTooltip (const String& newTooltip)
  47480. {
  47481. SettableTooltipClient::setTooltip (newTooltip);
  47482. filenameBox.setTooltip (newTooltip);
  47483. }
  47484. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47485. {
  47486. defaultBrowseFile = newDefaultDirectory;
  47487. }
  47488. void FilenameComponent::buttonClicked (Button*)
  47489. {
  47490. FileChooser fc (TRANS("Choose a new file"),
  47491. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47492. : getCurrentFile(),
  47493. wildcard);
  47494. if (isDir ? fc.browseForDirectory()
  47495. : (isSaving ? fc.browseForFileToSave (false)
  47496. : fc.browseForFileToOpen()))
  47497. {
  47498. setCurrentFile (fc.getResult(), true);
  47499. }
  47500. }
  47501. void FilenameComponent::comboBoxChanged (ComboBox*)
  47502. {
  47503. setCurrentFile (getCurrentFile(), true);
  47504. }
  47505. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47506. {
  47507. return true;
  47508. }
  47509. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47510. {
  47511. isFileDragOver = false;
  47512. repaint();
  47513. const File f (filenames[0]);
  47514. if (f.exists() && (f.isDirectory() == isDir))
  47515. setCurrentFile (f, true);
  47516. }
  47517. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47518. {
  47519. isFileDragOver = true;
  47520. repaint();
  47521. }
  47522. void FilenameComponent::fileDragExit (const StringArray&)
  47523. {
  47524. isFileDragOver = false;
  47525. repaint();
  47526. }
  47527. const File FilenameComponent::getCurrentFile() const
  47528. {
  47529. File f (filenameBox.getText());
  47530. if (enforcedSuffix.isNotEmpty())
  47531. f = f.withFileExtension (enforcedSuffix);
  47532. return f;
  47533. }
  47534. void FilenameComponent::setCurrentFile (File newFile,
  47535. const bool addToRecentlyUsedList,
  47536. const bool sendChangeNotification)
  47537. {
  47538. if (enforcedSuffix.isNotEmpty())
  47539. newFile = newFile.withFileExtension (enforcedSuffix);
  47540. if (newFile.getFullPathName() != lastFilename)
  47541. {
  47542. lastFilename = newFile.getFullPathName();
  47543. if (addToRecentlyUsedList)
  47544. addRecentlyUsedFile (newFile);
  47545. filenameBox.setText (lastFilename, true);
  47546. if (sendChangeNotification)
  47547. triggerAsyncUpdate();
  47548. }
  47549. }
  47550. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47551. {
  47552. filenameBox.setEditableText (shouldBeEditable);
  47553. }
  47554. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47555. {
  47556. StringArray names;
  47557. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47558. names.add (filenameBox.getItemText (i));
  47559. return names;
  47560. }
  47561. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47562. {
  47563. if (filenames != getRecentlyUsedFilenames())
  47564. {
  47565. filenameBox.clear();
  47566. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47567. filenameBox.addItem (filenames[i], i + 1);
  47568. }
  47569. }
  47570. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47571. {
  47572. maxRecentFiles = jmax (1, newMaximum);
  47573. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47574. }
  47575. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47576. {
  47577. StringArray files (getRecentlyUsedFilenames());
  47578. if (file.getFullPathName().isNotEmpty())
  47579. {
  47580. files.removeString (file.getFullPathName(), true);
  47581. files.insert (0, file.getFullPathName());
  47582. setRecentlyUsedFilenames (files);
  47583. }
  47584. }
  47585. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47586. {
  47587. listeners.add (listener);
  47588. }
  47589. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47590. {
  47591. listeners.remove (listener);
  47592. }
  47593. void FilenameComponent::handleAsyncUpdate()
  47594. {
  47595. Component::BailOutChecker checker (this);
  47596. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47597. }
  47598. END_JUCE_NAMESPACE
  47599. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47600. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47601. BEGIN_JUCE_NAMESPACE
  47602. FileSearchPathListComponent::FileSearchPathListComponent()
  47603. : addButton ("+"),
  47604. removeButton ("-"),
  47605. changeButton (TRANS ("change...")),
  47606. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47607. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47608. {
  47609. listBox.setModel (this);
  47610. addAndMakeVisible (&listBox);
  47611. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47612. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47613. listBox.setOutlineThickness (1);
  47614. addAndMakeVisible (&addButton);
  47615. addButton.addListener (this);
  47616. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47617. addAndMakeVisible (&removeButton);
  47618. removeButton.addListener (this);
  47619. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47620. addAndMakeVisible (&changeButton);
  47621. changeButton.addListener (this);
  47622. addAndMakeVisible (&upButton);
  47623. upButton.addListener (this);
  47624. {
  47625. Path arrowPath;
  47626. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47627. DrawablePath arrowImage;
  47628. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47629. arrowImage.setPath (arrowPath);
  47630. upButton.setImages (&arrowImage);
  47631. }
  47632. addAndMakeVisible (&downButton);
  47633. downButton.addListener (this);
  47634. {
  47635. Path arrowPath;
  47636. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47637. DrawablePath arrowImage;
  47638. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47639. arrowImage.setPath (arrowPath);
  47640. downButton.setImages (&arrowImage);
  47641. }
  47642. updateButtons();
  47643. }
  47644. FileSearchPathListComponent::~FileSearchPathListComponent()
  47645. {
  47646. }
  47647. void FileSearchPathListComponent::updateButtons()
  47648. {
  47649. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47650. removeButton.setEnabled (anythingSelected);
  47651. changeButton.setEnabled (anythingSelected);
  47652. upButton.setEnabled (anythingSelected);
  47653. downButton.setEnabled (anythingSelected);
  47654. }
  47655. void FileSearchPathListComponent::changed()
  47656. {
  47657. listBox.updateContent();
  47658. listBox.repaint();
  47659. updateButtons();
  47660. }
  47661. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47662. {
  47663. if (newPath.toString() != path.toString())
  47664. {
  47665. path = newPath;
  47666. changed();
  47667. }
  47668. }
  47669. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47670. {
  47671. defaultBrowseTarget = newDefaultDirectory;
  47672. }
  47673. int FileSearchPathListComponent::getNumRows()
  47674. {
  47675. return path.getNumPaths();
  47676. }
  47677. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47678. {
  47679. if (rowIsSelected)
  47680. g.fillAll (findColour (TextEditor::highlightColourId));
  47681. g.setColour (findColour (ListBox::textColourId));
  47682. Font f (height * 0.7f);
  47683. f.setHorizontalScale (0.9f);
  47684. g.setFont (f);
  47685. g.drawText (path [rowNumber].getFullPathName(),
  47686. 4, 0, width - 6, height,
  47687. Justification::centredLeft, true);
  47688. }
  47689. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47690. {
  47691. if (isPositiveAndBelow (row, path.getNumPaths()))
  47692. {
  47693. path.remove (row);
  47694. changed();
  47695. }
  47696. }
  47697. void FileSearchPathListComponent::returnKeyPressed (int row)
  47698. {
  47699. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47700. if (chooser.browseForDirectory())
  47701. {
  47702. path.remove (row);
  47703. path.add (chooser.getResult(), row);
  47704. changed();
  47705. }
  47706. }
  47707. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47708. {
  47709. returnKeyPressed (row);
  47710. }
  47711. void FileSearchPathListComponent::selectedRowsChanged (int)
  47712. {
  47713. updateButtons();
  47714. }
  47715. void FileSearchPathListComponent::paint (Graphics& g)
  47716. {
  47717. g.fillAll (findColour (backgroundColourId));
  47718. }
  47719. void FileSearchPathListComponent::resized()
  47720. {
  47721. const int buttonH = 22;
  47722. const int buttonY = getHeight() - buttonH - 4;
  47723. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47724. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47725. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47726. changeButton.changeWidthToFitText (buttonH);
  47727. downButton.setSize (buttonH * 2, buttonH);
  47728. upButton.setSize (buttonH * 2, buttonH);
  47729. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47730. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47731. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47732. }
  47733. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47734. {
  47735. return true;
  47736. }
  47737. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47738. {
  47739. for (int i = filenames.size(); --i >= 0;)
  47740. {
  47741. const File f (filenames[i]);
  47742. if (f.isDirectory())
  47743. {
  47744. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47745. path.add (f, row);
  47746. changed();
  47747. }
  47748. }
  47749. }
  47750. void FileSearchPathListComponent::buttonClicked (Button* button)
  47751. {
  47752. const int currentRow = listBox.getSelectedRow();
  47753. if (button == &removeButton)
  47754. {
  47755. deleteKeyPressed (currentRow);
  47756. }
  47757. else if (button == &addButton)
  47758. {
  47759. File start (defaultBrowseTarget);
  47760. if (start == File::nonexistent)
  47761. start = path [0];
  47762. if (start == File::nonexistent)
  47763. start = File::getCurrentWorkingDirectory();
  47764. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47765. if (chooser.browseForDirectory())
  47766. {
  47767. path.add (chooser.getResult(), currentRow);
  47768. }
  47769. }
  47770. else if (button == &changeButton)
  47771. {
  47772. returnKeyPressed (currentRow);
  47773. }
  47774. else if (button == &upButton)
  47775. {
  47776. if (currentRow > 0 && currentRow < path.getNumPaths())
  47777. {
  47778. const File f (path[currentRow]);
  47779. path.remove (currentRow);
  47780. path.add (f, currentRow - 1);
  47781. listBox.selectRow (currentRow - 1);
  47782. }
  47783. }
  47784. else if (button == &downButton)
  47785. {
  47786. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47787. {
  47788. const File f (path[currentRow]);
  47789. path.remove (currentRow);
  47790. path.add (f, currentRow + 1);
  47791. listBox.selectRow (currentRow + 1);
  47792. }
  47793. }
  47794. changed();
  47795. }
  47796. END_JUCE_NAMESPACE
  47797. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47798. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47799. BEGIN_JUCE_NAMESPACE
  47800. const Image juce_createIconForFile (const File& file);
  47801. class FileListTreeItem : public TreeViewItem,
  47802. public TimeSliceClient,
  47803. public AsyncUpdater,
  47804. public ChangeListener
  47805. {
  47806. public:
  47807. FileListTreeItem (FileTreeComponent& owner_,
  47808. DirectoryContentsList* const parentContentsList_,
  47809. const int indexInContentsList_,
  47810. const File& file_,
  47811. TimeSliceThread& thread_)
  47812. : file (file_),
  47813. owner (owner_),
  47814. parentContentsList (parentContentsList_),
  47815. indexInContentsList (indexInContentsList_),
  47816. subContentsList (0),
  47817. canDeleteSubContentsList (false),
  47818. thread (thread_),
  47819. icon (0)
  47820. {
  47821. DirectoryContentsList::FileInfo fileInfo;
  47822. if (parentContentsList_ != 0
  47823. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47824. {
  47825. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47826. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47827. isDirectory = fileInfo.isDirectory;
  47828. }
  47829. else
  47830. {
  47831. isDirectory = true;
  47832. }
  47833. }
  47834. ~FileListTreeItem()
  47835. {
  47836. thread.removeTimeSliceClient (this);
  47837. clearSubItems();
  47838. if (canDeleteSubContentsList)
  47839. delete subContentsList;
  47840. }
  47841. bool mightContainSubItems() { return isDirectory; }
  47842. const String getUniqueName() const { return file.getFullPathName(); }
  47843. int getItemHeight() const { return 22; }
  47844. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47845. void itemOpennessChanged (bool isNowOpen)
  47846. {
  47847. if (isNowOpen)
  47848. {
  47849. clearSubItems();
  47850. isDirectory = file.isDirectory();
  47851. if (isDirectory)
  47852. {
  47853. if (subContentsList == 0)
  47854. {
  47855. jassert (parentContentsList != 0);
  47856. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47857. l->setDirectory (file, true, true);
  47858. setSubContentsList (l);
  47859. canDeleteSubContentsList = true;
  47860. }
  47861. changeListenerCallback (0);
  47862. }
  47863. }
  47864. }
  47865. void setSubContentsList (DirectoryContentsList* newList)
  47866. {
  47867. jassert (subContentsList == 0);
  47868. subContentsList = newList;
  47869. newList->addChangeListener (this);
  47870. }
  47871. void changeListenerCallback (ChangeBroadcaster*)
  47872. {
  47873. clearSubItems();
  47874. if (isOpen() && subContentsList != 0)
  47875. {
  47876. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47877. {
  47878. FileListTreeItem* const item
  47879. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47880. addSubItem (item);
  47881. }
  47882. }
  47883. }
  47884. void paintItem (Graphics& g, int width, int height)
  47885. {
  47886. if (file != File::nonexistent)
  47887. {
  47888. updateIcon (true);
  47889. if (icon.isNull())
  47890. thread.addTimeSliceClient (this);
  47891. }
  47892. owner.getLookAndFeel()
  47893. .drawFileBrowserRow (g, width, height,
  47894. file.getFileName(),
  47895. &icon, fileSize, modTime,
  47896. isDirectory, isSelected(),
  47897. indexInContentsList, owner);
  47898. }
  47899. void itemClicked (const MouseEvent& e)
  47900. {
  47901. owner.sendMouseClickMessage (file, e);
  47902. }
  47903. void itemDoubleClicked (const MouseEvent& e)
  47904. {
  47905. TreeViewItem::itemDoubleClicked (e);
  47906. owner.sendDoubleClickMessage (file);
  47907. }
  47908. void itemSelectionChanged (bool)
  47909. {
  47910. owner.sendSelectionChangeMessage();
  47911. }
  47912. bool useTimeSlice()
  47913. {
  47914. updateIcon (false);
  47915. thread.removeTimeSliceClient (this);
  47916. return false;
  47917. }
  47918. void handleAsyncUpdate()
  47919. {
  47920. owner.repaint();
  47921. }
  47922. const File file;
  47923. private:
  47924. FileTreeComponent& owner;
  47925. DirectoryContentsList* parentContentsList;
  47926. int indexInContentsList;
  47927. DirectoryContentsList* subContentsList;
  47928. bool isDirectory, canDeleteSubContentsList;
  47929. TimeSliceThread& thread;
  47930. Image icon;
  47931. String fileSize;
  47932. String modTime;
  47933. void updateIcon (const bool onlyUpdateIfCached)
  47934. {
  47935. if (icon.isNull())
  47936. {
  47937. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47938. Image im (ImageCache::getFromHashCode (hashCode));
  47939. if (im.isNull() && ! onlyUpdateIfCached)
  47940. {
  47941. im = juce_createIconForFile (file);
  47942. if (im.isValid())
  47943. ImageCache::addImageToCache (im, hashCode);
  47944. }
  47945. if (im.isValid())
  47946. {
  47947. icon = im;
  47948. triggerAsyncUpdate();
  47949. }
  47950. }
  47951. }
  47952. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  47953. };
  47954. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47955. : DirectoryContentsDisplayComponent (listToShow)
  47956. {
  47957. FileListTreeItem* const root
  47958. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47959. listToShow.getTimeSliceThread());
  47960. root->setSubContentsList (&listToShow);
  47961. setRootItemVisible (false);
  47962. setRootItem (root);
  47963. }
  47964. FileTreeComponent::~FileTreeComponent()
  47965. {
  47966. deleteRootItem();
  47967. }
  47968. const File FileTreeComponent::getSelectedFile (const int index) const
  47969. {
  47970. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47971. return item != 0 ? item->file
  47972. : File::nonexistent;
  47973. }
  47974. void FileTreeComponent::deselectAllFiles()
  47975. {
  47976. clearSelectedItems();
  47977. }
  47978. void FileTreeComponent::scrollToTop()
  47979. {
  47980. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47981. }
  47982. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47983. {
  47984. dragAndDropDescription = description;
  47985. }
  47986. END_JUCE_NAMESPACE
  47987. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47988. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47989. BEGIN_JUCE_NAMESPACE
  47990. ImagePreviewComponent::ImagePreviewComponent()
  47991. {
  47992. }
  47993. ImagePreviewComponent::~ImagePreviewComponent()
  47994. {
  47995. }
  47996. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47997. {
  47998. const int availableW = proportionOfWidth (0.97f);
  47999. const int availableH = getHeight() - 13 * 4;
  48000. const double scale = jmin (1.0,
  48001. availableW / (double) w,
  48002. availableH / (double) h);
  48003. w = roundToInt (scale * w);
  48004. h = roundToInt (scale * h);
  48005. }
  48006. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48007. {
  48008. if (fileToLoad != file)
  48009. {
  48010. fileToLoad = file;
  48011. startTimer (100);
  48012. }
  48013. }
  48014. void ImagePreviewComponent::timerCallback()
  48015. {
  48016. stopTimer();
  48017. currentThumbnail = Image::null;
  48018. currentDetails = String::empty;
  48019. repaint();
  48020. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48021. if (in != 0)
  48022. {
  48023. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48024. if (format != 0)
  48025. {
  48026. currentThumbnail = format->decodeImage (*in);
  48027. if (currentThumbnail.isValid())
  48028. {
  48029. int w = currentThumbnail.getWidth();
  48030. int h = currentThumbnail.getHeight();
  48031. currentDetails
  48032. << fileToLoad.getFileName() << "\n"
  48033. << format->getFormatName() << "\n"
  48034. << w << " x " << h << " pixels\n"
  48035. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48036. getThumbSize (w, h);
  48037. currentThumbnail = currentThumbnail.rescaled (w, h);
  48038. }
  48039. }
  48040. }
  48041. }
  48042. void ImagePreviewComponent::paint (Graphics& g)
  48043. {
  48044. if (currentThumbnail.isValid())
  48045. {
  48046. g.setFont (13.0f);
  48047. int w = currentThumbnail.getWidth();
  48048. int h = currentThumbnail.getHeight();
  48049. getThumbSize (w, h);
  48050. const int numLines = 4;
  48051. const int totalH = 13 * numLines + h + 4;
  48052. const int y = (getHeight() - totalH) / 2;
  48053. g.drawImageWithin (currentThumbnail,
  48054. (getWidth() - w) / 2, y, w, h,
  48055. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48056. false);
  48057. g.drawFittedText (currentDetails,
  48058. 0, y + h + 4, getWidth(), 100,
  48059. Justification::centredTop, numLines);
  48060. }
  48061. }
  48062. END_JUCE_NAMESPACE
  48063. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48064. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48065. BEGIN_JUCE_NAMESPACE
  48066. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48067. const String& directoryWildcardPatterns,
  48068. const String& description_)
  48069. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48070. : (description_ + " (" + fileWildcardPatterns + ")"))
  48071. {
  48072. parse (fileWildcardPatterns, fileWildcards);
  48073. parse (directoryWildcardPatterns, directoryWildcards);
  48074. }
  48075. WildcardFileFilter::~WildcardFileFilter()
  48076. {
  48077. }
  48078. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48079. {
  48080. return match (file, fileWildcards);
  48081. }
  48082. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48083. {
  48084. return match (file, directoryWildcards);
  48085. }
  48086. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48087. {
  48088. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48089. result.trim();
  48090. result.removeEmptyStrings();
  48091. // special case for *.*, because people use it to mean "any file", but it
  48092. // would actually ignore files with no extension.
  48093. for (int i = result.size(); --i >= 0;)
  48094. if (result[i] == "*.*")
  48095. result.set (i, "*");
  48096. }
  48097. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48098. {
  48099. const String filename (file.getFileName());
  48100. for (int i = wildcards.size(); --i >= 0;)
  48101. if (filename.matchesWildcard (wildcards[i], true))
  48102. return true;
  48103. return false;
  48104. }
  48105. END_JUCE_NAMESPACE
  48106. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48107. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48108. BEGIN_JUCE_NAMESPACE
  48109. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48110. {
  48111. }
  48112. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48113. {
  48114. }
  48115. namespace KeyboardFocusHelpers
  48116. {
  48117. // This will sort a set of components, so that they are ordered in terms of
  48118. // left-to-right and then top-to-bottom.
  48119. class ScreenPositionComparator
  48120. {
  48121. public:
  48122. ScreenPositionComparator() {}
  48123. static int compareElements (const Component* const first, const Component* const second)
  48124. {
  48125. int explicitOrder1 = first->getExplicitFocusOrder();
  48126. if (explicitOrder1 <= 0)
  48127. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48128. int explicitOrder2 = second->getExplicitFocusOrder();
  48129. if (explicitOrder2 <= 0)
  48130. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48131. if (explicitOrder1 != explicitOrder2)
  48132. return explicitOrder1 - explicitOrder2;
  48133. const int diff = first->getY() - second->getY();
  48134. return (diff == 0) ? first->getX() - second->getX()
  48135. : diff;
  48136. }
  48137. };
  48138. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48139. {
  48140. if (parent->getNumChildComponents() > 0)
  48141. {
  48142. Array <Component*> localComps;
  48143. ScreenPositionComparator comparator;
  48144. int i;
  48145. for (i = parent->getNumChildComponents(); --i >= 0;)
  48146. {
  48147. Component* const c = parent->getChildComponent (i);
  48148. if (c->isVisible() && c->isEnabled())
  48149. localComps.addSorted (comparator, c);
  48150. }
  48151. for (i = 0; i < localComps.size(); ++i)
  48152. {
  48153. Component* const c = localComps.getUnchecked (i);
  48154. if (c->getWantsKeyboardFocus())
  48155. comps.add (c);
  48156. if (! c->isFocusContainer())
  48157. findAllFocusableComponents (c, comps);
  48158. }
  48159. }
  48160. }
  48161. }
  48162. namespace KeyboardFocusHelpers
  48163. {
  48164. Component* getIncrementedComponent (Component* const current, const int delta)
  48165. {
  48166. Component* focusContainer = current->getParentComponent();
  48167. if (focusContainer != 0)
  48168. {
  48169. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48170. focusContainer = focusContainer->getParentComponent();
  48171. if (focusContainer != 0)
  48172. {
  48173. Array <Component*> comps;
  48174. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48175. if (comps.size() > 0)
  48176. {
  48177. const int index = comps.indexOf (current);
  48178. return comps [(index + comps.size() + delta) % comps.size()];
  48179. }
  48180. }
  48181. }
  48182. return 0;
  48183. }
  48184. }
  48185. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48186. {
  48187. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48188. }
  48189. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48190. {
  48191. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48192. }
  48193. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48194. {
  48195. Array <Component*> comps;
  48196. if (parentComponent != 0)
  48197. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48198. return comps.getFirst();
  48199. }
  48200. END_JUCE_NAMESPACE
  48201. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48202. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48203. BEGIN_JUCE_NAMESPACE
  48204. bool KeyListener::keyStateChanged (const bool, Component*)
  48205. {
  48206. return false;
  48207. }
  48208. END_JUCE_NAMESPACE
  48209. /*** End of inlined file: juce_KeyListener.cpp ***/
  48210. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48211. BEGIN_JUCE_NAMESPACE
  48212. // N.B. these two includes are put here deliberately to avoid problems with
  48213. // old GCCs failing on long include paths
  48214. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48215. {
  48216. public:
  48217. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48218. const CommandID commandID_,
  48219. const String& keyName,
  48220. const int keyNum_)
  48221. : Button (keyName),
  48222. owner (owner_),
  48223. commandID (commandID_),
  48224. keyNum (keyNum_)
  48225. {
  48226. setWantsKeyboardFocus (false);
  48227. setTriggeredOnMouseDown (keyNum >= 0);
  48228. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48229. : TRANS("click to change this key-mapping"));
  48230. }
  48231. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48232. {
  48233. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48234. keyNum >= 0 ? getName() : String::empty);
  48235. }
  48236. void clicked()
  48237. {
  48238. if (keyNum >= 0)
  48239. {
  48240. // existing key clicked..
  48241. PopupMenu m;
  48242. m.addItem (1, TRANS("change this key-mapping"));
  48243. m.addSeparator();
  48244. m.addItem (2, TRANS("remove this key-mapping"));
  48245. switch (m.show())
  48246. {
  48247. case 1: assignNewKey(); break;
  48248. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48249. default: break;
  48250. }
  48251. }
  48252. else
  48253. {
  48254. assignNewKey(); // + button pressed..
  48255. }
  48256. }
  48257. void fitToContent (const int h) throw()
  48258. {
  48259. if (keyNum < 0)
  48260. {
  48261. setSize (h, h);
  48262. }
  48263. else
  48264. {
  48265. Font f (h * 0.6f);
  48266. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48267. }
  48268. }
  48269. class KeyEntryWindow : public AlertWindow
  48270. {
  48271. public:
  48272. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48273. : AlertWindow (TRANS("New key-mapping"),
  48274. TRANS("Please press a key combination now..."),
  48275. AlertWindow::NoIcon),
  48276. owner (owner_)
  48277. {
  48278. addButton (TRANS("Ok"), 1);
  48279. addButton (TRANS("Cancel"), 0);
  48280. // (avoid return + escape keys getting processed by the buttons..)
  48281. for (int i = getNumChildComponents(); --i >= 0;)
  48282. getChildComponent (i)->setWantsKeyboardFocus (false);
  48283. setWantsKeyboardFocus (true);
  48284. grabKeyboardFocus();
  48285. }
  48286. bool keyPressed (const KeyPress& key)
  48287. {
  48288. lastPress = key;
  48289. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48290. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48291. if (previousCommand != 0)
  48292. message << "\n\n" << TRANS("(Currently assigned to \"")
  48293. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48294. setMessage (message);
  48295. return true;
  48296. }
  48297. bool keyStateChanged (bool)
  48298. {
  48299. return true;
  48300. }
  48301. KeyPress lastPress;
  48302. private:
  48303. KeyMappingEditorComponent& owner;
  48304. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48305. };
  48306. void assignNewKey()
  48307. {
  48308. KeyEntryWindow entryWindow (owner);
  48309. if (entryWindow.runModalLoop() != 0)
  48310. {
  48311. entryWindow.setVisible (false);
  48312. if (entryWindow.lastPress.isValid())
  48313. {
  48314. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48315. if (previousCommand == 0
  48316. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48317. TRANS("Change key-mapping"),
  48318. TRANS("This key is already assigned to the command \"")
  48319. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48320. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48321. TRANS("Re-assign"),
  48322. TRANS("Cancel")))
  48323. {
  48324. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48325. if (keyNum >= 0)
  48326. owner.getMappings().removeKeyPress (commandID, keyNum);
  48327. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48328. }
  48329. }
  48330. }
  48331. }
  48332. private:
  48333. KeyMappingEditorComponent& owner;
  48334. const CommandID commandID;
  48335. const int keyNum;
  48336. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48337. };
  48338. class KeyMappingEditorComponent::ItemComponent : public Component
  48339. {
  48340. public:
  48341. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48342. : owner (owner_), commandID (commandID_)
  48343. {
  48344. setInterceptsMouseClicks (false, true);
  48345. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48346. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48347. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48348. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48349. addKeyPressButton (String::empty, -1, isReadOnly);
  48350. }
  48351. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48352. {
  48353. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48354. keyChangeButtons.add (b);
  48355. b->setEnabled (! isReadOnly);
  48356. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48357. addChildComponent (b);
  48358. }
  48359. void paint (Graphics& g)
  48360. {
  48361. g.setFont (getHeight() * 0.7f);
  48362. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48363. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48364. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48365. Justification::centredLeft, true);
  48366. }
  48367. void resized()
  48368. {
  48369. int x = getWidth() - 4;
  48370. for (int i = keyChangeButtons.size(); --i >= 0;)
  48371. {
  48372. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48373. b->fitToContent (getHeight() - 2);
  48374. b->setTopRightPosition (x, 1);
  48375. x = b->getX() - 5;
  48376. }
  48377. }
  48378. private:
  48379. KeyMappingEditorComponent& owner;
  48380. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48381. const CommandID commandID;
  48382. enum { maxNumAssignments = 3 };
  48383. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48384. };
  48385. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48386. {
  48387. public:
  48388. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48389. : owner (owner_), commandID (commandID_)
  48390. {
  48391. }
  48392. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48393. bool mightContainSubItems() { return false; }
  48394. int getItemHeight() const { return 20; }
  48395. Component* createItemComponent()
  48396. {
  48397. return new ItemComponent (owner, commandID);
  48398. }
  48399. private:
  48400. KeyMappingEditorComponent& owner;
  48401. const CommandID commandID;
  48402. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48403. };
  48404. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48405. {
  48406. public:
  48407. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48408. : owner (owner_), categoryName (name)
  48409. {
  48410. }
  48411. const String getUniqueName() const { return categoryName + "_cat"; }
  48412. bool mightContainSubItems() { return true; }
  48413. int getItemHeight() const { return 28; }
  48414. void paintItem (Graphics& g, int width, int height)
  48415. {
  48416. g.setFont (height * 0.6f, Font::bold);
  48417. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48418. g.drawText (categoryName,
  48419. 2, 0, width - 2, height,
  48420. Justification::centredLeft, true);
  48421. }
  48422. void itemOpennessChanged (bool isNowOpen)
  48423. {
  48424. if (isNowOpen)
  48425. {
  48426. if (getNumSubItems() == 0)
  48427. {
  48428. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48429. for (int i = 0; i < commands.size(); ++i)
  48430. {
  48431. if (owner.shouldCommandBeIncluded (commands[i]))
  48432. addSubItem (new MappingItem (owner, commands[i]));
  48433. }
  48434. }
  48435. }
  48436. else
  48437. {
  48438. clearSubItems();
  48439. }
  48440. }
  48441. private:
  48442. KeyMappingEditorComponent& owner;
  48443. String categoryName;
  48444. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48445. };
  48446. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48447. public ChangeListener,
  48448. public ButtonListener
  48449. {
  48450. public:
  48451. TopLevelItem (KeyMappingEditorComponent& owner_)
  48452. : owner (owner_)
  48453. {
  48454. setLinesDrawnForSubItems (false);
  48455. owner.getMappings().addChangeListener (this);
  48456. }
  48457. ~TopLevelItem()
  48458. {
  48459. owner.getMappings().removeChangeListener (this);
  48460. }
  48461. bool mightContainSubItems() { return true; }
  48462. const String getUniqueName() const { return "keys"; }
  48463. void changeListenerCallback (ChangeBroadcaster*)
  48464. {
  48465. const ScopedPointer <XmlElement> oldOpenness (owner.tree.getOpennessState (true));
  48466. clearSubItems();
  48467. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48468. for (int i = 0; i < categories.size(); ++i)
  48469. {
  48470. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48471. int count = 0;
  48472. for (int j = 0; j < commands.size(); ++j)
  48473. if (owner.shouldCommandBeIncluded (commands[j]))
  48474. ++count;
  48475. if (count > 0)
  48476. addSubItem (new CategoryItem (owner, categories[i]));
  48477. }
  48478. if (oldOpenness != 0)
  48479. owner.tree.restoreOpennessState (*oldOpenness);
  48480. }
  48481. void buttonClicked (Button*)
  48482. {
  48483. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48484. TRANS("Reset to defaults"),
  48485. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48486. TRANS("Reset")))
  48487. {
  48488. owner.getMappings().resetToDefaultMappings();
  48489. }
  48490. }
  48491. private:
  48492. KeyMappingEditorComponent& owner;
  48493. };
  48494. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48495. const bool showResetToDefaultButton)
  48496. : mappings (mappingManager),
  48497. resetButton (TRANS ("reset to defaults"))
  48498. {
  48499. treeItem = new TopLevelItem (*this);
  48500. if (showResetToDefaultButton)
  48501. {
  48502. addAndMakeVisible (&resetButton);
  48503. resetButton.addListener (treeItem);
  48504. }
  48505. addAndMakeVisible (&tree);
  48506. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48507. tree.setRootItemVisible (false);
  48508. tree.setDefaultOpenness (true);
  48509. tree.setRootItem (treeItem);
  48510. }
  48511. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48512. {
  48513. tree.setRootItem (0);
  48514. }
  48515. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48516. const Colour& textColour)
  48517. {
  48518. setColour (backgroundColourId, mainBackground);
  48519. setColour (textColourId, textColour);
  48520. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48521. }
  48522. void KeyMappingEditorComponent::parentHierarchyChanged()
  48523. {
  48524. treeItem->changeListenerCallback (0);
  48525. }
  48526. void KeyMappingEditorComponent::resized()
  48527. {
  48528. int h = getHeight();
  48529. if (resetButton.isVisible())
  48530. {
  48531. const int buttonHeight = 20;
  48532. h -= buttonHeight + 8;
  48533. int x = getWidth() - 8;
  48534. resetButton.changeWidthToFitText (buttonHeight);
  48535. resetButton.setTopRightPosition (x, h + 6);
  48536. }
  48537. tree.setBounds (0, 0, getWidth(), h);
  48538. }
  48539. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48540. {
  48541. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48542. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48543. }
  48544. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48545. {
  48546. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48547. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48548. }
  48549. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48550. {
  48551. return key.getTextDescription();
  48552. }
  48553. END_JUCE_NAMESPACE
  48554. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48555. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48556. BEGIN_JUCE_NAMESPACE
  48557. KeyPress::KeyPress() throw()
  48558. : keyCode (0),
  48559. mods (0),
  48560. textCharacter (0)
  48561. {
  48562. }
  48563. KeyPress::KeyPress (const int keyCode_,
  48564. const ModifierKeys& mods_,
  48565. const juce_wchar textCharacter_) throw()
  48566. : keyCode (keyCode_),
  48567. mods (mods_),
  48568. textCharacter (textCharacter_)
  48569. {
  48570. }
  48571. KeyPress::KeyPress (const int keyCode_) throw()
  48572. : keyCode (keyCode_),
  48573. textCharacter (0)
  48574. {
  48575. }
  48576. KeyPress::KeyPress (const KeyPress& other) throw()
  48577. : keyCode (other.keyCode),
  48578. mods (other.mods),
  48579. textCharacter (other.textCharacter)
  48580. {
  48581. }
  48582. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48583. {
  48584. keyCode = other.keyCode;
  48585. mods = other.mods;
  48586. textCharacter = other.textCharacter;
  48587. return *this;
  48588. }
  48589. bool KeyPress::operator== (const KeyPress& other) const throw()
  48590. {
  48591. return mods.getRawFlags() == other.mods.getRawFlags()
  48592. && (textCharacter == other.textCharacter
  48593. || textCharacter == 0
  48594. || other.textCharacter == 0)
  48595. && (keyCode == other.keyCode
  48596. || (keyCode < 256
  48597. && other.keyCode < 256
  48598. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48599. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48600. }
  48601. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48602. {
  48603. return ! operator== (other);
  48604. }
  48605. bool KeyPress::isCurrentlyDown() const
  48606. {
  48607. return isKeyCurrentlyDown (keyCode)
  48608. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48609. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48610. }
  48611. namespace KeyPressHelpers
  48612. {
  48613. struct KeyNameAndCode
  48614. {
  48615. const char* name;
  48616. int code;
  48617. };
  48618. const KeyNameAndCode translations[] =
  48619. {
  48620. { "spacebar", KeyPress::spaceKey },
  48621. { "return", KeyPress::returnKey },
  48622. { "escape", KeyPress::escapeKey },
  48623. { "backspace", KeyPress::backspaceKey },
  48624. { "cursor left", KeyPress::leftKey },
  48625. { "cursor right", KeyPress::rightKey },
  48626. { "cursor up", KeyPress::upKey },
  48627. { "cursor down", KeyPress::downKey },
  48628. { "page up", KeyPress::pageUpKey },
  48629. { "page down", KeyPress::pageDownKey },
  48630. { "home", KeyPress::homeKey },
  48631. { "end", KeyPress::endKey },
  48632. { "delete", KeyPress::deleteKey },
  48633. { "insert", KeyPress::insertKey },
  48634. { "tab", KeyPress::tabKey },
  48635. { "play", KeyPress::playKey },
  48636. { "stop", KeyPress::stopKey },
  48637. { "fast forward", KeyPress::fastForwardKey },
  48638. { "rewind", KeyPress::rewindKey }
  48639. };
  48640. const String numberPadPrefix() { return "numpad "; }
  48641. }
  48642. const KeyPress KeyPress::createFromDescription (const String& desc)
  48643. {
  48644. int modifiers = 0;
  48645. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48646. || desc.containsWholeWordIgnoreCase ("control")
  48647. || desc.containsWholeWordIgnoreCase ("ctl"))
  48648. modifiers |= ModifierKeys::ctrlModifier;
  48649. if (desc.containsWholeWordIgnoreCase ("shift")
  48650. || desc.containsWholeWordIgnoreCase ("shft"))
  48651. modifiers |= ModifierKeys::shiftModifier;
  48652. if (desc.containsWholeWordIgnoreCase ("alt")
  48653. || desc.containsWholeWordIgnoreCase ("option"))
  48654. modifiers |= ModifierKeys::altModifier;
  48655. if (desc.containsWholeWordIgnoreCase ("command")
  48656. || desc.containsWholeWordIgnoreCase ("cmd"))
  48657. modifiers |= ModifierKeys::commandModifier;
  48658. int key = 0;
  48659. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48660. {
  48661. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48662. {
  48663. key = KeyPressHelpers::translations[i].code;
  48664. break;
  48665. }
  48666. }
  48667. if (key == 0)
  48668. {
  48669. // see if it's a numpad key..
  48670. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48671. {
  48672. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48673. if (lastChar >= '0' && lastChar <= '9')
  48674. key = numberPad0 + lastChar - '0';
  48675. else if (lastChar == '+')
  48676. key = numberPadAdd;
  48677. else if (lastChar == '-')
  48678. key = numberPadSubtract;
  48679. else if (lastChar == '*')
  48680. key = numberPadMultiply;
  48681. else if (lastChar == '/')
  48682. key = numberPadDivide;
  48683. else if (lastChar == '.')
  48684. key = numberPadDecimalPoint;
  48685. else if (lastChar == '=')
  48686. key = numberPadEquals;
  48687. else if (desc.endsWith ("separator"))
  48688. key = numberPadSeparator;
  48689. else if (desc.endsWith ("delete"))
  48690. key = numberPadDelete;
  48691. }
  48692. if (key == 0)
  48693. {
  48694. // see if it's a function key..
  48695. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48696. for (int i = 1; i <= 12; ++i)
  48697. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48698. key = F1Key + i - 1;
  48699. if (key == 0)
  48700. {
  48701. // give up and use the hex code..
  48702. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48703. .toLowerCase()
  48704. .retainCharacters ("0123456789abcdef")
  48705. .getHexValue32();
  48706. if (hexCode > 0)
  48707. key = hexCode;
  48708. else
  48709. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48710. }
  48711. }
  48712. }
  48713. return KeyPress (key, ModifierKeys (modifiers), 0);
  48714. }
  48715. const String KeyPress::getTextDescription() const
  48716. {
  48717. String desc;
  48718. if (keyCode > 0)
  48719. {
  48720. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48721. // want to store it as being a slash, not shift+whatever.
  48722. if (textCharacter == '/')
  48723. return "/";
  48724. if (mods.isCtrlDown())
  48725. desc << "ctrl + ";
  48726. if (mods.isShiftDown())
  48727. desc << "shift + ";
  48728. #if JUCE_MAC
  48729. // only do this on the mac, because on Windows ctrl and command are the same,
  48730. // and this would get confusing
  48731. if (mods.isCommandDown())
  48732. desc << "command + ";
  48733. if (mods.isAltDown())
  48734. desc << "option + ";
  48735. #else
  48736. if (mods.isAltDown())
  48737. desc << "alt + ";
  48738. #endif
  48739. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48740. if (keyCode == KeyPressHelpers::translations[i].code)
  48741. return desc + KeyPressHelpers::translations[i].name;
  48742. if (keyCode >= F1Key && keyCode <= F16Key)
  48743. desc << 'F' << (1 + keyCode - F1Key);
  48744. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48745. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48746. else if (keyCode >= 33 && keyCode < 176)
  48747. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48748. else if (keyCode == numberPadAdd)
  48749. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48750. else if (keyCode == numberPadSubtract)
  48751. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48752. else if (keyCode == numberPadMultiply)
  48753. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48754. else if (keyCode == numberPadDivide)
  48755. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48756. else if (keyCode == numberPadSeparator)
  48757. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48758. else if (keyCode == numberPadDecimalPoint)
  48759. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48760. else if (keyCode == numberPadDelete)
  48761. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48762. else
  48763. desc << '#' << String::toHexString (keyCode);
  48764. }
  48765. return desc;
  48766. }
  48767. END_JUCE_NAMESPACE
  48768. /*** End of inlined file: juce_KeyPress.cpp ***/
  48769. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48770. BEGIN_JUCE_NAMESPACE
  48771. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48772. : commandManager (commandManager_)
  48773. {
  48774. // A manager is needed to get the descriptions of commands, and will be called when
  48775. // a command is invoked. So you can't leave this null..
  48776. jassert (commandManager_ != 0);
  48777. Desktop::getInstance().addFocusChangeListener (this);
  48778. }
  48779. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48780. : commandManager (other.commandManager)
  48781. {
  48782. Desktop::getInstance().addFocusChangeListener (this);
  48783. }
  48784. KeyPressMappingSet::~KeyPressMappingSet()
  48785. {
  48786. Desktop::getInstance().removeFocusChangeListener (this);
  48787. }
  48788. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48789. {
  48790. for (int i = 0; i < mappings.size(); ++i)
  48791. if (mappings.getUnchecked(i)->commandID == commandID)
  48792. return mappings.getUnchecked (i)->keypresses;
  48793. return Array <KeyPress> ();
  48794. }
  48795. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48796. const KeyPress& newKeyPress,
  48797. int insertIndex)
  48798. {
  48799. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48800. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48801. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48802. && ! newKeyPress.getModifiers().isShiftDown()));
  48803. if (findCommandForKeyPress (newKeyPress) != commandID)
  48804. {
  48805. removeKeyPress (newKeyPress);
  48806. if (newKeyPress.isValid())
  48807. {
  48808. for (int i = mappings.size(); --i >= 0;)
  48809. {
  48810. if (mappings.getUnchecked(i)->commandID == commandID)
  48811. {
  48812. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48813. sendChangeMessage();
  48814. return;
  48815. }
  48816. }
  48817. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48818. if (ci != 0)
  48819. {
  48820. CommandMapping* const cm = new CommandMapping();
  48821. cm->commandID = commandID;
  48822. cm->keypresses.add (newKeyPress);
  48823. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48824. mappings.add (cm);
  48825. sendChangeMessage();
  48826. }
  48827. }
  48828. }
  48829. }
  48830. void KeyPressMappingSet::resetToDefaultMappings()
  48831. {
  48832. mappings.clear();
  48833. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48834. {
  48835. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48836. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48837. {
  48838. addKeyPress (ci->commandID,
  48839. ci->defaultKeypresses.getReference (j));
  48840. }
  48841. }
  48842. sendChangeMessage();
  48843. }
  48844. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48845. {
  48846. clearAllKeyPresses (commandID);
  48847. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48848. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48849. {
  48850. addKeyPress (ci->commandID,
  48851. ci->defaultKeypresses.getReference (j));
  48852. }
  48853. }
  48854. void KeyPressMappingSet::clearAllKeyPresses()
  48855. {
  48856. if (mappings.size() > 0)
  48857. {
  48858. sendChangeMessage();
  48859. mappings.clear();
  48860. }
  48861. }
  48862. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48863. {
  48864. for (int i = mappings.size(); --i >= 0;)
  48865. {
  48866. if (mappings.getUnchecked(i)->commandID == commandID)
  48867. {
  48868. mappings.remove (i);
  48869. sendChangeMessage();
  48870. }
  48871. }
  48872. }
  48873. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48874. {
  48875. if (keypress.isValid())
  48876. {
  48877. for (int i = mappings.size(); --i >= 0;)
  48878. {
  48879. CommandMapping* const cm = mappings.getUnchecked(i);
  48880. for (int j = cm->keypresses.size(); --j >= 0;)
  48881. {
  48882. if (keypress == cm->keypresses [j])
  48883. {
  48884. cm->keypresses.remove (j);
  48885. sendChangeMessage();
  48886. }
  48887. }
  48888. }
  48889. }
  48890. }
  48891. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48892. {
  48893. for (int i = mappings.size(); --i >= 0;)
  48894. {
  48895. if (mappings.getUnchecked(i)->commandID == commandID)
  48896. {
  48897. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48898. sendChangeMessage();
  48899. break;
  48900. }
  48901. }
  48902. }
  48903. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48904. {
  48905. for (int i = 0; i < mappings.size(); ++i)
  48906. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48907. return mappings.getUnchecked(i)->commandID;
  48908. return 0;
  48909. }
  48910. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48911. {
  48912. for (int i = mappings.size(); --i >= 0;)
  48913. if (mappings.getUnchecked(i)->commandID == commandID)
  48914. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48915. return false;
  48916. }
  48917. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48918. const KeyPress& key,
  48919. const bool isKeyDown,
  48920. const int millisecsSinceKeyPressed,
  48921. Component* const originatingComponent) const
  48922. {
  48923. ApplicationCommandTarget::InvocationInfo info (commandID);
  48924. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48925. info.isKeyDown = isKeyDown;
  48926. info.keyPress = key;
  48927. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48928. info.originatingComponent = originatingComponent;
  48929. commandManager->invoke (info, false);
  48930. }
  48931. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48932. {
  48933. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48934. {
  48935. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48936. {
  48937. // if the XML was created as a set of differences from the default mappings,
  48938. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48939. resetToDefaultMappings();
  48940. }
  48941. else
  48942. {
  48943. // if the XML was created calling createXml (false), then we need to clear all
  48944. // the keys and treat the xml as describing the entire set of mappings.
  48945. clearAllKeyPresses();
  48946. }
  48947. forEachXmlChildElement (xmlVersion, map)
  48948. {
  48949. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48950. if (commandId != 0)
  48951. {
  48952. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48953. if (map->hasTagName ("MAPPING"))
  48954. {
  48955. addKeyPress (commandId, key);
  48956. }
  48957. else if (map->hasTagName ("UNMAPPING"))
  48958. {
  48959. if (containsMapping (commandId, key))
  48960. removeKeyPress (key);
  48961. }
  48962. }
  48963. }
  48964. return true;
  48965. }
  48966. return false;
  48967. }
  48968. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48969. {
  48970. ScopedPointer <KeyPressMappingSet> defaultSet;
  48971. if (saveDifferencesFromDefaultSet)
  48972. {
  48973. defaultSet = new KeyPressMappingSet (commandManager);
  48974. defaultSet->resetToDefaultMappings();
  48975. }
  48976. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48977. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48978. int i;
  48979. for (i = 0; i < mappings.size(); ++i)
  48980. {
  48981. const CommandMapping* const cm = mappings.getUnchecked(i);
  48982. for (int j = 0; j < cm->keypresses.size(); ++j)
  48983. {
  48984. if (defaultSet == 0
  48985. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48986. {
  48987. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48988. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48989. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48990. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48991. }
  48992. }
  48993. }
  48994. if (defaultSet != 0)
  48995. {
  48996. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48997. {
  48998. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48999. for (int j = 0; j < cm->keypresses.size(); ++j)
  49000. {
  49001. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49002. {
  49003. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49004. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49005. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49006. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49007. }
  49008. }
  49009. }
  49010. }
  49011. return doc;
  49012. }
  49013. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49014. Component* originatingComponent)
  49015. {
  49016. bool used = false;
  49017. const CommandID commandID = findCommandForKeyPress (key);
  49018. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49019. if (ci != 0
  49020. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49021. {
  49022. ApplicationCommandInfo info (0);
  49023. if (commandManager->getTargetForCommand (commandID, info) != 0
  49024. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49025. {
  49026. invokeCommand (commandID, key, true, 0, originatingComponent);
  49027. used = true;
  49028. }
  49029. else
  49030. {
  49031. if (originatingComponent != 0)
  49032. originatingComponent->getLookAndFeel().playAlertSound();
  49033. }
  49034. }
  49035. return used;
  49036. }
  49037. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49038. {
  49039. bool used = false;
  49040. const uint32 now = Time::getMillisecondCounter();
  49041. for (int i = mappings.size(); --i >= 0;)
  49042. {
  49043. CommandMapping* const cm = mappings.getUnchecked(i);
  49044. if (cm->wantsKeyUpDownCallbacks)
  49045. {
  49046. for (int j = cm->keypresses.size(); --j >= 0;)
  49047. {
  49048. const KeyPress key (cm->keypresses.getReference (j));
  49049. const bool isDown = key.isCurrentlyDown();
  49050. int keyPressEntryIndex = 0;
  49051. bool wasDown = false;
  49052. for (int k = keysDown.size(); --k >= 0;)
  49053. {
  49054. if (key == keysDown.getUnchecked(k)->key)
  49055. {
  49056. keyPressEntryIndex = k;
  49057. wasDown = true;
  49058. used = true;
  49059. break;
  49060. }
  49061. }
  49062. if (isDown != wasDown)
  49063. {
  49064. int millisecs = 0;
  49065. if (isDown)
  49066. {
  49067. KeyPressTime* const k = new KeyPressTime();
  49068. k->key = key;
  49069. k->timeWhenPressed = now;
  49070. keysDown.add (k);
  49071. }
  49072. else
  49073. {
  49074. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49075. if (now > pressTime)
  49076. millisecs = now - pressTime;
  49077. keysDown.remove (keyPressEntryIndex);
  49078. }
  49079. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49080. used = true;
  49081. }
  49082. }
  49083. }
  49084. }
  49085. return used;
  49086. }
  49087. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49088. {
  49089. if (focusedComponent != 0)
  49090. focusedComponent->keyStateChanged (false);
  49091. }
  49092. END_JUCE_NAMESPACE
  49093. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49094. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49095. BEGIN_JUCE_NAMESPACE
  49096. ModifierKeys::ModifierKeys (const int flags_) throw()
  49097. : flags (flags_)
  49098. {
  49099. }
  49100. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49101. : flags (other.flags)
  49102. {
  49103. }
  49104. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49105. {
  49106. flags = other.flags;
  49107. return *this;
  49108. }
  49109. ModifierKeys ModifierKeys::currentModifiers;
  49110. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49111. {
  49112. return currentModifiers;
  49113. }
  49114. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49115. {
  49116. int num = 0;
  49117. if (isLeftButtonDown()) ++num;
  49118. if (isRightButtonDown()) ++num;
  49119. if (isMiddleButtonDown()) ++num;
  49120. return num;
  49121. }
  49122. END_JUCE_NAMESPACE
  49123. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49124. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49125. BEGIN_JUCE_NAMESPACE
  49126. class ComponentAnimator::AnimationTask
  49127. {
  49128. public:
  49129. AnimationTask (Component* const comp)
  49130. : component (comp)
  49131. {
  49132. }
  49133. void reset (const Rectangle<int>& finalBounds,
  49134. float finalAlpha,
  49135. int millisecondsToSpendMoving,
  49136. bool useProxyComponent,
  49137. double startSpeed_, double endSpeed_)
  49138. {
  49139. msElapsed = 0;
  49140. msTotal = jmax (1, millisecondsToSpendMoving);
  49141. lastProgress = 0;
  49142. destination = finalBounds;
  49143. destAlpha = finalAlpha;
  49144. isMoving = (finalBounds != component->getBounds());
  49145. isChangingAlpha = (finalAlpha != component->getAlpha());
  49146. left = component->getX();
  49147. top = component->getY();
  49148. right = component->getRight();
  49149. bottom = component->getBottom();
  49150. alpha = component->getAlpha();
  49151. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49152. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49153. midSpeed = invTotalDistance;
  49154. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49155. if (useProxyComponent)
  49156. proxy = new ProxyComponent (*component);
  49157. else
  49158. proxy = 0;
  49159. component->setVisible (! useProxyComponent);
  49160. }
  49161. bool useTimeslice (const int elapsed)
  49162. {
  49163. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49164. : static_cast <Component*> (component);
  49165. if (c != 0)
  49166. {
  49167. msElapsed += elapsed;
  49168. double newProgress = msElapsed / (double) msTotal;
  49169. if (newProgress >= 0 && newProgress < 1.0)
  49170. {
  49171. newProgress = timeToDistance (newProgress);
  49172. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49173. jassert (newProgress >= lastProgress);
  49174. lastProgress = newProgress;
  49175. if (delta < 1.0)
  49176. {
  49177. bool stillBusy = false;
  49178. if (isMoving)
  49179. {
  49180. left += (destination.getX() - left) * delta;
  49181. top += (destination.getY() - top) * delta;
  49182. right += (destination.getRight() - right) * delta;
  49183. bottom += (destination.getBottom() - bottom) * delta;
  49184. const Rectangle<int> newBounds (roundToInt (left),
  49185. roundToInt (top),
  49186. roundToInt (right - left),
  49187. roundToInt (bottom - top));
  49188. if (newBounds != destination)
  49189. {
  49190. c->setBounds (newBounds);
  49191. stillBusy = true;
  49192. }
  49193. }
  49194. if (isChangingAlpha)
  49195. {
  49196. alpha += (destAlpha - alpha) * delta;
  49197. c->setAlpha ((float) alpha);
  49198. stillBusy = true;
  49199. }
  49200. if (stillBusy)
  49201. return true;
  49202. }
  49203. }
  49204. }
  49205. moveToFinalDestination();
  49206. return false;
  49207. }
  49208. void moveToFinalDestination()
  49209. {
  49210. if (component != 0)
  49211. {
  49212. component->setAlpha ((float) destAlpha);
  49213. component->setBounds (destination);
  49214. }
  49215. }
  49216. class ProxyComponent : public Component
  49217. {
  49218. public:
  49219. ProxyComponent (Component& component)
  49220. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49221. {
  49222. setBounds (component.getBounds());
  49223. setAlpha (component.getAlpha());
  49224. setInterceptsMouseClicks (false, false);
  49225. Component* const parent = component.getParentComponent();
  49226. if (parent != 0)
  49227. parent->addAndMakeVisible (this);
  49228. else if (component.isOnDesktop() && component.getPeer() != 0)
  49229. addToDesktop (component.getPeer()->getStyleFlags());
  49230. else
  49231. jassertfalse; // seem to be trying to animate a component that's not visible..
  49232. setVisible (true);
  49233. toBehind (&component);
  49234. }
  49235. void paint (Graphics& g)
  49236. {
  49237. g.setOpacity (1.0f);
  49238. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49239. 0, 0, image.getWidth(), image.getHeight());
  49240. }
  49241. private:
  49242. Image image;
  49243. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49244. };
  49245. WeakReference<Component> component;
  49246. ScopedPointer<Component> proxy;
  49247. Rectangle<int> destination;
  49248. double destAlpha;
  49249. int msElapsed, msTotal;
  49250. double startSpeed, midSpeed, endSpeed, lastProgress;
  49251. double left, top, right, bottom, alpha;
  49252. bool isMoving, isChangingAlpha;
  49253. private:
  49254. double timeToDistance (const double time) const throw()
  49255. {
  49256. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49257. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49258. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49259. }
  49260. };
  49261. ComponentAnimator::ComponentAnimator()
  49262. : lastTime (0)
  49263. {
  49264. }
  49265. ComponentAnimator::~ComponentAnimator()
  49266. {
  49267. }
  49268. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49269. {
  49270. for (int i = tasks.size(); --i >= 0;)
  49271. if (component == tasks.getUnchecked(i)->component.get())
  49272. return tasks.getUnchecked(i);
  49273. return 0;
  49274. }
  49275. void ComponentAnimator::animateComponent (Component* const component,
  49276. const Rectangle<int>& finalBounds,
  49277. const float finalAlpha,
  49278. const int millisecondsToSpendMoving,
  49279. const bool useProxyComponent,
  49280. const double startSpeed,
  49281. const double endSpeed)
  49282. {
  49283. // the speeds must be 0 or greater!
  49284. jassert (startSpeed >= 0 && endSpeed >= 0)
  49285. if (component != 0)
  49286. {
  49287. AnimationTask* at = findTaskFor (component);
  49288. if (at == 0)
  49289. {
  49290. at = new AnimationTask (component);
  49291. tasks.add (at);
  49292. sendChangeMessage();
  49293. }
  49294. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49295. useProxyComponent, startSpeed, endSpeed);
  49296. if (! isTimerRunning())
  49297. {
  49298. lastTime = Time::getMillisecondCounter();
  49299. startTimer (1000 / 50);
  49300. }
  49301. }
  49302. }
  49303. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49304. {
  49305. if (component != 0)
  49306. {
  49307. if (component->isShowing() && millisecondsToTake > 0)
  49308. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49309. component->setVisible (false);
  49310. }
  49311. }
  49312. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49313. {
  49314. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49315. {
  49316. component->setAlpha (0.0f);
  49317. component->setVisible (true);
  49318. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49319. }
  49320. }
  49321. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49322. {
  49323. if (tasks.size() > 0)
  49324. {
  49325. if (moveComponentsToTheirFinalPositions)
  49326. for (int i = tasks.size(); --i >= 0;)
  49327. tasks.getUnchecked(i)->moveToFinalDestination();
  49328. tasks.clear();
  49329. sendChangeMessage();
  49330. }
  49331. }
  49332. void ComponentAnimator::cancelAnimation (Component* const component,
  49333. const bool moveComponentToItsFinalPosition)
  49334. {
  49335. AnimationTask* const at = findTaskFor (component);
  49336. if (at != 0)
  49337. {
  49338. if (moveComponentToItsFinalPosition)
  49339. at->moveToFinalDestination();
  49340. tasks.removeObject (at);
  49341. sendChangeMessage();
  49342. }
  49343. }
  49344. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49345. {
  49346. jassert (component != 0);
  49347. AnimationTask* const at = findTaskFor (component);
  49348. if (at != 0)
  49349. return at->destination;
  49350. return component->getBounds();
  49351. }
  49352. bool ComponentAnimator::isAnimating (Component* component) const
  49353. {
  49354. return findTaskFor (component) != 0;
  49355. }
  49356. void ComponentAnimator::timerCallback()
  49357. {
  49358. const uint32 timeNow = Time::getMillisecondCounter();
  49359. if (lastTime == 0 || lastTime == timeNow)
  49360. lastTime = timeNow;
  49361. const int elapsed = timeNow - lastTime;
  49362. for (int i = tasks.size(); --i >= 0;)
  49363. {
  49364. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49365. {
  49366. tasks.remove (i);
  49367. sendChangeMessage();
  49368. }
  49369. }
  49370. lastTime = timeNow;
  49371. if (tasks.size() == 0)
  49372. stopTimer();
  49373. }
  49374. END_JUCE_NAMESPACE
  49375. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49376. /*** Start of inlined file: juce_ComponentBuilder.cpp ***/
  49377. BEGIN_JUCE_NAMESPACE
  49378. namespace ComponentBuilderHelpers
  49379. {
  49380. const String getStateId (const ValueTree& state)
  49381. {
  49382. return state [ComponentBuilder::idProperty].toString();
  49383. }
  49384. Component* findComponentWithID (OwnedArray<Component>& components, const String& compId)
  49385. {
  49386. jassert (compId.isNotEmpty());
  49387. for (int i = components.size(); --i >= 0;)
  49388. {
  49389. Component* const c = components.getUnchecked (i);
  49390. if (c->getComponentID() == compId)
  49391. return components.removeAndReturn (i);
  49392. }
  49393. return 0;
  49394. }
  49395. Component* findComponentWithID (Component* const c, const String& compId)
  49396. {
  49397. jassert (compId.isNotEmpty());
  49398. if (c->getComponentID() == compId)
  49399. return c;
  49400. for (int i = c->getNumChildComponents(); --i >= 0;)
  49401. {
  49402. Component* const child = findComponentWithID (c->getChildComponent (i), compId);
  49403. if (child != 0)
  49404. return child;
  49405. }
  49406. return 0;
  49407. }
  49408. Component* createNewComponent (ComponentBuilder::TypeHandler& type,
  49409. const ValueTree& state, Component* parent)
  49410. {
  49411. Component* const c = type.addNewComponentFromState (state, parent);
  49412. jassert (c != 0);
  49413. c->setComponentID (getStateId (state));
  49414. return c;
  49415. }
  49416. void updateComponent (ComponentBuilder& builder, const ValueTree& state)
  49417. {
  49418. Component* topLevelComp = builder.getManagedComponent();
  49419. if (topLevelComp != 0)
  49420. {
  49421. ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state);
  49422. const String uid (getStateId (state));
  49423. if (type == 0 || uid.isEmpty())
  49424. {
  49425. // ..handle the case where a child of the actual state node has changed.
  49426. if (state.getParent().isValid())
  49427. updateComponent (builder, state.getParent());
  49428. }
  49429. else
  49430. {
  49431. Component* const changedComp = findComponentWithID (topLevelComp, uid);
  49432. if (changedComp != 0)
  49433. type->updateComponentFromState (changedComp, state);
  49434. }
  49435. }
  49436. }
  49437. }
  49438. const Identifier ComponentBuilder::idProperty ("id");
  49439. ComponentBuilder::ComponentBuilder (const ValueTree& state_)
  49440. : state (state_), imageProvider (0)
  49441. {
  49442. state.addListener (this);
  49443. }
  49444. ComponentBuilder::~ComponentBuilder()
  49445. {
  49446. state.removeListener (this);
  49447. #if JUCE_DEBUG
  49448. // Don't delete the managed component!! The builder owns that component, and will delete
  49449. // it automatically when it gets deleted.
  49450. jassert (componentRef.get() == static_cast <Component*> (component));
  49451. #endif
  49452. }
  49453. Component* ComponentBuilder::getManagedComponent()
  49454. {
  49455. if (component == 0)
  49456. {
  49457. component = createComponent();
  49458. #if JUCE_DEBUG
  49459. componentRef = component;
  49460. #endif
  49461. }
  49462. return component;
  49463. }
  49464. Component* ComponentBuilder::createComponent()
  49465. {
  49466. jassert (types.size() > 0); // You need to register all the necessary types before you can load a component!
  49467. TypeHandler* const type = getHandlerForState (state);
  49468. jassert (type != 0); // trying to create a component from an unknown type of ValueTree
  49469. return type != 0 ? ComponentBuilderHelpers::createNewComponent (*type, state, 0) : 0;
  49470. }
  49471. void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type)
  49472. {
  49473. jassert (type != 0);
  49474. // Don't try to move your types around! Once a type has been added to a builder, the
  49475. // builder owns it, and you should leave it alone!
  49476. jassert (type->builder == 0);
  49477. types.add (type);
  49478. type->builder = this;
  49479. }
  49480. ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const
  49481. {
  49482. const Identifier targetType (s.getType());
  49483. for (int i = 0; i < types.size(); ++i)
  49484. {
  49485. TypeHandler* const t = types.getUnchecked(i);
  49486. if (t->getType() == targetType)
  49487. return t;
  49488. }
  49489. return 0;
  49490. }
  49491. int ComponentBuilder::getNumHandlers() const throw()
  49492. {
  49493. return types.size();
  49494. }
  49495. ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const throw()
  49496. {
  49497. return types [index];
  49498. }
  49499. void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) throw()
  49500. {
  49501. imageProvider = newImageProvider;
  49502. }
  49503. ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const throw()
  49504. {
  49505. return imageProvider;
  49506. }
  49507. void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  49508. {
  49509. ComponentBuilderHelpers::updateComponent (*this, tree);
  49510. }
  49511. void ComponentBuilder::valueTreeChildrenChanged (ValueTree& tree)
  49512. {
  49513. ComponentBuilderHelpers::updateComponent (*this, tree);
  49514. }
  49515. void ComponentBuilder::valueTreeParentChanged (ValueTree& tree)
  49516. {
  49517. ComponentBuilderHelpers::updateComponent (*this, tree);
  49518. }
  49519. ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType_)
  49520. : builder (0), valueTreeType (valueTreeType_)
  49521. {
  49522. }
  49523. ComponentBuilder::TypeHandler::~TypeHandler()
  49524. {
  49525. }
  49526. ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const throw()
  49527. {
  49528. // A type handler needs to be registered with a ComponentBuilder before using it!
  49529. jassert (builder != 0);
  49530. return builder;
  49531. }
  49532. void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
  49533. {
  49534. using namespace ComponentBuilderHelpers;
  49535. const int numExistingChildComps = parent.getNumChildComponents();
  49536. Array <Component*> componentsInOrder;
  49537. componentsInOrder.ensureStorageAllocated (numExistingChildComps);
  49538. {
  49539. OwnedArray<Component> existingComponents;
  49540. existingComponents.ensureStorageAllocated (numExistingChildComps);
  49541. int i;
  49542. for (i = 0; i < numExistingChildComps; ++i)
  49543. existingComponents.add (parent.getChildComponent (i));
  49544. const int newNumChildren = children.getNumChildren();
  49545. for (i = 0; i < newNumChildren; ++i)
  49546. {
  49547. const ValueTree childState (children.getChild (i));
  49548. ComponentBuilder::TypeHandler* const type = getHandlerForState (childState);
  49549. jassert (type != 0);
  49550. if (type != 0)
  49551. {
  49552. Component* c = findComponentWithID (existingComponents, getStateId (childState));
  49553. if (c == 0)
  49554. c = createNewComponent (*type, childState, &parent);
  49555. componentsInOrder.add (c);
  49556. }
  49557. }
  49558. // (remaining unused items in existingComponents get deleted here as it goes out of scope)
  49559. }
  49560. // Make sure the z-order is correct..
  49561. if (componentsInOrder.size() > 0)
  49562. {
  49563. componentsInOrder.getLast()->toFront (false);
  49564. for (int i = componentsInOrder.size() - 1; --i >= 0;)
  49565. componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
  49566. }
  49567. }
  49568. END_JUCE_NAMESPACE
  49569. /*** End of inlined file: juce_ComponentBuilder.cpp ***/
  49570. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49571. BEGIN_JUCE_NAMESPACE
  49572. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49573. : minW (0),
  49574. maxW (0x3fffffff),
  49575. minH (0),
  49576. maxH (0x3fffffff),
  49577. minOffTop (0),
  49578. minOffLeft (0),
  49579. minOffBottom (0),
  49580. minOffRight (0),
  49581. aspectRatio (0.0)
  49582. {
  49583. }
  49584. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49585. {
  49586. }
  49587. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49588. {
  49589. minW = minimumWidth;
  49590. }
  49591. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49592. {
  49593. maxW = maximumWidth;
  49594. }
  49595. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49596. {
  49597. minH = minimumHeight;
  49598. }
  49599. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49600. {
  49601. maxH = maximumHeight;
  49602. }
  49603. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49604. {
  49605. jassert (maxW >= minimumWidth);
  49606. jassert (maxH >= minimumHeight);
  49607. jassert (minimumWidth > 0 && minimumHeight > 0);
  49608. minW = minimumWidth;
  49609. minH = minimumHeight;
  49610. if (minW > maxW)
  49611. maxW = minW;
  49612. if (minH > maxH)
  49613. maxH = minH;
  49614. }
  49615. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49616. {
  49617. jassert (maximumWidth >= minW);
  49618. jassert (maximumHeight >= minH);
  49619. jassert (maximumWidth > 0 && maximumHeight > 0);
  49620. maxW = jmax (minW, maximumWidth);
  49621. maxH = jmax (minH, maximumHeight);
  49622. }
  49623. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49624. const int minimumHeight,
  49625. const int maximumWidth,
  49626. const int maximumHeight) throw()
  49627. {
  49628. jassert (maximumWidth >= minimumWidth);
  49629. jassert (maximumHeight >= minimumHeight);
  49630. jassert (maximumWidth > 0 && maximumHeight > 0);
  49631. jassert (minimumWidth > 0 && minimumHeight > 0);
  49632. minW = jmax (0, minimumWidth);
  49633. minH = jmax (0, minimumHeight);
  49634. maxW = jmax (minW, maximumWidth);
  49635. maxH = jmax (minH, maximumHeight);
  49636. }
  49637. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49638. const int minimumWhenOffTheLeft,
  49639. const int minimumWhenOffTheBottom,
  49640. const int minimumWhenOffTheRight) throw()
  49641. {
  49642. minOffTop = minimumWhenOffTheTop;
  49643. minOffLeft = minimumWhenOffTheLeft;
  49644. minOffBottom = minimumWhenOffTheBottom;
  49645. minOffRight = minimumWhenOffTheRight;
  49646. }
  49647. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49648. {
  49649. aspectRatio = jmax (0.0, widthOverHeight);
  49650. }
  49651. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49652. {
  49653. return aspectRatio;
  49654. }
  49655. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49656. const Rectangle<int>& targetBounds,
  49657. const bool isStretchingTop,
  49658. const bool isStretchingLeft,
  49659. const bool isStretchingBottom,
  49660. const bool isStretchingRight)
  49661. {
  49662. jassert (component != 0);
  49663. Rectangle<int> limits, bounds (targetBounds);
  49664. BorderSize<int> border;
  49665. Component* const parent = component->getParentComponent();
  49666. if (parent == 0)
  49667. {
  49668. ComponentPeer* peer = component->getPeer();
  49669. if (peer != 0)
  49670. border = peer->getFrameSize();
  49671. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49672. }
  49673. else
  49674. {
  49675. limits.setSize (parent->getWidth(), parent->getHeight());
  49676. }
  49677. border.addTo (bounds);
  49678. checkBounds (bounds,
  49679. border.addedTo (component->getBounds()), limits,
  49680. isStretchingTop, isStretchingLeft,
  49681. isStretchingBottom, isStretchingRight);
  49682. border.subtractFrom (bounds);
  49683. applyBoundsToComponent (component, bounds);
  49684. }
  49685. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49686. {
  49687. setBoundsForComponent (component, component->getBounds(),
  49688. false, false, false, false);
  49689. }
  49690. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49691. const Rectangle<int>& bounds)
  49692. {
  49693. component->setBounds (bounds);
  49694. }
  49695. void ComponentBoundsConstrainer::resizeStart()
  49696. {
  49697. }
  49698. void ComponentBoundsConstrainer::resizeEnd()
  49699. {
  49700. }
  49701. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49702. const Rectangle<int>& old,
  49703. const Rectangle<int>& limits,
  49704. const bool isStretchingTop,
  49705. const bool isStretchingLeft,
  49706. const bool isStretchingBottom,
  49707. const bool isStretchingRight)
  49708. {
  49709. // constrain the size if it's being stretched..
  49710. if (isStretchingLeft)
  49711. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49712. if (isStretchingRight)
  49713. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49714. if (isStretchingTop)
  49715. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49716. if (isStretchingBottom)
  49717. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49718. if (bounds.isEmpty())
  49719. return;
  49720. if (minOffTop > 0)
  49721. {
  49722. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49723. if (bounds.getY() < limit)
  49724. {
  49725. if (isStretchingTop)
  49726. bounds.setTop (limits.getY());
  49727. else
  49728. bounds.setY (limit);
  49729. }
  49730. }
  49731. if (minOffLeft > 0)
  49732. {
  49733. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49734. if (bounds.getX() < limit)
  49735. {
  49736. if (isStretchingLeft)
  49737. bounds.setLeft (limits.getX());
  49738. else
  49739. bounds.setX (limit);
  49740. }
  49741. }
  49742. if (minOffBottom > 0)
  49743. {
  49744. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49745. if (bounds.getY() > limit)
  49746. {
  49747. if (isStretchingBottom)
  49748. bounds.setBottom (limits.getBottom());
  49749. else
  49750. bounds.setY (limit);
  49751. }
  49752. }
  49753. if (minOffRight > 0)
  49754. {
  49755. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49756. if (bounds.getX() > limit)
  49757. {
  49758. if (isStretchingRight)
  49759. bounds.setRight (limits.getRight());
  49760. else
  49761. bounds.setX (limit);
  49762. }
  49763. }
  49764. // constrain the aspect ratio if one has been specified..
  49765. if (aspectRatio > 0.0)
  49766. {
  49767. bool adjustWidth;
  49768. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49769. {
  49770. adjustWidth = true;
  49771. }
  49772. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49773. {
  49774. adjustWidth = false;
  49775. }
  49776. else
  49777. {
  49778. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49779. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49780. adjustWidth = (oldRatio > newRatio);
  49781. }
  49782. if (adjustWidth)
  49783. {
  49784. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49785. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49786. {
  49787. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49788. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49789. }
  49790. }
  49791. else
  49792. {
  49793. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49794. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49795. {
  49796. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49797. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49798. }
  49799. }
  49800. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49801. {
  49802. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49803. }
  49804. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49805. {
  49806. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49807. }
  49808. else
  49809. {
  49810. if (isStretchingLeft)
  49811. bounds.setX (old.getRight() - bounds.getWidth());
  49812. if (isStretchingTop)
  49813. bounds.setY (old.getBottom() - bounds.getHeight());
  49814. }
  49815. }
  49816. jassert (! bounds.isEmpty());
  49817. }
  49818. END_JUCE_NAMESPACE
  49819. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49820. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49821. BEGIN_JUCE_NAMESPACE
  49822. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49823. : component (component_),
  49824. lastPeer (0),
  49825. reentrant (false),
  49826. wasShowing (component_->isShowing())
  49827. {
  49828. jassert (component != 0); // can't use this with a null pointer..
  49829. component->addComponentListener (this);
  49830. registerWithParentComps();
  49831. }
  49832. ComponentMovementWatcher::~ComponentMovementWatcher()
  49833. {
  49834. if (component != 0)
  49835. component->removeComponentListener (this);
  49836. unregister();
  49837. }
  49838. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49839. {
  49840. if (component != 0 && ! reentrant)
  49841. {
  49842. const ScopedValueSetter<bool> setter (reentrant, true);
  49843. ComponentPeer* const peer = component->getPeer();
  49844. if (peer != lastPeer)
  49845. {
  49846. componentPeerChanged();
  49847. if (component == 0)
  49848. return;
  49849. lastPeer = peer;
  49850. }
  49851. unregister();
  49852. registerWithParentComps();
  49853. componentMovedOrResized (*component, true, true);
  49854. if (component != 0)
  49855. componentVisibilityChanged (*component);
  49856. }
  49857. }
  49858. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49859. {
  49860. if (component != 0)
  49861. {
  49862. if (wasMoved)
  49863. {
  49864. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49865. wasMoved = lastBounds.getPosition() != pos;
  49866. lastBounds.setPosition (pos);
  49867. }
  49868. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49869. lastBounds.setSize (component->getWidth(), component->getHeight());
  49870. if (wasMoved || wasResized)
  49871. componentMovedOrResized (wasMoved, wasResized);
  49872. }
  49873. }
  49874. void ComponentMovementWatcher::componentBeingDeleted (Component& comp)
  49875. {
  49876. registeredParentComps.removeValue (&comp);
  49877. if (component == &comp)
  49878. unregister();
  49879. }
  49880. void ComponentMovementWatcher::componentVisibilityChanged (Component&)
  49881. {
  49882. if (component != 0)
  49883. {
  49884. const bool isShowingNow = component->isShowing();
  49885. if (wasShowing != isShowingNow)
  49886. {
  49887. wasShowing = isShowingNow;
  49888. componentVisibilityChanged();
  49889. }
  49890. }
  49891. }
  49892. void ComponentMovementWatcher::registerWithParentComps()
  49893. {
  49894. Component* p = component->getParentComponent();
  49895. while (p != 0)
  49896. {
  49897. p->addComponentListener (this);
  49898. registeredParentComps.add (p);
  49899. p = p->getParentComponent();
  49900. }
  49901. }
  49902. void ComponentMovementWatcher::unregister()
  49903. {
  49904. for (int i = registeredParentComps.size(); --i >= 0;)
  49905. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49906. registeredParentComps.clear();
  49907. }
  49908. END_JUCE_NAMESPACE
  49909. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49910. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49911. BEGIN_JUCE_NAMESPACE
  49912. GroupComponent::GroupComponent (const String& componentName,
  49913. const String& labelText)
  49914. : Component (componentName),
  49915. text (labelText),
  49916. justification (Justification::left)
  49917. {
  49918. setInterceptsMouseClicks (false, true);
  49919. }
  49920. GroupComponent::~GroupComponent()
  49921. {
  49922. }
  49923. void GroupComponent::setText (const String& newText)
  49924. {
  49925. if (text != newText)
  49926. {
  49927. text = newText;
  49928. repaint();
  49929. }
  49930. }
  49931. const String GroupComponent::getText() const
  49932. {
  49933. return text;
  49934. }
  49935. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49936. {
  49937. if (justification != newJustification)
  49938. {
  49939. justification = newJustification;
  49940. repaint();
  49941. }
  49942. }
  49943. void GroupComponent::paint (Graphics& g)
  49944. {
  49945. getLookAndFeel()
  49946. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49947. text, justification,
  49948. *this);
  49949. }
  49950. void GroupComponent::enablementChanged()
  49951. {
  49952. repaint();
  49953. }
  49954. void GroupComponent::colourChanged()
  49955. {
  49956. repaint();
  49957. }
  49958. END_JUCE_NAMESPACE
  49959. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49960. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49961. BEGIN_JUCE_NAMESPACE
  49962. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49963. : DocumentWindow (String::empty, backgroundColour,
  49964. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49965. {
  49966. }
  49967. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49968. {
  49969. }
  49970. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49971. {
  49972. MultiDocumentPanel* const owner = getOwner();
  49973. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49974. if (owner != 0)
  49975. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49976. }
  49977. void MultiDocumentPanelWindow::closeButtonPressed()
  49978. {
  49979. MultiDocumentPanel* const owner = getOwner();
  49980. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49981. if (owner != 0)
  49982. owner->closeDocument (getContentComponent(), true);
  49983. }
  49984. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49985. {
  49986. DocumentWindow::activeWindowStatusChanged();
  49987. updateOrder();
  49988. }
  49989. void MultiDocumentPanelWindow::broughtToFront()
  49990. {
  49991. DocumentWindow::broughtToFront();
  49992. updateOrder();
  49993. }
  49994. void MultiDocumentPanelWindow::updateOrder()
  49995. {
  49996. MultiDocumentPanel* const owner = getOwner();
  49997. if (owner != 0)
  49998. owner->updateOrder();
  49999. }
  50000. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50001. {
  50002. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50003. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50004. }
  50005. class MDITabbedComponentInternal : public TabbedComponent
  50006. {
  50007. public:
  50008. MDITabbedComponentInternal()
  50009. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50010. {
  50011. }
  50012. ~MDITabbedComponentInternal()
  50013. {
  50014. }
  50015. void currentTabChanged (int, const String&)
  50016. {
  50017. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50018. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50019. if (owner != 0)
  50020. owner->updateOrder();
  50021. }
  50022. };
  50023. MultiDocumentPanel::MultiDocumentPanel()
  50024. : mode (MaximisedWindowsWithTabs),
  50025. backgroundColour (Colours::lightblue),
  50026. maximumNumDocuments (0),
  50027. numDocsBeforeTabsUsed (0)
  50028. {
  50029. setOpaque (true);
  50030. }
  50031. MultiDocumentPanel::~MultiDocumentPanel()
  50032. {
  50033. closeAllDocuments (false);
  50034. }
  50035. namespace MultiDocHelpers
  50036. {
  50037. bool shouldDeleteComp (Component* const c)
  50038. {
  50039. return c->getProperties() ["mdiDocumentDelete_"];
  50040. }
  50041. }
  50042. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50043. {
  50044. while (components.size() > 0)
  50045. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50046. return false;
  50047. return true;
  50048. }
  50049. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50050. {
  50051. return new MultiDocumentPanelWindow (backgroundColour);
  50052. }
  50053. void MultiDocumentPanel::addWindow (Component* component)
  50054. {
  50055. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50056. dw->setResizable (true, false);
  50057. dw->setContentComponent (component, false, true);
  50058. dw->setName (component->getName());
  50059. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50060. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50061. int x = 4;
  50062. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50063. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50064. x += 16;
  50065. dw->setTopLeftPosition (x, x);
  50066. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50067. if (pos.toString().isNotEmpty())
  50068. dw->restoreWindowStateFromString (pos.toString());
  50069. addAndMakeVisible (dw);
  50070. dw->toFront (true);
  50071. }
  50072. bool MultiDocumentPanel::addDocument (Component* const component,
  50073. const Colour& docColour,
  50074. const bool deleteWhenRemoved)
  50075. {
  50076. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50077. // with a frame-within-a-frame! Just pass in the bare content component.
  50078. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50079. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50080. return false;
  50081. components.add (component);
  50082. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50083. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50084. component->addComponentListener (this);
  50085. if (mode == FloatingWindows)
  50086. {
  50087. if (isFullscreenWhenOneDocument())
  50088. {
  50089. if (components.size() == 1)
  50090. {
  50091. addAndMakeVisible (component);
  50092. }
  50093. else
  50094. {
  50095. if (components.size() == 2)
  50096. addWindow (components.getFirst());
  50097. addWindow (component);
  50098. }
  50099. }
  50100. else
  50101. {
  50102. addWindow (component);
  50103. }
  50104. }
  50105. else
  50106. {
  50107. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50108. {
  50109. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50110. Array <Component*> temp (components);
  50111. for (int i = 0; i < temp.size(); ++i)
  50112. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50113. resized();
  50114. }
  50115. else
  50116. {
  50117. if (tabComponent != 0)
  50118. tabComponent->addTab (component->getName(), docColour, component, false);
  50119. else
  50120. addAndMakeVisible (component);
  50121. }
  50122. setActiveDocument (component);
  50123. }
  50124. resized();
  50125. activeDocumentChanged();
  50126. return true;
  50127. }
  50128. bool MultiDocumentPanel::closeDocument (Component* component,
  50129. const bool checkItsOkToCloseFirst)
  50130. {
  50131. if (components.contains (component))
  50132. {
  50133. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50134. return false;
  50135. component->removeComponentListener (this);
  50136. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50137. component->getProperties().remove ("mdiDocumentDelete_");
  50138. component->getProperties().remove ("mdiDocumentBkg_");
  50139. if (mode == FloatingWindows)
  50140. {
  50141. for (int i = getNumChildComponents(); --i >= 0;)
  50142. {
  50143. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50144. if (dw != 0 && dw->getContentComponent() == component)
  50145. {
  50146. dw->setContentComponent (0, false);
  50147. delete dw;
  50148. break;
  50149. }
  50150. }
  50151. if (shouldDelete)
  50152. delete component;
  50153. components.removeValue (component);
  50154. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50155. {
  50156. for (int i = getNumChildComponents(); --i >= 0;)
  50157. {
  50158. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50159. if (dw != 0)
  50160. {
  50161. dw->setContentComponent (0, false);
  50162. delete dw;
  50163. }
  50164. }
  50165. addAndMakeVisible (components.getFirst());
  50166. }
  50167. }
  50168. else
  50169. {
  50170. jassert (components.indexOf (component) >= 0);
  50171. if (tabComponent != 0)
  50172. {
  50173. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50174. if (tabComponent->getTabContentComponent (i) == component)
  50175. tabComponent->removeTab (i);
  50176. }
  50177. else
  50178. {
  50179. removeChildComponent (component);
  50180. }
  50181. if (shouldDelete)
  50182. delete component;
  50183. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50184. tabComponent = 0;
  50185. components.removeValue (component);
  50186. if (components.size() > 0 && tabComponent == 0)
  50187. addAndMakeVisible (components.getFirst());
  50188. }
  50189. resized();
  50190. activeDocumentChanged();
  50191. }
  50192. else
  50193. {
  50194. jassertfalse;
  50195. }
  50196. return true;
  50197. }
  50198. int MultiDocumentPanel::getNumDocuments() const throw()
  50199. {
  50200. return components.size();
  50201. }
  50202. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50203. {
  50204. return components [index];
  50205. }
  50206. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50207. {
  50208. if (mode == FloatingWindows)
  50209. {
  50210. for (int i = getNumChildComponents(); --i >= 0;)
  50211. {
  50212. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50213. if (dw != 0 && dw->isActiveWindow())
  50214. return dw->getContentComponent();
  50215. }
  50216. }
  50217. return components.getLast();
  50218. }
  50219. void MultiDocumentPanel::setActiveDocument (Component* component)
  50220. {
  50221. if (mode == FloatingWindows)
  50222. {
  50223. component = getContainerComp (component);
  50224. if (component != 0)
  50225. component->toFront (true);
  50226. }
  50227. else if (tabComponent != 0)
  50228. {
  50229. jassert (components.indexOf (component) >= 0);
  50230. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50231. {
  50232. if (tabComponent->getTabContentComponent (i) == component)
  50233. {
  50234. tabComponent->setCurrentTabIndex (i);
  50235. break;
  50236. }
  50237. }
  50238. }
  50239. else
  50240. {
  50241. component->grabKeyboardFocus();
  50242. }
  50243. }
  50244. void MultiDocumentPanel::activeDocumentChanged()
  50245. {
  50246. }
  50247. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50248. {
  50249. maximumNumDocuments = newNumber;
  50250. }
  50251. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50252. {
  50253. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50254. }
  50255. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50256. {
  50257. return numDocsBeforeTabsUsed != 0;
  50258. }
  50259. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50260. {
  50261. if (mode != newLayoutMode)
  50262. {
  50263. mode = newLayoutMode;
  50264. if (mode == FloatingWindows)
  50265. {
  50266. tabComponent = 0;
  50267. }
  50268. else
  50269. {
  50270. for (int i = getNumChildComponents(); --i >= 0;)
  50271. {
  50272. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50273. if (dw != 0)
  50274. {
  50275. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50276. dw->setContentComponent (0, false);
  50277. delete dw;
  50278. }
  50279. }
  50280. }
  50281. resized();
  50282. const Array <Component*> tempComps (components);
  50283. components.clear();
  50284. for (int i = 0; i < tempComps.size(); ++i)
  50285. {
  50286. Component* const c = tempComps.getUnchecked(i);
  50287. addDocument (c,
  50288. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50289. MultiDocHelpers::shouldDeleteComp (c));
  50290. }
  50291. }
  50292. }
  50293. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50294. {
  50295. if (backgroundColour != newBackgroundColour)
  50296. {
  50297. backgroundColour = newBackgroundColour;
  50298. setOpaque (newBackgroundColour.isOpaque());
  50299. repaint();
  50300. }
  50301. }
  50302. void MultiDocumentPanel::paint (Graphics& g)
  50303. {
  50304. g.fillAll (backgroundColour);
  50305. }
  50306. void MultiDocumentPanel::resized()
  50307. {
  50308. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50309. {
  50310. for (int i = getNumChildComponents(); --i >= 0;)
  50311. getChildComponent (i)->setBounds (getLocalBounds());
  50312. }
  50313. setWantsKeyboardFocus (components.size() == 0);
  50314. }
  50315. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50316. {
  50317. if (mode == FloatingWindows)
  50318. {
  50319. for (int i = 0; i < getNumChildComponents(); ++i)
  50320. {
  50321. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50322. if (dw != 0 && dw->getContentComponent() == c)
  50323. {
  50324. c = dw;
  50325. break;
  50326. }
  50327. }
  50328. }
  50329. return c;
  50330. }
  50331. void MultiDocumentPanel::componentNameChanged (Component&)
  50332. {
  50333. if (mode == FloatingWindows)
  50334. {
  50335. for (int i = 0; i < getNumChildComponents(); ++i)
  50336. {
  50337. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50338. if (dw != 0)
  50339. dw->setName (dw->getContentComponent()->getName());
  50340. }
  50341. }
  50342. else if (tabComponent != 0)
  50343. {
  50344. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50345. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50346. }
  50347. }
  50348. void MultiDocumentPanel::updateOrder()
  50349. {
  50350. const Array <Component*> oldList (components);
  50351. if (mode == FloatingWindows)
  50352. {
  50353. components.clear();
  50354. for (int i = 0; i < getNumChildComponents(); ++i)
  50355. {
  50356. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50357. if (dw != 0)
  50358. components.add (dw->getContentComponent());
  50359. }
  50360. }
  50361. else
  50362. {
  50363. if (tabComponent != 0)
  50364. {
  50365. Component* const current = tabComponent->getCurrentContentComponent();
  50366. if (current != 0)
  50367. {
  50368. components.removeValue (current);
  50369. components.add (current);
  50370. }
  50371. }
  50372. }
  50373. if (components != oldList)
  50374. activeDocumentChanged();
  50375. }
  50376. END_JUCE_NAMESPACE
  50377. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50378. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50379. BEGIN_JUCE_NAMESPACE
  50380. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50381. : zone (zoneFlags)
  50382. {}
  50383. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50384. : zone (other.zone)
  50385. {}
  50386. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50387. {
  50388. zone = other.zone;
  50389. return *this;
  50390. }
  50391. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50392. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50393. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50394. const BorderSize<int>& border,
  50395. const Point<int>& position)
  50396. {
  50397. int z = 0;
  50398. if (totalSize.contains (position)
  50399. && ! border.subtractedFrom (totalSize).contains (position))
  50400. {
  50401. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50402. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50403. z |= left;
  50404. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50405. z |= right;
  50406. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50407. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50408. z |= top;
  50409. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50410. z |= bottom;
  50411. }
  50412. return Zone (z);
  50413. }
  50414. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50415. {
  50416. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50417. switch (zone)
  50418. {
  50419. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50420. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50421. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50422. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50423. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50424. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50425. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50426. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50427. default: break;
  50428. }
  50429. return mc;
  50430. }
  50431. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50432. ComponentBoundsConstrainer* const constrainer_)
  50433. : component (componentToResize),
  50434. constrainer (constrainer_),
  50435. borderSize (5),
  50436. mouseZone (0)
  50437. {
  50438. }
  50439. ResizableBorderComponent::~ResizableBorderComponent()
  50440. {
  50441. }
  50442. void ResizableBorderComponent::paint (Graphics& g)
  50443. {
  50444. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50445. }
  50446. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50447. {
  50448. updateMouseZone (e);
  50449. }
  50450. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50451. {
  50452. updateMouseZone (e);
  50453. }
  50454. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50455. {
  50456. if (component == 0)
  50457. {
  50458. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50459. return;
  50460. }
  50461. updateMouseZone (e);
  50462. originalBounds = component->getBounds();
  50463. if (constrainer != 0)
  50464. constrainer->resizeStart();
  50465. }
  50466. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50467. {
  50468. if (component == 0)
  50469. {
  50470. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50471. return;
  50472. }
  50473. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50474. if (constrainer != 0)
  50475. constrainer->setBoundsForComponent (component, bounds,
  50476. mouseZone.isDraggingTopEdge(),
  50477. mouseZone.isDraggingLeftEdge(),
  50478. mouseZone.isDraggingBottomEdge(),
  50479. mouseZone.isDraggingRightEdge());
  50480. else
  50481. component->setBounds (bounds);
  50482. }
  50483. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50484. {
  50485. if (constrainer != 0)
  50486. constrainer->resizeEnd();
  50487. }
  50488. bool ResizableBorderComponent::hitTest (int x, int y)
  50489. {
  50490. return x < borderSize.getLeft()
  50491. || x >= getWidth() - borderSize.getRight()
  50492. || y < borderSize.getTop()
  50493. || y >= getHeight() - borderSize.getBottom();
  50494. }
  50495. void ResizableBorderComponent::setBorderThickness (const BorderSize<int>& newBorderSize)
  50496. {
  50497. if (borderSize != newBorderSize)
  50498. {
  50499. borderSize = newBorderSize;
  50500. repaint();
  50501. }
  50502. }
  50503. const BorderSize<int> ResizableBorderComponent::getBorderThickness() const
  50504. {
  50505. return borderSize;
  50506. }
  50507. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50508. {
  50509. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50510. if (mouseZone != newZone)
  50511. {
  50512. mouseZone = newZone;
  50513. setMouseCursor (newZone.getMouseCursor());
  50514. }
  50515. }
  50516. END_JUCE_NAMESPACE
  50517. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50518. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50519. BEGIN_JUCE_NAMESPACE
  50520. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50521. ComponentBoundsConstrainer* const constrainer_)
  50522. : component (componentToResize),
  50523. constrainer (constrainer_)
  50524. {
  50525. setRepaintsOnMouseActivity (true);
  50526. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50527. }
  50528. ResizableCornerComponent::~ResizableCornerComponent()
  50529. {
  50530. }
  50531. void ResizableCornerComponent::paint (Graphics& g)
  50532. {
  50533. getLookAndFeel()
  50534. .drawCornerResizer (g, getWidth(), getHeight(),
  50535. isMouseOverOrDragging(),
  50536. isMouseButtonDown());
  50537. }
  50538. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50539. {
  50540. if (component == 0)
  50541. {
  50542. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50543. return;
  50544. }
  50545. originalBounds = component->getBounds();
  50546. if (constrainer != 0)
  50547. constrainer->resizeStart();
  50548. }
  50549. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50550. {
  50551. if (component == 0)
  50552. {
  50553. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50554. return;
  50555. }
  50556. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50557. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50558. if (constrainer != 0)
  50559. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50560. else
  50561. component->setBounds (r);
  50562. }
  50563. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50564. {
  50565. if (constrainer != 0)
  50566. constrainer->resizeStart();
  50567. }
  50568. bool ResizableCornerComponent::hitTest (int x, int y)
  50569. {
  50570. if (getWidth() <= 0)
  50571. return false;
  50572. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50573. return y >= yAtX - getHeight() / 4;
  50574. }
  50575. END_JUCE_NAMESPACE
  50576. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50577. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50578. BEGIN_JUCE_NAMESPACE
  50579. class ScrollBar::ScrollbarButton : public Button
  50580. {
  50581. public:
  50582. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50583. : Button (String::empty),
  50584. direction (direction_),
  50585. owner (owner_)
  50586. {
  50587. setWantsKeyboardFocus (false);
  50588. }
  50589. void paintButton (Graphics& g, bool over, bool down)
  50590. {
  50591. getLookAndFeel()
  50592. .drawScrollbarButton (g, owner,
  50593. getWidth(), getHeight(),
  50594. direction,
  50595. owner.isVertical(),
  50596. over, down);
  50597. }
  50598. void clicked()
  50599. {
  50600. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50601. }
  50602. int direction;
  50603. private:
  50604. ScrollBar& owner;
  50605. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50606. };
  50607. ScrollBar::ScrollBar (const bool vertical_,
  50608. const bool buttonsAreVisible)
  50609. : totalRange (0.0, 1.0),
  50610. visibleRange (0.0, 0.1),
  50611. singleStepSize (0.1),
  50612. thumbAreaStart (0),
  50613. thumbAreaSize (0),
  50614. thumbStart (0),
  50615. thumbSize (0),
  50616. initialDelayInMillisecs (100),
  50617. repeatDelayInMillisecs (50),
  50618. minimumDelayInMillisecs (10),
  50619. vertical (vertical_),
  50620. isDraggingThumb (false),
  50621. autohides (true)
  50622. {
  50623. setButtonVisibility (buttonsAreVisible);
  50624. setRepaintsOnMouseActivity (true);
  50625. setFocusContainer (true);
  50626. }
  50627. ScrollBar::~ScrollBar()
  50628. {
  50629. upButton = 0;
  50630. downButton = 0;
  50631. }
  50632. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50633. {
  50634. if (totalRange != newRangeLimit)
  50635. {
  50636. totalRange = newRangeLimit;
  50637. setCurrentRange (visibleRange);
  50638. updateThumbPosition();
  50639. }
  50640. }
  50641. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50642. {
  50643. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50644. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50645. }
  50646. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50647. {
  50648. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50649. if (visibleRange != constrainedRange)
  50650. {
  50651. visibleRange = constrainedRange;
  50652. updateThumbPosition();
  50653. triggerAsyncUpdate();
  50654. }
  50655. }
  50656. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50657. {
  50658. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50659. }
  50660. void ScrollBar::setCurrentRangeStart (const double newStart)
  50661. {
  50662. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50663. }
  50664. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50665. {
  50666. singleStepSize = newSingleStepSize;
  50667. }
  50668. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50669. {
  50670. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50671. }
  50672. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50673. {
  50674. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50675. }
  50676. void ScrollBar::scrollToTop()
  50677. {
  50678. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50679. }
  50680. void ScrollBar::scrollToBottom()
  50681. {
  50682. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50683. }
  50684. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50685. const int repeatDelayInMillisecs_,
  50686. const int minimumDelayInMillisecs_)
  50687. {
  50688. initialDelayInMillisecs = initialDelayInMillisecs_;
  50689. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50690. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50691. if (upButton != 0)
  50692. {
  50693. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50694. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50695. }
  50696. }
  50697. void ScrollBar::addListener (Listener* const listener)
  50698. {
  50699. listeners.add (listener);
  50700. }
  50701. void ScrollBar::removeListener (Listener* const listener)
  50702. {
  50703. listeners.remove (listener);
  50704. }
  50705. void ScrollBar::handleAsyncUpdate()
  50706. {
  50707. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50708. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50709. }
  50710. void ScrollBar::updateThumbPosition()
  50711. {
  50712. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50713. : thumbAreaSize);
  50714. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50715. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50716. if (newThumbSize > thumbAreaSize)
  50717. newThumbSize = thumbAreaSize;
  50718. int newThumbStart = thumbAreaStart;
  50719. if (totalRange.getLength() > visibleRange.getLength())
  50720. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50721. / (totalRange.getLength() - visibleRange.getLength()));
  50722. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50723. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50724. {
  50725. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50726. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50727. if (vertical)
  50728. repaint (0, repaintStart, getWidth(), repaintSize);
  50729. else
  50730. repaint (repaintStart, 0, repaintSize, getHeight());
  50731. thumbStart = newThumbStart;
  50732. thumbSize = newThumbSize;
  50733. }
  50734. }
  50735. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50736. {
  50737. if (vertical != shouldBeVertical)
  50738. {
  50739. vertical = shouldBeVertical;
  50740. if (upButton != 0)
  50741. {
  50742. upButton->direction = vertical ? 0 : 3;
  50743. downButton->direction = vertical ? 2 : 1;
  50744. }
  50745. updateThumbPosition();
  50746. }
  50747. }
  50748. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50749. {
  50750. upButton = 0;
  50751. downButton = 0;
  50752. if (buttonsAreVisible)
  50753. {
  50754. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50755. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50756. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50757. }
  50758. updateThumbPosition();
  50759. }
  50760. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50761. {
  50762. autohides = shouldHideWhenFullRange;
  50763. updateThumbPosition();
  50764. }
  50765. bool ScrollBar::autoHides() const throw()
  50766. {
  50767. return autohides;
  50768. }
  50769. void ScrollBar::paint (Graphics& g)
  50770. {
  50771. if (thumbAreaSize > 0)
  50772. {
  50773. LookAndFeel& lf = getLookAndFeel();
  50774. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50775. ? thumbSize : 0;
  50776. if (vertical)
  50777. {
  50778. lf.drawScrollbar (g, *this,
  50779. 0, thumbAreaStart,
  50780. getWidth(), thumbAreaSize,
  50781. vertical,
  50782. thumbStart, thumb,
  50783. isMouseOver(), isMouseButtonDown());
  50784. }
  50785. else
  50786. {
  50787. lf.drawScrollbar (g, *this,
  50788. thumbAreaStart, 0,
  50789. thumbAreaSize, getHeight(),
  50790. vertical,
  50791. thumbStart, thumb,
  50792. isMouseOver(), isMouseButtonDown());
  50793. }
  50794. }
  50795. }
  50796. void ScrollBar::lookAndFeelChanged()
  50797. {
  50798. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50799. }
  50800. void ScrollBar::resized()
  50801. {
  50802. const int length = ((vertical) ? getHeight() : getWidth());
  50803. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50804. : 0;
  50805. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50806. {
  50807. thumbAreaStart = length >> 1;
  50808. thumbAreaSize = 0;
  50809. }
  50810. else
  50811. {
  50812. thumbAreaStart = buttonSize;
  50813. thumbAreaSize = length - (buttonSize << 1);
  50814. }
  50815. if (upButton != 0)
  50816. {
  50817. if (vertical)
  50818. {
  50819. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50820. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50821. }
  50822. else
  50823. {
  50824. upButton->setBounds (0, 0, buttonSize, getHeight());
  50825. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50826. }
  50827. }
  50828. updateThumbPosition();
  50829. }
  50830. void ScrollBar::mouseDown (const MouseEvent& e)
  50831. {
  50832. isDraggingThumb = false;
  50833. lastMousePos = vertical ? e.y : e.x;
  50834. dragStartMousePos = lastMousePos;
  50835. dragStartRange = visibleRange.getStart();
  50836. if (dragStartMousePos < thumbStart)
  50837. {
  50838. moveScrollbarInPages (-1);
  50839. startTimer (400);
  50840. }
  50841. else if (dragStartMousePos >= thumbStart + thumbSize)
  50842. {
  50843. moveScrollbarInPages (1);
  50844. startTimer (400);
  50845. }
  50846. else
  50847. {
  50848. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50849. && (thumbAreaSize > thumbSize);
  50850. }
  50851. }
  50852. void ScrollBar::mouseDrag (const MouseEvent& e)
  50853. {
  50854. const int mousePos = vertical ? e.y : e.x;
  50855. if (isDraggingThumb && lastMousePos != mousePos)
  50856. {
  50857. const int deltaPixels = mousePos - dragStartMousePos;
  50858. setCurrentRangeStart (dragStartRange
  50859. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50860. / (thumbAreaSize - thumbSize));
  50861. }
  50862. lastMousePos = mousePos;
  50863. }
  50864. void ScrollBar::mouseUp (const MouseEvent&)
  50865. {
  50866. isDraggingThumb = false;
  50867. stopTimer();
  50868. repaint();
  50869. }
  50870. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50871. float wheelIncrementX,
  50872. float wheelIncrementY)
  50873. {
  50874. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50875. if (increment < 0)
  50876. increment = jmin (increment * 10.0f, -1.0f);
  50877. else if (increment > 0)
  50878. increment = jmax (increment * 10.0f, 1.0f);
  50879. setCurrentRange (visibleRange - singleStepSize * increment);
  50880. }
  50881. void ScrollBar::timerCallback()
  50882. {
  50883. if (isMouseButtonDown())
  50884. {
  50885. startTimer (40);
  50886. if (lastMousePos < thumbStart)
  50887. setCurrentRange (visibleRange - visibleRange.getLength());
  50888. else if (lastMousePos > thumbStart + thumbSize)
  50889. setCurrentRangeStart (visibleRange.getEnd());
  50890. }
  50891. else
  50892. {
  50893. stopTimer();
  50894. }
  50895. }
  50896. bool ScrollBar::keyPressed (const KeyPress& key)
  50897. {
  50898. if (! isVisible())
  50899. return false;
  50900. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50901. moveScrollbarInSteps (-1);
  50902. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50903. moveScrollbarInSteps (1);
  50904. else if (key.isKeyCode (KeyPress::pageUpKey))
  50905. moveScrollbarInPages (-1);
  50906. else if (key.isKeyCode (KeyPress::pageDownKey))
  50907. moveScrollbarInPages (1);
  50908. else if (key.isKeyCode (KeyPress::homeKey))
  50909. scrollToTop();
  50910. else if (key.isKeyCode (KeyPress::endKey))
  50911. scrollToBottom();
  50912. else
  50913. return false;
  50914. return true;
  50915. }
  50916. END_JUCE_NAMESPACE
  50917. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50918. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50919. BEGIN_JUCE_NAMESPACE
  50920. StretchableLayoutManager::StretchableLayoutManager()
  50921. : totalSize (0)
  50922. {
  50923. }
  50924. StretchableLayoutManager::~StretchableLayoutManager()
  50925. {
  50926. }
  50927. void StretchableLayoutManager::clearAllItems()
  50928. {
  50929. items.clear();
  50930. totalSize = 0;
  50931. }
  50932. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50933. const double minimumSize,
  50934. const double maximumSize,
  50935. const double preferredSize)
  50936. {
  50937. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50938. if (layout == 0)
  50939. {
  50940. layout = new ItemLayoutProperties();
  50941. layout->itemIndex = itemIndex;
  50942. int i;
  50943. for (i = 0; i < items.size(); ++i)
  50944. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50945. break;
  50946. items.insert (i, layout);
  50947. }
  50948. layout->minSize = minimumSize;
  50949. layout->maxSize = maximumSize;
  50950. layout->preferredSize = preferredSize;
  50951. layout->currentSize = 0;
  50952. }
  50953. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50954. double& minimumSize,
  50955. double& maximumSize,
  50956. double& preferredSize) const
  50957. {
  50958. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50959. if (layout != 0)
  50960. {
  50961. minimumSize = layout->minSize;
  50962. maximumSize = layout->maxSize;
  50963. preferredSize = layout->preferredSize;
  50964. return true;
  50965. }
  50966. return false;
  50967. }
  50968. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50969. {
  50970. totalSize = newTotalSize;
  50971. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50972. }
  50973. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50974. {
  50975. int pos = 0;
  50976. for (int i = 0; i < itemIndex; ++i)
  50977. {
  50978. const ItemLayoutProperties* const layout = getInfoFor (i);
  50979. if (layout != 0)
  50980. pos += layout->currentSize;
  50981. }
  50982. return pos;
  50983. }
  50984. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50985. {
  50986. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50987. if (layout != 0)
  50988. return layout->currentSize;
  50989. return 0;
  50990. }
  50991. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50992. {
  50993. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50994. if (layout != 0)
  50995. return -layout->currentSize / (double) totalSize;
  50996. return 0;
  50997. }
  50998. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50999. int newPosition)
  51000. {
  51001. for (int i = items.size(); --i >= 0;)
  51002. {
  51003. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51004. if (layout->itemIndex == itemIndex)
  51005. {
  51006. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51007. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51008. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51009. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51010. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51011. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51012. endPos += layout->currentSize;
  51013. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51014. updatePrefSizesToMatchCurrentPositions();
  51015. break;
  51016. }
  51017. }
  51018. }
  51019. void StretchableLayoutManager::layOutComponents (Component** const components,
  51020. int numComponents,
  51021. int x, int y, int w, int h,
  51022. const bool vertically,
  51023. const bool resizeOtherDimension)
  51024. {
  51025. setTotalSize (vertically ? h : w);
  51026. int pos = vertically ? y : x;
  51027. for (int i = 0; i < numComponents; ++i)
  51028. {
  51029. const ItemLayoutProperties* const layout = getInfoFor (i);
  51030. if (layout != 0)
  51031. {
  51032. Component* const c = components[i];
  51033. if (c != 0)
  51034. {
  51035. if (i == numComponents - 1)
  51036. {
  51037. // if it's the last item, crop it to exactly fit the available space..
  51038. if (resizeOtherDimension)
  51039. {
  51040. if (vertically)
  51041. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51042. else
  51043. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51044. }
  51045. else
  51046. {
  51047. if (vertically)
  51048. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51049. else
  51050. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51051. }
  51052. }
  51053. else
  51054. {
  51055. if (resizeOtherDimension)
  51056. {
  51057. if (vertically)
  51058. c->setBounds (x, pos, w, layout->currentSize);
  51059. else
  51060. c->setBounds (pos, y, layout->currentSize, h);
  51061. }
  51062. else
  51063. {
  51064. if (vertically)
  51065. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51066. else
  51067. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51068. }
  51069. }
  51070. }
  51071. pos += layout->currentSize;
  51072. }
  51073. }
  51074. }
  51075. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51076. {
  51077. for (int i = items.size(); --i >= 0;)
  51078. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51079. return items.getUnchecked(i);
  51080. return 0;
  51081. }
  51082. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51083. const int endIndex,
  51084. const int availableSpace,
  51085. int startPos)
  51086. {
  51087. // calculate the total sizes
  51088. int i;
  51089. double totalIdealSize = 0.0;
  51090. int totalMinimums = 0;
  51091. for (i = startIndex; i < endIndex; ++i)
  51092. {
  51093. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51094. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51095. totalMinimums += layout->currentSize;
  51096. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51097. }
  51098. if (totalIdealSize <= 0)
  51099. totalIdealSize = 1.0;
  51100. // now calc the best sizes..
  51101. int extraSpace = availableSpace - totalMinimums;
  51102. while (extraSpace > 0)
  51103. {
  51104. int numWantingMoreSpace = 0;
  51105. int numHavingTakenExtraSpace = 0;
  51106. // first figure out how many comps want a slice of the extra space..
  51107. for (i = startIndex; i < endIndex; ++i)
  51108. {
  51109. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51110. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51111. const int bestSize = jlimit (layout->currentSize,
  51112. jmax (layout->currentSize,
  51113. sizeToRealSize (layout->maxSize, totalSize)),
  51114. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51115. if (bestSize > layout->currentSize)
  51116. ++numWantingMoreSpace;
  51117. }
  51118. // ..share out the extra space..
  51119. for (i = startIndex; i < endIndex; ++i)
  51120. {
  51121. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51122. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51123. int bestSize = jlimit (layout->currentSize,
  51124. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51125. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51126. const int extraWanted = bestSize - layout->currentSize;
  51127. if (extraWanted > 0)
  51128. {
  51129. const int extraAllowed = jmin (extraWanted,
  51130. extraSpace / jmax (1, numWantingMoreSpace));
  51131. if (extraAllowed > 0)
  51132. {
  51133. ++numHavingTakenExtraSpace;
  51134. --numWantingMoreSpace;
  51135. layout->currentSize += extraAllowed;
  51136. extraSpace -= extraAllowed;
  51137. }
  51138. }
  51139. }
  51140. if (numHavingTakenExtraSpace <= 0)
  51141. break;
  51142. }
  51143. // ..and calculate the end position
  51144. for (i = startIndex; i < endIndex; ++i)
  51145. {
  51146. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51147. startPos += layout->currentSize;
  51148. }
  51149. return startPos;
  51150. }
  51151. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51152. const int endIndex) const
  51153. {
  51154. int totalMinimums = 0;
  51155. for (int i = startIndex; i < endIndex; ++i)
  51156. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51157. return totalMinimums;
  51158. }
  51159. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51160. {
  51161. int totalMaximums = 0;
  51162. for (int i = startIndex; i < endIndex; ++i)
  51163. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51164. return totalMaximums;
  51165. }
  51166. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51167. {
  51168. for (int i = 0; i < items.size(); ++i)
  51169. {
  51170. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51171. layout->preferredSize
  51172. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51173. : getItemCurrentAbsoluteSize (i);
  51174. }
  51175. }
  51176. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51177. {
  51178. if (size < 0)
  51179. size *= -totalSpace;
  51180. return roundToInt (size);
  51181. }
  51182. END_JUCE_NAMESPACE
  51183. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51184. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51185. BEGIN_JUCE_NAMESPACE
  51186. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51187. const int itemIndex_,
  51188. const bool isVertical_)
  51189. : layout (layout_),
  51190. itemIndex (itemIndex_),
  51191. isVertical (isVertical_)
  51192. {
  51193. setRepaintsOnMouseActivity (true);
  51194. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51195. : MouseCursor::UpDownResizeCursor));
  51196. }
  51197. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51198. {
  51199. }
  51200. void StretchableLayoutResizerBar::paint (Graphics& g)
  51201. {
  51202. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51203. getWidth(), getHeight(),
  51204. isVertical,
  51205. isMouseOver(),
  51206. isMouseButtonDown());
  51207. }
  51208. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51209. {
  51210. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51211. }
  51212. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51213. {
  51214. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51215. : e.getDistanceFromDragStartY());
  51216. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51217. {
  51218. layout->setItemPosition (itemIndex, desiredPos);
  51219. hasBeenMoved();
  51220. }
  51221. }
  51222. void StretchableLayoutResizerBar::hasBeenMoved()
  51223. {
  51224. if (getParentComponent() != 0)
  51225. getParentComponent()->resized();
  51226. }
  51227. END_JUCE_NAMESPACE
  51228. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51229. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51230. BEGIN_JUCE_NAMESPACE
  51231. StretchableObjectResizer::StretchableObjectResizer()
  51232. {
  51233. }
  51234. StretchableObjectResizer::~StretchableObjectResizer()
  51235. {
  51236. }
  51237. void StretchableObjectResizer::addItem (const double size,
  51238. const double minSize, const double maxSize,
  51239. const int order)
  51240. {
  51241. // the order must be >= 0 but less than the maximum integer value.
  51242. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51243. Item* const item = new Item();
  51244. item->size = size;
  51245. item->minSize = minSize;
  51246. item->maxSize = maxSize;
  51247. item->order = order;
  51248. items.add (item);
  51249. }
  51250. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51251. {
  51252. const Item* const it = items [index];
  51253. return it != 0 ? it->size : 0;
  51254. }
  51255. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51256. {
  51257. int order = 0;
  51258. for (;;)
  51259. {
  51260. double currentSize = 0;
  51261. double minSize = 0;
  51262. double maxSize = 0;
  51263. int nextHighestOrder = std::numeric_limits<int>::max();
  51264. for (int i = 0; i < items.size(); ++i)
  51265. {
  51266. const Item* const it = items.getUnchecked(i);
  51267. currentSize += it->size;
  51268. if (it->order <= order)
  51269. {
  51270. minSize += it->minSize;
  51271. maxSize += it->maxSize;
  51272. }
  51273. else
  51274. {
  51275. minSize += it->size;
  51276. maxSize += it->size;
  51277. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51278. }
  51279. }
  51280. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51281. if (thisIterationTarget >= currentSize)
  51282. {
  51283. const double availableExtraSpace = maxSize - currentSize;
  51284. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51285. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51286. for (int i = 0; i < items.size(); ++i)
  51287. {
  51288. Item* const it = items.getUnchecked(i);
  51289. if (it->order <= order)
  51290. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51291. }
  51292. }
  51293. else
  51294. {
  51295. const double amountOfSlack = currentSize - minSize;
  51296. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51297. const double scale = targetAmountOfSlack / amountOfSlack;
  51298. for (int i = 0; i < items.size(); ++i)
  51299. {
  51300. Item* const it = items.getUnchecked(i);
  51301. if (it->order <= order)
  51302. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51303. }
  51304. }
  51305. if (nextHighestOrder < std::numeric_limits<int>::max())
  51306. order = nextHighestOrder;
  51307. else
  51308. break;
  51309. }
  51310. }
  51311. END_JUCE_NAMESPACE
  51312. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51313. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51314. BEGIN_JUCE_NAMESPACE
  51315. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51316. : Button (name),
  51317. owner (owner_),
  51318. overlapPixels (0)
  51319. {
  51320. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51321. setComponentEffect (&shadow);
  51322. setWantsKeyboardFocus (false);
  51323. }
  51324. TabBarButton::~TabBarButton()
  51325. {
  51326. }
  51327. int TabBarButton::getIndex() const
  51328. {
  51329. return owner.indexOfTabButton (this);
  51330. }
  51331. void TabBarButton::paintButton (Graphics& g,
  51332. bool isMouseOverButton,
  51333. bool isButtonDown)
  51334. {
  51335. const Rectangle<int> area (getActiveArea());
  51336. g.setOrigin (area.getX(), area.getY());
  51337. getLookAndFeel()
  51338. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51339. owner.getTabBackgroundColour (getIndex()),
  51340. getIndex(), getButtonText(), *this,
  51341. owner.getOrientation(),
  51342. isMouseOverButton, isButtonDown,
  51343. getToggleState());
  51344. }
  51345. void TabBarButton::clicked (const ModifierKeys& mods)
  51346. {
  51347. if (mods.isPopupMenu())
  51348. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51349. else
  51350. owner.setCurrentTabIndex (getIndex());
  51351. }
  51352. bool TabBarButton::hitTest (int mx, int my)
  51353. {
  51354. const Rectangle<int> area (getActiveArea());
  51355. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51356. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51357. {
  51358. if (isPositiveAndBelow (mx, getWidth())
  51359. && my >= area.getY() + overlapPixels
  51360. && my < area.getBottom() - overlapPixels)
  51361. return true;
  51362. }
  51363. else
  51364. {
  51365. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51366. && isPositiveAndBelow (my, getHeight()))
  51367. return true;
  51368. }
  51369. Path p;
  51370. getLookAndFeel()
  51371. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51372. owner.getOrientation(), false, false, getToggleState());
  51373. return p.contains ((float) (mx - area.getX()),
  51374. (float) (my - area.getY()));
  51375. }
  51376. int TabBarButton::getBestTabLength (const int depth)
  51377. {
  51378. return jlimit (depth * 2,
  51379. depth * 7,
  51380. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51381. }
  51382. const Rectangle<int> TabBarButton::getActiveArea()
  51383. {
  51384. Rectangle<int> r (getLocalBounds());
  51385. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51386. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51387. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51388. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51389. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51390. return r;
  51391. }
  51392. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51393. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51394. {
  51395. public:
  51396. BehindFrontTabComp (TabbedButtonBar& owner_)
  51397. : owner (owner_)
  51398. {
  51399. setInterceptsMouseClicks (false, false);
  51400. }
  51401. void paint (Graphics& g)
  51402. {
  51403. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51404. owner, owner.getOrientation());
  51405. }
  51406. void enablementChanged()
  51407. {
  51408. repaint();
  51409. }
  51410. void buttonClicked (Button*)
  51411. {
  51412. owner.showExtraItemsMenu();
  51413. }
  51414. private:
  51415. TabbedButtonBar& owner;
  51416. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51417. };
  51418. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51419. : orientation (orientation_),
  51420. minimumScale (0.7),
  51421. currentTabIndex (-1)
  51422. {
  51423. setInterceptsMouseClicks (false, true);
  51424. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51425. setFocusContainer (true);
  51426. }
  51427. TabbedButtonBar::~TabbedButtonBar()
  51428. {
  51429. tabs.clear();
  51430. extraTabsButton = 0;
  51431. }
  51432. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51433. {
  51434. orientation = newOrientation;
  51435. for (int i = getNumChildComponents(); --i >= 0;)
  51436. getChildComponent (i)->resized();
  51437. resized();
  51438. }
  51439. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51440. {
  51441. return new TabBarButton (name, *this);
  51442. }
  51443. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51444. {
  51445. minimumScale = newMinimumScale;
  51446. resized();
  51447. }
  51448. void TabbedButtonBar::clearTabs()
  51449. {
  51450. tabs.clear();
  51451. extraTabsButton = 0;
  51452. setCurrentTabIndex (-1);
  51453. }
  51454. void TabbedButtonBar::addTab (const String& tabName,
  51455. const Colour& tabBackgroundColour,
  51456. int insertIndex)
  51457. {
  51458. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51459. if (tabName.isNotEmpty())
  51460. {
  51461. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51462. insertIndex = tabs.size();
  51463. TabInfo* newTab = new TabInfo();
  51464. newTab->name = tabName;
  51465. newTab->colour = tabBackgroundColour;
  51466. newTab->component = createTabButton (tabName, insertIndex);
  51467. jassert (newTab->component != 0);
  51468. tabs.insert (insertIndex, newTab);
  51469. addAndMakeVisible (newTab->component, insertIndex);
  51470. resized();
  51471. if (currentTabIndex < 0)
  51472. setCurrentTabIndex (0);
  51473. }
  51474. }
  51475. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51476. {
  51477. TabInfo* const tab = tabs [tabIndex];
  51478. if (tab != 0 && tab->name != newName)
  51479. {
  51480. tab->name = newName;
  51481. tab->component->setButtonText (newName);
  51482. resized();
  51483. }
  51484. }
  51485. void TabbedButtonBar::removeTab (const int tabIndex)
  51486. {
  51487. if (tabs [tabIndex] != 0)
  51488. {
  51489. const int oldTabIndex = currentTabIndex;
  51490. if (currentTabIndex == tabIndex)
  51491. currentTabIndex = -1;
  51492. tabs.remove (tabIndex);
  51493. resized();
  51494. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51495. }
  51496. }
  51497. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51498. {
  51499. tabs.move (currentIndex, newIndex);
  51500. resized();
  51501. }
  51502. int TabbedButtonBar::getNumTabs() const
  51503. {
  51504. return tabs.size();
  51505. }
  51506. const String TabbedButtonBar::getCurrentTabName() const
  51507. {
  51508. TabInfo* tab = tabs [currentTabIndex];
  51509. return tab == 0 ? String::empty : tab->name;
  51510. }
  51511. const StringArray TabbedButtonBar::getTabNames() const
  51512. {
  51513. StringArray names;
  51514. for (int i = 0; i < tabs.size(); ++i)
  51515. names.add (tabs.getUnchecked(i)->name);
  51516. return names;
  51517. }
  51518. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51519. {
  51520. if (currentTabIndex != newIndex)
  51521. {
  51522. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51523. newIndex = -1;
  51524. currentTabIndex = newIndex;
  51525. for (int i = 0; i < tabs.size(); ++i)
  51526. {
  51527. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51528. tb->setToggleState (i == newIndex, false);
  51529. }
  51530. resized();
  51531. if (sendChangeMessage_)
  51532. sendChangeMessage();
  51533. currentTabChanged (newIndex, getCurrentTabName());
  51534. }
  51535. }
  51536. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51537. {
  51538. TabInfo* const tab = tabs[index];
  51539. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51540. }
  51541. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51542. {
  51543. for (int i = tabs.size(); --i >= 0;)
  51544. if (tabs.getUnchecked(i)->component == button)
  51545. return i;
  51546. return -1;
  51547. }
  51548. void TabbedButtonBar::lookAndFeelChanged()
  51549. {
  51550. extraTabsButton = 0;
  51551. resized();
  51552. }
  51553. void TabbedButtonBar::resized()
  51554. {
  51555. int depth = getWidth();
  51556. int length = getHeight();
  51557. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51558. swapVariables (depth, length);
  51559. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51560. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51561. int i, totalLength = overlap;
  51562. int numVisibleButtons = tabs.size();
  51563. for (i = 0; i < tabs.size(); ++i)
  51564. {
  51565. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51566. totalLength += tb->getBestTabLength (depth) - overlap;
  51567. tb->overlapPixels = overlap / 2;
  51568. }
  51569. double scale = 1.0;
  51570. if (totalLength > length)
  51571. scale = jmax (minimumScale, length / (double) totalLength);
  51572. const bool isTooBig = totalLength * scale > length;
  51573. int tabsButtonPos = 0;
  51574. if (isTooBig)
  51575. {
  51576. if (extraTabsButton == 0)
  51577. {
  51578. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51579. extraTabsButton->addListener (behindFrontTab);
  51580. extraTabsButton->setAlwaysOnTop (true);
  51581. extraTabsButton->setTriggeredOnMouseDown (true);
  51582. }
  51583. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51584. extraTabsButton->setSize (buttonSize, buttonSize);
  51585. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51586. {
  51587. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51588. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51589. }
  51590. else
  51591. {
  51592. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51593. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51594. }
  51595. totalLength = 0;
  51596. for (i = 0; i < tabs.size(); ++i)
  51597. {
  51598. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51599. const int newLength = totalLength + tb->getBestTabLength (depth);
  51600. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51601. {
  51602. totalLength += overlap;
  51603. break;
  51604. }
  51605. numVisibleButtons = i + 1;
  51606. totalLength = newLength - overlap;
  51607. }
  51608. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51609. }
  51610. else
  51611. {
  51612. extraTabsButton = 0;
  51613. }
  51614. int pos = 0;
  51615. TabBarButton* frontTab = 0;
  51616. for (i = 0; i < tabs.size(); ++i)
  51617. {
  51618. TabBarButton* const tb = getTabButton (i);
  51619. if (tb != 0)
  51620. {
  51621. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51622. if (i < numVisibleButtons)
  51623. {
  51624. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51625. tb->setBounds (pos, 0, bestLength, getHeight());
  51626. else
  51627. tb->setBounds (0, pos, getWidth(), bestLength);
  51628. tb->toBack();
  51629. if (i == currentTabIndex)
  51630. frontTab = tb;
  51631. tb->setVisible (true);
  51632. }
  51633. else
  51634. {
  51635. tb->setVisible (false);
  51636. }
  51637. pos += bestLength - overlap;
  51638. }
  51639. }
  51640. behindFrontTab->setBounds (getLocalBounds());
  51641. if (frontTab != 0)
  51642. {
  51643. frontTab->toFront (false);
  51644. behindFrontTab->toBehind (frontTab);
  51645. }
  51646. }
  51647. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51648. {
  51649. TabInfo* const tab = tabs [tabIndex];
  51650. return tab == 0 ? Colours::white : tab->colour;
  51651. }
  51652. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51653. {
  51654. TabInfo* const tab = tabs [tabIndex];
  51655. if (tab != 0 && tab->colour != newColour)
  51656. {
  51657. tab->colour = newColour;
  51658. repaint();
  51659. }
  51660. }
  51661. void TabbedButtonBar::showExtraItemsMenu()
  51662. {
  51663. PopupMenu m;
  51664. for (int i = 0; i < tabs.size(); ++i)
  51665. {
  51666. const TabInfo* const tab = tabs.getUnchecked(i);
  51667. if (! tab->component->isVisible())
  51668. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51669. }
  51670. const int res = m.showAt (extraTabsButton);
  51671. if (res != 0)
  51672. setCurrentTabIndex (res - 1);
  51673. }
  51674. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51675. {
  51676. }
  51677. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51678. {
  51679. }
  51680. END_JUCE_NAMESPACE
  51681. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51682. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51683. BEGIN_JUCE_NAMESPACE
  51684. namespace TabbedComponentHelpers
  51685. {
  51686. const Identifier deleteComponentId ("deleteByTabComp_");
  51687. void deleteIfNecessary (Component* const comp)
  51688. {
  51689. if (comp != 0 && (bool) comp->getProperties() [deleteComponentId])
  51690. delete comp;
  51691. }
  51692. const Rectangle<int> getTabArea (Rectangle<int>& content, BorderSize<int>& outline,
  51693. const TabbedButtonBar::Orientation orientation, const int tabDepth)
  51694. {
  51695. switch (orientation)
  51696. {
  51697. case TabbedButtonBar::TabsAtTop: outline.setTop (0); return content.removeFromTop (tabDepth);
  51698. case TabbedButtonBar::TabsAtBottom: outline.setBottom (0); return content.removeFromBottom (tabDepth);
  51699. case TabbedButtonBar::TabsAtLeft: outline.setLeft (0); return content.removeFromLeft (tabDepth);
  51700. case TabbedButtonBar::TabsAtRight: outline.setRight (0); return content.removeFromRight (tabDepth);
  51701. default: jassertfalse; break;
  51702. }
  51703. return Rectangle<int>();
  51704. }
  51705. }
  51706. class TabbedComponent::ButtonBar : public TabbedButtonBar
  51707. {
  51708. public:
  51709. ButtonBar (TabbedComponent& owner_, const TabbedButtonBar::Orientation orientation_)
  51710. : TabbedButtonBar (orientation_),
  51711. owner (owner_)
  51712. {
  51713. }
  51714. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51715. {
  51716. owner.changeCallback (newCurrentTabIndex, newTabName);
  51717. }
  51718. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51719. {
  51720. owner.popupMenuClickOnTab (tabIndex, tabName);
  51721. }
  51722. const Colour getTabBackgroundColour (const int tabIndex)
  51723. {
  51724. return owner.tabs->getTabBackgroundColour (tabIndex);
  51725. }
  51726. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51727. {
  51728. return owner.createTabButton (tabName, tabIndex);
  51729. }
  51730. private:
  51731. TabbedComponent& owner;
  51732. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonBar);
  51733. };
  51734. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51735. : tabDepth (30),
  51736. outlineThickness (1),
  51737. edgeIndent (0)
  51738. {
  51739. addAndMakeVisible (tabs = new ButtonBar (*this, orientation));
  51740. }
  51741. TabbedComponent::~TabbedComponent()
  51742. {
  51743. clearTabs();
  51744. tabs = 0;
  51745. }
  51746. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51747. {
  51748. tabs->setOrientation (orientation);
  51749. resized();
  51750. }
  51751. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51752. {
  51753. return tabs->getOrientation();
  51754. }
  51755. void TabbedComponent::setTabBarDepth (const int newDepth)
  51756. {
  51757. if (tabDepth != newDepth)
  51758. {
  51759. tabDepth = newDepth;
  51760. resized();
  51761. }
  51762. }
  51763. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51764. {
  51765. return new TabBarButton (tabName, *tabs);
  51766. }
  51767. void TabbedComponent::clearTabs()
  51768. {
  51769. if (panelComponent != 0)
  51770. {
  51771. panelComponent->setVisible (false);
  51772. removeChildComponent (panelComponent);
  51773. panelComponent = 0;
  51774. }
  51775. tabs->clearTabs();
  51776. for (int i = contentComponents.size(); --i >= 0;)
  51777. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (i));
  51778. contentComponents.clear();
  51779. }
  51780. void TabbedComponent::addTab (const String& tabName,
  51781. const Colour& tabBackgroundColour,
  51782. Component* const contentComponent,
  51783. const bool deleteComponentWhenNotNeeded,
  51784. const int insertIndex)
  51785. {
  51786. contentComponents.insert (insertIndex, WeakReference<Component> (contentComponent));
  51787. if (deleteComponentWhenNotNeeded && contentComponent != 0)
  51788. contentComponent->getProperties().set (TabbedComponentHelpers::deleteComponentId, true);
  51789. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51790. }
  51791. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51792. {
  51793. tabs->setTabName (tabIndex, newName);
  51794. }
  51795. void TabbedComponent::removeTab (const int tabIndex)
  51796. {
  51797. if (isPositiveAndBelow (tabIndex, contentComponents.size()))
  51798. {
  51799. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (tabIndex));
  51800. contentComponents.remove (tabIndex);
  51801. tabs->removeTab (tabIndex);
  51802. }
  51803. }
  51804. int TabbedComponent::getNumTabs() const
  51805. {
  51806. return tabs->getNumTabs();
  51807. }
  51808. const StringArray TabbedComponent::getTabNames() const
  51809. {
  51810. return tabs->getTabNames();
  51811. }
  51812. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51813. {
  51814. return contentComponents [tabIndex];
  51815. }
  51816. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51817. {
  51818. return tabs->getTabBackgroundColour (tabIndex);
  51819. }
  51820. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51821. {
  51822. tabs->setTabBackgroundColour (tabIndex, newColour);
  51823. if (getCurrentTabIndex() == tabIndex)
  51824. repaint();
  51825. }
  51826. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51827. {
  51828. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51829. }
  51830. int TabbedComponent::getCurrentTabIndex() const
  51831. {
  51832. return tabs->getCurrentTabIndex();
  51833. }
  51834. const String TabbedComponent::getCurrentTabName() const
  51835. {
  51836. return tabs->getCurrentTabName();
  51837. }
  51838. void TabbedComponent::setOutline (const int thickness)
  51839. {
  51840. outlineThickness = thickness;
  51841. resized();
  51842. repaint();
  51843. }
  51844. void TabbedComponent::setIndent (const int indentThickness)
  51845. {
  51846. edgeIndent = indentThickness;
  51847. resized();
  51848. repaint();
  51849. }
  51850. void TabbedComponent::paint (Graphics& g)
  51851. {
  51852. g.fillAll (findColour (backgroundColourId));
  51853. Rectangle<int> content (getLocalBounds());
  51854. BorderSize<int> outline (outlineThickness);
  51855. TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth);
  51856. g.reduceClipRegion (content);
  51857. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51858. if (outlineThickness > 0)
  51859. {
  51860. RectangleList rl (content);
  51861. rl.subtract (outline.subtractedFrom (content));
  51862. g.reduceClipRegion (rl);
  51863. g.fillAll (findColour (outlineColourId));
  51864. }
  51865. }
  51866. void TabbedComponent::resized()
  51867. {
  51868. Rectangle<int> content (getLocalBounds());
  51869. BorderSize<int> outline (outlineThickness);
  51870. tabs->setBounds (TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth));
  51871. content = BorderSize<int> (edgeIndent).subtractedFrom (outline.subtractedFrom (content));
  51872. for (int i = contentComponents.size(); --i >= 0;)
  51873. if (contentComponents.getReference (i) != 0)
  51874. contentComponents.getReference (i)->setBounds (content);
  51875. }
  51876. void TabbedComponent::lookAndFeelChanged()
  51877. {
  51878. for (int i = contentComponents.size(); --i >= 0;)
  51879. if (contentComponents.getReference (i) != 0)
  51880. contentComponents.getReference (i)->lookAndFeelChanged();
  51881. }
  51882. void TabbedComponent::changeCallback (const int newCurrentTabIndex, const String& newTabName)
  51883. {
  51884. if (panelComponent != 0)
  51885. {
  51886. panelComponent->setVisible (false);
  51887. removeChildComponent (panelComponent);
  51888. panelComponent = 0;
  51889. }
  51890. if (getCurrentTabIndex() >= 0)
  51891. {
  51892. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51893. if (panelComponent != 0)
  51894. {
  51895. // do these ops as two stages instead of addAndMakeVisible() so that the
  51896. // component has always got a parent when it gets the visibilityChanged() callback
  51897. addChildComponent (panelComponent);
  51898. panelComponent->setVisible (true);
  51899. panelComponent->toFront (true);
  51900. }
  51901. repaint();
  51902. }
  51903. resized();
  51904. currentTabChanged (newCurrentTabIndex, newTabName);
  51905. }
  51906. void TabbedComponent::currentTabChanged (const int, const String&) {}
  51907. void TabbedComponent::popupMenuClickOnTab (const int, const String&) {}
  51908. END_JUCE_NAMESPACE
  51909. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51910. /*** Start of inlined file: juce_Viewport.cpp ***/
  51911. BEGIN_JUCE_NAMESPACE
  51912. Viewport::Viewport (const String& componentName)
  51913. : Component (componentName),
  51914. scrollBarThickness (0),
  51915. singleStepX (16),
  51916. singleStepY (16),
  51917. showHScrollbar (true),
  51918. showVScrollbar (true),
  51919. verticalScrollBar (true),
  51920. horizontalScrollBar (false)
  51921. {
  51922. // content holder is used to clip the contents so they don't overlap the scrollbars
  51923. addAndMakeVisible (&contentHolder);
  51924. contentHolder.setInterceptsMouseClicks (false, true);
  51925. addChildComponent (&verticalScrollBar);
  51926. addChildComponent (&horizontalScrollBar);
  51927. verticalScrollBar.addListener (this);
  51928. horizontalScrollBar.addListener (this);
  51929. setInterceptsMouseClicks (false, true);
  51930. setWantsKeyboardFocus (true);
  51931. }
  51932. Viewport::~Viewport()
  51933. {
  51934. deleteContentComp();
  51935. }
  51936. void Viewport::visibleAreaChanged (const Rectangle<int>&)
  51937. {
  51938. }
  51939. void Viewport::deleteContentComp()
  51940. {
  51941. // This sets the content comp to a null pointer before deleting the old one, in case
  51942. // anything tries to use the old one while it's in mid-deletion..
  51943. ScopedPointer<Component> oldCompDeleter (contentComp);
  51944. contentComp = 0;
  51945. }
  51946. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51947. {
  51948. if (contentComp.get() != newViewedComponent)
  51949. {
  51950. deleteContentComp();
  51951. contentComp = newViewedComponent;
  51952. if (contentComp != 0)
  51953. {
  51954. contentHolder.addAndMakeVisible (contentComp);
  51955. setViewPosition (0, 0);
  51956. contentComp->addComponentListener (this);
  51957. }
  51958. updateVisibleArea();
  51959. }
  51960. }
  51961. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51962. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51963. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51964. {
  51965. if (contentComp != 0)
  51966. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51967. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51968. }
  51969. void Viewport::setViewPosition (const Point<int>& newPosition)
  51970. {
  51971. setViewPosition (newPosition.getX(), newPosition.getY());
  51972. }
  51973. void Viewport::setViewPositionProportionately (const double x, const double y)
  51974. {
  51975. if (contentComp != 0)
  51976. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51977. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51978. }
  51979. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51980. {
  51981. if (contentComp != 0)
  51982. {
  51983. int dx = 0, dy = 0;
  51984. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51985. {
  51986. if (mouseX < activeBorderThickness)
  51987. dx = activeBorderThickness - mouseX;
  51988. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51989. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51990. if (dx < 0)
  51991. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51992. else
  51993. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51994. }
  51995. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51996. {
  51997. if (mouseY < activeBorderThickness)
  51998. dy = activeBorderThickness - mouseY;
  51999. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52000. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52001. if (dy < 0)
  52002. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52003. else
  52004. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52005. }
  52006. if (dx != 0 || dy != 0)
  52007. {
  52008. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52009. contentComp->getY() + dy);
  52010. return true;
  52011. }
  52012. }
  52013. return false;
  52014. }
  52015. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52016. {
  52017. updateVisibleArea();
  52018. }
  52019. void Viewport::resized()
  52020. {
  52021. updateVisibleArea();
  52022. }
  52023. void Viewport::updateVisibleArea()
  52024. {
  52025. const int scrollbarWidth = getScrollBarThickness();
  52026. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52027. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52028. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52029. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52030. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52031. Rectangle<int> contentArea (getLocalBounds());
  52032. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52033. {
  52034. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52035. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52036. if (vBarVisible)
  52037. contentArea.setWidth (getWidth() - scrollbarWidth);
  52038. if (hBarVisible)
  52039. contentArea.setHeight (getHeight() - scrollbarWidth);
  52040. if (! contentArea.contains (contentComp->getBounds()))
  52041. {
  52042. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52043. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52044. }
  52045. }
  52046. if (vBarVisible)
  52047. contentArea.setWidth (getWidth() - scrollbarWidth);
  52048. if (hBarVisible)
  52049. contentArea.setHeight (getHeight() - scrollbarWidth);
  52050. contentHolder.setBounds (contentArea);
  52051. Rectangle<int> contentBounds;
  52052. if (contentComp != 0)
  52053. contentBounds = contentHolder.getLocalArea (contentComp, contentComp->getLocalBounds());
  52054. Point<int> visibleOrigin (-contentBounds.getPosition());
  52055. if (hBarVisible)
  52056. {
  52057. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52058. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52059. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52060. horizontalScrollBar.setSingleStepSize (singleStepX);
  52061. horizontalScrollBar.cancelPendingUpdate();
  52062. }
  52063. else if (canShowHBar)
  52064. {
  52065. visibleOrigin.setX (0);
  52066. }
  52067. if (vBarVisible)
  52068. {
  52069. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52070. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52071. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52072. verticalScrollBar.setSingleStepSize (singleStepY);
  52073. verticalScrollBar.cancelPendingUpdate();
  52074. }
  52075. else if (canShowVBar)
  52076. {
  52077. visibleOrigin.setY (0);
  52078. }
  52079. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52080. horizontalScrollBar.setVisible (hBarVisible);
  52081. verticalScrollBar.setVisible (vBarVisible);
  52082. setViewPosition (visibleOrigin);
  52083. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52084. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52085. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52086. if (lastVisibleArea != visibleArea)
  52087. {
  52088. lastVisibleArea = visibleArea;
  52089. visibleAreaChanged (visibleArea);
  52090. }
  52091. horizontalScrollBar.handleUpdateNowIfNeeded();
  52092. verticalScrollBar.handleUpdateNowIfNeeded();
  52093. }
  52094. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52095. {
  52096. if (singleStepX != stepX || singleStepY != stepY)
  52097. {
  52098. singleStepX = stepX;
  52099. singleStepY = stepY;
  52100. updateVisibleArea();
  52101. }
  52102. }
  52103. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52104. const bool showHorizontalScrollbarIfNeeded)
  52105. {
  52106. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52107. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52108. {
  52109. showVScrollbar = showVerticalScrollbarIfNeeded;
  52110. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52111. updateVisibleArea();
  52112. }
  52113. }
  52114. void Viewport::setScrollBarThickness (const int thickness)
  52115. {
  52116. if (scrollBarThickness != thickness)
  52117. {
  52118. scrollBarThickness = thickness;
  52119. updateVisibleArea();
  52120. }
  52121. }
  52122. int Viewport::getScrollBarThickness() const
  52123. {
  52124. return scrollBarThickness > 0 ? scrollBarThickness
  52125. : getLookAndFeel().getDefaultScrollbarWidth();
  52126. }
  52127. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52128. {
  52129. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52130. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52131. }
  52132. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52133. {
  52134. const int newRangeStartInt = roundToInt (newRangeStart);
  52135. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52136. {
  52137. setViewPosition (newRangeStartInt, getViewPositionY());
  52138. }
  52139. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52140. {
  52141. setViewPosition (getViewPositionX(), newRangeStartInt);
  52142. }
  52143. }
  52144. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52145. {
  52146. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52147. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52148. }
  52149. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52150. {
  52151. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52152. {
  52153. const bool hasVertBar = verticalScrollBar.isVisible();
  52154. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52155. if (hasHorzBar || hasVertBar)
  52156. {
  52157. if (wheelIncrementX != 0)
  52158. {
  52159. wheelIncrementX *= 14.0f * singleStepX;
  52160. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52161. : jmax (wheelIncrementX, 1.0f);
  52162. }
  52163. if (wheelIncrementY != 0)
  52164. {
  52165. wheelIncrementY *= 14.0f * singleStepY;
  52166. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52167. : jmax (wheelIncrementY, 1.0f);
  52168. }
  52169. Point<int> pos (getViewPosition());
  52170. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52171. {
  52172. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52173. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52174. }
  52175. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52176. {
  52177. if (wheelIncrementX == 0 && ! hasVertBar)
  52178. wheelIncrementX = wheelIncrementY;
  52179. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52180. }
  52181. else if (hasVertBar && wheelIncrementY != 0)
  52182. {
  52183. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52184. }
  52185. if (pos != getViewPosition())
  52186. {
  52187. setViewPosition (pos);
  52188. return true;
  52189. }
  52190. }
  52191. }
  52192. return false;
  52193. }
  52194. bool Viewport::keyPressed (const KeyPress& key)
  52195. {
  52196. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52197. || key.isKeyCode (KeyPress::downKey)
  52198. || key.isKeyCode (KeyPress::pageUpKey)
  52199. || key.isKeyCode (KeyPress::pageDownKey)
  52200. || key.isKeyCode (KeyPress::homeKey)
  52201. || key.isKeyCode (KeyPress::endKey);
  52202. if (verticalScrollBar.isVisible() && isUpDownKey)
  52203. return verticalScrollBar.keyPressed (key);
  52204. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52205. || key.isKeyCode (KeyPress::rightKey);
  52206. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52207. return horizontalScrollBar.keyPressed (key);
  52208. return false;
  52209. }
  52210. END_JUCE_NAMESPACE
  52211. /*** End of inlined file: juce_Viewport.cpp ***/
  52212. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52213. BEGIN_JUCE_NAMESPACE
  52214. namespace LookAndFeelHelpers
  52215. {
  52216. void createRoundedPath (Path& p,
  52217. const float x, const float y,
  52218. const float w, const float h,
  52219. const float cs,
  52220. const bool curveTopLeft, const bool curveTopRight,
  52221. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52222. {
  52223. const float cs2 = 2.0f * cs;
  52224. if (curveTopLeft)
  52225. {
  52226. p.startNewSubPath (x, y + cs);
  52227. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52228. }
  52229. else
  52230. {
  52231. p.startNewSubPath (x, y);
  52232. }
  52233. if (curveTopRight)
  52234. {
  52235. p.lineTo (x + w - cs, y);
  52236. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52237. }
  52238. else
  52239. {
  52240. p.lineTo (x + w, y);
  52241. }
  52242. if (curveBottomRight)
  52243. {
  52244. p.lineTo (x + w, y + h - cs);
  52245. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52246. }
  52247. else
  52248. {
  52249. p.lineTo (x + w, y + h);
  52250. }
  52251. if (curveBottomLeft)
  52252. {
  52253. p.lineTo (x + cs, y + h);
  52254. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52255. }
  52256. else
  52257. {
  52258. p.lineTo (x, y + h);
  52259. }
  52260. p.closeSubPath();
  52261. }
  52262. const Colour createBaseColour (const Colour& buttonColour,
  52263. const bool hasKeyboardFocus,
  52264. const bool isMouseOverButton,
  52265. const bool isButtonDown) throw()
  52266. {
  52267. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52268. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52269. if (isButtonDown)
  52270. return baseColour.contrasting (0.2f);
  52271. else if (isMouseOverButton)
  52272. return baseColour.contrasting (0.1f);
  52273. return baseColour;
  52274. }
  52275. const TextLayout layoutTooltipText (const String& text) throw()
  52276. {
  52277. const float tooltipFontSize = 12.0f;
  52278. const int maxToolTipWidth = 400;
  52279. const Font f (tooltipFontSize, Font::bold);
  52280. TextLayout tl (text, f);
  52281. tl.layout (maxToolTipWidth, Justification::left, true);
  52282. return tl;
  52283. }
  52284. LookAndFeel* defaultLF = 0;
  52285. LookAndFeel* currentDefaultLF = 0;
  52286. }
  52287. LookAndFeel::LookAndFeel()
  52288. {
  52289. /* if this fails it means you're trying to create a LookAndFeel object before
  52290. the static Colours have been initialised. That ain't gonna work. It probably
  52291. means that you're using a static LookAndFeel object and that your compiler has
  52292. decided to intialise it before the Colours class.
  52293. */
  52294. jassert (Colours::white == Colour (0xffffffff));
  52295. // set up the standard set of colours..
  52296. const int textButtonColour = 0xffbbbbff;
  52297. const int textHighlightColour = 0x401111ee;
  52298. const int standardOutlineColour = 0xb2808080;
  52299. static const int standardColours[] =
  52300. {
  52301. TextButton::buttonColourId, textButtonColour,
  52302. TextButton::buttonOnColourId, 0xff4444ff,
  52303. TextButton::textColourOnId, 0xff000000,
  52304. TextButton::textColourOffId, 0xff000000,
  52305. ComboBox::buttonColourId, 0xffbbbbff,
  52306. ComboBox::outlineColourId, standardOutlineColour,
  52307. ToggleButton::textColourId, 0xff000000,
  52308. TextEditor::backgroundColourId, 0xffffffff,
  52309. TextEditor::textColourId, 0xff000000,
  52310. TextEditor::highlightColourId, textHighlightColour,
  52311. TextEditor::highlightedTextColourId, 0xff000000,
  52312. TextEditor::caretColourId, 0xff000000,
  52313. TextEditor::outlineColourId, 0x00000000,
  52314. TextEditor::focusedOutlineColourId, textButtonColour,
  52315. TextEditor::shadowColourId, 0x38000000,
  52316. Label::backgroundColourId, 0x00000000,
  52317. Label::textColourId, 0xff000000,
  52318. Label::outlineColourId, 0x00000000,
  52319. ScrollBar::backgroundColourId, 0x00000000,
  52320. ScrollBar::thumbColourId, 0xffffffff,
  52321. TreeView::linesColourId, 0x4c000000,
  52322. TreeView::backgroundColourId, 0x00000000,
  52323. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52324. PopupMenu::backgroundColourId, 0xffffffff,
  52325. PopupMenu::textColourId, 0xff000000,
  52326. PopupMenu::headerTextColourId, 0xff000000,
  52327. PopupMenu::highlightedTextColourId, 0xffffffff,
  52328. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52329. ComboBox::textColourId, 0xff000000,
  52330. ComboBox::backgroundColourId, 0xffffffff,
  52331. ComboBox::arrowColourId, 0x99000000,
  52332. ListBox::backgroundColourId, 0xffffffff,
  52333. ListBox::outlineColourId, standardOutlineColour,
  52334. ListBox::textColourId, 0xff000000,
  52335. Slider::backgroundColourId, 0x00000000,
  52336. Slider::thumbColourId, textButtonColour,
  52337. Slider::trackColourId, 0x7fffffff,
  52338. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52339. Slider::rotarySliderOutlineColourId, 0x66000000,
  52340. Slider::textBoxTextColourId, 0xff000000,
  52341. Slider::textBoxBackgroundColourId, 0xffffffff,
  52342. Slider::textBoxHighlightColourId, textHighlightColour,
  52343. Slider::textBoxOutlineColourId, standardOutlineColour,
  52344. ResizableWindow::backgroundColourId, 0xff777777,
  52345. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52346. AlertWindow::backgroundColourId, 0xffededed,
  52347. AlertWindow::textColourId, 0xff000000,
  52348. AlertWindow::outlineColourId, 0xff666666,
  52349. ProgressBar::backgroundColourId, 0xffeeeeee,
  52350. ProgressBar::foregroundColourId, 0xffaaaaee,
  52351. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52352. TooltipWindow::textColourId, 0xff000000,
  52353. TooltipWindow::outlineColourId, 0x4c000000,
  52354. TabbedComponent::backgroundColourId, 0x00000000,
  52355. TabbedComponent::outlineColourId, 0xff777777,
  52356. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52357. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52358. Toolbar::backgroundColourId, 0xfff6f8f9,
  52359. Toolbar::separatorColourId, 0x4c000000,
  52360. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52361. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52362. Toolbar::labelTextColourId, 0xff000000,
  52363. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52364. HyperlinkButton::textColourId, 0xcc1111ee,
  52365. GroupComponent::outlineColourId, 0x66000000,
  52366. GroupComponent::textColourId, 0xff000000,
  52367. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52368. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52369. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52370. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52371. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52372. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52373. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52374. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52375. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52376. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52377. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52378. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52379. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52380. CodeEditorComponent::caretColourId, 0xff000000,
  52381. CodeEditorComponent::highlightColourId, textHighlightColour,
  52382. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52383. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52384. ColourSelector::labelTextColourId, 0xff000000,
  52385. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52386. KeyMappingEditorComponent::textColourId, 0xff000000,
  52387. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52388. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52389. DrawableButton::textColourId, 0xff000000,
  52390. };
  52391. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52392. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52393. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52394. if (defaultSansName.isEmpty())
  52395. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52396. defaultSans = defaultSansName;
  52397. defaultSerif = defaultSerifName;
  52398. defaultFixed = defaultFixedName;
  52399. Font::setFallbackFontName (defaultFallback);
  52400. }
  52401. LookAndFeel::~LookAndFeel()
  52402. {
  52403. if (this == LookAndFeelHelpers::currentDefaultLF)
  52404. setDefaultLookAndFeel (0);
  52405. }
  52406. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52407. {
  52408. const int index = colourIds.indexOf (colourId);
  52409. if (index >= 0)
  52410. return colours [index];
  52411. jassertfalse;
  52412. return Colours::black;
  52413. }
  52414. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52415. {
  52416. const int index = colourIds.indexOf (colourId);
  52417. if (index >= 0)
  52418. {
  52419. colours.set (index, colour);
  52420. }
  52421. else
  52422. {
  52423. colourIds.add (colourId);
  52424. colours.add (colour);
  52425. }
  52426. }
  52427. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52428. {
  52429. return colourIds.contains (colourId);
  52430. }
  52431. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52432. {
  52433. // if this happens, your app hasn't initialised itself properly.. if you're
  52434. // trying to hack your own main() function, have a look at
  52435. // JUCEApplication::initialiseForGUI()
  52436. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52437. return *LookAndFeelHelpers::currentDefaultLF;
  52438. }
  52439. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52440. {
  52441. using namespace LookAndFeelHelpers;
  52442. if (newDefaultLookAndFeel == 0)
  52443. {
  52444. if (defaultLF == 0)
  52445. defaultLF = new LookAndFeel();
  52446. newDefaultLookAndFeel = defaultLF;
  52447. }
  52448. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52449. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52450. {
  52451. Component* const c = Desktop::getInstance().getComponent (i);
  52452. if (c != 0)
  52453. c->sendLookAndFeelChange();
  52454. }
  52455. }
  52456. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52457. {
  52458. using namespace LookAndFeelHelpers;
  52459. if (currentDefaultLF == defaultLF)
  52460. currentDefaultLF = 0;
  52461. deleteAndZero (defaultLF);
  52462. }
  52463. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52464. {
  52465. String faceName (font.getTypefaceName());
  52466. if (faceName == Font::getDefaultSansSerifFontName())
  52467. faceName = defaultSans;
  52468. else if (faceName == Font::getDefaultSerifFontName())
  52469. faceName = defaultSerif;
  52470. else if (faceName == Font::getDefaultMonospacedFontName())
  52471. faceName = defaultFixed;
  52472. Font f (font);
  52473. f.setTypefaceName (faceName);
  52474. return Typeface::createSystemTypefaceFor (f);
  52475. }
  52476. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52477. {
  52478. defaultSans = newName;
  52479. }
  52480. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52481. {
  52482. return component.getMouseCursor();
  52483. }
  52484. void LookAndFeel::drawButtonBackground (Graphics& g,
  52485. Button& button,
  52486. const Colour& backgroundColour,
  52487. bool isMouseOverButton,
  52488. bool isButtonDown)
  52489. {
  52490. const int width = button.getWidth();
  52491. const int height = button.getHeight();
  52492. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52493. const float halfThickness = outlineThickness * 0.5f;
  52494. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52495. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52496. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52497. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52498. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52499. button.hasKeyboardFocus (true),
  52500. isMouseOverButton, isButtonDown)
  52501. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52502. drawGlassLozenge (g,
  52503. indentL,
  52504. indentT,
  52505. width - indentL - indentR,
  52506. height - indentT - indentB,
  52507. baseColour, outlineThickness, -1.0f,
  52508. button.isConnectedOnLeft(),
  52509. button.isConnectedOnRight(),
  52510. button.isConnectedOnTop(),
  52511. button.isConnectedOnBottom());
  52512. }
  52513. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52514. {
  52515. return button.getFont();
  52516. }
  52517. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52518. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52519. {
  52520. Font font (getFontForTextButton (button));
  52521. g.setFont (font);
  52522. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52523. : TextButton::textColourOffId)
  52524. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52525. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52526. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52527. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52528. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52529. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52530. g.drawFittedText (button.getButtonText(),
  52531. leftIndent,
  52532. yIndent,
  52533. button.getWidth() - leftIndent - rightIndent,
  52534. button.getHeight() - yIndent * 2,
  52535. Justification::centred, 2);
  52536. }
  52537. void LookAndFeel::drawTickBox (Graphics& g,
  52538. Component& component,
  52539. float x, float y, float w, float h,
  52540. const bool ticked,
  52541. const bool isEnabled,
  52542. const bool isMouseOverButton,
  52543. const bool isButtonDown)
  52544. {
  52545. const float boxSize = w * 0.7f;
  52546. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52547. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52548. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52549. true, isMouseOverButton, isButtonDown),
  52550. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52551. if (ticked)
  52552. {
  52553. Path tick;
  52554. tick.startNewSubPath (1.5f, 3.0f);
  52555. tick.lineTo (3.0f, 6.0f);
  52556. tick.lineTo (6.0f, 0.0f);
  52557. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52558. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52559. .translated (x, y));
  52560. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52561. }
  52562. }
  52563. void LookAndFeel::drawToggleButton (Graphics& g,
  52564. ToggleButton& button,
  52565. bool isMouseOverButton,
  52566. bool isButtonDown)
  52567. {
  52568. if (button.hasKeyboardFocus (true))
  52569. {
  52570. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52571. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52572. }
  52573. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52574. const float tickWidth = fontSize * 1.1f;
  52575. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52576. tickWidth, tickWidth,
  52577. button.getToggleState(),
  52578. button.isEnabled(),
  52579. isMouseOverButton,
  52580. isButtonDown);
  52581. g.setColour (button.findColour (ToggleButton::textColourId));
  52582. g.setFont (fontSize);
  52583. if (! button.isEnabled())
  52584. g.setOpacity (0.5f);
  52585. const int textX = (int) tickWidth + 5;
  52586. g.drawFittedText (button.getButtonText(),
  52587. textX, 0,
  52588. button.getWidth() - textX - 2, button.getHeight(),
  52589. Justification::centredLeft, 10);
  52590. }
  52591. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52592. {
  52593. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52594. const int tickWidth = jmin (24, button.getHeight());
  52595. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52596. button.getHeight());
  52597. }
  52598. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52599. const String& message,
  52600. const String& button1,
  52601. const String& button2,
  52602. const String& button3,
  52603. AlertWindow::AlertIconType iconType,
  52604. int numButtons,
  52605. Component* associatedComponent)
  52606. {
  52607. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52608. if (numButtons == 1)
  52609. {
  52610. aw->addButton (button1, 0,
  52611. KeyPress (KeyPress::escapeKey, 0, 0),
  52612. KeyPress (KeyPress::returnKey, 0, 0));
  52613. }
  52614. else
  52615. {
  52616. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52617. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52618. if (button1ShortCut == button2ShortCut)
  52619. button2ShortCut = KeyPress();
  52620. if (numButtons == 2)
  52621. {
  52622. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52623. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52624. }
  52625. else if (numButtons == 3)
  52626. {
  52627. aw->addButton (button1, 1, button1ShortCut);
  52628. aw->addButton (button2, 2, button2ShortCut);
  52629. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52630. }
  52631. }
  52632. return aw;
  52633. }
  52634. void LookAndFeel::drawAlertBox (Graphics& g,
  52635. AlertWindow& alert,
  52636. const Rectangle<int>& textArea,
  52637. TextLayout& textLayout)
  52638. {
  52639. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52640. int iconSpaceUsed = 0;
  52641. Justification alignment (Justification::horizontallyCentred);
  52642. const int iconWidth = 80;
  52643. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52644. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52645. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52646. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52647. iconSize, iconSize);
  52648. if (alert.getAlertType() != AlertWindow::NoIcon)
  52649. {
  52650. Path icon;
  52651. uint32 colour;
  52652. char character;
  52653. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52654. {
  52655. colour = 0x55ff5555;
  52656. character = '!';
  52657. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52658. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52659. (float) iconRect.getX(), (float) iconRect.getBottom());
  52660. icon = icon.createPathWithRoundedCorners (5.0f);
  52661. }
  52662. else
  52663. {
  52664. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52665. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52666. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52667. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52668. }
  52669. GlyphArrangement ga;
  52670. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52671. String::charToString (character),
  52672. (float) iconRect.getX(), (float) iconRect.getY(),
  52673. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52674. Justification::centred, false);
  52675. ga.createPath (icon);
  52676. icon.setUsingNonZeroWinding (false);
  52677. g.setColour (Colour (colour));
  52678. g.fillPath (icon);
  52679. iconSpaceUsed = iconWidth;
  52680. alignment = Justification::left;
  52681. }
  52682. g.setColour (alert.findColour (AlertWindow::textColourId));
  52683. textLayout.drawWithin (g,
  52684. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52685. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52686. alignment.getFlags() | Justification::top);
  52687. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52688. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52689. }
  52690. int LookAndFeel::getAlertBoxWindowFlags()
  52691. {
  52692. return ComponentPeer::windowAppearsOnTaskbar
  52693. | ComponentPeer::windowHasDropShadow;
  52694. }
  52695. int LookAndFeel::getAlertWindowButtonHeight()
  52696. {
  52697. return 28;
  52698. }
  52699. const Font LookAndFeel::getAlertWindowMessageFont()
  52700. {
  52701. return Font (15.0f);
  52702. }
  52703. const Font LookAndFeel::getAlertWindowFont()
  52704. {
  52705. return Font (12.0f);
  52706. }
  52707. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52708. int width, int height,
  52709. double progress, const String& textToShow)
  52710. {
  52711. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52712. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52713. g.fillAll (background);
  52714. if (progress >= 0.0f && progress < 1.0f)
  52715. {
  52716. drawGlassLozenge (g, 1.0f, 1.0f,
  52717. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52718. (float) (height - 2),
  52719. foreground,
  52720. 0.5f, 0.0f,
  52721. true, true, true, true);
  52722. }
  52723. else
  52724. {
  52725. // spinning bar..
  52726. g.setColour (foreground);
  52727. const int stripeWidth = height * 2;
  52728. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52729. Path p;
  52730. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52731. p.addQuadrilateral (x, 0.0f,
  52732. x + stripeWidth * 0.5f, 0.0f,
  52733. x, (float) height,
  52734. x - stripeWidth * 0.5f, (float) height);
  52735. Image im (Image::ARGB, width, height, true);
  52736. {
  52737. Graphics g2 (im);
  52738. drawGlassLozenge (g2, 1.0f, 1.0f,
  52739. (float) (width - 2),
  52740. (float) (height - 2),
  52741. foreground,
  52742. 0.5f, 0.0f,
  52743. true, true, true, true);
  52744. }
  52745. g.setTiledImageFill (im, 0, 0, 0.85f);
  52746. g.fillPath (p);
  52747. }
  52748. if (textToShow.isNotEmpty())
  52749. {
  52750. g.setColour (Colour::contrasting (background, foreground));
  52751. g.setFont (height * 0.6f);
  52752. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52753. }
  52754. }
  52755. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52756. {
  52757. const float radius = jmin (w, h) * 0.4f;
  52758. const float thickness = radius * 0.15f;
  52759. Path p;
  52760. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52761. radius * 0.6f, thickness,
  52762. thickness * 0.5f);
  52763. const float cx = x + w * 0.5f;
  52764. const float cy = y + h * 0.5f;
  52765. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52766. for (int i = 0; i < 12; ++i)
  52767. {
  52768. const int n = (i + 12 - animationIndex) % 12;
  52769. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52770. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52771. .translated (cx, cy));
  52772. }
  52773. }
  52774. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52775. ScrollBar& scrollbar,
  52776. int width, int height,
  52777. int buttonDirection,
  52778. bool /*isScrollbarVertical*/,
  52779. bool /*isMouseOverButton*/,
  52780. bool isButtonDown)
  52781. {
  52782. Path p;
  52783. if (buttonDirection == 0)
  52784. p.addTriangle (width * 0.5f, height * 0.2f,
  52785. width * 0.1f, height * 0.7f,
  52786. width * 0.9f, height * 0.7f);
  52787. else if (buttonDirection == 1)
  52788. p.addTriangle (width * 0.8f, height * 0.5f,
  52789. width * 0.3f, height * 0.1f,
  52790. width * 0.3f, height * 0.9f);
  52791. else if (buttonDirection == 2)
  52792. p.addTriangle (width * 0.5f, height * 0.8f,
  52793. width * 0.1f, height * 0.3f,
  52794. width * 0.9f, height * 0.3f);
  52795. else if (buttonDirection == 3)
  52796. p.addTriangle (width * 0.2f, height * 0.5f,
  52797. width * 0.7f, height * 0.1f,
  52798. width * 0.7f, height * 0.9f);
  52799. if (isButtonDown)
  52800. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52801. else
  52802. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52803. g.fillPath (p);
  52804. g.setColour (Colour (0x80000000));
  52805. g.strokePath (p, PathStrokeType (0.5f));
  52806. }
  52807. void LookAndFeel::drawScrollbar (Graphics& g,
  52808. ScrollBar& scrollbar,
  52809. int x, int y,
  52810. int width, int height,
  52811. bool isScrollbarVertical,
  52812. int thumbStartPosition,
  52813. int thumbSize,
  52814. bool /*isMouseOver*/,
  52815. bool /*isMouseDown*/)
  52816. {
  52817. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52818. Path slotPath, thumbPath;
  52819. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52820. const float slotIndentx2 = slotIndent * 2.0f;
  52821. const float thumbIndent = slotIndent + 1.0f;
  52822. const float thumbIndentx2 = thumbIndent * 2.0f;
  52823. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52824. if (isScrollbarVertical)
  52825. {
  52826. slotPath.addRoundedRectangle (x + slotIndent,
  52827. y + slotIndent,
  52828. width - slotIndentx2,
  52829. height - slotIndentx2,
  52830. (width - slotIndentx2) * 0.5f);
  52831. if (thumbSize > 0)
  52832. thumbPath.addRoundedRectangle (x + thumbIndent,
  52833. thumbStartPosition + thumbIndent,
  52834. width - thumbIndentx2,
  52835. thumbSize - thumbIndentx2,
  52836. (width - thumbIndentx2) * 0.5f);
  52837. gx1 = (float) x;
  52838. gx2 = x + width * 0.7f;
  52839. }
  52840. else
  52841. {
  52842. slotPath.addRoundedRectangle (x + slotIndent,
  52843. y + slotIndent,
  52844. width - slotIndentx2,
  52845. height - slotIndentx2,
  52846. (height - slotIndentx2) * 0.5f);
  52847. if (thumbSize > 0)
  52848. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52849. y + thumbIndent,
  52850. thumbSize - thumbIndentx2,
  52851. height - thumbIndentx2,
  52852. (height - thumbIndentx2) * 0.5f);
  52853. gy1 = (float) y;
  52854. gy2 = y + height * 0.7f;
  52855. }
  52856. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52857. Colour trackColour1, trackColour2;
  52858. if (scrollbar.isColourSpecified (ScrollBar::trackColourId))
  52859. {
  52860. trackColour1 = trackColour2 = scrollbar.findColour (ScrollBar::trackColourId);
  52861. }
  52862. else
  52863. {
  52864. trackColour1 = thumbColour.overlaidWith (Colour (0x44000000));
  52865. trackColour2 = thumbColour.overlaidWith (Colour (0x19000000));
  52866. }
  52867. g.setGradientFill (ColourGradient (trackColour1, gx1, gy1,
  52868. trackColour2, gx2, gy2, false));
  52869. g.fillPath (slotPath);
  52870. if (isScrollbarVertical)
  52871. {
  52872. gx1 = x + width * 0.6f;
  52873. gx2 = (float) x + width;
  52874. }
  52875. else
  52876. {
  52877. gy1 = y + height * 0.6f;
  52878. gy2 = (float) y + height;
  52879. }
  52880. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52881. Colour (0x19000000), gx2, gy2, false));
  52882. g.fillPath (slotPath);
  52883. g.setColour (thumbColour);
  52884. g.fillPath (thumbPath);
  52885. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52886. Colours::transparentBlack, gx2, gy2, false));
  52887. g.saveState();
  52888. if (isScrollbarVertical)
  52889. g.reduceClipRegion (x + width / 2, y, width, height);
  52890. else
  52891. g.reduceClipRegion (x, y + height / 2, width, height);
  52892. g.fillPath (thumbPath);
  52893. g.restoreState();
  52894. g.setColour (Colour (0x4c000000));
  52895. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52896. }
  52897. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52898. {
  52899. return 0;
  52900. }
  52901. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52902. {
  52903. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52904. }
  52905. int LookAndFeel::getDefaultScrollbarWidth()
  52906. {
  52907. return 18;
  52908. }
  52909. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52910. {
  52911. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52912. : scrollbar.getHeight());
  52913. }
  52914. const Path LookAndFeel::getTickShape (const float height)
  52915. {
  52916. static const unsigned char tickShapeData[] =
  52917. {
  52918. 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,
  52919. 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,
  52920. 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,
  52921. 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,
  52922. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52923. };
  52924. Path p;
  52925. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52926. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52927. return p;
  52928. }
  52929. const Path LookAndFeel::getCrossShape (const float height)
  52930. {
  52931. static const unsigned char crossShapeData[] =
  52932. {
  52933. 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,
  52934. 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,
  52935. 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,
  52936. 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,
  52937. 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,
  52938. 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,
  52939. 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
  52940. };
  52941. Path p;
  52942. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52943. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52944. return p;
  52945. }
  52946. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52947. {
  52948. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52949. x += (w - boxSize) >> 1;
  52950. y += (h - boxSize) >> 1;
  52951. w = boxSize;
  52952. h = boxSize;
  52953. g.setColour (Colour (0xe5ffffff));
  52954. g.fillRect (x, y, w, h);
  52955. g.setColour (Colour (0x80000000));
  52956. g.drawRect (x, y, w, h);
  52957. const float size = boxSize / 2 + 1.0f;
  52958. const float centre = (float) (boxSize / 2);
  52959. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52960. if (isPlus)
  52961. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52962. }
  52963. void LookAndFeel::drawBubble (Graphics& g,
  52964. float tipX, float tipY,
  52965. float boxX, float boxY,
  52966. float boxW, float boxH)
  52967. {
  52968. int side = 0;
  52969. if (tipX < boxX)
  52970. side = 1;
  52971. else if (tipX > boxX + boxW)
  52972. side = 3;
  52973. else if (tipY > boxY + boxH)
  52974. side = 2;
  52975. const float indent = 2.0f;
  52976. Path p;
  52977. p.addBubble (boxX + indent,
  52978. boxY + indent,
  52979. boxW - indent * 2.0f,
  52980. boxH - indent * 2.0f,
  52981. 5.0f,
  52982. tipX, tipY,
  52983. side,
  52984. 0.5f,
  52985. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52986. //xxx need to take comp as param for colour
  52987. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52988. g.fillPath (p);
  52989. //xxx as above
  52990. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52991. g.strokePath (p, PathStrokeType (1.33f));
  52992. }
  52993. const Font LookAndFeel::getPopupMenuFont()
  52994. {
  52995. return Font (17.0f);
  52996. }
  52997. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52998. const bool isSeparator,
  52999. int standardMenuItemHeight,
  53000. int& idealWidth,
  53001. int& idealHeight)
  53002. {
  53003. if (isSeparator)
  53004. {
  53005. idealWidth = 50;
  53006. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53007. }
  53008. else
  53009. {
  53010. Font font (getPopupMenuFont());
  53011. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53012. font.setHeight (standardMenuItemHeight / 1.3f);
  53013. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53014. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53015. }
  53016. }
  53017. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53018. {
  53019. const Colour background (findColour (PopupMenu::backgroundColourId));
  53020. g.fillAll (background);
  53021. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53022. for (int i = 0; i < height; i += 3)
  53023. g.fillRect (0, i, width, 1);
  53024. #if ! JUCE_MAC
  53025. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53026. g.drawRect (0, 0, width, height);
  53027. #endif
  53028. }
  53029. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53030. int width, int height,
  53031. bool isScrollUpArrow)
  53032. {
  53033. const Colour background (findColour (PopupMenu::backgroundColourId));
  53034. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53035. background.withAlpha (0.0f),
  53036. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53037. false));
  53038. g.fillRect (1, 1, width - 2, height - 2);
  53039. const float hw = width * 0.5f;
  53040. const float arrowW = height * 0.3f;
  53041. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53042. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53043. Path p;
  53044. p.addTriangle (hw - arrowW, y1,
  53045. hw + arrowW, y1,
  53046. hw, y2);
  53047. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53048. g.fillPath (p);
  53049. }
  53050. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53051. int width, int height,
  53052. const bool isSeparator,
  53053. const bool isActive,
  53054. const bool isHighlighted,
  53055. const bool isTicked,
  53056. const bool hasSubMenu,
  53057. const String& text,
  53058. const String& shortcutKeyText,
  53059. Image* image,
  53060. const Colour* const textColourToUse)
  53061. {
  53062. const float halfH = height * 0.5f;
  53063. if (isSeparator)
  53064. {
  53065. const float separatorIndent = 5.5f;
  53066. g.setColour (Colour (0x33000000));
  53067. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53068. g.setColour (Colour (0x66ffffff));
  53069. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53070. }
  53071. else
  53072. {
  53073. Colour textColour (findColour (PopupMenu::textColourId));
  53074. if (textColourToUse != 0)
  53075. textColour = *textColourToUse;
  53076. if (isHighlighted)
  53077. {
  53078. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53079. g.fillRect (1, 1, width - 2, height - 2);
  53080. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53081. }
  53082. else
  53083. {
  53084. g.setColour (textColour);
  53085. }
  53086. if (! isActive)
  53087. g.setOpacity (0.3f);
  53088. Font font (getPopupMenuFont());
  53089. if (font.getHeight() > height / 1.3f)
  53090. font.setHeight (height / 1.3f);
  53091. g.setFont (font);
  53092. const int leftBorder = (height * 5) / 4;
  53093. const int rightBorder = 4;
  53094. if (image != 0)
  53095. {
  53096. g.drawImageWithin (*image,
  53097. 2, 1, leftBorder - 4, height - 2,
  53098. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53099. }
  53100. else if (isTicked)
  53101. {
  53102. const Path tick (getTickShape (1.0f));
  53103. const float th = font.getAscent();
  53104. const float ty = halfH - th * 0.5f;
  53105. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53106. th, true));
  53107. }
  53108. g.drawFittedText (text,
  53109. leftBorder, 0,
  53110. width - (leftBorder + rightBorder), height,
  53111. Justification::centredLeft, 1);
  53112. if (shortcutKeyText.isNotEmpty())
  53113. {
  53114. Font f2 (font);
  53115. f2.setHeight (f2.getHeight() * 0.75f);
  53116. f2.setHorizontalScale (0.95f);
  53117. g.setFont (f2);
  53118. g.drawText (shortcutKeyText,
  53119. leftBorder,
  53120. 0,
  53121. width - (leftBorder + rightBorder + 4),
  53122. height,
  53123. Justification::centredRight,
  53124. true);
  53125. }
  53126. if (hasSubMenu)
  53127. {
  53128. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53129. const float x = width - height * 0.6f;
  53130. Path p;
  53131. p.addTriangle (x, halfH - arrowH * 0.5f,
  53132. x, halfH + arrowH * 0.5f,
  53133. x + arrowH * 0.6f, halfH);
  53134. g.fillPath (p);
  53135. }
  53136. }
  53137. }
  53138. int LookAndFeel::getMenuWindowFlags()
  53139. {
  53140. return ComponentPeer::windowHasDropShadow;
  53141. }
  53142. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53143. bool, MenuBarComponent& menuBar)
  53144. {
  53145. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53146. if (menuBar.isEnabled())
  53147. {
  53148. drawShinyButtonShape (g,
  53149. -4.0f, 0.0f,
  53150. width + 8.0f, (float) height,
  53151. 0.0f,
  53152. baseColour,
  53153. 0.4f,
  53154. true, true, true, true);
  53155. }
  53156. else
  53157. {
  53158. g.fillAll (baseColour);
  53159. }
  53160. }
  53161. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53162. {
  53163. return Font (menuBar.getHeight() * 0.7f);
  53164. }
  53165. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53166. {
  53167. return getMenuBarFont (menuBar, itemIndex, itemText)
  53168. .getStringWidth (itemText) + menuBar.getHeight();
  53169. }
  53170. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53171. int width, int height,
  53172. int itemIndex,
  53173. const String& itemText,
  53174. bool isMouseOverItem,
  53175. bool isMenuOpen,
  53176. bool /*isMouseOverBar*/,
  53177. MenuBarComponent& menuBar)
  53178. {
  53179. if (! menuBar.isEnabled())
  53180. {
  53181. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53182. .withMultipliedAlpha (0.5f));
  53183. }
  53184. else if (isMenuOpen || isMouseOverItem)
  53185. {
  53186. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53187. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53188. }
  53189. else
  53190. {
  53191. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53192. }
  53193. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53194. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53195. }
  53196. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53197. TextEditor& textEditor)
  53198. {
  53199. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53200. }
  53201. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53202. {
  53203. if (textEditor.isEnabled())
  53204. {
  53205. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53206. {
  53207. const int border = 2;
  53208. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53209. g.drawRect (0, 0, width, height, border);
  53210. g.setOpacity (1.0f);
  53211. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53212. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53213. }
  53214. else
  53215. {
  53216. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53217. g.drawRect (0, 0, width, height);
  53218. g.setOpacity (1.0f);
  53219. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53220. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53221. }
  53222. }
  53223. }
  53224. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53225. const bool isButtonDown,
  53226. int buttonX, int buttonY,
  53227. int buttonW, int buttonH,
  53228. ComboBox& box)
  53229. {
  53230. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53231. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53232. {
  53233. g.setColour (box.findColour (TextButton::buttonColourId));
  53234. g.drawRect (0, 0, width, height, 2);
  53235. }
  53236. else
  53237. {
  53238. g.setColour (box.findColour (ComboBox::outlineColourId));
  53239. g.drawRect (0, 0, width, height);
  53240. }
  53241. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53242. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53243. box.hasKeyboardFocus (true),
  53244. false, isButtonDown)
  53245. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53246. drawGlassLozenge (g,
  53247. buttonX + outlineThickness, buttonY + outlineThickness,
  53248. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53249. baseColour, outlineThickness, -1.0f,
  53250. true, true, true, true);
  53251. if (box.isEnabled())
  53252. {
  53253. const float arrowX = 0.3f;
  53254. const float arrowH = 0.2f;
  53255. Path p;
  53256. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53257. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53258. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53259. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53260. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53261. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53262. g.setColour (box.findColour (ComboBox::arrowColourId));
  53263. g.fillPath (p);
  53264. }
  53265. }
  53266. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53267. {
  53268. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53269. }
  53270. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53271. {
  53272. return new Label (String::empty, String::empty);
  53273. }
  53274. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53275. {
  53276. label.setBounds (1, 1,
  53277. box.getWidth() + 3 - box.getHeight(),
  53278. box.getHeight() - 2);
  53279. label.setFont (getComboBoxFont (box));
  53280. }
  53281. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53282. {
  53283. g.fillAll (label.findColour (Label::backgroundColourId));
  53284. if (! label.isBeingEdited())
  53285. {
  53286. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53287. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53288. g.setFont (label.getFont());
  53289. g.drawFittedText (label.getText(),
  53290. label.getHorizontalBorderSize(),
  53291. label.getVerticalBorderSize(),
  53292. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53293. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53294. label.getJustificationType(),
  53295. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53296. label.getMinimumHorizontalScale());
  53297. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53298. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53299. }
  53300. else if (label.isEnabled())
  53301. {
  53302. g.setColour (label.findColour (Label::outlineColourId));
  53303. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53304. }
  53305. }
  53306. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53307. int x, int y,
  53308. int width, int height,
  53309. float /*sliderPos*/,
  53310. float /*minSliderPos*/,
  53311. float /*maxSliderPos*/,
  53312. const Slider::SliderStyle /*style*/,
  53313. Slider& slider)
  53314. {
  53315. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53316. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53317. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53318. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53319. Path indent;
  53320. if (slider.isHorizontal())
  53321. {
  53322. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53323. const float ih = sliderRadius;
  53324. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53325. gradCol2, 0.0f, iy + ih, false));
  53326. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53327. width + sliderRadius, ih,
  53328. 5.0f);
  53329. g.fillPath (indent);
  53330. }
  53331. else
  53332. {
  53333. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53334. const float iw = sliderRadius;
  53335. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53336. gradCol2, ix + iw, 0.0f, false));
  53337. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53338. iw, height + sliderRadius,
  53339. 5.0f);
  53340. g.fillPath (indent);
  53341. }
  53342. g.setColour (Colour (0x4c000000));
  53343. g.strokePath (indent, PathStrokeType (0.5f));
  53344. }
  53345. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53346. int x, int y,
  53347. int width, int height,
  53348. float sliderPos,
  53349. float minSliderPos,
  53350. float maxSliderPos,
  53351. const Slider::SliderStyle style,
  53352. Slider& slider)
  53353. {
  53354. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53355. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53356. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53357. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53358. slider.isMouseButtonDown() && slider.isEnabled()));
  53359. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53360. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53361. {
  53362. float kx, ky;
  53363. if (style == Slider::LinearVertical)
  53364. {
  53365. kx = x + width * 0.5f;
  53366. ky = sliderPos;
  53367. }
  53368. else
  53369. {
  53370. kx = sliderPos;
  53371. ky = y + height * 0.5f;
  53372. }
  53373. drawGlassSphere (g,
  53374. kx - sliderRadius,
  53375. ky - sliderRadius,
  53376. sliderRadius * 2.0f,
  53377. knobColour, outlineThickness);
  53378. }
  53379. else
  53380. {
  53381. if (style == Slider::ThreeValueVertical)
  53382. {
  53383. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53384. sliderPos - sliderRadius,
  53385. sliderRadius * 2.0f,
  53386. knobColour, outlineThickness);
  53387. }
  53388. else if (style == Slider::ThreeValueHorizontal)
  53389. {
  53390. drawGlassSphere (g,sliderPos - sliderRadius,
  53391. y + height * 0.5f - sliderRadius,
  53392. sliderRadius * 2.0f,
  53393. knobColour, outlineThickness);
  53394. }
  53395. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53396. {
  53397. const float sr = jmin (sliderRadius, width * 0.4f);
  53398. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53399. minSliderPos - sliderRadius,
  53400. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53401. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53402. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53403. }
  53404. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53405. {
  53406. const float sr = jmin (sliderRadius, height * 0.4f);
  53407. drawGlassPointer (g, minSliderPos - sr,
  53408. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53409. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53410. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53411. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53412. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53413. }
  53414. }
  53415. }
  53416. void LookAndFeel::drawLinearSlider (Graphics& g,
  53417. int x, int y,
  53418. int width, int height,
  53419. float sliderPos,
  53420. float minSliderPos,
  53421. float maxSliderPos,
  53422. const Slider::SliderStyle style,
  53423. Slider& slider)
  53424. {
  53425. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53426. if (style == Slider::LinearBar)
  53427. {
  53428. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53429. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53430. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53431. false, isMouseOver,
  53432. isMouseOver || slider.isMouseButtonDown()));
  53433. drawShinyButtonShape (g,
  53434. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53435. baseColour,
  53436. slider.isEnabled() ? 0.9f : 0.3f,
  53437. true, true, true, true);
  53438. }
  53439. else
  53440. {
  53441. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53442. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53443. }
  53444. }
  53445. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53446. {
  53447. return jmin (7,
  53448. slider.getHeight() / 2,
  53449. slider.getWidth() / 2) + 2;
  53450. }
  53451. void LookAndFeel::drawRotarySlider (Graphics& g,
  53452. int x, int y,
  53453. int width, int height,
  53454. float sliderPos,
  53455. const float rotaryStartAngle,
  53456. const float rotaryEndAngle,
  53457. Slider& slider)
  53458. {
  53459. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53460. const float centreX = x + width * 0.5f;
  53461. const float centreY = y + height * 0.5f;
  53462. const float rx = centreX - radius;
  53463. const float ry = centreY - radius;
  53464. const float rw = radius * 2.0f;
  53465. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53466. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53467. if (radius > 12.0f)
  53468. {
  53469. if (slider.isEnabled())
  53470. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53471. else
  53472. g.setColour (Colour (0x80808080));
  53473. const float thickness = 0.7f;
  53474. {
  53475. Path filledArc;
  53476. filledArc.addPieSegment (rx, ry, rw, rw,
  53477. rotaryStartAngle,
  53478. angle,
  53479. thickness);
  53480. g.fillPath (filledArc);
  53481. }
  53482. if (thickness > 0)
  53483. {
  53484. const float innerRadius = radius * 0.2f;
  53485. Path p;
  53486. p.addTriangle (-innerRadius, 0.0f,
  53487. 0.0f, -radius * thickness * 1.1f,
  53488. innerRadius, 0.0f);
  53489. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53490. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53491. }
  53492. if (slider.isEnabled())
  53493. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53494. else
  53495. g.setColour (Colour (0x80808080));
  53496. Path outlineArc;
  53497. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53498. outlineArc.closeSubPath();
  53499. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53500. }
  53501. else
  53502. {
  53503. if (slider.isEnabled())
  53504. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53505. else
  53506. g.setColour (Colour (0x80808080));
  53507. Path p;
  53508. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53509. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53510. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53511. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53512. }
  53513. }
  53514. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53515. {
  53516. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53517. }
  53518. class SliderLabelComp : public Label
  53519. {
  53520. public:
  53521. SliderLabelComp() : Label (String::empty, String::empty) {}
  53522. ~SliderLabelComp() {}
  53523. void mouseWheelMove (const MouseEvent&, float, float) {}
  53524. };
  53525. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53526. {
  53527. Label* const l = new SliderLabelComp();
  53528. l->setJustificationType (Justification::centred);
  53529. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53530. l->setColour (Label::backgroundColourId,
  53531. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53532. : slider.findColour (Slider::textBoxBackgroundColourId));
  53533. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53534. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53535. l->setColour (TextEditor::backgroundColourId,
  53536. slider.findColour (Slider::textBoxBackgroundColourId)
  53537. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53538. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53539. return l;
  53540. }
  53541. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53542. {
  53543. return 0;
  53544. }
  53545. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53546. {
  53547. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53548. width = tl.getWidth() + 14;
  53549. height = tl.getHeight() + 6;
  53550. }
  53551. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53552. {
  53553. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53554. const Colour textCol (findColour (TooltipWindow::textColourId));
  53555. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53556. g.setColour (findColour (TooltipWindow::outlineColourId));
  53557. g.drawRect (0, 0, width, height, 1);
  53558. #endif
  53559. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53560. g.setColour (findColour (TooltipWindow::textColourId));
  53561. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53562. }
  53563. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53564. {
  53565. return new TextButton (text, TRANS("click to browse for a different file"));
  53566. }
  53567. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53568. ComboBox* filenameBox,
  53569. Button* browseButton)
  53570. {
  53571. browseButton->setSize (80, filenameComp.getHeight());
  53572. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53573. if (tb != 0)
  53574. tb->changeWidthToFitText();
  53575. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53576. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53577. }
  53578. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53579. int imageX, int imageY, int imageW, int imageH,
  53580. const Colour& overlayColour,
  53581. float imageOpacity,
  53582. ImageButton& button)
  53583. {
  53584. if (! button.isEnabled())
  53585. imageOpacity *= 0.3f;
  53586. if (! overlayColour.isOpaque())
  53587. {
  53588. g.setOpacity (imageOpacity);
  53589. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53590. 0, 0, image->getWidth(), image->getHeight(), false);
  53591. }
  53592. if (! overlayColour.isTransparent())
  53593. {
  53594. g.setColour (overlayColour);
  53595. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53596. 0, 0, image->getWidth(), image->getHeight(), true);
  53597. }
  53598. }
  53599. void LookAndFeel::drawCornerResizer (Graphics& g,
  53600. int w, int h,
  53601. bool /*isMouseOver*/,
  53602. bool /*isMouseDragging*/)
  53603. {
  53604. const float lineThickness = jmin (w, h) * 0.075f;
  53605. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53606. {
  53607. g.setColour (Colours::lightgrey);
  53608. g.drawLine (w * i,
  53609. h + 1.0f,
  53610. w + 1.0f,
  53611. h * i,
  53612. lineThickness);
  53613. g.setColour (Colours::darkgrey);
  53614. g.drawLine (w * i + lineThickness,
  53615. h + 1.0f,
  53616. w + 1.0f,
  53617. h * i + lineThickness,
  53618. lineThickness);
  53619. }
  53620. }
  53621. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize<int>& border)
  53622. {
  53623. if (! border.isEmpty())
  53624. {
  53625. const Rectangle<int> fullSize (0, 0, w, h);
  53626. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53627. g.saveState();
  53628. g.excludeClipRegion (centreArea);
  53629. g.setColour (Colour (0x50000000));
  53630. g.drawRect (fullSize);
  53631. g.setColour (Colour (0x19000000));
  53632. g.drawRect (centreArea.expanded (1, 1));
  53633. g.restoreState();
  53634. }
  53635. }
  53636. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53637. const BorderSize<int>& /*border*/, ResizableWindow& window)
  53638. {
  53639. g.fillAll (window.getBackgroundColour());
  53640. }
  53641. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53642. const BorderSize<int>& /*border*/, ResizableWindow&)
  53643. {
  53644. }
  53645. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53646. Graphics& g, int w, int h,
  53647. int titleSpaceX, int titleSpaceW,
  53648. const Image* icon,
  53649. bool drawTitleTextOnLeft)
  53650. {
  53651. const bool isActive = window.isActiveWindow();
  53652. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53653. 0.0f, 0.0f,
  53654. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53655. 0.0f, (float) h, false));
  53656. g.fillAll();
  53657. Font font (h * 0.65f, Font::bold);
  53658. g.setFont (font);
  53659. int textW = font.getStringWidth (window.getName());
  53660. int iconW = 0;
  53661. int iconH = 0;
  53662. if (icon != 0)
  53663. {
  53664. iconH = (int) font.getHeight();
  53665. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53666. }
  53667. textW = jmin (titleSpaceW, textW + iconW);
  53668. int textX = drawTitleTextOnLeft ? titleSpaceX
  53669. : jmax (titleSpaceX, (w - textW) / 2);
  53670. if (textX + textW > titleSpaceX + titleSpaceW)
  53671. textX = titleSpaceX + titleSpaceW - textW;
  53672. if (icon != 0)
  53673. {
  53674. g.setOpacity (isActive ? 1.0f : 0.6f);
  53675. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53676. RectanglePlacement::centred, false);
  53677. textX += iconW;
  53678. textW -= iconW;
  53679. }
  53680. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53681. g.setColour (findColour (DocumentWindow::textColourId));
  53682. else
  53683. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53684. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53685. }
  53686. class GlassWindowButton : public Button
  53687. {
  53688. public:
  53689. GlassWindowButton (const String& name, const Colour& col,
  53690. const Path& normalShape_,
  53691. const Path& toggledShape_) throw()
  53692. : Button (name),
  53693. colour (col),
  53694. normalShape (normalShape_),
  53695. toggledShape (toggledShape_)
  53696. {
  53697. }
  53698. ~GlassWindowButton()
  53699. {
  53700. }
  53701. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53702. {
  53703. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53704. if (! isEnabled())
  53705. alpha *= 0.5f;
  53706. float x = 0, y = 0, diam;
  53707. if (getWidth() < getHeight())
  53708. {
  53709. diam = (float) getWidth();
  53710. y = (getHeight() - getWidth()) * 0.5f;
  53711. }
  53712. else
  53713. {
  53714. diam = (float) getHeight();
  53715. y = (getWidth() - getHeight()) * 0.5f;
  53716. }
  53717. x += diam * 0.05f;
  53718. y += diam * 0.05f;
  53719. diam *= 0.9f;
  53720. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53721. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53722. g.fillEllipse (x, y, diam, diam);
  53723. x += 2.0f;
  53724. y += 2.0f;
  53725. diam -= 4.0f;
  53726. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53727. Path& p = getToggleState() ? toggledShape : normalShape;
  53728. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53729. diam * 0.4f, diam * 0.4f, true));
  53730. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53731. g.fillPath (p, t);
  53732. }
  53733. private:
  53734. Colour colour;
  53735. Path normalShape, toggledShape;
  53736. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53737. };
  53738. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53739. {
  53740. Path shape;
  53741. const float crossThickness = 0.25f;
  53742. if (buttonType == DocumentWindow::closeButton)
  53743. {
  53744. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53745. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53746. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53747. }
  53748. else if (buttonType == DocumentWindow::minimiseButton)
  53749. {
  53750. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53751. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53752. }
  53753. else if (buttonType == DocumentWindow::maximiseButton)
  53754. {
  53755. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53756. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53757. Path fullscreenShape;
  53758. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53759. fullscreenShape.lineTo (0.0f, 100.0f);
  53760. fullscreenShape.lineTo (0.0f, 0.0f);
  53761. fullscreenShape.lineTo (100.0f, 0.0f);
  53762. fullscreenShape.lineTo (100.0f, 45.0f);
  53763. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53764. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53765. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53766. }
  53767. jassertfalse;
  53768. return 0;
  53769. }
  53770. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53771. int titleBarX,
  53772. int titleBarY,
  53773. int titleBarW,
  53774. int titleBarH,
  53775. Button* minimiseButton,
  53776. Button* maximiseButton,
  53777. Button* closeButton,
  53778. bool positionTitleBarButtonsOnLeft)
  53779. {
  53780. const int buttonW = titleBarH - titleBarH / 8;
  53781. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53782. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53783. if (closeButton != 0)
  53784. {
  53785. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53786. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53787. }
  53788. if (positionTitleBarButtonsOnLeft)
  53789. swapVariables (minimiseButton, maximiseButton);
  53790. if (maximiseButton != 0)
  53791. {
  53792. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53793. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53794. }
  53795. if (minimiseButton != 0)
  53796. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53797. }
  53798. int LookAndFeel::getDefaultMenuBarHeight()
  53799. {
  53800. return 24;
  53801. }
  53802. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53803. {
  53804. return new DropShadower (0.4f, 1, 5, 10);
  53805. }
  53806. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53807. int w, int h,
  53808. bool /*isVerticalBar*/,
  53809. bool isMouseOver,
  53810. bool isMouseDragging)
  53811. {
  53812. float alpha = 0.5f;
  53813. if (isMouseOver || isMouseDragging)
  53814. {
  53815. g.fillAll (Colour (0x190000ff));
  53816. alpha = 1.0f;
  53817. }
  53818. const float cx = w * 0.5f;
  53819. const float cy = h * 0.5f;
  53820. const float cr = jmin (w, h) * 0.4f;
  53821. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53822. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53823. true));
  53824. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53825. }
  53826. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53827. const String& text,
  53828. const Justification& position,
  53829. GroupComponent& group)
  53830. {
  53831. const float textH = 15.0f;
  53832. const float indent = 3.0f;
  53833. const float textEdgeGap = 4.0f;
  53834. float cs = 5.0f;
  53835. Font f (textH);
  53836. Path p;
  53837. float x = indent;
  53838. float y = f.getAscent() - 3.0f;
  53839. float w = jmax (0.0f, width - x * 2.0f);
  53840. float h = jmax (0.0f, height - y - indent);
  53841. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53842. const float cs2 = 2.0f * cs;
  53843. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53844. float textX = cs + textEdgeGap;
  53845. if (position.testFlags (Justification::horizontallyCentred))
  53846. textX = cs + (w - cs2 - textW) * 0.5f;
  53847. else if (position.testFlags (Justification::right))
  53848. textX = w - cs - textW - textEdgeGap;
  53849. p.startNewSubPath (x + textX + textW, y);
  53850. p.lineTo (x + w - cs, y);
  53851. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53852. p.lineTo (x + w, y + h - cs);
  53853. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53854. p.lineTo (x + cs, y + h);
  53855. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53856. p.lineTo (x, y + cs);
  53857. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53858. p.lineTo (x + textX, y);
  53859. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53860. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53861. .withMultipliedAlpha (alpha));
  53862. g.strokePath (p, PathStrokeType (2.0f));
  53863. g.setColour (group.findColour (GroupComponent::textColourId)
  53864. .withMultipliedAlpha (alpha));
  53865. g.setFont (f);
  53866. g.drawText (text,
  53867. roundToInt (x + textX), 0,
  53868. roundToInt (textW),
  53869. roundToInt (textH),
  53870. Justification::centred, true);
  53871. }
  53872. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53873. {
  53874. return 1 + tabDepth / 3;
  53875. }
  53876. int LookAndFeel::getTabButtonSpaceAroundImage()
  53877. {
  53878. return 4;
  53879. }
  53880. void LookAndFeel::createTabButtonShape (Path& p,
  53881. int width, int height,
  53882. int /*tabIndex*/,
  53883. const String& /*text*/,
  53884. Button& /*button*/,
  53885. TabbedButtonBar::Orientation orientation,
  53886. const bool /*isMouseOver*/,
  53887. const bool /*isMouseDown*/,
  53888. const bool /*isFrontTab*/)
  53889. {
  53890. const float w = (float) width;
  53891. const float h = (float) height;
  53892. float length = w;
  53893. float depth = h;
  53894. if (orientation == TabbedButtonBar::TabsAtLeft
  53895. || orientation == TabbedButtonBar::TabsAtRight)
  53896. {
  53897. swapVariables (length, depth);
  53898. }
  53899. const float indent = (float) getTabButtonOverlap ((int) depth);
  53900. const float overhang = 4.0f;
  53901. if (orientation == TabbedButtonBar::TabsAtLeft)
  53902. {
  53903. p.startNewSubPath (w, 0.0f);
  53904. p.lineTo (0.0f, indent);
  53905. p.lineTo (0.0f, h - indent);
  53906. p.lineTo (w, h);
  53907. p.lineTo (w + overhang, h + overhang);
  53908. p.lineTo (w + overhang, -overhang);
  53909. }
  53910. else if (orientation == TabbedButtonBar::TabsAtRight)
  53911. {
  53912. p.startNewSubPath (0.0f, 0.0f);
  53913. p.lineTo (w, indent);
  53914. p.lineTo (w, h - indent);
  53915. p.lineTo (0.0f, h);
  53916. p.lineTo (-overhang, h + overhang);
  53917. p.lineTo (-overhang, -overhang);
  53918. }
  53919. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53920. {
  53921. p.startNewSubPath (0.0f, 0.0f);
  53922. p.lineTo (indent, h);
  53923. p.lineTo (w - indent, h);
  53924. p.lineTo (w, 0.0f);
  53925. p.lineTo (w + overhang, -overhang);
  53926. p.lineTo (-overhang, -overhang);
  53927. }
  53928. else
  53929. {
  53930. p.startNewSubPath (0.0f, h);
  53931. p.lineTo (indent, 0.0f);
  53932. p.lineTo (w - indent, 0.0f);
  53933. p.lineTo (w, h);
  53934. p.lineTo (w + overhang, h + overhang);
  53935. p.lineTo (-overhang, h + overhang);
  53936. }
  53937. p.closeSubPath();
  53938. p = p.createPathWithRoundedCorners (3.0f);
  53939. }
  53940. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53941. const Path& path,
  53942. const Colour& preferredColour,
  53943. int /*tabIndex*/,
  53944. const String& /*text*/,
  53945. Button& button,
  53946. TabbedButtonBar::Orientation /*orientation*/,
  53947. const bool /*isMouseOver*/,
  53948. const bool /*isMouseDown*/,
  53949. const bool isFrontTab)
  53950. {
  53951. g.setColour (isFrontTab ? preferredColour
  53952. : preferredColour.withMultipliedAlpha (0.9f));
  53953. g.fillPath (path);
  53954. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53955. : TabbedButtonBar::tabOutlineColourId, false)
  53956. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53957. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53958. }
  53959. void LookAndFeel::drawTabButtonText (Graphics& g,
  53960. int x, int y, int w, int h,
  53961. const Colour& preferredBackgroundColour,
  53962. int /*tabIndex*/,
  53963. const String& text,
  53964. Button& button,
  53965. TabbedButtonBar::Orientation orientation,
  53966. const bool isMouseOver,
  53967. const bool isMouseDown,
  53968. const bool isFrontTab)
  53969. {
  53970. int length = w;
  53971. int depth = h;
  53972. if (orientation == TabbedButtonBar::TabsAtLeft
  53973. || orientation == TabbedButtonBar::TabsAtRight)
  53974. {
  53975. swapVariables (length, depth);
  53976. }
  53977. Font font (depth * 0.6f);
  53978. font.setUnderline (button.hasKeyboardFocus (false));
  53979. GlyphArrangement textLayout;
  53980. textLayout.addFittedText (font, text.trim(),
  53981. 0.0f, 0.0f, (float) length, (float) depth,
  53982. Justification::centred,
  53983. jmax (1, depth / 12));
  53984. AffineTransform transform;
  53985. if (orientation == TabbedButtonBar::TabsAtLeft)
  53986. {
  53987. transform = transform.rotated (float_Pi * -0.5f)
  53988. .translated ((float) x, (float) (y + h));
  53989. }
  53990. else if (orientation == TabbedButtonBar::TabsAtRight)
  53991. {
  53992. transform = transform.rotated (float_Pi * 0.5f)
  53993. .translated ((float) (x + w), (float) y);
  53994. }
  53995. else
  53996. {
  53997. transform = transform.translated ((float) x, (float) y);
  53998. }
  53999. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54000. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54001. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54002. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54003. else
  54004. g.setColour (preferredBackgroundColour.contrasting());
  54005. if (! (isMouseOver || isMouseDown))
  54006. g.setOpacity (0.8f);
  54007. if (! button.isEnabled())
  54008. g.setOpacity (0.3f);
  54009. textLayout.draw (g, transform);
  54010. }
  54011. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54012. const String& text,
  54013. int tabDepth,
  54014. Button&)
  54015. {
  54016. Font f (tabDepth * 0.6f);
  54017. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54018. }
  54019. void LookAndFeel::drawTabButton (Graphics& g,
  54020. int w, int h,
  54021. const Colour& preferredColour,
  54022. int tabIndex,
  54023. const String& text,
  54024. Button& button,
  54025. TabbedButtonBar::Orientation orientation,
  54026. const bool isMouseOver,
  54027. const bool isMouseDown,
  54028. const bool isFrontTab)
  54029. {
  54030. int length = w;
  54031. int depth = h;
  54032. if (orientation == TabbedButtonBar::TabsAtLeft
  54033. || orientation == TabbedButtonBar::TabsAtRight)
  54034. {
  54035. swapVariables (length, depth);
  54036. }
  54037. Path tabShape;
  54038. createTabButtonShape (tabShape, w, h,
  54039. tabIndex, text, button, orientation,
  54040. isMouseOver, isMouseDown, isFrontTab);
  54041. fillTabButtonShape (g, tabShape, preferredColour,
  54042. tabIndex, text, button, orientation,
  54043. isMouseOver, isMouseDown, isFrontTab);
  54044. const int indent = getTabButtonOverlap (depth);
  54045. int x = 0, y = 0;
  54046. if (orientation == TabbedButtonBar::TabsAtLeft
  54047. || orientation == TabbedButtonBar::TabsAtRight)
  54048. {
  54049. y += indent;
  54050. h -= indent * 2;
  54051. }
  54052. else
  54053. {
  54054. x += indent;
  54055. w -= indent * 2;
  54056. }
  54057. drawTabButtonText (g, x, y, w, h, preferredColour,
  54058. tabIndex, text, button, orientation,
  54059. isMouseOver, isMouseDown, isFrontTab);
  54060. }
  54061. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54062. int w, int h,
  54063. TabbedButtonBar& tabBar,
  54064. TabbedButtonBar::Orientation orientation)
  54065. {
  54066. const float shadowSize = 0.2f;
  54067. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54068. Rectangle<int> shadowRect;
  54069. if (orientation == TabbedButtonBar::TabsAtLeft)
  54070. {
  54071. x1 = (float) w;
  54072. x2 = w * (1.0f - shadowSize);
  54073. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54074. }
  54075. else if (orientation == TabbedButtonBar::TabsAtRight)
  54076. {
  54077. x2 = w * shadowSize;
  54078. shadowRect.setBounds (0, 0, (int) x2, h);
  54079. }
  54080. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54081. {
  54082. y2 = h * shadowSize;
  54083. shadowRect.setBounds (0, 0, w, (int) y2);
  54084. }
  54085. else
  54086. {
  54087. y1 = (float) h;
  54088. y2 = h * (1.0f - shadowSize);
  54089. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54090. }
  54091. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54092. Colours::transparentBlack, x2, y2, false));
  54093. shadowRect.expand (2, 2);
  54094. g.fillRect (shadowRect);
  54095. g.setColour (Colour (0x80000000));
  54096. if (orientation == TabbedButtonBar::TabsAtLeft)
  54097. {
  54098. g.fillRect (w - 1, 0, 1, h);
  54099. }
  54100. else if (orientation == TabbedButtonBar::TabsAtRight)
  54101. {
  54102. g.fillRect (0, 0, 1, h);
  54103. }
  54104. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54105. {
  54106. g.fillRect (0, 0, w, 1);
  54107. }
  54108. else
  54109. {
  54110. g.fillRect (0, h - 1, w, 1);
  54111. }
  54112. }
  54113. Button* LookAndFeel::createTabBarExtrasButton()
  54114. {
  54115. const float thickness = 7.0f;
  54116. const float indent = 22.0f;
  54117. Path p;
  54118. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54119. DrawablePath ellipse;
  54120. ellipse.setPath (p);
  54121. ellipse.setFill (Colour (0x99ffffff));
  54122. p.clear();
  54123. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54124. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54125. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54126. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54127. p.setUsingNonZeroWinding (false);
  54128. DrawablePath dp;
  54129. dp.setPath (p);
  54130. dp.setFill (Colour (0x59000000));
  54131. DrawableComposite normalImage;
  54132. normalImage.addAndMakeVisible (ellipse.createCopy());
  54133. normalImage.addAndMakeVisible (dp.createCopy());
  54134. dp.setFill (Colour (0xcc000000));
  54135. DrawableComposite overImage;
  54136. overImage.addAndMakeVisible (ellipse.createCopy());
  54137. overImage.addAndMakeVisible (dp.createCopy());
  54138. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54139. db->setImages (&normalImage, &overImage, 0);
  54140. return db;
  54141. }
  54142. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54143. {
  54144. g.fillAll (Colours::white);
  54145. const int w = header.getWidth();
  54146. const int h = header.getHeight();
  54147. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54148. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54149. false));
  54150. g.fillRect (0, h / 2, w, h);
  54151. g.setColour (Colour (0x33000000));
  54152. g.fillRect (0, h - 1, w, 1);
  54153. for (int i = header.getNumColumns (true); --i >= 0;)
  54154. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54155. }
  54156. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54157. int width, int height,
  54158. bool isMouseOver, bool isMouseDown,
  54159. int columnFlags)
  54160. {
  54161. if (isMouseDown)
  54162. g.fillAll (Colour (0x8899aadd));
  54163. else if (isMouseOver)
  54164. g.fillAll (Colour (0x5599aadd));
  54165. int rightOfText = width - 4;
  54166. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54167. {
  54168. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54169. const float bottom = height - top;
  54170. const float w = height * 0.5f;
  54171. const float x = rightOfText - (w * 1.25f);
  54172. rightOfText = (int) x;
  54173. Path sortArrow;
  54174. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54175. g.setColour (Colour (0x99000000));
  54176. g.fillPath (sortArrow);
  54177. }
  54178. g.setColour (Colours::black);
  54179. g.setFont (height * 0.5f, Font::bold);
  54180. const int textX = 4;
  54181. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54182. }
  54183. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54184. {
  54185. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54186. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54187. background.darker (0.1f),
  54188. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54189. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54190. false));
  54191. g.fillAll();
  54192. }
  54193. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54194. {
  54195. return createTabBarExtrasButton();
  54196. }
  54197. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54198. bool isMouseOver, bool isMouseDown,
  54199. ToolbarItemComponent& component)
  54200. {
  54201. if (isMouseDown)
  54202. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54203. else if (isMouseOver)
  54204. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54205. }
  54206. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54207. const String& text, ToolbarItemComponent& component)
  54208. {
  54209. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54210. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54211. const float fontHeight = jmin (14.0f, height * 0.85f);
  54212. g.setFont (fontHeight);
  54213. g.drawFittedText (text,
  54214. x, y, width, height,
  54215. Justification::centred,
  54216. jmax (1, height / (int) fontHeight));
  54217. }
  54218. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54219. bool isOpen, int width, int height)
  54220. {
  54221. const int buttonSize = (height * 3) / 4;
  54222. const int buttonIndent = (height - buttonSize) / 2;
  54223. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54224. const int textX = buttonIndent * 2 + buttonSize + 2;
  54225. g.setColour (Colours::black);
  54226. g.setFont (height * 0.7f, Font::bold);
  54227. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54228. }
  54229. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54230. PropertyComponent&)
  54231. {
  54232. g.setColour (Colour (0x66ffffff));
  54233. g.fillRect (0, 0, width, height - 1);
  54234. }
  54235. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54236. PropertyComponent& component)
  54237. {
  54238. g.setColour (Colours::black);
  54239. if (! component.isEnabled())
  54240. g.setOpacity (0.6f);
  54241. g.setFont (jmin (height, 24) * 0.65f);
  54242. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54243. g.drawFittedText (component.getName(),
  54244. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54245. Justification::centredLeft, 2);
  54246. }
  54247. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54248. {
  54249. return Rectangle<int> (component.getWidth() / 3, 1,
  54250. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54251. }
  54252. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54253. {
  54254. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54255. {
  54256. Graphics g2 (content);
  54257. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54258. g2.fillPath (path);
  54259. g2.setColour (Colours::white.withAlpha (0.8f));
  54260. g2.strokePath (path, PathStrokeType (2.0f));
  54261. }
  54262. DropShadowEffect shadow;
  54263. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54264. shadow.applyEffect (content, g, 1.0f);
  54265. }
  54266. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54267. const String& instructions,
  54268. GlyphArrangement& text,
  54269. int width)
  54270. {
  54271. text.clear();
  54272. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54273. 8.0f, 22.0f, width - 16.0f,
  54274. Justification::centred);
  54275. text.addJustifiedText (Font (14.0f), instructions,
  54276. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54277. Justification::centred);
  54278. }
  54279. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54280. const String& filename, Image* icon,
  54281. const String& fileSizeDescription,
  54282. const String& fileTimeDescription,
  54283. const bool isDirectory,
  54284. const bool isItemSelected,
  54285. const int /*itemIndex*/,
  54286. DirectoryContentsDisplayComponent&)
  54287. {
  54288. if (isItemSelected)
  54289. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54290. const int x = 32;
  54291. g.setColour (Colours::black);
  54292. if (icon != 0 && icon->isValid())
  54293. {
  54294. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54295. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54296. false);
  54297. }
  54298. else
  54299. {
  54300. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54301. : getDefaultDocumentFileImage();
  54302. if (d != 0)
  54303. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54304. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54305. }
  54306. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54307. g.setFont (height * 0.7f);
  54308. if (width > 450 && ! isDirectory)
  54309. {
  54310. const int sizeX = roundToInt (width * 0.7f);
  54311. const int dateX = roundToInt (width * 0.8f);
  54312. g.drawFittedText (filename,
  54313. x, 0, sizeX - x, height,
  54314. Justification::centredLeft, 1);
  54315. g.setFont (height * 0.5f);
  54316. g.setColour (Colours::darkgrey);
  54317. if (! isDirectory)
  54318. {
  54319. g.drawFittedText (fileSizeDescription,
  54320. sizeX, 0, dateX - sizeX - 8, height,
  54321. Justification::centredRight, 1);
  54322. g.drawFittedText (fileTimeDescription,
  54323. dateX, 0, width - 8 - dateX, height,
  54324. Justification::centredRight, 1);
  54325. }
  54326. }
  54327. else
  54328. {
  54329. g.drawFittedText (filename,
  54330. x, 0, width - x, height,
  54331. Justification::centredLeft, 1);
  54332. }
  54333. }
  54334. Button* LookAndFeel::createFileBrowserGoUpButton()
  54335. {
  54336. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54337. Path arrowPath;
  54338. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54339. DrawablePath arrowImage;
  54340. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54341. arrowImage.setPath (arrowPath);
  54342. goUpButton->setImages (&arrowImage);
  54343. return goUpButton;
  54344. }
  54345. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54346. DirectoryContentsDisplayComponent* fileListComponent,
  54347. FilePreviewComponent* previewComp,
  54348. ComboBox* currentPathBox,
  54349. TextEditor* filenameBox,
  54350. Button* goUpButton)
  54351. {
  54352. const int x = 8;
  54353. int w = browserComp.getWidth() - x - x;
  54354. if (previewComp != 0)
  54355. {
  54356. const int previewWidth = w / 3;
  54357. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54358. w -= previewWidth + 4;
  54359. }
  54360. int y = 4;
  54361. const int controlsHeight = 22;
  54362. const int bottomSectionHeight = controlsHeight + 8;
  54363. const int upButtonWidth = 50;
  54364. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54365. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54366. y += controlsHeight + 4;
  54367. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54368. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54369. y = listAsComp->getBottom() + 4;
  54370. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54371. }
  54372. // Pulls a drawable out of compressed valuetree data..
  54373. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54374. {
  54375. MemoryInputStream m (data, numBytes, false);
  54376. GZIPDecompressorInputStream gz (m);
  54377. ValueTree drawable (ValueTree::readFromStream (gz));
  54378. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54379. }
  54380. const Drawable* LookAndFeel::getDefaultFolderImage()
  54381. {
  54382. if (folderImage == 0)
  54383. {
  54384. static const unsigned char drawableData[] =
  54385. { 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,
  54386. 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,
  54387. 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,
  54388. 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,
  54389. 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,
  54390. 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,
  54391. 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,
  54392. 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,
  54393. 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,
  54394. 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,
  54395. 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,
  54396. 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,
  54397. 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,
  54398. 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,
  54399. 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 };
  54400. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54401. }
  54402. return folderImage;
  54403. }
  54404. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54405. {
  54406. if (documentImage == 0)
  54407. {
  54408. static const unsigned char drawableData[] =
  54409. { 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,
  54410. 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,
  54411. 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,
  54412. 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,
  54413. 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,
  54414. 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,
  54415. 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,
  54416. 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,
  54417. 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,
  54418. 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,
  54419. 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,
  54420. 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,
  54421. 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,
  54422. 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,
  54423. 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,
  54424. 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,
  54425. 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,
  54426. 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,
  54427. 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,
  54428. 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,
  54429. 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,
  54430. 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,
  54431. 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 };
  54432. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54433. }
  54434. return documentImage;
  54435. }
  54436. void LookAndFeel::playAlertSound()
  54437. {
  54438. PlatformUtilities::beep();
  54439. }
  54440. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54441. {
  54442. g.setColour (Colours::white.withAlpha (0.7f));
  54443. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54444. g.setColour (Colours::black.withAlpha (0.2f));
  54445. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54446. const int totalBlocks = 7;
  54447. const int numBlocks = roundToInt (totalBlocks * level);
  54448. const float w = (width - 6.0f) / (float) totalBlocks;
  54449. for (int i = 0; i < totalBlocks; ++i)
  54450. {
  54451. if (i >= numBlocks)
  54452. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54453. else
  54454. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54455. : Colours::red);
  54456. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54457. }
  54458. }
  54459. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54460. {
  54461. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54462. if (keyDescription.isNotEmpty())
  54463. {
  54464. if (button.isEnabled())
  54465. {
  54466. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54467. g.fillAll (textColour.withAlpha (alpha));
  54468. g.setOpacity (0.3f);
  54469. g.drawBevel (0, 0, width, height, 2);
  54470. }
  54471. g.setColour (textColour);
  54472. g.setFont (height * 0.6f);
  54473. g.drawFittedText (keyDescription,
  54474. 3, 0, width - 6, height,
  54475. Justification::centred, 1);
  54476. }
  54477. else
  54478. {
  54479. const float thickness = 7.0f;
  54480. const float indent = 22.0f;
  54481. Path p;
  54482. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54483. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54484. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54485. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54486. p.setUsingNonZeroWinding (false);
  54487. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54488. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54489. }
  54490. if (button.hasKeyboardFocus (false))
  54491. {
  54492. g.setColour (textColour.withAlpha (0.4f));
  54493. g.drawRect (0, 0, width, height);
  54494. }
  54495. }
  54496. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54497. float x, float y, float w, float h,
  54498. float maxCornerSize,
  54499. const Colour& baseColour,
  54500. const float strokeWidth,
  54501. const bool flatOnLeft,
  54502. const bool flatOnRight,
  54503. const bool flatOnTop,
  54504. const bool flatOnBottom) throw()
  54505. {
  54506. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54507. return;
  54508. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54509. Path outline;
  54510. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54511. ! (flatOnLeft || flatOnTop),
  54512. ! (flatOnRight || flatOnTop),
  54513. ! (flatOnLeft || flatOnBottom),
  54514. ! (flatOnRight || flatOnBottom));
  54515. ColourGradient cg (baseColour, 0.0f, y,
  54516. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54517. false);
  54518. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54519. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54520. g.setGradientFill (cg);
  54521. g.fillPath (outline);
  54522. g.setColour (Colour (0x80000000));
  54523. g.strokePath (outline, PathStrokeType (strokeWidth));
  54524. }
  54525. void LookAndFeel::drawGlassSphere (Graphics& g,
  54526. const float x, const float y,
  54527. const float diameter,
  54528. const Colour& colour,
  54529. const float outlineThickness) throw()
  54530. {
  54531. if (diameter <= outlineThickness)
  54532. return;
  54533. Path p;
  54534. p.addEllipse (x, y, diameter, diameter);
  54535. {
  54536. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54537. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54538. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54539. g.setGradientFill (cg);
  54540. g.fillPath (p);
  54541. }
  54542. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54543. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54544. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54545. ColourGradient cg (Colours::transparentBlack,
  54546. x + diameter * 0.5f, y + diameter * 0.5f,
  54547. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54548. x, y + diameter * 0.5f, true);
  54549. cg.addColour (0.7, Colours::transparentBlack);
  54550. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54551. g.setGradientFill (cg);
  54552. g.fillPath (p);
  54553. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54554. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54555. }
  54556. void LookAndFeel::drawGlassPointer (Graphics& g,
  54557. const float x, const float y,
  54558. const float diameter,
  54559. const Colour& colour, const float outlineThickness,
  54560. const int direction) throw()
  54561. {
  54562. if (diameter <= outlineThickness)
  54563. return;
  54564. Path p;
  54565. p.startNewSubPath (x + diameter * 0.5f, y);
  54566. p.lineTo (x + diameter, y + diameter * 0.6f);
  54567. p.lineTo (x + diameter, y + diameter);
  54568. p.lineTo (x, y + diameter);
  54569. p.lineTo (x, y + diameter * 0.6f);
  54570. p.closeSubPath();
  54571. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54572. {
  54573. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54574. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54575. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54576. g.setGradientFill (cg);
  54577. g.fillPath (p);
  54578. }
  54579. ColourGradient cg (Colours::transparentBlack,
  54580. x + diameter * 0.5f, y + diameter * 0.5f,
  54581. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54582. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54583. cg.addColour (0.5, Colours::transparentBlack);
  54584. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54585. g.setGradientFill (cg);
  54586. g.fillPath (p);
  54587. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54588. g.strokePath (p, PathStrokeType (outlineThickness));
  54589. }
  54590. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54591. const float x, const float y,
  54592. const float width, const float height,
  54593. const Colour& colour,
  54594. const float outlineThickness,
  54595. const float cornerSize,
  54596. const bool flatOnLeft,
  54597. const bool flatOnRight,
  54598. const bool flatOnTop,
  54599. const bool flatOnBottom) throw()
  54600. {
  54601. if (width <= outlineThickness || height <= outlineThickness)
  54602. return;
  54603. const int intX = (int) x;
  54604. const int intY = (int) y;
  54605. const int intW = (int) width;
  54606. const int intH = (int) height;
  54607. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54608. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54609. const int intEdge = (int) edgeBlurRadius;
  54610. Path outline;
  54611. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54612. ! (flatOnLeft || flatOnTop),
  54613. ! (flatOnRight || flatOnTop),
  54614. ! (flatOnLeft || flatOnBottom),
  54615. ! (flatOnRight || flatOnBottom));
  54616. {
  54617. ColourGradient cg (colour.darker (0.2f), 0, y,
  54618. colour.darker (0.2f), 0, y + height, false);
  54619. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54620. cg.addColour (0.4, colour);
  54621. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54622. g.setGradientFill (cg);
  54623. g.fillPath (outline);
  54624. }
  54625. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54626. colour.darker (0.2f), x, y + height * 0.5f, true);
  54627. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54628. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54629. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54630. {
  54631. g.saveState();
  54632. g.setGradientFill (cg);
  54633. g.reduceClipRegion (intX, intY, intEdge, intH);
  54634. g.fillPath (outline);
  54635. g.restoreState();
  54636. }
  54637. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54638. {
  54639. cg.point1.setX (x + width - edgeBlurRadius);
  54640. cg.point2.setX (x + width);
  54641. g.saveState();
  54642. g.setGradientFill (cg);
  54643. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54644. g.fillPath (outline);
  54645. g.restoreState();
  54646. }
  54647. {
  54648. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54649. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54650. Path highlight;
  54651. LookAndFeelHelpers::createRoundedPath (highlight,
  54652. x + leftIndent,
  54653. y + cs * 0.1f,
  54654. width - (leftIndent + rightIndent),
  54655. height * 0.4f, cs * 0.4f,
  54656. ! (flatOnLeft || flatOnTop),
  54657. ! (flatOnRight || flatOnTop),
  54658. ! (flatOnLeft || flatOnBottom),
  54659. ! (flatOnRight || flatOnBottom));
  54660. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54661. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54662. g.fillPath (highlight);
  54663. }
  54664. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54665. g.strokePath (outline, PathStrokeType (outlineThickness));
  54666. }
  54667. END_JUCE_NAMESPACE
  54668. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54669. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54670. BEGIN_JUCE_NAMESPACE
  54671. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54672. {
  54673. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54674. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54675. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54676. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54677. setColour (Slider::thumbColourId, Colours::white);
  54678. setColour (Slider::trackColourId, Colour (0x7f000000));
  54679. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54680. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54681. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54682. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54683. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54684. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54685. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54686. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54687. }
  54688. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54689. {
  54690. }
  54691. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54692. Button& button,
  54693. const Colour& backgroundColour,
  54694. bool isMouseOverButton,
  54695. bool isButtonDown)
  54696. {
  54697. const int width = button.getWidth();
  54698. const int height = button.getHeight();
  54699. const float indent = 2.0f;
  54700. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54701. roundToInt (height * 0.4f));
  54702. Path p;
  54703. p.addRoundedRectangle (indent, indent,
  54704. width - indent * 2.0f,
  54705. height - indent * 2.0f,
  54706. (float) cornerSize);
  54707. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54708. if (isMouseOverButton)
  54709. {
  54710. if (isButtonDown)
  54711. bc = bc.brighter();
  54712. else if (bc.getBrightness() > 0.5f)
  54713. bc = bc.darker (0.1f);
  54714. else
  54715. bc = bc.brighter (0.1f);
  54716. }
  54717. g.setColour (bc);
  54718. g.fillPath (p);
  54719. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54720. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54721. }
  54722. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54723. Component& /*component*/,
  54724. float x, float y, float w, float h,
  54725. const bool ticked,
  54726. const bool isEnabled,
  54727. const bool /*isMouseOverButton*/,
  54728. const bool isButtonDown)
  54729. {
  54730. Path box;
  54731. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54732. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54733. : Colours::lightgrey.withAlpha (0.1f));
  54734. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54735. g.fillPath (box, trans);
  54736. g.setColour (Colours::black.withAlpha (0.6f));
  54737. g.strokePath (box, PathStrokeType (0.9f), trans);
  54738. if (ticked)
  54739. {
  54740. Path tick;
  54741. tick.startNewSubPath (1.5f, 3.0f);
  54742. tick.lineTo (3.0f, 6.0f);
  54743. tick.lineTo (6.0f, 0.0f);
  54744. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54745. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54746. }
  54747. }
  54748. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54749. ToggleButton& button,
  54750. bool isMouseOverButton,
  54751. bool isButtonDown)
  54752. {
  54753. if (button.hasKeyboardFocus (true))
  54754. {
  54755. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54756. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54757. }
  54758. const int tickWidth = jmin (20, button.getHeight() - 4);
  54759. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54760. (float) tickWidth, (float) tickWidth,
  54761. button.getToggleState(),
  54762. button.isEnabled(),
  54763. isMouseOverButton,
  54764. isButtonDown);
  54765. g.setColour (button.findColour (ToggleButton::textColourId));
  54766. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54767. if (! button.isEnabled())
  54768. g.setOpacity (0.5f);
  54769. const int textX = tickWidth + 5;
  54770. g.drawFittedText (button.getButtonText(),
  54771. textX, 4,
  54772. button.getWidth() - textX - 2, button.getHeight() - 8,
  54773. Justification::centredLeft, 10);
  54774. }
  54775. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54776. int width, int height,
  54777. double progress, const String& textToShow)
  54778. {
  54779. if (progress < 0 || progress >= 1.0)
  54780. {
  54781. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54782. }
  54783. else
  54784. {
  54785. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54786. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54787. g.fillAll (background);
  54788. g.setColour (foreground);
  54789. g.fillRect (1, 1,
  54790. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54791. height - 2);
  54792. if (textToShow.isNotEmpty())
  54793. {
  54794. g.setColour (Colour::contrasting (background, foreground));
  54795. g.setFont (height * 0.6f);
  54796. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54797. }
  54798. }
  54799. }
  54800. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54801. ScrollBar& bar,
  54802. int width, int height,
  54803. int buttonDirection,
  54804. bool isScrollbarVertical,
  54805. bool isMouseOverButton,
  54806. bool isButtonDown)
  54807. {
  54808. if (isScrollbarVertical)
  54809. width -= 2;
  54810. else
  54811. height -= 2;
  54812. Path p;
  54813. if (buttonDirection == 0)
  54814. p.addTriangle (width * 0.5f, height * 0.2f,
  54815. width * 0.1f, height * 0.7f,
  54816. width * 0.9f, height * 0.7f);
  54817. else if (buttonDirection == 1)
  54818. p.addTriangle (width * 0.8f, height * 0.5f,
  54819. width * 0.3f, height * 0.1f,
  54820. width * 0.3f, height * 0.9f);
  54821. else if (buttonDirection == 2)
  54822. p.addTriangle (width * 0.5f, height * 0.8f,
  54823. width * 0.1f, height * 0.3f,
  54824. width * 0.9f, height * 0.3f);
  54825. else if (buttonDirection == 3)
  54826. p.addTriangle (width * 0.2f, height * 0.5f,
  54827. width * 0.7f, height * 0.1f,
  54828. width * 0.7f, height * 0.9f);
  54829. if (isButtonDown)
  54830. g.setColour (Colours::white);
  54831. else if (isMouseOverButton)
  54832. g.setColour (Colours::white.withAlpha (0.7f));
  54833. else
  54834. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54835. g.fillPath (p);
  54836. g.setColour (Colours::black.withAlpha (0.5f));
  54837. g.strokePath (p, PathStrokeType (0.5f));
  54838. }
  54839. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54840. ScrollBar& bar,
  54841. int x, int y,
  54842. int width, int height,
  54843. bool isScrollbarVertical,
  54844. int thumbStartPosition,
  54845. int thumbSize,
  54846. bool isMouseOver,
  54847. bool isMouseDown)
  54848. {
  54849. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54850. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54851. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54852. if (thumbSize > 0.0f)
  54853. {
  54854. Rectangle<int> thumb;
  54855. if (isScrollbarVertical)
  54856. {
  54857. width -= 2;
  54858. g.fillRect (x + roundToInt (width * 0.35f), y,
  54859. roundToInt (width * 0.3f), height);
  54860. thumb.setBounds (x + 1, thumbStartPosition,
  54861. width - 2, thumbSize);
  54862. }
  54863. else
  54864. {
  54865. height -= 2;
  54866. g.fillRect (x, y + roundToInt (height * 0.35f),
  54867. width, roundToInt (height * 0.3f));
  54868. thumb.setBounds (thumbStartPosition, y + 1,
  54869. thumbSize, height - 2);
  54870. }
  54871. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54872. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54873. g.fillRect (thumb);
  54874. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54875. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54876. if (thumbSize > 16)
  54877. {
  54878. for (int i = 3; --i >= 0;)
  54879. {
  54880. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54881. g.setColour (Colours::black.withAlpha (0.15f));
  54882. if (isScrollbarVertical)
  54883. {
  54884. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54885. g.setColour (Colours::white.withAlpha (0.15f));
  54886. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54887. }
  54888. else
  54889. {
  54890. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54891. g.setColour (Colours::white.withAlpha (0.15f));
  54892. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54893. }
  54894. }
  54895. }
  54896. }
  54897. }
  54898. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54899. {
  54900. return &scrollbarShadow;
  54901. }
  54902. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54903. {
  54904. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54905. g.setColour (Colours::black.withAlpha (0.6f));
  54906. g.drawRect (0, 0, width, height);
  54907. }
  54908. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54909. bool, MenuBarComponent& menuBar)
  54910. {
  54911. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54912. }
  54913. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54914. {
  54915. if (textEditor.isEnabled())
  54916. {
  54917. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54918. g.drawRect (0, 0, width, height);
  54919. }
  54920. }
  54921. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54922. const bool isButtonDown,
  54923. int buttonX, int buttonY,
  54924. int buttonW, int buttonH,
  54925. ComboBox& box)
  54926. {
  54927. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54928. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54929. : ComboBox::backgroundColourId));
  54930. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54931. g.setColour (box.findColour (ComboBox::outlineColourId));
  54932. g.drawRect (0, 0, width, height);
  54933. const float arrowX = 0.2f;
  54934. const float arrowH = 0.3f;
  54935. if (box.isEnabled())
  54936. {
  54937. Path p;
  54938. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54939. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54940. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54941. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54942. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54943. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54944. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54945. : ComboBox::buttonColourId));
  54946. g.fillPath (p);
  54947. }
  54948. }
  54949. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54950. {
  54951. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54952. f.setHorizontalScale (0.9f);
  54953. return f;
  54954. }
  54955. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54956. {
  54957. Path p;
  54958. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54959. g.setColour (fill);
  54960. g.fillPath (p);
  54961. g.setColour (outline);
  54962. g.strokePath (p, PathStrokeType (0.3f));
  54963. }
  54964. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54965. int x, int y,
  54966. int w, int h,
  54967. float sliderPos,
  54968. float minSliderPos,
  54969. float maxSliderPos,
  54970. const Slider::SliderStyle style,
  54971. Slider& slider)
  54972. {
  54973. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54974. if (style == Slider::LinearBar)
  54975. {
  54976. g.setColour (slider.findColour (Slider::thumbColourId));
  54977. g.fillRect (x, y, (int) sliderPos - x, h);
  54978. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54979. g.drawRect (x, y, (int) sliderPos - x, h);
  54980. }
  54981. else
  54982. {
  54983. g.setColour (slider.findColour (Slider::trackColourId)
  54984. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54985. if (slider.isHorizontal())
  54986. {
  54987. g.fillRect (x, y + roundToInt (h * 0.6f),
  54988. w, roundToInt (h * 0.2f));
  54989. }
  54990. else
  54991. {
  54992. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54993. jmin (4, roundToInt (w * 0.2f)), h);
  54994. }
  54995. float alpha = 0.35f;
  54996. if (slider.isEnabled())
  54997. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54998. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54999. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55000. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55001. {
  55002. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55003. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55004. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55005. fill, outline);
  55006. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55007. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55008. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55009. fill, outline);
  55010. }
  55011. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55012. {
  55013. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55014. minSliderPos - 7.0f, y + h * 0.9f ,
  55015. minSliderPos, y + h * 0.9f,
  55016. fill, outline);
  55017. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55018. maxSliderPos, y + h * 0.9f,
  55019. maxSliderPos + 7.0f, y + h * 0.9f,
  55020. fill, outline);
  55021. }
  55022. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55023. {
  55024. drawTriangle (g, sliderPos, y + h * 0.9f,
  55025. sliderPos - 7.0f, y + h * 0.2f,
  55026. sliderPos + 7.0f, y + h * 0.2f,
  55027. fill, outline);
  55028. }
  55029. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55030. {
  55031. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55032. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55033. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55034. fill, outline);
  55035. }
  55036. }
  55037. }
  55038. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55039. {
  55040. if (isIncrement)
  55041. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55042. else
  55043. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55044. }
  55045. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55046. {
  55047. return &scrollbarShadow;
  55048. }
  55049. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55050. {
  55051. return 8;
  55052. }
  55053. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55054. int w, int h,
  55055. bool isMouseOver,
  55056. bool isMouseDragging)
  55057. {
  55058. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55059. : Colours::darkgrey);
  55060. const float lineThickness = jmin (w, h) * 0.1f;
  55061. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55062. {
  55063. g.drawLine (w * i,
  55064. h + 1.0f,
  55065. w + 1.0f,
  55066. h * i,
  55067. lineThickness);
  55068. }
  55069. }
  55070. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55071. {
  55072. Path shape;
  55073. if (buttonType == DocumentWindow::closeButton)
  55074. {
  55075. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55076. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55077. ShapeButton* const b = new ShapeButton ("close",
  55078. Colour (0x7fff3333),
  55079. Colour (0xd7ff3333),
  55080. Colour (0xf7ff3333));
  55081. b->setShape (shape, true, true, true);
  55082. return b;
  55083. }
  55084. else if (buttonType == DocumentWindow::minimiseButton)
  55085. {
  55086. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55087. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55088. DrawablePath dp;
  55089. dp.setPath (shape);
  55090. dp.setFill (Colours::black.withAlpha (0.3f));
  55091. b->setImages (&dp);
  55092. return b;
  55093. }
  55094. else if (buttonType == DocumentWindow::maximiseButton)
  55095. {
  55096. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55097. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55098. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55099. DrawablePath dp;
  55100. dp.setPath (shape);
  55101. dp.setFill (Colours::black.withAlpha (0.3f));
  55102. b->setImages (&dp);
  55103. return b;
  55104. }
  55105. jassertfalse;
  55106. return 0;
  55107. }
  55108. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55109. int titleBarX,
  55110. int titleBarY,
  55111. int titleBarW,
  55112. int titleBarH,
  55113. Button* minimiseButton,
  55114. Button* maximiseButton,
  55115. Button* closeButton,
  55116. bool positionTitleBarButtonsOnLeft)
  55117. {
  55118. titleBarY += titleBarH / 8;
  55119. titleBarH -= titleBarH / 4;
  55120. const int buttonW = titleBarH;
  55121. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55122. : titleBarX + titleBarW - buttonW - 4;
  55123. if (closeButton != 0)
  55124. {
  55125. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55126. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55127. : -(buttonW + buttonW / 5);
  55128. }
  55129. if (positionTitleBarButtonsOnLeft)
  55130. swapVariables (minimiseButton, maximiseButton);
  55131. if (maximiseButton != 0)
  55132. {
  55133. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55134. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55135. }
  55136. if (minimiseButton != 0)
  55137. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55138. }
  55139. END_JUCE_NAMESPACE
  55140. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55141. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55142. BEGIN_JUCE_NAMESPACE
  55143. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55144. : model (0),
  55145. itemUnderMouse (-1),
  55146. currentPopupIndex (-1),
  55147. topLevelIndexClicked (0),
  55148. lastMouseX (0),
  55149. lastMouseY (0)
  55150. {
  55151. setRepaintsOnMouseActivity (true);
  55152. setWantsKeyboardFocus (false);
  55153. setMouseClickGrabsKeyboardFocus (false);
  55154. setModel (model_);
  55155. }
  55156. MenuBarComponent::~MenuBarComponent()
  55157. {
  55158. setModel (0);
  55159. Desktop::getInstance().removeGlobalMouseListener (this);
  55160. }
  55161. MenuBarModel* MenuBarComponent::getModel() const throw()
  55162. {
  55163. return model;
  55164. }
  55165. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55166. {
  55167. if (model != newModel)
  55168. {
  55169. if (model != 0)
  55170. model->removeListener (this);
  55171. model = newModel;
  55172. if (model != 0)
  55173. model->addListener (this);
  55174. repaint();
  55175. menuBarItemsChanged (0);
  55176. }
  55177. }
  55178. void MenuBarComponent::paint (Graphics& g)
  55179. {
  55180. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55181. getLookAndFeel().drawMenuBarBackground (g,
  55182. getWidth(),
  55183. getHeight(),
  55184. isMouseOverBar,
  55185. *this);
  55186. if (model != 0)
  55187. {
  55188. for (int i = 0; i < menuNames.size(); ++i)
  55189. {
  55190. Graphics::ScopedSaveState ss (g);
  55191. g.setOrigin (xPositions [i], 0);
  55192. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55193. getLookAndFeel().drawMenuBarItem (g,
  55194. xPositions[i + 1] - xPositions[i],
  55195. getHeight(),
  55196. i,
  55197. menuNames[i],
  55198. i == itemUnderMouse,
  55199. i == currentPopupIndex,
  55200. isMouseOverBar,
  55201. *this);
  55202. }
  55203. }
  55204. }
  55205. void MenuBarComponent::resized()
  55206. {
  55207. xPositions.clear();
  55208. int x = 0;
  55209. xPositions.add (x);
  55210. for (int i = 0; i < menuNames.size(); ++i)
  55211. {
  55212. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55213. xPositions.add (x);
  55214. }
  55215. }
  55216. int MenuBarComponent::getItemAt (const int x, const int y)
  55217. {
  55218. for (int i = 0; i < xPositions.size(); ++i)
  55219. if (x >= xPositions[i] && x < xPositions[i + 1])
  55220. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55221. return -1;
  55222. }
  55223. void MenuBarComponent::repaintMenuItem (int index)
  55224. {
  55225. if (isPositiveAndBelow (index, xPositions.size()))
  55226. {
  55227. const int x1 = xPositions [index];
  55228. const int x2 = xPositions [index + 1];
  55229. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55230. }
  55231. }
  55232. void MenuBarComponent::setItemUnderMouse (const int index)
  55233. {
  55234. if (itemUnderMouse != index)
  55235. {
  55236. repaintMenuItem (itemUnderMouse);
  55237. itemUnderMouse = index;
  55238. repaintMenuItem (itemUnderMouse);
  55239. }
  55240. }
  55241. void MenuBarComponent::setOpenItem (int index)
  55242. {
  55243. if (currentPopupIndex != index)
  55244. {
  55245. repaintMenuItem (currentPopupIndex);
  55246. currentPopupIndex = index;
  55247. repaintMenuItem (currentPopupIndex);
  55248. if (index >= 0)
  55249. Desktop::getInstance().addGlobalMouseListener (this);
  55250. else
  55251. Desktop::getInstance().removeGlobalMouseListener (this);
  55252. }
  55253. }
  55254. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55255. {
  55256. setItemUnderMouse (getItemAt (x, y));
  55257. }
  55258. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55259. {
  55260. public:
  55261. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55262. : bar (bar_), topLevelIndex (topLevelIndex_)
  55263. {
  55264. }
  55265. void modalStateFinished (int returnValue)
  55266. {
  55267. if (bar != 0)
  55268. bar->menuDismissed (topLevelIndex, returnValue);
  55269. }
  55270. private:
  55271. Component::SafePointer<MenuBarComponent> bar;
  55272. const int topLevelIndex;
  55273. JUCE_DECLARE_NON_COPYABLE (AsyncCallback);
  55274. };
  55275. void MenuBarComponent::showMenu (int index)
  55276. {
  55277. if (index != currentPopupIndex)
  55278. {
  55279. PopupMenu::dismissAllActiveMenus();
  55280. menuBarItemsChanged (0);
  55281. setOpenItem (index);
  55282. setItemUnderMouse (index);
  55283. if (index >= 0)
  55284. {
  55285. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55286. menuNames [itemUnderMouse]));
  55287. if (m.lookAndFeel == 0)
  55288. m.setLookAndFeel (&getLookAndFeel());
  55289. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55290. m.showMenu (localAreaToGlobal (itemPos),
  55291. 0, itemPos.getWidth(), 0, 0, this,
  55292. new AsyncCallback (this, index));
  55293. }
  55294. }
  55295. }
  55296. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55297. {
  55298. topLevelIndexClicked = topLevelIndex;
  55299. postCommandMessage (itemId);
  55300. }
  55301. void MenuBarComponent::handleCommandMessage (int commandId)
  55302. {
  55303. const Point<int> mousePos (getMouseXYRelative());
  55304. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55305. if (currentPopupIndex == topLevelIndexClicked)
  55306. setOpenItem (-1);
  55307. if (commandId != 0 && model != 0)
  55308. model->menuItemSelected (commandId, topLevelIndexClicked);
  55309. }
  55310. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55311. {
  55312. if (e.eventComponent == this)
  55313. updateItemUnderMouse (e.x, e.y);
  55314. }
  55315. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55316. {
  55317. if (e.eventComponent == this)
  55318. updateItemUnderMouse (e.x, e.y);
  55319. }
  55320. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55321. {
  55322. if (currentPopupIndex < 0)
  55323. {
  55324. const MouseEvent e2 (e.getEventRelativeTo (this));
  55325. updateItemUnderMouse (e2.x, e2.y);
  55326. currentPopupIndex = -2;
  55327. showMenu (itemUnderMouse);
  55328. }
  55329. }
  55330. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55331. {
  55332. const MouseEvent e2 (e.getEventRelativeTo (this));
  55333. const int item = getItemAt (e2.x, e2.y);
  55334. if (item >= 0)
  55335. showMenu (item);
  55336. }
  55337. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55338. {
  55339. const MouseEvent e2 (e.getEventRelativeTo (this));
  55340. updateItemUnderMouse (e2.x, e2.y);
  55341. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55342. {
  55343. setOpenItem (-1);
  55344. PopupMenu::dismissAllActiveMenus();
  55345. }
  55346. }
  55347. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55348. {
  55349. const MouseEvent e2 (e.getEventRelativeTo (this));
  55350. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55351. {
  55352. if (currentPopupIndex >= 0)
  55353. {
  55354. const int item = getItemAt (e2.x, e2.y);
  55355. if (item >= 0)
  55356. showMenu (item);
  55357. }
  55358. else
  55359. {
  55360. updateItemUnderMouse (e2.x, e2.y);
  55361. }
  55362. lastMouseX = e2.x;
  55363. lastMouseY = e2.y;
  55364. }
  55365. }
  55366. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55367. {
  55368. bool used = false;
  55369. const int numMenus = menuNames.size();
  55370. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55371. if (key.isKeyCode (KeyPress::leftKey))
  55372. {
  55373. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55374. used = true;
  55375. }
  55376. else if (key.isKeyCode (KeyPress::rightKey))
  55377. {
  55378. showMenu ((currentIndex + 1) % numMenus);
  55379. used = true;
  55380. }
  55381. return used;
  55382. }
  55383. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55384. {
  55385. StringArray newNames;
  55386. if (model != 0)
  55387. newNames = model->getMenuBarNames();
  55388. if (newNames != menuNames)
  55389. {
  55390. menuNames = newNames;
  55391. repaint();
  55392. resized();
  55393. }
  55394. }
  55395. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55396. const ApplicationCommandTarget::InvocationInfo& info)
  55397. {
  55398. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55399. return;
  55400. for (int i = 0; i < menuNames.size(); ++i)
  55401. {
  55402. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55403. if (menu.containsCommandItem (info.commandID))
  55404. {
  55405. setItemUnderMouse (i);
  55406. startTimer (200);
  55407. break;
  55408. }
  55409. }
  55410. }
  55411. void MenuBarComponent::timerCallback()
  55412. {
  55413. stopTimer();
  55414. const Point<int> mousePos (getMouseXYRelative());
  55415. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55416. }
  55417. END_JUCE_NAMESPACE
  55418. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55419. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55420. BEGIN_JUCE_NAMESPACE
  55421. MenuBarModel::MenuBarModel() throw()
  55422. : manager (0)
  55423. {
  55424. }
  55425. MenuBarModel::~MenuBarModel()
  55426. {
  55427. setApplicationCommandManagerToWatch (0);
  55428. }
  55429. void MenuBarModel::menuItemsChanged()
  55430. {
  55431. triggerAsyncUpdate();
  55432. }
  55433. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55434. {
  55435. if (manager != newManager)
  55436. {
  55437. if (manager != 0)
  55438. manager->removeListener (this);
  55439. manager = newManager;
  55440. if (manager != 0)
  55441. manager->addListener (this);
  55442. }
  55443. }
  55444. void MenuBarModel::addListener (Listener* const newListener) throw()
  55445. {
  55446. listeners.add (newListener);
  55447. }
  55448. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55449. {
  55450. // Trying to remove a listener that isn't on the list!
  55451. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55452. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55453. jassert (listeners.contains (listenerToRemove));
  55454. listeners.remove (listenerToRemove);
  55455. }
  55456. void MenuBarModel::handleAsyncUpdate()
  55457. {
  55458. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55459. }
  55460. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55461. {
  55462. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55463. }
  55464. void MenuBarModel::applicationCommandListChanged()
  55465. {
  55466. menuItemsChanged();
  55467. }
  55468. END_JUCE_NAMESPACE
  55469. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55470. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55471. BEGIN_JUCE_NAMESPACE
  55472. class PopupMenu::Item
  55473. {
  55474. public:
  55475. Item()
  55476. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55477. usesColour (false), customComp (0), commandManager (0)
  55478. {
  55479. }
  55480. Item (const int itemId_,
  55481. const String& text_,
  55482. const bool active_,
  55483. const bool isTicked_,
  55484. const Image& im,
  55485. const Colour& textColour_,
  55486. const bool usesColour_,
  55487. CustomComponent* const customComp_,
  55488. const PopupMenu* const subMenu_,
  55489. ApplicationCommandManager* const commandManager_)
  55490. : itemId (itemId_), text (text_), textColour (textColour_),
  55491. active (active_), isSeparator (false), isTicked (isTicked_),
  55492. usesColour (usesColour_), image (im), customComp (customComp_),
  55493. commandManager (commandManager_)
  55494. {
  55495. if (subMenu_ != 0)
  55496. subMenu = new PopupMenu (*subMenu_);
  55497. if (commandManager_ != 0 && itemId_ != 0)
  55498. {
  55499. String shortcutKey;
  55500. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55501. ->getKeyPressesAssignedToCommand (itemId_));
  55502. for (int i = 0; i < keyPresses.size(); ++i)
  55503. {
  55504. const String key (keyPresses.getReference(i).getTextDescription());
  55505. if (shortcutKey.isNotEmpty())
  55506. shortcutKey << ", ";
  55507. if (key.length() == 1)
  55508. shortcutKey << "shortcut: '" << key << '\'';
  55509. else
  55510. shortcutKey << key;
  55511. }
  55512. shortcutKey = shortcutKey.trim();
  55513. if (shortcutKey.isNotEmpty())
  55514. text << "<end>" << shortcutKey;
  55515. }
  55516. }
  55517. Item (const Item& other)
  55518. : itemId (other.itemId),
  55519. text (other.text),
  55520. textColour (other.textColour),
  55521. active (other.active),
  55522. isSeparator (other.isSeparator),
  55523. isTicked (other.isTicked),
  55524. usesColour (other.usesColour),
  55525. image (other.image),
  55526. customComp (other.customComp),
  55527. commandManager (other.commandManager)
  55528. {
  55529. if (other.subMenu != 0)
  55530. subMenu = new PopupMenu (*(other.subMenu));
  55531. }
  55532. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55533. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55534. const int itemId;
  55535. String text;
  55536. const Colour textColour;
  55537. const bool active, isSeparator, isTicked, usesColour;
  55538. Image image;
  55539. ReferenceCountedObjectPtr <CustomComponent> customComp;
  55540. ScopedPointer <PopupMenu> subMenu;
  55541. ApplicationCommandManager* const commandManager;
  55542. private:
  55543. Item& operator= (const Item&);
  55544. JUCE_LEAK_DETECTOR (Item);
  55545. };
  55546. class PopupMenu::ItemComponent : public Component
  55547. {
  55548. public:
  55549. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight)
  55550. : itemInfo (itemInfo_),
  55551. isHighlighted (false)
  55552. {
  55553. if (itemInfo.customComp != 0)
  55554. addAndMakeVisible (itemInfo.customComp);
  55555. int itemW = 80;
  55556. int itemH = 16;
  55557. getIdealSize (itemW, itemH, standardItemHeight);
  55558. setSize (itemW, jlimit (2, 600, itemH));
  55559. }
  55560. ~ItemComponent()
  55561. {
  55562. if (itemInfo.customComp != 0)
  55563. removeChildComponent (itemInfo.customComp);
  55564. }
  55565. void getIdealSize (int& idealWidth, int& idealHeight, const int standardItemHeight)
  55566. {
  55567. if (itemInfo.customComp != 0)
  55568. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55569. else
  55570. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55571. itemInfo.isSeparator,
  55572. standardItemHeight,
  55573. idealWidth, idealHeight);
  55574. }
  55575. void paint (Graphics& g)
  55576. {
  55577. if (itemInfo.customComp == 0)
  55578. {
  55579. String mainText (itemInfo.text);
  55580. String endText;
  55581. const int endIndex = mainText.indexOf ("<end>");
  55582. if (endIndex >= 0)
  55583. {
  55584. endText = mainText.substring (endIndex + 5).trim();
  55585. mainText = mainText.substring (0, endIndex);
  55586. }
  55587. getLookAndFeel()
  55588. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55589. itemInfo.isSeparator,
  55590. itemInfo.active,
  55591. isHighlighted,
  55592. itemInfo.isTicked,
  55593. itemInfo.subMenu != 0,
  55594. mainText, endText,
  55595. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55596. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55597. }
  55598. }
  55599. void resized()
  55600. {
  55601. if (getNumChildComponents() > 0)
  55602. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55603. }
  55604. void setHighlighted (bool shouldBeHighlighted)
  55605. {
  55606. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55607. if (isHighlighted != shouldBeHighlighted)
  55608. {
  55609. isHighlighted = shouldBeHighlighted;
  55610. if (itemInfo.customComp != 0)
  55611. itemInfo.customComp->setHighlighted (shouldBeHighlighted);
  55612. repaint();
  55613. }
  55614. }
  55615. PopupMenu::Item itemInfo;
  55616. private:
  55617. bool isHighlighted;
  55618. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55619. };
  55620. namespace PopupMenuSettings
  55621. {
  55622. const int scrollZone = 24;
  55623. const int borderSize = 2;
  55624. const int timerInterval = 50;
  55625. const int dismissCommandId = 0x6287345f;
  55626. }
  55627. class PopupMenu::Window : public Component,
  55628. private Timer
  55629. {
  55630. public:
  55631. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55632. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55633. const int minimumWidth_, const int maximumNumColumns_,
  55634. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55635. ApplicationCommandManager** const managerOfChosenCommand_,
  55636. Component* const componentAttachedTo_)
  55637. : Component ("menu"),
  55638. owner (owner_),
  55639. activeSubMenu (0),
  55640. managerOfChosenCommand (managerOfChosenCommand_),
  55641. componentAttachedTo (componentAttachedTo_),
  55642. componentAttachedToOriginal (componentAttachedTo_),
  55643. minimumWidth (minimumWidth_),
  55644. maximumNumColumns (maximumNumColumns_),
  55645. standardItemHeight (standardItemHeight_),
  55646. isOver (false),
  55647. hasBeenOver (false),
  55648. isDown (false),
  55649. needsToScroll (false),
  55650. dismissOnMouseUp (dismissOnMouseUp_),
  55651. hideOnExit (false),
  55652. disableMouseMoves (false),
  55653. hasAnyJuceCompHadFocus (false),
  55654. numColumns (0),
  55655. contentHeight (0),
  55656. childYOffset (0),
  55657. menuCreationTime (Time::getMillisecondCounter()),
  55658. lastMouseMoveTime (0),
  55659. timeEnteredCurrentChildComp (0),
  55660. scrollAcceleration (1.0)
  55661. {
  55662. lastFocused = lastScroll = menuCreationTime;
  55663. setWantsKeyboardFocus (false);
  55664. setMouseClickGrabsKeyboardFocus (false);
  55665. setAlwaysOnTop (true);
  55666. setLookAndFeel (menu.lookAndFeel);
  55667. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55668. for (int i = 0; i < menu.items.size(); ++i)
  55669. {
  55670. PopupMenu::ItemComponent* const itemComp = new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight);
  55671. items.add (itemComp);
  55672. addAndMakeVisible (itemComp);
  55673. itemComp->addMouseListener (this, false);
  55674. }
  55675. calculateWindowPos (target, alignToRectangle);
  55676. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55677. updateYPositions();
  55678. if (itemIdThatMustBeVisible != 0)
  55679. {
  55680. const int y = target.getY() - windowPos.getY();
  55681. ensureItemIsVisible (itemIdThatMustBeVisible,
  55682. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55683. }
  55684. resizeToBestWindowPos();
  55685. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55686. getActiveWindows().add (this);
  55687. Desktop::getInstance().addGlobalMouseListener (this);
  55688. }
  55689. ~Window()
  55690. {
  55691. getActiveWindows().removeValue (this);
  55692. Desktop::getInstance().removeGlobalMouseListener (this);
  55693. activeSubMenu = 0;
  55694. items.clear();
  55695. }
  55696. static Window* create (const PopupMenu& menu,
  55697. bool dismissOnMouseUp,
  55698. Window* const owner_,
  55699. const Rectangle<int>& target,
  55700. int minimumWidth,
  55701. int maximumNumColumns,
  55702. int standardItemHeight,
  55703. bool alignToRectangle,
  55704. int itemIdThatMustBeVisible,
  55705. ApplicationCommandManager** managerOfChosenCommand,
  55706. Component* componentAttachedTo)
  55707. {
  55708. if (menu.items.size() > 0)
  55709. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55710. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55711. managerOfChosenCommand, componentAttachedTo);
  55712. return 0;
  55713. }
  55714. void paint (Graphics& g)
  55715. {
  55716. if (isOpaque())
  55717. g.fillAll (Colours::white);
  55718. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55719. }
  55720. void paintOverChildren (Graphics& g)
  55721. {
  55722. if (isScrolling())
  55723. {
  55724. LookAndFeel& lf = getLookAndFeel();
  55725. if (isScrollZoneActive (false))
  55726. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55727. if (isScrollZoneActive (true))
  55728. {
  55729. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55730. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55731. }
  55732. }
  55733. }
  55734. bool isScrollZoneActive (bool bottomOne) const
  55735. {
  55736. return isScrolling()
  55737. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55738. : childYOffset > 0);
  55739. }
  55740. // hide this and all sub-comps
  55741. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55742. {
  55743. if (isVisible())
  55744. {
  55745. activeSubMenu = 0;
  55746. currentChild = 0;
  55747. exitModalState (item != 0 ? item->itemId : 0);
  55748. if (makeInvisible)
  55749. setVisible (false);
  55750. if (item != 0
  55751. && item->commandManager != 0
  55752. && item->itemId != 0)
  55753. {
  55754. *managerOfChosenCommand = item->commandManager;
  55755. }
  55756. }
  55757. }
  55758. void dismissMenu (const PopupMenu::Item* const item)
  55759. {
  55760. if (owner != 0)
  55761. {
  55762. owner->dismissMenu (item);
  55763. }
  55764. else
  55765. {
  55766. if (item != 0)
  55767. {
  55768. // need a copy of this on the stack as the one passed in will get deleted during this call
  55769. const PopupMenu::Item mi (*item);
  55770. hide (&mi, false);
  55771. }
  55772. else
  55773. {
  55774. hide (0, false);
  55775. }
  55776. }
  55777. }
  55778. void mouseMove (const MouseEvent&) { timerCallback(); }
  55779. void mouseDown (const MouseEvent&) { timerCallback(); }
  55780. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55781. void mouseUp (const MouseEvent&) { timerCallback(); }
  55782. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55783. {
  55784. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55785. lastMouse = Point<int> (-1, -1);
  55786. }
  55787. bool keyPressed (const KeyPress& key)
  55788. {
  55789. if (key.isKeyCode (KeyPress::downKey))
  55790. {
  55791. selectNextItem (1);
  55792. }
  55793. else if (key.isKeyCode (KeyPress::upKey))
  55794. {
  55795. selectNextItem (-1);
  55796. }
  55797. else if (key.isKeyCode (KeyPress::leftKey))
  55798. {
  55799. if (owner != 0)
  55800. {
  55801. Component::SafePointer<Window> parentWindow (owner);
  55802. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55803. hide (0, true);
  55804. if (parentWindow != 0)
  55805. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55806. disableTimerUntilMouseMoves();
  55807. }
  55808. else if (componentAttachedTo != 0)
  55809. {
  55810. componentAttachedTo->keyPressed (key);
  55811. }
  55812. }
  55813. else if (key.isKeyCode (KeyPress::rightKey))
  55814. {
  55815. disableTimerUntilMouseMoves();
  55816. if (showSubMenuFor (currentChild))
  55817. {
  55818. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55819. activeSubMenu->selectNextItem (1);
  55820. }
  55821. else if (componentAttachedTo != 0)
  55822. {
  55823. componentAttachedTo->keyPressed (key);
  55824. }
  55825. }
  55826. else if (key.isKeyCode (KeyPress::returnKey))
  55827. {
  55828. triggerCurrentlyHighlightedItem();
  55829. }
  55830. else if (key.isKeyCode (KeyPress::escapeKey))
  55831. {
  55832. dismissMenu (0);
  55833. }
  55834. else
  55835. {
  55836. return false;
  55837. }
  55838. return true;
  55839. }
  55840. void inputAttemptWhenModal()
  55841. {
  55842. WeakReference<Component> deletionChecker (this);
  55843. timerCallback();
  55844. if (deletionChecker != 0 && ! isOverAnyMenu())
  55845. {
  55846. if (componentAttachedTo != 0)
  55847. {
  55848. // we want to dismiss the menu, but if we do it synchronously, then
  55849. // the mouse-click will be allowed to pass through. That's good, except
  55850. // when the user clicks on the button that orginally popped the menu up,
  55851. // as they'll expect the menu to go away, and in fact it'll just
  55852. // come back. So only dismiss synchronously if they're not on the original
  55853. // comp that we're attached to.
  55854. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55855. if (componentAttachedTo->reallyContains (mousePos, true))
  55856. {
  55857. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55858. return;
  55859. }
  55860. }
  55861. dismissMenu (0);
  55862. }
  55863. }
  55864. void handleCommandMessage (int commandId)
  55865. {
  55866. Component::handleCommandMessage (commandId);
  55867. if (commandId == PopupMenuSettings::dismissCommandId)
  55868. dismissMenu (0);
  55869. }
  55870. void timerCallback()
  55871. {
  55872. if (! isVisible())
  55873. return;
  55874. if (componentAttachedTo != componentAttachedToOriginal)
  55875. {
  55876. dismissMenu (0);
  55877. return;
  55878. }
  55879. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55880. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55881. return;
  55882. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55883. // move rather than a real timer callback
  55884. const Point<int> globalMousePos (Desktop::getMousePosition());
  55885. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55886. const uint32 now = Time::getMillisecondCounter();
  55887. if (now > timeEnteredCurrentChildComp + 100
  55888. && reallyContains (localMousePos, true)
  55889. && currentChild != 0
  55890. && (! disableMouseMoves)
  55891. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55892. {
  55893. showSubMenuFor (currentChild);
  55894. }
  55895. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55896. {
  55897. highlightItemUnderMouse (globalMousePos, localMousePos);
  55898. }
  55899. bool overScrollArea = false;
  55900. if (isScrolling()
  55901. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  55902. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55903. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55904. {
  55905. if (now > lastScroll + 20)
  55906. {
  55907. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55908. int amount = 0;
  55909. for (int i = 0; i < items.size() && amount == 0; ++i)
  55910. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55911. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55912. lastScroll = now;
  55913. }
  55914. overScrollArea = true;
  55915. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55916. }
  55917. else
  55918. {
  55919. scrollAcceleration = 1.0;
  55920. }
  55921. const bool wasDown = isDown;
  55922. bool isOverAny = isOverAnyMenu();
  55923. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55924. {
  55925. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55926. isOverAny = isOverAnyMenu();
  55927. }
  55928. if (hideOnExit && hasBeenOver && ! isOverAny)
  55929. {
  55930. hide (0, true);
  55931. }
  55932. else
  55933. {
  55934. isDown = hasBeenOver
  55935. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55936. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55937. bool anyFocused = Process::isForegroundProcess();
  55938. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55939. {
  55940. // because no component at all may have focus, our test here will
  55941. // only be triggered when something has focus and then loses it.
  55942. anyFocused = ! hasAnyJuceCompHadFocus;
  55943. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55944. {
  55945. if (ComponentPeer::getPeer (i)->isFocused())
  55946. {
  55947. anyFocused = true;
  55948. hasAnyJuceCompHadFocus = true;
  55949. break;
  55950. }
  55951. }
  55952. }
  55953. if (! anyFocused)
  55954. {
  55955. if (now > lastFocused + 10)
  55956. {
  55957. wasHiddenBecauseOfAppChange() = true;
  55958. dismissMenu (0);
  55959. return; // may have been deleted by the previous call..
  55960. }
  55961. }
  55962. else if (wasDown && now > menuCreationTime + 250
  55963. && ! (isDown || overScrollArea))
  55964. {
  55965. isOver = reallyContains (localMousePos, true);
  55966. if (isOver)
  55967. {
  55968. triggerCurrentlyHighlightedItem();
  55969. }
  55970. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55971. {
  55972. dismissMenu (0);
  55973. }
  55974. return; // may have been deleted by the previous calls..
  55975. }
  55976. else
  55977. {
  55978. lastFocused = now;
  55979. }
  55980. }
  55981. }
  55982. static Array<Window*>& getActiveWindows()
  55983. {
  55984. static Array<Window*> activeMenuWindows;
  55985. return activeMenuWindows;
  55986. }
  55987. static bool& wasHiddenBecauseOfAppChange() throw()
  55988. {
  55989. static bool b = false;
  55990. return b;
  55991. }
  55992. private:
  55993. Window* owner;
  55994. OwnedArray <PopupMenu::ItemComponent> items;
  55995. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55996. ScopedPointer <Window> activeSubMenu;
  55997. ApplicationCommandManager** managerOfChosenCommand;
  55998. WeakReference<Component> componentAttachedTo;
  55999. Component* componentAttachedToOriginal;
  56000. Rectangle<int> windowPos;
  56001. Point<int> lastMouse;
  56002. int minimumWidth, maximumNumColumns, standardItemHeight;
  56003. bool isOver, hasBeenOver, isDown, needsToScroll;
  56004. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56005. int numColumns, contentHeight, childYOffset;
  56006. Array <int> columnWidths;
  56007. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56008. double scrollAcceleration;
  56009. bool overlaps (const Rectangle<int>& r) const
  56010. {
  56011. return r.intersects (getBounds())
  56012. || (owner != 0 && owner->overlaps (r));
  56013. }
  56014. bool isOverAnyMenu() const
  56015. {
  56016. return (owner != 0) ? owner->isOverAnyMenu()
  56017. : isOverChildren();
  56018. }
  56019. bool isOverChildren() const
  56020. {
  56021. return isVisible()
  56022. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56023. }
  56024. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56025. {
  56026. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  56027. isOver = reallyContains (relPos, true);
  56028. if (activeSubMenu != 0)
  56029. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56030. }
  56031. bool treeContains (const Window* const window) const throw()
  56032. {
  56033. const Window* mw = this;
  56034. while (mw->owner != 0)
  56035. mw = mw->owner;
  56036. while (mw != 0)
  56037. {
  56038. if (mw == window)
  56039. return true;
  56040. mw = mw->activeSubMenu;
  56041. }
  56042. return false;
  56043. }
  56044. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56045. {
  56046. const Rectangle<int> mon (Desktop::getInstance()
  56047. .getMonitorAreaContaining (target.getCentre(),
  56048. #if JUCE_MAC
  56049. true));
  56050. #else
  56051. false)); // on windows, don't stop the menu overlapping the taskbar
  56052. #endif
  56053. int x, y, widthToUse, heightToUse;
  56054. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56055. if (alignToRectangle)
  56056. {
  56057. x = target.getX();
  56058. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56059. const int spaceOver = target.getY() - mon.getY();
  56060. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56061. y = target.getBottom();
  56062. else
  56063. y = target.getY() - heightToUse;
  56064. }
  56065. else
  56066. {
  56067. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56068. if (owner != 0)
  56069. {
  56070. if (owner->owner != 0)
  56071. {
  56072. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56073. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56074. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56075. tendTowardsRight = true;
  56076. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56077. tendTowardsRight = false;
  56078. }
  56079. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56080. {
  56081. tendTowardsRight = true;
  56082. }
  56083. }
  56084. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56085. target.getX() - mon.getX()) - 32;
  56086. if (biggestSpace < widthToUse)
  56087. {
  56088. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56089. if (numColumns > 1)
  56090. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56091. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56092. }
  56093. if (tendTowardsRight)
  56094. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56095. else
  56096. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56097. y = target.getY();
  56098. if (target.getCentreY() > mon.getCentreY())
  56099. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56100. }
  56101. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56102. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56103. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56104. // sets this flag if it's big enough to obscure any of its parent menus
  56105. hideOnExit = (owner != 0)
  56106. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56107. }
  56108. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56109. {
  56110. numColumns = 0;
  56111. contentHeight = 0;
  56112. const int maxMenuH = getParentHeight() - 24;
  56113. int totalW;
  56114. do
  56115. {
  56116. ++numColumns;
  56117. totalW = workOutBestSize (maxMenuW);
  56118. if (totalW > maxMenuW)
  56119. {
  56120. numColumns = jmax (1, numColumns - 1);
  56121. totalW = workOutBestSize (maxMenuW); // to update col widths
  56122. break;
  56123. }
  56124. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56125. {
  56126. break;
  56127. }
  56128. } while (numColumns < maximumNumColumns);
  56129. const int actualH = jmin (contentHeight, maxMenuH);
  56130. needsToScroll = contentHeight > actualH;
  56131. width = updateYPositions();
  56132. height = actualH + PopupMenuSettings::borderSize * 2;
  56133. }
  56134. int workOutBestSize (const int maxMenuW)
  56135. {
  56136. int totalW = 0;
  56137. contentHeight = 0;
  56138. int childNum = 0;
  56139. for (int col = 0; col < numColumns; ++col)
  56140. {
  56141. int i, colW = 50, colH = 0;
  56142. const int numChildren = jmin (items.size() - childNum,
  56143. (items.size() + numColumns - 1) / numColumns);
  56144. for (i = numChildren; --i >= 0;)
  56145. {
  56146. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56147. colH += items.getUnchecked (childNum + i)->getHeight();
  56148. }
  56149. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56150. columnWidths.set (col, colW);
  56151. totalW += colW;
  56152. contentHeight = jmax (contentHeight, colH);
  56153. childNum += numChildren;
  56154. }
  56155. if (totalW < minimumWidth)
  56156. {
  56157. totalW = minimumWidth;
  56158. for (int col = 0; col < numColumns; ++col)
  56159. columnWidths.set (0, totalW / numColumns);
  56160. }
  56161. return totalW;
  56162. }
  56163. void ensureItemIsVisible (const int itemId, int wantedY)
  56164. {
  56165. jassert (itemId != 0)
  56166. for (int i = items.size(); --i >= 0;)
  56167. {
  56168. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56169. if (m != 0
  56170. && m->itemInfo.itemId == itemId
  56171. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56172. {
  56173. const int currentY = m->getY();
  56174. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56175. {
  56176. if (wantedY < 0)
  56177. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56178. jmax (PopupMenuSettings::scrollZone,
  56179. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56180. currentY);
  56181. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56182. int deltaY = wantedY - currentY;
  56183. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56184. jmin (windowPos.getHeight(), mon.getHeight()));
  56185. const int newY = jlimit (mon.getY(),
  56186. mon.getBottom() - windowPos.getHeight(),
  56187. windowPos.getY() + deltaY);
  56188. deltaY -= newY - windowPos.getY();
  56189. childYOffset -= deltaY;
  56190. windowPos.setPosition (windowPos.getX(), newY);
  56191. updateYPositions();
  56192. }
  56193. break;
  56194. }
  56195. }
  56196. }
  56197. void resizeToBestWindowPos()
  56198. {
  56199. Rectangle<int> r (windowPos);
  56200. if (childYOffset < 0)
  56201. {
  56202. r.setBounds (r.getX(), r.getY() - childYOffset,
  56203. r.getWidth(), r.getHeight() + childYOffset);
  56204. }
  56205. else if (childYOffset > 0)
  56206. {
  56207. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56208. if (spaceAtBottom > 0)
  56209. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56210. }
  56211. setBounds (r);
  56212. updateYPositions();
  56213. }
  56214. void alterChildYPos (const int delta)
  56215. {
  56216. if (isScrolling())
  56217. {
  56218. childYOffset += delta;
  56219. if (delta < 0)
  56220. {
  56221. childYOffset = jmax (childYOffset, 0);
  56222. }
  56223. else if (delta > 0)
  56224. {
  56225. childYOffset = jmin (childYOffset,
  56226. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56227. }
  56228. updateYPositions();
  56229. }
  56230. else
  56231. {
  56232. childYOffset = 0;
  56233. }
  56234. resizeToBestWindowPos();
  56235. repaint();
  56236. }
  56237. int updateYPositions()
  56238. {
  56239. int x = 0;
  56240. int childNum = 0;
  56241. for (int col = 0; col < numColumns; ++col)
  56242. {
  56243. const int numChildren = jmin (items.size() - childNum,
  56244. (items.size() + numColumns - 1) / numColumns);
  56245. const int colW = columnWidths [col];
  56246. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56247. for (int i = 0; i < numChildren; ++i)
  56248. {
  56249. Component* const c = items.getUnchecked (childNum + i);
  56250. c->setBounds (x, y, colW, c->getHeight());
  56251. y += c->getHeight();
  56252. }
  56253. x += colW;
  56254. childNum += numChildren;
  56255. }
  56256. return x;
  56257. }
  56258. bool isScrolling() const throw()
  56259. {
  56260. return childYOffset != 0 || needsToScroll;
  56261. }
  56262. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56263. {
  56264. if (currentChild != 0)
  56265. currentChild->setHighlighted (false);
  56266. currentChild = child;
  56267. if (currentChild != 0)
  56268. {
  56269. currentChild->setHighlighted (true);
  56270. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56271. }
  56272. }
  56273. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56274. {
  56275. activeSubMenu = 0;
  56276. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56277. {
  56278. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56279. dismissOnMouseUp,
  56280. this,
  56281. childComp->getScreenBounds(),
  56282. 0, maximumNumColumns,
  56283. standardItemHeight,
  56284. false, 0, managerOfChosenCommand,
  56285. componentAttachedTo);
  56286. if (activeSubMenu != 0)
  56287. {
  56288. activeSubMenu->setVisible (true);
  56289. activeSubMenu->enterModalState (false);
  56290. activeSubMenu->toFront (false);
  56291. return true;
  56292. }
  56293. }
  56294. return false;
  56295. }
  56296. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56297. {
  56298. isOver = reallyContains (localMousePos, true);
  56299. if (isOver)
  56300. hasBeenOver = true;
  56301. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56302. {
  56303. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56304. if (disableMouseMoves && isOver)
  56305. disableMouseMoves = false;
  56306. }
  56307. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56308. return;
  56309. bool isMovingTowardsMenu = false;
  56310. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56311. {
  56312. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56313. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56314. // extends from the last mouse pos to the submenu's rectangle..
  56315. float subX = (float) activeSubMenu->getScreenX();
  56316. if (activeSubMenu->getX() > getX())
  56317. {
  56318. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56319. }
  56320. else
  56321. {
  56322. lastMouse += Point<int> (2, 0);
  56323. subX += activeSubMenu->getWidth();
  56324. }
  56325. Path areaTowardsSubMenu;
  56326. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56327. subX, (float) activeSubMenu->getScreenY(),
  56328. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56329. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56330. }
  56331. lastMouse = globalMousePos;
  56332. if (! isMovingTowardsMenu)
  56333. {
  56334. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56335. if (c == this)
  56336. c = 0;
  56337. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56338. if (mic == 0 && c != 0)
  56339. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56340. if (mic != currentChild
  56341. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56342. {
  56343. if (isOver && (c != 0) && (activeSubMenu != 0))
  56344. activeSubMenu->hide (0, true);
  56345. if (! isOver)
  56346. mic = 0;
  56347. setCurrentlyHighlightedChild (mic);
  56348. }
  56349. }
  56350. }
  56351. void triggerCurrentlyHighlightedItem()
  56352. {
  56353. if (currentChild != 0
  56354. && currentChild->itemInfo.canBeTriggered()
  56355. && (currentChild->itemInfo.customComp == 0
  56356. || currentChild->itemInfo.customComp->isTriggeredAutomatically()))
  56357. {
  56358. dismissMenu (&currentChild->itemInfo);
  56359. }
  56360. }
  56361. void selectNextItem (const int delta)
  56362. {
  56363. disableTimerUntilMouseMoves();
  56364. PopupMenu::ItemComponent* mic = 0;
  56365. bool wasLastOne = (currentChild == 0);
  56366. const int numItems = items.size();
  56367. for (int i = 0; i < numItems + 1; ++i)
  56368. {
  56369. int index = (delta > 0) ? i : (numItems - 1 - i);
  56370. index = (index + numItems) % numItems;
  56371. mic = items.getUnchecked (index);
  56372. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56373. && wasLastOne)
  56374. break;
  56375. if (mic == currentChild)
  56376. wasLastOne = true;
  56377. }
  56378. setCurrentlyHighlightedChild (mic);
  56379. }
  56380. void disableTimerUntilMouseMoves()
  56381. {
  56382. disableMouseMoves = true;
  56383. if (owner != 0)
  56384. owner->disableTimerUntilMouseMoves();
  56385. }
  56386. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56387. };
  56388. PopupMenu::PopupMenu()
  56389. : lookAndFeel (0),
  56390. separatorPending (false)
  56391. {
  56392. }
  56393. PopupMenu::PopupMenu (const PopupMenu& other)
  56394. : lookAndFeel (other.lookAndFeel),
  56395. separatorPending (false)
  56396. {
  56397. items.addCopiesOf (other.items);
  56398. }
  56399. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56400. {
  56401. if (this != &other)
  56402. {
  56403. lookAndFeel = other.lookAndFeel;
  56404. clear();
  56405. items.addCopiesOf (other.items);
  56406. }
  56407. return *this;
  56408. }
  56409. PopupMenu::~PopupMenu()
  56410. {
  56411. clear();
  56412. }
  56413. void PopupMenu::clear()
  56414. {
  56415. items.clear();
  56416. separatorPending = false;
  56417. }
  56418. void PopupMenu::addSeparatorIfPending()
  56419. {
  56420. if (separatorPending)
  56421. {
  56422. separatorPending = false;
  56423. if (items.size() > 0)
  56424. items.add (new Item());
  56425. }
  56426. }
  56427. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56428. const bool isActive, const bool isTicked, const Image& iconToUse)
  56429. {
  56430. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56431. // didn't pick anything, so you shouldn't use it as the id
  56432. // for an item..
  56433. addSeparatorIfPending();
  56434. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56435. Colours::black, false, 0, 0, 0));
  56436. }
  56437. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56438. const int commandID,
  56439. const String& displayName)
  56440. {
  56441. jassert (commandManager != 0 && commandID != 0);
  56442. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56443. if (registeredInfo != 0)
  56444. {
  56445. ApplicationCommandInfo info (*registeredInfo);
  56446. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56447. addSeparatorIfPending();
  56448. items.add (new Item (commandID,
  56449. displayName.isNotEmpty() ? displayName
  56450. : info.shortName,
  56451. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56452. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56453. Image::null,
  56454. Colours::black,
  56455. false,
  56456. 0, 0,
  56457. commandManager));
  56458. }
  56459. }
  56460. void PopupMenu::addColouredItem (const int itemResultId,
  56461. const String& itemText,
  56462. const Colour& itemTextColour,
  56463. const bool isActive,
  56464. const bool isTicked,
  56465. const Image& iconToUse)
  56466. {
  56467. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56468. // didn't pick anything, so you shouldn't use it as the id
  56469. // for an item..
  56470. addSeparatorIfPending();
  56471. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56472. itemTextColour, true, 0, 0, 0));
  56473. }
  56474. void PopupMenu::addCustomItem (const int itemResultId, CustomComponent* const customComponent)
  56475. {
  56476. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56477. // didn't pick anything, so you shouldn't use it as the id
  56478. // for an item..
  56479. addSeparatorIfPending();
  56480. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56481. Colours::black, false, customComponent, 0, 0));
  56482. }
  56483. class NormalComponentWrapper : public PopupMenu::CustomComponent
  56484. {
  56485. public:
  56486. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56487. const bool triggerMenuItemAutomaticallyWhenClicked)
  56488. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56489. width (w), height (h)
  56490. {
  56491. addAndMakeVisible (comp);
  56492. }
  56493. void getIdealSize (int& idealWidth, int& idealHeight)
  56494. {
  56495. idealWidth = width;
  56496. idealHeight = height;
  56497. }
  56498. void resized()
  56499. {
  56500. if (getChildComponent(0) != 0)
  56501. getChildComponent(0)->setBounds (getLocalBounds());
  56502. }
  56503. private:
  56504. const int width, height;
  56505. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56506. };
  56507. void PopupMenu::addCustomItem (const int itemResultId,
  56508. Component* customComponent,
  56509. int idealWidth, int idealHeight,
  56510. const bool triggerMenuItemAutomaticallyWhenClicked)
  56511. {
  56512. addCustomItem (itemResultId,
  56513. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56514. triggerMenuItemAutomaticallyWhenClicked));
  56515. }
  56516. void PopupMenu::addSubMenu (const String& subMenuName,
  56517. const PopupMenu& subMenu,
  56518. const bool isActive,
  56519. const Image& iconToUse,
  56520. const bool isTicked)
  56521. {
  56522. addSeparatorIfPending();
  56523. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56524. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56525. }
  56526. void PopupMenu::addSeparator()
  56527. {
  56528. separatorPending = true;
  56529. }
  56530. class HeaderItemComponent : public PopupMenu::CustomComponent
  56531. {
  56532. public:
  56533. HeaderItemComponent (const String& name)
  56534. : PopupMenu::CustomComponent (false)
  56535. {
  56536. setName (name);
  56537. }
  56538. void paint (Graphics& g)
  56539. {
  56540. Font f (getLookAndFeel().getPopupMenuFont());
  56541. f.setBold (true);
  56542. g.setFont (f);
  56543. g.setColour (findColour (PopupMenu::headerTextColourId));
  56544. g.drawFittedText (getName(),
  56545. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56546. Justification::bottomLeft, 1);
  56547. }
  56548. void getIdealSize (int& idealWidth, int& idealHeight)
  56549. {
  56550. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56551. idealHeight += idealHeight / 2;
  56552. idealWidth += idealWidth / 4;
  56553. }
  56554. private:
  56555. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56556. };
  56557. void PopupMenu::addSectionHeader (const String& title)
  56558. {
  56559. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56560. }
  56561. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56562. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56563. {
  56564. public:
  56565. PopupMenuCompletionCallback()
  56566. : managerOfChosenCommand (0)
  56567. {
  56568. }
  56569. void modalStateFinished (int result)
  56570. {
  56571. if (managerOfChosenCommand != 0 && result != 0)
  56572. {
  56573. ApplicationCommandTarget::InvocationInfo info (result);
  56574. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56575. managerOfChosenCommand->invoke (info, true);
  56576. }
  56577. // (this would be the place to fade out the component, if that's what's required)
  56578. component = 0;
  56579. }
  56580. ApplicationCommandManager* managerOfChosenCommand;
  56581. ScopedPointer<Component> component;
  56582. private:
  56583. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56584. };
  56585. int PopupMenu::showMenu (const Rectangle<int>& target,
  56586. const int itemIdThatMustBeVisible,
  56587. const int minimumWidth,
  56588. const int maximumNumColumns,
  56589. const int standardItemHeight,
  56590. Component* const componentAttachedTo,
  56591. ModalComponentManager::Callback* userCallback)
  56592. {
  56593. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56594. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56595. WeakReference<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56596. Window::wasHiddenBecauseOfAppChange() = false;
  56597. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56598. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56599. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56600. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56601. standardItemHeight, ! target.isEmpty(), itemIdThatMustBeVisible,
  56602. &callback->managerOfChosenCommand, componentAttachedTo);
  56603. if (callback->component == 0)
  56604. return 0;
  56605. callback->component->enterModalState (false, userCallbackDeleter.release());
  56606. callback->component->toFront (false); // need to do this after making it modal, or it could
  56607. // be stuck behind other comps that are already modal..
  56608. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56609. callbackDeleter.release();
  56610. if (userCallback != 0)
  56611. return 0;
  56612. const int result = callback->component->runModalLoop();
  56613. if (! Window::wasHiddenBecauseOfAppChange())
  56614. {
  56615. if (prevTopLevel != 0)
  56616. prevTopLevel->toFront (true);
  56617. if (prevFocused != 0)
  56618. prevFocused->grabKeyboardFocus();
  56619. }
  56620. return result;
  56621. }
  56622. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56623. const int minimumWidth, const int maximumNumColumns,
  56624. const int standardItemHeight,
  56625. ModalComponentManager::Callback* callback)
  56626. {
  56627. return showMenu (Rectangle<int>().withPosition (Desktop::getMousePosition()),
  56628. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56629. standardItemHeight, 0, callback);
  56630. }
  56631. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56632. const int itemIdThatMustBeVisible,
  56633. const int minimumWidth, const int maximumNumColumns,
  56634. const int standardItemHeight,
  56635. ModalComponentManager::Callback* callback)
  56636. {
  56637. return showMenu (screenAreaToAttachTo,
  56638. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56639. standardItemHeight, 0, callback);
  56640. }
  56641. int PopupMenu::showAt (Component* componentToAttachTo,
  56642. const int itemIdThatMustBeVisible,
  56643. const int minimumWidth, const int maximumNumColumns,
  56644. const int standardItemHeight,
  56645. ModalComponentManager::Callback* callback)
  56646. {
  56647. if (componentToAttachTo != 0)
  56648. {
  56649. return showMenu (componentToAttachTo->getScreenBounds(),
  56650. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56651. standardItemHeight, componentToAttachTo, callback);
  56652. }
  56653. else
  56654. {
  56655. return show (itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56656. standardItemHeight, callback);
  56657. }
  56658. }
  56659. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56660. {
  56661. const int numWindows = Window::getActiveWindows().size();
  56662. for (int i = numWindows; --i >= 0;)
  56663. {
  56664. Window* const pmw = Window::getActiveWindows()[i];
  56665. if (pmw != 0)
  56666. pmw->dismissMenu (0);
  56667. }
  56668. return numWindows > 0;
  56669. }
  56670. int PopupMenu::getNumItems() const throw()
  56671. {
  56672. int num = 0;
  56673. for (int i = items.size(); --i >= 0;)
  56674. if (! (items.getUnchecked(i))->isSeparator)
  56675. ++num;
  56676. return num;
  56677. }
  56678. bool PopupMenu::containsCommandItem (const int commandID) const
  56679. {
  56680. for (int i = items.size(); --i >= 0;)
  56681. {
  56682. const Item* mi = items.getUnchecked (i);
  56683. if ((mi->itemId == commandID && mi->commandManager != 0)
  56684. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56685. {
  56686. return true;
  56687. }
  56688. }
  56689. return false;
  56690. }
  56691. bool PopupMenu::containsAnyActiveItems() const throw()
  56692. {
  56693. for (int i = items.size(); --i >= 0;)
  56694. {
  56695. const Item* const mi = items.getUnchecked (i);
  56696. if (mi->subMenu != 0)
  56697. {
  56698. if (mi->subMenu->containsAnyActiveItems())
  56699. return true;
  56700. }
  56701. else if (mi->active)
  56702. {
  56703. return true;
  56704. }
  56705. }
  56706. return false;
  56707. }
  56708. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56709. {
  56710. lookAndFeel = newLookAndFeel;
  56711. }
  56712. PopupMenu::CustomComponent::CustomComponent (const bool isTriggeredAutomatically_)
  56713. : isHighlighted (false),
  56714. triggeredAutomatically (isTriggeredAutomatically_)
  56715. {
  56716. }
  56717. PopupMenu::CustomComponent::~CustomComponent()
  56718. {
  56719. }
  56720. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  56721. {
  56722. isHighlighted = shouldBeHighlighted;
  56723. repaint();
  56724. }
  56725. void PopupMenu::CustomComponent::triggerMenuItem()
  56726. {
  56727. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56728. if (mic != 0)
  56729. {
  56730. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56731. if (pmw != 0)
  56732. {
  56733. pmw->dismissMenu (&mic->itemInfo);
  56734. }
  56735. else
  56736. {
  56737. // something must have gone wrong with the component hierarchy if this happens..
  56738. jassertfalse;
  56739. }
  56740. }
  56741. else
  56742. {
  56743. // why isn't this component inside a menu? Not much point triggering the item if
  56744. // there's no menu.
  56745. jassertfalse;
  56746. }
  56747. }
  56748. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56749. : subMenu (0),
  56750. itemId (0),
  56751. isSeparator (false),
  56752. isTicked (false),
  56753. isEnabled (false),
  56754. isCustomComponent (false),
  56755. isSectionHeader (false),
  56756. customColour (0),
  56757. customImage (0),
  56758. menu (menu_),
  56759. index (0)
  56760. {
  56761. }
  56762. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56763. {
  56764. }
  56765. bool PopupMenu::MenuItemIterator::next()
  56766. {
  56767. if (index >= menu.items.size())
  56768. return false;
  56769. const Item* const item = menu.items.getUnchecked (index);
  56770. ++index;
  56771. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56772. subMenu = item->subMenu;
  56773. itemId = item->itemId;
  56774. isSeparator = item->isSeparator;
  56775. isTicked = item->isTicked;
  56776. isEnabled = item->active;
  56777. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <CustomComponent*> (item->customComp)) != 0;
  56778. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56779. customColour = item->usesColour ? &(item->textColour) : 0;
  56780. customImage = item->image;
  56781. commandManager = item->commandManager;
  56782. return true;
  56783. }
  56784. END_JUCE_NAMESPACE
  56785. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56786. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56787. BEGIN_JUCE_NAMESPACE
  56788. ComponentDragger::ComponentDragger()
  56789. {
  56790. }
  56791. ComponentDragger::~ComponentDragger()
  56792. {
  56793. }
  56794. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  56795. {
  56796. jassert (componentToDrag != 0);
  56797. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56798. if (componentToDrag != 0)
  56799. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  56800. }
  56801. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  56802. ComponentBoundsConstrainer* const constrainer)
  56803. {
  56804. jassert (componentToDrag != 0);
  56805. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56806. if (componentToDrag != 0)
  56807. {
  56808. Rectangle<int> bounds (componentToDrag->getBounds());
  56809. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  56810. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  56811. // the current mouse position instead of the one that the event contains...
  56812. if (componentToDrag->isOnDesktop())
  56813. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  56814. else
  56815. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  56816. if (constrainer != 0)
  56817. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56818. else
  56819. componentToDrag->setBounds (bounds);
  56820. }
  56821. }
  56822. END_JUCE_NAMESPACE
  56823. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56824. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56825. BEGIN_JUCE_NAMESPACE
  56826. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56827. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56828. class DragImageComponent : public Component,
  56829. public Timer
  56830. {
  56831. public:
  56832. DragImageComponent (const Image& im,
  56833. const String& desc,
  56834. Component* const sourceComponent,
  56835. Component* const mouseDragSource_,
  56836. DragAndDropContainer* const o,
  56837. const Point<int>& imageOffset_)
  56838. : image (im),
  56839. source (sourceComponent),
  56840. mouseDragSource (mouseDragSource_),
  56841. owner (o),
  56842. dragDesc (desc),
  56843. imageOffset (imageOffset_),
  56844. hasCheckedForExternalDrag (false),
  56845. drawImage (true)
  56846. {
  56847. setSize (im.getWidth(), im.getHeight());
  56848. if (mouseDragSource == 0)
  56849. mouseDragSource = source;
  56850. mouseDragSource->addMouseListener (this, false);
  56851. startTimer (200);
  56852. setInterceptsMouseClicks (false, false);
  56853. setAlwaysOnTop (true);
  56854. }
  56855. ~DragImageComponent()
  56856. {
  56857. if (owner->dragImageComponent == this)
  56858. owner->dragImageComponent.release();
  56859. if (mouseDragSource != 0)
  56860. {
  56861. mouseDragSource->removeMouseListener (this);
  56862. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56863. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56864. }
  56865. }
  56866. void paint (Graphics& g)
  56867. {
  56868. if (isOpaque())
  56869. g.fillAll (Colours::white);
  56870. if (drawImage)
  56871. {
  56872. g.setOpacity (1.0f);
  56873. g.drawImageAt (image, 0, 0);
  56874. }
  56875. }
  56876. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56877. {
  56878. Component* hit = getParentComponent();
  56879. if (hit == 0)
  56880. {
  56881. hit = Desktop::getInstance().findComponentAt (screenPos);
  56882. }
  56883. else
  56884. {
  56885. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56886. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56887. }
  56888. // (note: use a local copy of the dragDesc member in case the callback runs
  56889. // a modal loop and deletes this object before the method completes)
  56890. const String dragDescLocal (dragDesc);
  56891. while (hit != 0)
  56892. {
  56893. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56894. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56895. {
  56896. relativePos = hit->getLocalPoint (0, screenPos);
  56897. return ddt;
  56898. }
  56899. hit = hit->getParentComponent();
  56900. }
  56901. return 0;
  56902. }
  56903. void mouseUp (const MouseEvent& e)
  56904. {
  56905. if (e.originalComponent != this)
  56906. {
  56907. if (mouseDragSource != 0)
  56908. mouseDragSource->removeMouseListener (this);
  56909. bool dropAccepted = false;
  56910. DragAndDropTarget* ddt = 0;
  56911. Point<int> relPos;
  56912. if (isVisible())
  56913. {
  56914. setVisible (false);
  56915. ddt = findTarget (e.getScreenPosition(), relPos);
  56916. // fade this component and remove it - it'll be deleted later by the timer callback
  56917. dropAccepted = ddt != 0;
  56918. setVisible (true);
  56919. if (dropAccepted || source == 0)
  56920. {
  56921. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56922. }
  56923. else
  56924. {
  56925. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56926. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56927. Desktop::getInstance().getAnimator().animateComponent (this,
  56928. getBounds() + (target - ourCentre),
  56929. 0.0f, 120,
  56930. true, 1.0, 1.0);
  56931. }
  56932. }
  56933. if (getParentComponent() != 0)
  56934. getParentComponent()->removeChildComponent (this);
  56935. if (dropAccepted && ddt != 0)
  56936. {
  56937. // (note: use a local copy of the dragDesc member in case the callback runs
  56938. // a modal loop and deletes this object before the method completes)
  56939. const String dragDescLocal (dragDesc);
  56940. currentlyOverComp = 0;
  56941. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56942. }
  56943. // careful - this object could now be deleted..
  56944. }
  56945. }
  56946. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56947. {
  56948. // (note: use a local copy of the dragDesc member in case the callback runs
  56949. // a modal loop and deletes this object before it returns)
  56950. const String dragDescLocal (dragDesc);
  56951. Point<int> newPos (screenPos + imageOffset);
  56952. if (getParentComponent() != 0)
  56953. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56954. //if (newX != getX() || newY != getY())
  56955. {
  56956. setTopLeftPosition (newPos.getX(), newPos.getY());
  56957. Point<int> relPos;
  56958. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56959. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56960. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56961. if (ddtComp != currentlyOverComp)
  56962. {
  56963. if (currentlyOverComp != 0 && source != 0
  56964. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56965. {
  56966. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56967. }
  56968. currentlyOverComp = ddtComp;
  56969. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56970. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56971. }
  56972. DragAndDropTarget* target = getCurrentlyOver();
  56973. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56974. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56975. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56976. {
  56977. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56978. {
  56979. hasCheckedForExternalDrag = true;
  56980. StringArray files;
  56981. bool canMoveFiles = false;
  56982. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56983. && files.size() > 0)
  56984. {
  56985. WeakReference<Component> cdw (this);
  56986. setVisible (false);
  56987. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56988. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56989. if (cdw != 0)
  56990. delete this;
  56991. return;
  56992. }
  56993. }
  56994. }
  56995. }
  56996. }
  56997. void mouseDrag (const MouseEvent& e)
  56998. {
  56999. if (e.originalComponent != this)
  57000. updateLocation (true, e.getScreenPosition());
  57001. }
  57002. void timerCallback()
  57003. {
  57004. if (source == 0)
  57005. {
  57006. delete this;
  57007. }
  57008. else if (! isMouseButtonDownAnywhere())
  57009. {
  57010. if (mouseDragSource != 0)
  57011. mouseDragSource->removeMouseListener (this);
  57012. delete this;
  57013. }
  57014. }
  57015. private:
  57016. Image image;
  57017. WeakReference<Component> source;
  57018. WeakReference<Component> mouseDragSource;
  57019. DragAndDropContainer* const owner;
  57020. WeakReference<Component> currentlyOverComp;
  57021. DragAndDropTarget* getCurrentlyOver()
  57022. {
  57023. return dynamic_cast <DragAndDropTarget*> (currentlyOverComp.get());
  57024. }
  57025. String dragDesc;
  57026. const Point<int> imageOffset;
  57027. bool hasCheckedForExternalDrag, drawImage;
  57028. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  57029. };
  57030. DragAndDropContainer::DragAndDropContainer()
  57031. {
  57032. }
  57033. DragAndDropContainer::~DragAndDropContainer()
  57034. {
  57035. dragImageComponent = 0;
  57036. }
  57037. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57038. Component* sourceComponent,
  57039. const Image& dragImage_,
  57040. const bool allowDraggingToExternalWindows,
  57041. const Point<int>* imageOffsetFromMouse)
  57042. {
  57043. Image dragImage (dragImage_);
  57044. if (dragImageComponent == 0)
  57045. {
  57046. Component* const thisComp = dynamic_cast <Component*> (this);
  57047. if (thisComp == 0)
  57048. {
  57049. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57050. return;
  57051. }
  57052. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57053. if (draggingSource == 0 || ! draggingSource->isDragging())
  57054. {
  57055. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57056. return;
  57057. }
  57058. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57059. Point<int> imageOffset;
  57060. if (dragImage.isNull())
  57061. {
  57062. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57063. .convertedToFormat (Image::ARGB);
  57064. dragImage.multiplyAllAlphas (0.6f);
  57065. const int lo = 150;
  57066. const int hi = 400;
  57067. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  57068. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57069. for (int y = dragImage.getHeight(); --y >= 0;)
  57070. {
  57071. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57072. for (int x = dragImage.getWidth(); --x >= 0;)
  57073. {
  57074. const int dx = x - clipped.getX();
  57075. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57076. if (distance > lo)
  57077. {
  57078. const float alpha = (distance > hi) ? 0
  57079. : (hi - distance) / (float) (hi - lo)
  57080. + Random::getSystemRandom().nextFloat() * 0.008f;
  57081. dragImage.multiplyAlphaAt (x, y, alpha);
  57082. }
  57083. }
  57084. }
  57085. imageOffset = -clipped;
  57086. }
  57087. else
  57088. {
  57089. if (imageOffsetFromMouse == 0)
  57090. imageOffset = -dragImage.getBounds().getCentre();
  57091. else
  57092. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57093. }
  57094. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57095. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57096. currentDragDesc = sourceDescription;
  57097. if (allowDraggingToExternalWindows)
  57098. {
  57099. if (! Desktop::canUseSemiTransparentWindows())
  57100. dragImageComponent->setOpaque (true);
  57101. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57102. | ComponentPeer::windowIsTemporary
  57103. | ComponentPeer::windowIgnoresKeyPresses);
  57104. }
  57105. else
  57106. thisComp->addChildComponent (dragImageComponent);
  57107. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57108. dragImageComponent->setVisible (true);
  57109. }
  57110. }
  57111. bool DragAndDropContainer::isDragAndDropActive() const
  57112. {
  57113. return dragImageComponent != 0;
  57114. }
  57115. const String DragAndDropContainer::getCurrentDragDescription() const
  57116. {
  57117. return (dragImageComponent != 0) ? currentDragDesc
  57118. : String::empty;
  57119. }
  57120. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57121. {
  57122. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57123. }
  57124. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57125. {
  57126. return false;
  57127. }
  57128. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57129. {
  57130. }
  57131. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57132. {
  57133. }
  57134. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57135. {
  57136. }
  57137. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57138. {
  57139. return true;
  57140. }
  57141. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57142. {
  57143. }
  57144. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57145. {
  57146. }
  57147. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57148. {
  57149. }
  57150. END_JUCE_NAMESPACE
  57151. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57152. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57153. BEGIN_JUCE_NAMESPACE
  57154. class MouseCursor::SharedCursorHandle
  57155. {
  57156. public:
  57157. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57158. : handle (createStandardMouseCursor (type)),
  57159. refCount (1),
  57160. standardType (type),
  57161. isStandard (true)
  57162. {
  57163. }
  57164. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57165. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57166. refCount (1),
  57167. standardType (MouseCursor::NormalCursor),
  57168. isStandard (false)
  57169. {
  57170. }
  57171. ~SharedCursorHandle()
  57172. {
  57173. deleteMouseCursor (handle, isStandard);
  57174. }
  57175. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57176. {
  57177. const ScopedLock sl (getLock());
  57178. for (int i = 0; i < getCursors().size(); ++i)
  57179. {
  57180. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57181. if (sc->standardType == type)
  57182. return sc->retain();
  57183. }
  57184. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57185. getCursors().add (sc);
  57186. return sc;
  57187. }
  57188. SharedCursorHandle* retain() throw()
  57189. {
  57190. ++refCount;
  57191. return this;
  57192. }
  57193. void release()
  57194. {
  57195. if (--refCount == 0)
  57196. {
  57197. if (isStandard)
  57198. {
  57199. const ScopedLock sl (getLock());
  57200. getCursors().removeValue (this);
  57201. }
  57202. delete this;
  57203. }
  57204. }
  57205. void* getHandle() const throw() { return handle; }
  57206. private:
  57207. void* const handle;
  57208. Atomic <int> refCount;
  57209. const MouseCursor::StandardCursorType standardType;
  57210. const bool isStandard;
  57211. static CriticalSection& getLock()
  57212. {
  57213. static CriticalSection lock;
  57214. return lock;
  57215. }
  57216. static Array <SharedCursorHandle*>& getCursors()
  57217. {
  57218. static Array <SharedCursorHandle*> cursors;
  57219. return cursors;
  57220. }
  57221. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57222. };
  57223. MouseCursor::MouseCursor()
  57224. : cursorHandle (0)
  57225. {
  57226. }
  57227. MouseCursor::MouseCursor (const StandardCursorType type)
  57228. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57229. {
  57230. }
  57231. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57232. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57233. {
  57234. }
  57235. MouseCursor::MouseCursor (const MouseCursor& other)
  57236. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57237. {
  57238. }
  57239. MouseCursor::~MouseCursor()
  57240. {
  57241. if (cursorHandle != 0)
  57242. cursorHandle->release();
  57243. }
  57244. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57245. {
  57246. if (other.cursorHandle != 0)
  57247. other.cursorHandle->retain();
  57248. if (cursorHandle != 0)
  57249. cursorHandle->release();
  57250. cursorHandle = other.cursorHandle;
  57251. return *this;
  57252. }
  57253. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57254. {
  57255. return getHandle() == other.getHandle();
  57256. }
  57257. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57258. {
  57259. return getHandle() != other.getHandle();
  57260. }
  57261. void* MouseCursor::getHandle() const throw()
  57262. {
  57263. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57264. }
  57265. void MouseCursor::showWaitCursor()
  57266. {
  57267. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57268. }
  57269. void MouseCursor::hideWaitCursor()
  57270. {
  57271. Desktop::getInstance().getMainMouseSource().revealCursor();
  57272. }
  57273. END_JUCE_NAMESPACE
  57274. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57275. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57276. BEGIN_JUCE_NAMESPACE
  57277. MouseEvent::MouseEvent (MouseInputSource& source_,
  57278. const Point<int>& position,
  57279. const ModifierKeys& mods_,
  57280. Component* const eventComponent_,
  57281. Component* const originator,
  57282. const Time& eventTime_,
  57283. const Point<int> mouseDownPos_,
  57284. const Time& mouseDownTime_,
  57285. const int numberOfClicks_,
  57286. const bool mouseWasDragged) throw()
  57287. : x (position.getX()),
  57288. y (position.getY()),
  57289. mods (mods_),
  57290. eventComponent (eventComponent_),
  57291. originalComponent (originator),
  57292. eventTime (eventTime_),
  57293. source (source_),
  57294. mouseDownPos (mouseDownPos_),
  57295. mouseDownTime (mouseDownTime_),
  57296. numberOfClicks (numberOfClicks_),
  57297. wasMovedSinceMouseDown (mouseWasDragged)
  57298. {
  57299. }
  57300. MouseEvent::~MouseEvent() throw()
  57301. {
  57302. }
  57303. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57304. {
  57305. if (otherComponent == 0)
  57306. {
  57307. jassertfalse;
  57308. return *this;
  57309. }
  57310. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57311. mods, otherComponent, originalComponent, eventTime,
  57312. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57313. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57314. }
  57315. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57316. {
  57317. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57318. eventTime, mouseDownPos, mouseDownTime,
  57319. numberOfClicks, wasMovedSinceMouseDown);
  57320. }
  57321. bool MouseEvent::mouseWasClicked() const throw()
  57322. {
  57323. return ! wasMovedSinceMouseDown;
  57324. }
  57325. int MouseEvent::getMouseDownX() const throw()
  57326. {
  57327. return mouseDownPos.getX();
  57328. }
  57329. int MouseEvent::getMouseDownY() const throw()
  57330. {
  57331. return mouseDownPos.getY();
  57332. }
  57333. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57334. {
  57335. return mouseDownPos;
  57336. }
  57337. int MouseEvent::getDistanceFromDragStartX() const throw()
  57338. {
  57339. return x - mouseDownPos.getX();
  57340. }
  57341. int MouseEvent::getDistanceFromDragStartY() const throw()
  57342. {
  57343. return y - mouseDownPos.getY();
  57344. }
  57345. int MouseEvent::getDistanceFromDragStart() const throw()
  57346. {
  57347. return mouseDownPos.getDistanceFrom (getPosition());
  57348. }
  57349. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57350. {
  57351. return getPosition() - mouseDownPos;
  57352. }
  57353. int MouseEvent::getLengthOfMousePress() const throw()
  57354. {
  57355. if (mouseDownTime.toMilliseconds() > 0)
  57356. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57357. return 0;
  57358. }
  57359. const Point<int> MouseEvent::getPosition() const throw()
  57360. {
  57361. return Point<int> (x, y);
  57362. }
  57363. int MouseEvent::getScreenX() const
  57364. {
  57365. return getScreenPosition().getX();
  57366. }
  57367. int MouseEvent::getScreenY() const
  57368. {
  57369. return getScreenPosition().getY();
  57370. }
  57371. const Point<int> MouseEvent::getScreenPosition() const
  57372. {
  57373. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57374. }
  57375. int MouseEvent::getMouseDownScreenX() const
  57376. {
  57377. return getMouseDownScreenPosition().getX();
  57378. }
  57379. int MouseEvent::getMouseDownScreenY() const
  57380. {
  57381. return getMouseDownScreenPosition().getY();
  57382. }
  57383. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57384. {
  57385. return eventComponent->localPointToGlobal (mouseDownPos);
  57386. }
  57387. int MouseEvent::doubleClickTimeOutMs = 400;
  57388. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57389. {
  57390. doubleClickTimeOutMs = newTime;
  57391. }
  57392. int MouseEvent::getDoubleClickTimeout() throw()
  57393. {
  57394. return doubleClickTimeOutMs;
  57395. }
  57396. END_JUCE_NAMESPACE
  57397. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57398. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57399. BEGIN_JUCE_NAMESPACE
  57400. class MouseInputSourceInternal : public AsyncUpdater
  57401. {
  57402. public:
  57403. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57404. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57405. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57406. mouseEventCounter (0)
  57407. {
  57408. }
  57409. bool isDragging() const throw()
  57410. {
  57411. return buttonState.isAnyMouseButtonDown();
  57412. }
  57413. Component* getComponentUnderMouse() const
  57414. {
  57415. return static_cast <Component*> (componentUnderMouse);
  57416. }
  57417. const ModifierKeys getCurrentModifiers() const
  57418. {
  57419. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57420. }
  57421. ComponentPeer* getPeer()
  57422. {
  57423. if (! ComponentPeer::isValidPeer (lastPeer))
  57424. lastPeer = 0;
  57425. return lastPeer;
  57426. }
  57427. Component* findComponentAt (const Point<int>& screenPos)
  57428. {
  57429. ComponentPeer* const peer = getPeer();
  57430. if (peer != 0)
  57431. {
  57432. Component* const comp = peer->getComponent();
  57433. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57434. // (the contains() call is needed to test for overlapping desktop windows)
  57435. if (comp->contains (relativePos))
  57436. return comp->getComponentAt (relativePos);
  57437. }
  57438. return 0;
  57439. }
  57440. const Point<int> getScreenPosition() const
  57441. {
  57442. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57443. // value, because that can cause continuity problems.
  57444. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57445. : lastScreenPos);
  57446. }
  57447. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const Time& time)
  57448. {
  57449. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57450. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57451. }
  57452. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const Time& time)
  57453. {
  57454. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57455. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57456. }
  57457. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const Time& time)
  57458. {
  57459. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57460. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57461. }
  57462. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const Time& time)
  57463. {
  57464. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57465. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57466. }
  57467. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const Time& time)
  57468. {
  57469. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57470. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57471. }
  57472. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const Time& time)
  57473. {
  57474. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57475. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57476. }
  57477. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const Time& time, float x, float y)
  57478. {
  57479. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57480. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57481. }
  57482. // (returns true if the button change caused a modal event loop)
  57483. bool setButtons (const Point<int>& screenPos, const Time& time, const ModifierKeys& newButtonState)
  57484. {
  57485. if (buttonState == newButtonState)
  57486. return false;
  57487. setScreenPos (screenPos, time, false);
  57488. // (ignore secondary clicks when there's already a button down)
  57489. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57490. {
  57491. buttonState = newButtonState;
  57492. return false;
  57493. }
  57494. const int lastCounter = mouseEventCounter;
  57495. if (buttonState.isAnyMouseButtonDown())
  57496. {
  57497. Component* const current = getComponentUnderMouse();
  57498. if (current != 0)
  57499. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57500. enableUnboundedMouseMovement (false, false);
  57501. }
  57502. buttonState = newButtonState;
  57503. if (buttonState.isAnyMouseButtonDown())
  57504. {
  57505. Desktop::getInstance().incrementMouseClickCounter();
  57506. Component* const current = getComponentUnderMouse();
  57507. if (current != 0)
  57508. {
  57509. registerMouseDown (screenPos, time, current, buttonState);
  57510. sendMouseDown (current, screenPos, time);
  57511. }
  57512. }
  57513. return lastCounter != mouseEventCounter;
  57514. }
  57515. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const Time& time)
  57516. {
  57517. Component* current = getComponentUnderMouse();
  57518. if (newComponent != current)
  57519. {
  57520. WeakReference<Component> safeNewComp (newComponent);
  57521. const ModifierKeys originalButtonState (buttonState);
  57522. if (current != 0)
  57523. {
  57524. setButtons (screenPos, time, ModifierKeys());
  57525. sendMouseExit (current, screenPos, time);
  57526. buttonState = originalButtonState;
  57527. }
  57528. componentUnderMouse = safeNewComp;
  57529. current = getComponentUnderMouse();
  57530. if (current != 0)
  57531. sendMouseEnter (current, screenPos, time);
  57532. revealCursor (false);
  57533. setButtons (screenPos, time, originalButtonState);
  57534. }
  57535. }
  57536. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const Time& time)
  57537. {
  57538. ModifierKeys::updateCurrentModifiers();
  57539. if (newPeer != lastPeer)
  57540. {
  57541. setComponentUnderMouse (0, screenPos, time);
  57542. lastPeer = newPeer;
  57543. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57544. }
  57545. }
  57546. void setScreenPos (const Point<int>& newScreenPos, const Time& time, const bool forceUpdate)
  57547. {
  57548. if (! isDragging())
  57549. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57550. if (newScreenPos != lastScreenPos || forceUpdate)
  57551. {
  57552. cancelPendingUpdate();
  57553. lastScreenPos = newScreenPos;
  57554. Component* const current = getComponentUnderMouse();
  57555. if (current != 0)
  57556. {
  57557. if (isDragging())
  57558. {
  57559. registerMouseDrag (newScreenPos);
  57560. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57561. if (isUnboundedMouseModeOn)
  57562. handleUnboundedDrag (current);
  57563. }
  57564. else
  57565. {
  57566. sendMouseMove (current, newScreenPos, time);
  57567. }
  57568. }
  57569. revealCursor (false);
  57570. }
  57571. }
  57572. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const Time& time, const ModifierKeys& newMods)
  57573. {
  57574. jassert (newPeer != 0);
  57575. lastTime = time;
  57576. ++mouseEventCounter;
  57577. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57578. if (isDragging() && newMods.isAnyMouseButtonDown())
  57579. {
  57580. setScreenPos (screenPos, time, false);
  57581. }
  57582. else
  57583. {
  57584. setPeer (newPeer, screenPos, time);
  57585. ComponentPeer* peer = getPeer();
  57586. if (peer != 0)
  57587. {
  57588. if (setButtons (screenPos, time, newMods))
  57589. return; // some modal events have been dispatched, so the current event is now out-of-date
  57590. peer = getPeer();
  57591. if (peer != 0)
  57592. setScreenPos (screenPos, time, false);
  57593. }
  57594. }
  57595. }
  57596. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const Time& time, float x, float y)
  57597. {
  57598. jassert (peer != 0);
  57599. lastTime = time;
  57600. ++mouseEventCounter;
  57601. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57602. setPeer (peer, screenPos, time);
  57603. setScreenPos (screenPos, time, false);
  57604. triggerFakeMove();
  57605. if (! isDragging())
  57606. {
  57607. Component* current = getComponentUnderMouse();
  57608. if (current != 0)
  57609. sendMouseWheel (current, screenPos, time, x, y);
  57610. }
  57611. }
  57612. const Time getLastMouseDownTime() const throw()
  57613. {
  57614. return Time (mouseDowns[0].time);
  57615. }
  57616. const Point<int> getLastMouseDownPosition() const throw()
  57617. {
  57618. return mouseDowns[0].position;
  57619. }
  57620. int getNumberOfMultipleClicks() const throw()
  57621. {
  57622. int numClicks = 0;
  57623. if (mouseDowns[0].time != Time())
  57624. {
  57625. if (! mouseMovedSignificantlySincePressed)
  57626. ++numClicks;
  57627. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57628. {
  57629. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57630. ++numClicks;
  57631. else
  57632. break;
  57633. }
  57634. }
  57635. return numClicks;
  57636. }
  57637. bool hasMouseMovedSignificantlySincePressed() const throw()
  57638. {
  57639. return mouseMovedSignificantlySincePressed
  57640. || lastTime > mouseDowns[0].time + RelativeTime::milliseconds (300);
  57641. }
  57642. void triggerFakeMove()
  57643. {
  57644. triggerAsyncUpdate();
  57645. }
  57646. void handleAsyncUpdate()
  57647. {
  57648. setScreenPos (lastScreenPos, jmax (lastTime, Time::getCurrentTime()), true);
  57649. }
  57650. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57651. {
  57652. enable = enable && isDragging();
  57653. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57654. if (enable != isUnboundedMouseModeOn)
  57655. {
  57656. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57657. {
  57658. // when released, return the mouse to within the component's bounds
  57659. Component* current = getComponentUnderMouse();
  57660. if (current != 0)
  57661. Desktop::setMousePosition (current->getScreenBounds()
  57662. .getConstrainedPoint (lastScreenPos));
  57663. }
  57664. isUnboundedMouseModeOn = enable;
  57665. unboundedMouseOffset = Point<int>();
  57666. revealCursor (true);
  57667. }
  57668. }
  57669. void handleUnboundedDrag (Component* current)
  57670. {
  57671. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57672. if (! screenArea.contains (lastScreenPos))
  57673. {
  57674. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57675. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57676. Desktop::setMousePosition (componentCentre);
  57677. }
  57678. else if (isCursorVisibleUntilOffscreen
  57679. && (! unboundedMouseOffset.isOrigin())
  57680. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57681. {
  57682. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57683. unboundedMouseOffset = Point<int>();
  57684. }
  57685. }
  57686. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57687. {
  57688. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57689. {
  57690. cursor = MouseCursor::NoCursor;
  57691. forcedUpdate = true;
  57692. }
  57693. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57694. {
  57695. currentCursorHandle = cursor.getHandle();
  57696. cursor.showInWindow (getPeer());
  57697. }
  57698. }
  57699. void hideCursor()
  57700. {
  57701. showMouseCursor (MouseCursor::NoCursor, true);
  57702. }
  57703. void revealCursor (bool forcedUpdate)
  57704. {
  57705. MouseCursor mc (MouseCursor::NormalCursor);
  57706. Component* current = getComponentUnderMouse();
  57707. if (current != 0)
  57708. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57709. showMouseCursor (mc, forcedUpdate);
  57710. }
  57711. const int index;
  57712. const bool isMouseDevice;
  57713. Point<int> lastScreenPos;
  57714. ModifierKeys buttonState;
  57715. private:
  57716. MouseInputSource& source;
  57717. WeakReference<Component> componentUnderMouse;
  57718. ComponentPeer* lastPeer;
  57719. Point<int> unboundedMouseOffset;
  57720. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57721. void* currentCursorHandle;
  57722. int mouseEventCounter;
  57723. struct RecentMouseDown
  57724. {
  57725. RecentMouseDown() : component (0)
  57726. {
  57727. }
  57728. Point<int> position;
  57729. Time time;
  57730. Component* component;
  57731. ModifierKeys buttons;
  57732. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetweenMs) const
  57733. {
  57734. return time - other.time < RelativeTime::milliseconds (maxTimeBetweenMs)
  57735. && abs (position.getX() - other.position.getX()) < 8
  57736. && abs (position.getY() - other.position.getY()) < 8
  57737. && buttons == other.buttons;;
  57738. }
  57739. };
  57740. RecentMouseDown mouseDowns[4];
  57741. bool mouseMovedSignificantlySincePressed;
  57742. Time lastTime;
  57743. void registerMouseDown (const Point<int>& screenPos, const Time& time,
  57744. Component* const component, const ModifierKeys& modifiers) throw()
  57745. {
  57746. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57747. mouseDowns[i] = mouseDowns[i - 1];
  57748. mouseDowns[0].position = screenPos;
  57749. mouseDowns[0].time = time;
  57750. mouseDowns[0].component = component;
  57751. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57752. mouseMovedSignificantlySincePressed = false;
  57753. }
  57754. void registerMouseDrag (const Point<int>& screenPos) throw()
  57755. {
  57756. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57757. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57758. }
  57759. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  57760. };
  57761. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57762. {
  57763. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57764. }
  57765. MouseInputSource::~MouseInputSource()
  57766. {
  57767. }
  57768. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57769. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57770. bool MouseInputSource::canHover() const { return isMouse(); }
  57771. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57772. int MouseInputSource::getIndex() const { return pimpl->index; }
  57773. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57774. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57775. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57776. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57777. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57778. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57779. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57780. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57781. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57782. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57783. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57784. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57785. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57786. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57787. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57788. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57789. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57790. {
  57791. pimpl->handleEvent (peer, positionWithinPeer, Time (time), mods.withOnlyMouseButtons());
  57792. }
  57793. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57794. {
  57795. pimpl->handleWheel (peer, positionWithinPeer, Time (time), x, y);
  57796. }
  57797. END_JUCE_NAMESPACE
  57798. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57799. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57800. BEGIN_JUCE_NAMESPACE
  57801. void MouseListener::mouseEnter (const MouseEvent&)
  57802. {
  57803. }
  57804. void MouseListener::mouseExit (const MouseEvent&)
  57805. {
  57806. }
  57807. void MouseListener::mouseDown (const MouseEvent&)
  57808. {
  57809. }
  57810. void MouseListener::mouseUp (const MouseEvent&)
  57811. {
  57812. }
  57813. void MouseListener::mouseDrag (const MouseEvent&)
  57814. {
  57815. }
  57816. void MouseListener::mouseMove (const MouseEvent&)
  57817. {
  57818. }
  57819. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57820. {
  57821. }
  57822. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57823. {
  57824. }
  57825. END_JUCE_NAMESPACE
  57826. /*** End of inlined file: juce_MouseListener.cpp ***/
  57827. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57828. BEGIN_JUCE_NAMESPACE
  57829. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57830. const String& buttonTextWhenTrue,
  57831. const String& buttonTextWhenFalse)
  57832. : PropertyComponent (name),
  57833. onText (buttonTextWhenTrue),
  57834. offText (buttonTextWhenFalse)
  57835. {
  57836. addAndMakeVisible (&button);
  57837. button.setClickingTogglesState (false);
  57838. button.addListener (this);
  57839. }
  57840. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57841. const String& name,
  57842. const String& buttonText)
  57843. : PropertyComponent (name),
  57844. onText (buttonText),
  57845. offText (buttonText)
  57846. {
  57847. addAndMakeVisible (&button);
  57848. button.setClickingTogglesState (false);
  57849. button.setButtonText (buttonText);
  57850. button.getToggleStateValue().referTo (valueToControl);
  57851. button.setClickingTogglesState (true);
  57852. }
  57853. BooleanPropertyComponent::~BooleanPropertyComponent()
  57854. {
  57855. }
  57856. void BooleanPropertyComponent::setState (const bool newState)
  57857. {
  57858. button.setToggleState (newState, true);
  57859. }
  57860. bool BooleanPropertyComponent::getState() const
  57861. {
  57862. return button.getToggleState();
  57863. }
  57864. void BooleanPropertyComponent::paint (Graphics& g)
  57865. {
  57866. PropertyComponent::paint (g);
  57867. g.setColour (Colours::white);
  57868. g.fillRect (button.getBounds());
  57869. g.setColour (findColour (ComboBox::outlineColourId));
  57870. g.drawRect (button.getBounds());
  57871. }
  57872. void BooleanPropertyComponent::refresh()
  57873. {
  57874. button.setToggleState (getState(), false);
  57875. button.setButtonText (button.getToggleState() ? onText : offText);
  57876. }
  57877. void BooleanPropertyComponent::buttonClicked (Button*)
  57878. {
  57879. setState (! getState());
  57880. }
  57881. END_JUCE_NAMESPACE
  57882. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57883. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57884. BEGIN_JUCE_NAMESPACE
  57885. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57886. const bool triggerOnMouseDown)
  57887. : PropertyComponent (name)
  57888. {
  57889. addAndMakeVisible (&button);
  57890. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57891. button.addListener (this);
  57892. }
  57893. ButtonPropertyComponent::~ButtonPropertyComponent()
  57894. {
  57895. }
  57896. void ButtonPropertyComponent::refresh()
  57897. {
  57898. button.setButtonText (getButtonText());
  57899. }
  57900. void ButtonPropertyComponent::buttonClicked (Button*)
  57901. {
  57902. buttonClicked();
  57903. }
  57904. END_JUCE_NAMESPACE
  57905. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57906. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57907. BEGIN_JUCE_NAMESPACE
  57908. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57909. public ValueListener
  57910. {
  57911. public:
  57912. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57913. : sourceValue (sourceValue_),
  57914. mappings (mappings_)
  57915. {
  57916. sourceValue.addListener (this);
  57917. }
  57918. ~RemapperValueSource() {}
  57919. const var getValue() const
  57920. {
  57921. return mappings.indexOf (sourceValue.getValue()) + 1;
  57922. }
  57923. void setValue (const var& newValue)
  57924. {
  57925. const var remappedVal (mappings [(int) newValue - 1]);
  57926. if (remappedVal != sourceValue)
  57927. sourceValue = remappedVal;
  57928. }
  57929. void valueChanged (Value&)
  57930. {
  57931. sendChangeMessage (true);
  57932. }
  57933. protected:
  57934. Value sourceValue;
  57935. Array<var> mappings;
  57936. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  57937. };
  57938. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57939. : PropertyComponent (name),
  57940. isCustomClass (true)
  57941. {
  57942. }
  57943. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57944. const String& name,
  57945. const StringArray& choices_,
  57946. const Array <var>& correspondingValues)
  57947. : PropertyComponent (name),
  57948. choices (choices_),
  57949. isCustomClass (false)
  57950. {
  57951. // The array of corresponding values must contain one value for each of the items in
  57952. // the choices array!
  57953. jassert (correspondingValues.size() == choices.size());
  57954. createComboBox();
  57955. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57956. }
  57957. ChoicePropertyComponent::~ChoicePropertyComponent()
  57958. {
  57959. }
  57960. void ChoicePropertyComponent::createComboBox()
  57961. {
  57962. addAndMakeVisible (&comboBox);
  57963. for (int i = 0; i < choices.size(); ++i)
  57964. {
  57965. if (choices[i].isNotEmpty())
  57966. comboBox.addItem (choices[i], i + 1);
  57967. else
  57968. comboBox.addSeparator();
  57969. }
  57970. comboBox.setEditableText (false);
  57971. }
  57972. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57973. {
  57974. jassertfalse; // you need to override this method in your subclass!
  57975. }
  57976. int ChoicePropertyComponent::getIndex() const
  57977. {
  57978. jassertfalse; // you need to override this method in your subclass!
  57979. return -1;
  57980. }
  57981. const StringArray& ChoicePropertyComponent::getChoices() const
  57982. {
  57983. return choices;
  57984. }
  57985. void ChoicePropertyComponent::refresh()
  57986. {
  57987. if (isCustomClass)
  57988. {
  57989. if (! comboBox.isVisible())
  57990. {
  57991. createComboBox();
  57992. comboBox.addListener (this);
  57993. }
  57994. comboBox.setSelectedId (getIndex() + 1, true);
  57995. }
  57996. }
  57997. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57998. {
  57999. if (isCustomClass)
  58000. {
  58001. const int newIndex = comboBox.getSelectedId() - 1;
  58002. if (newIndex != getIndex())
  58003. setIndex (newIndex);
  58004. }
  58005. }
  58006. END_JUCE_NAMESPACE
  58007. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58008. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58009. BEGIN_JUCE_NAMESPACE
  58010. PropertyComponent::PropertyComponent (const String& name,
  58011. const int preferredHeight_)
  58012. : Component (name),
  58013. preferredHeight (preferredHeight_)
  58014. {
  58015. jassert (name.isNotEmpty());
  58016. }
  58017. PropertyComponent::~PropertyComponent()
  58018. {
  58019. }
  58020. void PropertyComponent::paint (Graphics& g)
  58021. {
  58022. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58023. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58024. }
  58025. void PropertyComponent::resized()
  58026. {
  58027. if (getNumChildComponents() > 0)
  58028. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58029. }
  58030. void PropertyComponent::enablementChanged()
  58031. {
  58032. repaint();
  58033. }
  58034. END_JUCE_NAMESPACE
  58035. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58036. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58037. BEGIN_JUCE_NAMESPACE
  58038. class PropertySectionComponent : public Component
  58039. {
  58040. public:
  58041. PropertySectionComponent (const String& sectionTitle,
  58042. const Array <PropertyComponent*>& newProperties,
  58043. const bool sectionIsOpen_)
  58044. : Component (sectionTitle),
  58045. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58046. sectionIsOpen (sectionIsOpen_)
  58047. {
  58048. propertyComps.addArray (newProperties);
  58049. for (int i = propertyComps.size(); --i >= 0;)
  58050. {
  58051. addAndMakeVisible (propertyComps.getUnchecked(i));
  58052. propertyComps.getUnchecked(i)->refresh();
  58053. }
  58054. }
  58055. ~PropertySectionComponent()
  58056. {
  58057. propertyComps.clear();
  58058. }
  58059. void paint (Graphics& g)
  58060. {
  58061. if (titleHeight > 0)
  58062. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58063. }
  58064. void resized()
  58065. {
  58066. int y = titleHeight;
  58067. for (int i = 0; i < propertyComps.size(); ++i)
  58068. {
  58069. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  58070. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  58071. y = pec->getBottom();
  58072. }
  58073. }
  58074. int getPreferredHeight() const
  58075. {
  58076. int y = titleHeight;
  58077. if (isOpen())
  58078. {
  58079. for (int i = propertyComps.size(); --i >= 0;)
  58080. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  58081. }
  58082. return y;
  58083. }
  58084. void setOpen (const bool open)
  58085. {
  58086. if (sectionIsOpen != open)
  58087. {
  58088. sectionIsOpen = open;
  58089. for (int i = propertyComps.size(); --i >= 0;)
  58090. propertyComps.getUnchecked(i)->setVisible (open);
  58091. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58092. if (pp != 0)
  58093. pp->resized();
  58094. }
  58095. }
  58096. bool isOpen() const
  58097. {
  58098. return sectionIsOpen;
  58099. }
  58100. void refreshAll() const
  58101. {
  58102. for (int i = propertyComps.size(); --i >= 0;)
  58103. propertyComps.getUnchecked (i)->refresh();
  58104. }
  58105. void mouseUp (const MouseEvent& e)
  58106. {
  58107. if (e.getMouseDownX() < titleHeight
  58108. && e.x < titleHeight
  58109. && e.y < titleHeight
  58110. && e.getNumberOfClicks() != 2)
  58111. {
  58112. setOpen (! isOpen());
  58113. }
  58114. }
  58115. void mouseDoubleClick (const MouseEvent& e)
  58116. {
  58117. if (e.y < titleHeight)
  58118. setOpen (! isOpen());
  58119. }
  58120. private:
  58121. OwnedArray <PropertyComponent> propertyComps;
  58122. int titleHeight;
  58123. bool sectionIsOpen;
  58124. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58125. };
  58126. class PropertyPanel::PropertyHolderComponent : public Component
  58127. {
  58128. public:
  58129. PropertyHolderComponent() {}
  58130. void paint (Graphics&) {}
  58131. void updateLayout (int width)
  58132. {
  58133. int y = 0;
  58134. for (int i = 0; i < sections.size(); ++i)
  58135. {
  58136. PropertySectionComponent* const section = sections.getUnchecked(i);
  58137. section->setBounds (0, y, width, section->getPreferredHeight());
  58138. y = section->getBottom();
  58139. }
  58140. setSize (width, y);
  58141. repaint();
  58142. }
  58143. void refreshAll() const
  58144. {
  58145. for (int i = 0; i < sections.size(); ++i)
  58146. sections.getUnchecked(i)->refreshAll();
  58147. }
  58148. void clear()
  58149. {
  58150. sections.clear();
  58151. }
  58152. void addSection (PropertySectionComponent* newSection)
  58153. {
  58154. sections.add (newSection);
  58155. addAndMakeVisible (newSection, 0);
  58156. }
  58157. int getNumSections() const throw() { return sections.size(); }
  58158. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58159. private:
  58160. OwnedArray<PropertySectionComponent> sections;
  58161. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58162. };
  58163. PropertyPanel::PropertyPanel()
  58164. {
  58165. messageWhenEmpty = TRANS("(nothing selected)");
  58166. addAndMakeVisible (&viewport);
  58167. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58168. viewport.setFocusContainer (true);
  58169. }
  58170. PropertyPanel::~PropertyPanel()
  58171. {
  58172. clear();
  58173. }
  58174. void PropertyPanel::paint (Graphics& g)
  58175. {
  58176. if (propertyHolderComponent->getNumSections() == 0)
  58177. {
  58178. g.setColour (Colours::black.withAlpha (0.5f));
  58179. g.setFont (14.0f);
  58180. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58181. Justification::centred, true);
  58182. }
  58183. }
  58184. void PropertyPanel::resized()
  58185. {
  58186. viewport.setBounds (getLocalBounds());
  58187. updatePropHolderLayout();
  58188. }
  58189. void PropertyPanel::clear()
  58190. {
  58191. if (propertyHolderComponent->getNumSections() > 0)
  58192. {
  58193. propertyHolderComponent->clear();
  58194. repaint();
  58195. }
  58196. }
  58197. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58198. {
  58199. if (propertyHolderComponent->getNumSections() == 0)
  58200. repaint();
  58201. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58202. updatePropHolderLayout();
  58203. }
  58204. void PropertyPanel::addSection (const String& sectionTitle,
  58205. const Array <PropertyComponent*>& newProperties,
  58206. const bool shouldBeOpen)
  58207. {
  58208. jassert (sectionTitle.isNotEmpty());
  58209. if (propertyHolderComponent->getNumSections() == 0)
  58210. repaint();
  58211. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58212. updatePropHolderLayout();
  58213. }
  58214. void PropertyPanel::updatePropHolderLayout() const
  58215. {
  58216. const int maxWidth = viewport.getMaximumVisibleWidth();
  58217. propertyHolderComponent->updateLayout (maxWidth);
  58218. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58219. if (maxWidth != newMaxWidth)
  58220. {
  58221. // need to do this twice because of scrollbars changing the size, etc.
  58222. propertyHolderComponent->updateLayout (newMaxWidth);
  58223. }
  58224. }
  58225. void PropertyPanel::refreshAll() const
  58226. {
  58227. propertyHolderComponent->refreshAll();
  58228. }
  58229. const StringArray PropertyPanel::getSectionNames() const
  58230. {
  58231. StringArray s;
  58232. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58233. {
  58234. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58235. if (section->getName().isNotEmpty())
  58236. s.add (section->getName());
  58237. }
  58238. return s;
  58239. }
  58240. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58241. {
  58242. int index = 0;
  58243. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58244. {
  58245. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58246. if (section->getName().isNotEmpty())
  58247. {
  58248. if (index == sectionIndex)
  58249. return section->isOpen();
  58250. ++index;
  58251. }
  58252. }
  58253. return false;
  58254. }
  58255. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58256. {
  58257. int index = 0;
  58258. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58259. {
  58260. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58261. if (section->getName().isNotEmpty())
  58262. {
  58263. if (index == sectionIndex)
  58264. {
  58265. section->setOpen (shouldBeOpen);
  58266. break;
  58267. }
  58268. ++index;
  58269. }
  58270. }
  58271. }
  58272. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58273. {
  58274. int index = 0;
  58275. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58276. {
  58277. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58278. if (section->getName().isNotEmpty())
  58279. {
  58280. if (index == sectionIndex)
  58281. {
  58282. section->setEnabled (shouldBeEnabled);
  58283. break;
  58284. }
  58285. ++index;
  58286. }
  58287. }
  58288. }
  58289. XmlElement* PropertyPanel::getOpennessState() const
  58290. {
  58291. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58292. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58293. const StringArray sections (getSectionNames());
  58294. for (int i = 0; i < sections.size(); ++i)
  58295. {
  58296. if (sections[i].isNotEmpty())
  58297. {
  58298. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58299. e->setAttribute ("name", sections[i]);
  58300. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58301. }
  58302. }
  58303. return xml;
  58304. }
  58305. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58306. {
  58307. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58308. {
  58309. const StringArray sections (getSectionNames());
  58310. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58311. {
  58312. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58313. e->getBoolAttribute ("open"));
  58314. }
  58315. viewport.setViewPosition (viewport.getViewPositionX(),
  58316. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58317. }
  58318. }
  58319. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58320. {
  58321. if (messageWhenEmpty != newMessage)
  58322. {
  58323. messageWhenEmpty = newMessage;
  58324. repaint();
  58325. }
  58326. }
  58327. const String& PropertyPanel::getMessageWhenEmpty() const
  58328. {
  58329. return messageWhenEmpty;
  58330. }
  58331. END_JUCE_NAMESPACE
  58332. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58333. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58334. BEGIN_JUCE_NAMESPACE
  58335. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58336. const double rangeMin,
  58337. const double rangeMax,
  58338. const double interval,
  58339. const double skewFactor)
  58340. : PropertyComponent (name)
  58341. {
  58342. addAndMakeVisible (&slider);
  58343. slider.setRange (rangeMin, rangeMax, interval);
  58344. slider.setSkewFactor (skewFactor);
  58345. slider.setSliderStyle (Slider::LinearBar);
  58346. slider.addListener (this);
  58347. }
  58348. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58349. const String& name,
  58350. const double rangeMin,
  58351. const double rangeMax,
  58352. const double interval,
  58353. const double skewFactor)
  58354. : PropertyComponent (name)
  58355. {
  58356. addAndMakeVisible (&slider);
  58357. slider.setRange (rangeMin, rangeMax, interval);
  58358. slider.setSkewFactor (skewFactor);
  58359. slider.setSliderStyle (Slider::LinearBar);
  58360. slider.getValueObject().referTo (valueToControl);
  58361. }
  58362. SliderPropertyComponent::~SliderPropertyComponent()
  58363. {
  58364. }
  58365. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58366. {
  58367. }
  58368. double SliderPropertyComponent::getValue() const
  58369. {
  58370. return slider.getValue();
  58371. }
  58372. void SliderPropertyComponent::refresh()
  58373. {
  58374. slider.setValue (getValue(), false);
  58375. }
  58376. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58377. {
  58378. if (getValue() != slider.getValue())
  58379. setValue (slider.getValue());
  58380. }
  58381. END_JUCE_NAMESPACE
  58382. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58383. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58384. BEGIN_JUCE_NAMESPACE
  58385. class TextPropLabel : public Label
  58386. {
  58387. public:
  58388. TextPropLabel (TextPropertyComponent& owner_,
  58389. const int maxChars_, const bool isMultiline_)
  58390. : Label (String::empty, String::empty),
  58391. owner (owner_),
  58392. maxChars (maxChars_),
  58393. isMultiline (isMultiline_)
  58394. {
  58395. setEditable (true, true, false);
  58396. setColour (backgroundColourId, Colours::white);
  58397. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58398. }
  58399. TextEditor* createEditorComponent()
  58400. {
  58401. TextEditor* const textEditor = Label::createEditorComponent();
  58402. textEditor->setInputRestrictions (maxChars);
  58403. if (isMultiline)
  58404. {
  58405. textEditor->setMultiLine (true, true);
  58406. textEditor->setReturnKeyStartsNewLine (true);
  58407. }
  58408. return textEditor;
  58409. }
  58410. void textWasEdited()
  58411. {
  58412. owner.textWasEdited();
  58413. }
  58414. private:
  58415. TextPropertyComponent& owner;
  58416. int maxChars;
  58417. bool isMultiline;
  58418. };
  58419. TextPropertyComponent::TextPropertyComponent (const String& name,
  58420. const int maxNumChars,
  58421. const bool isMultiLine)
  58422. : PropertyComponent (name)
  58423. {
  58424. createEditor (maxNumChars, isMultiLine);
  58425. }
  58426. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58427. const String& name,
  58428. const int maxNumChars,
  58429. const bool isMultiLine)
  58430. : PropertyComponent (name)
  58431. {
  58432. createEditor (maxNumChars, isMultiLine);
  58433. textEditor->getTextValue().referTo (valueToControl);
  58434. }
  58435. TextPropertyComponent::~TextPropertyComponent()
  58436. {
  58437. }
  58438. void TextPropertyComponent::setText (const String& newText)
  58439. {
  58440. textEditor->setText (newText, true);
  58441. }
  58442. const String TextPropertyComponent::getText() const
  58443. {
  58444. return textEditor->getText();
  58445. }
  58446. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58447. {
  58448. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58449. if (isMultiLine)
  58450. {
  58451. textEditor->setJustificationType (Justification::topLeft);
  58452. preferredHeight = 120;
  58453. }
  58454. }
  58455. void TextPropertyComponent::refresh()
  58456. {
  58457. textEditor->setText (getText(), false);
  58458. }
  58459. void TextPropertyComponent::textWasEdited()
  58460. {
  58461. const String newText (textEditor->getText());
  58462. if (getText() != newText)
  58463. setText (newText);
  58464. }
  58465. END_JUCE_NAMESPACE
  58466. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58467. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58468. BEGIN_JUCE_NAMESPACE
  58469. class SimpleDeviceManagerInputLevelMeter : public Component,
  58470. public Timer
  58471. {
  58472. public:
  58473. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58474. : manager (manager_),
  58475. level (0)
  58476. {
  58477. startTimer (50);
  58478. manager->enableInputLevelMeasurement (true);
  58479. }
  58480. ~SimpleDeviceManagerInputLevelMeter()
  58481. {
  58482. manager->enableInputLevelMeasurement (false);
  58483. }
  58484. void timerCallback()
  58485. {
  58486. const float newLevel = (float) manager->getCurrentInputLevel();
  58487. if (std::abs (level - newLevel) > 0.005f)
  58488. {
  58489. level = newLevel;
  58490. repaint();
  58491. }
  58492. }
  58493. void paint (Graphics& g)
  58494. {
  58495. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58496. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58497. }
  58498. private:
  58499. AudioDeviceManager* const manager;
  58500. float level;
  58501. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58502. };
  58503. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58504. public ListBoxModel
  58505. {
  58506. public:
  58507. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58508. const String& noItemsMessage_,
  58509. const int minNumber_,
  58510. const int maxNumber_)
  58511. : ListBox (String::empty, 0),
  58512. deviceManager (deviceManager_),
  58513. noItemsMessage (noItemsMessage_),
  58514. minNumber (minNumber_),
  58515. maxNumber (maxNumber_)
  58516. {
  58517. items = MidiInput::getDevices();
  58518. setModel (this);
  58519. setOutlineThickness (1);
  58520. }
  58521. ~MidiInputSelectorComponentListBox()
  58522. {
  58523. }
  58524. int getNumRows()
  58525. {
  58526. return items.size();
  58527. }
  58528. void paintListBoxItem (int row,
  58529. Graphics& g,
  58530. int width, int height,
  58531. bool rowIsSelected)
  58532. {
  58533. if (isPositiveAndBelow (row, items.size()))
  58534. {
  58535. if (rowIsSelected)
  58536. g.fillAll (findColour (TextEditor::highlightColourId)
  58537. .withMultipliedAlpha (0.3f));
  58538. const String item (items [row]);
  58539. bool enabled = deviceManager.isMidiInputEnabled (item);
  58540. const int x = getTickX();
  58541. const float tickW = height * 0.75f;
  58542. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58543. enabled, true, true, false);
  58544. g.setFont (height * 0.6f);
  58545. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58546. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58547. }
  58548. }
  58549. void listBoxItemClicked (int row, const MouseEvent& e)
  58550. {
  58551. selectRow (row);
  58552. if (e.x < getTickX())
  58553. flipEnablement (row);
  58554. }
  58555. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58556. {
  58557. flipEnablement (row);
  58558. }
  58559. void returnKeyPressed (int row)
  58560. {
  58561. flipEnablement (row);
  58562. }
  58563. void paint (Graphics& g)
  58564. {
  58565. ListBox::paint (g);
  58566. if (items.size() == 0)
  58567. {
  58568. g.setColour (Colours::grey);
  58569. g.setFont (13.0f);
  58570. g.drawText (noItemsMessage,
  58571. 0, 0, getWidth(), getHeight() / 2,
  58572. Justification::centred, true);
  58573. }
  58574. }
  58575. int getBestHeight (const int preferredHeight)
  58576. {
  58577. const int extra = getOutlineThickness() * 2;
  58578. return jmax (getRowHeight() * 2 + extra,
  58579. jmin (getRowHeight() * getNumRows() + extra,
  58580. preferredHeight));
  58581. }
  58582. private:
  58583. AudioDeviceManager& deviceManager;
  58584. const String noItemsMessage;
  58585. StringArray items;
  58586. int minNumber, maxNumber;
  58587. void flipEnablement (const int row)
  58588. {
  58589. if (isPositiveAndBelow (row, items.size()))
  58590. {
  58591. const String item (items [row]);
  58592. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58593. }
  58594. }
  58595. int getTickX() const
  58596. {
  58597. return getRowHeight() + 5;
  58598. }
  58599. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58600. };
  58601. class AudioDeviceSettingsPanel : public Component,
  58602. public ChangeListener,
  58603. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58604. public ButtonListener
  58605. {
  58606. public:
  58607. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58608. AudioIODeviceType::DeviceSetupDetails& setup_,
  58609. const bool hideAdvancedOptionsWithButton)
  58610. : type (type_),
  58611. setup (setup_)
  58612. {
  58613. if (hideAdvancedOptionsWithButton)
  58614. {
  58615. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58616. showAdvancedSettingsButton->addListener (this);
  58617. }
  58618. type->scanForDevices();
  58619. setup.manager->addChangeListener (this);
  58620. changeListenerCallback (0);
  58621. }
  58622. ~AudioDeviceSettingsPanel()
  58623. {
  58624. setup.manager->removeChangeListener (this);
  58625. }
  58626. void resized()
  58627. {
  58628. const int lx = proportionOfWidth (0.35f);
  58629. const int w = proportionOfWidth (0.4f);
  58630. const int h = 24;
  58631. const int space = 6;
  58632. const int dh = h + space;
  58633. int y = 0;
  58634. if (outputDeviceDropDown != 0)
  58635. {
  58636. outputDeviceDropDown->setBounds (lx, y, w, h);
  58637. if (testButton != 0)
  58638. testButton->setBounds (proportionOfWidth (0.77f),
  58639. outputDeviceDropDown->getY(),
  58640. proportionOfWidth (0.18f),
  58641. h);
  58642. y += dh;
  58643. }
  58644. if (inputDeviceDropDown != 0)
  58645. {
  58646. inputDeviceDropDown->setBounds (lx, y, w, h);
  58647. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58648. inputDeviceDropDown->getY(),
  58649. proportionOfWidth (0.18f),
  58650. h);
  58651. y += dh;
  58652. }
  58653. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58654. if (outputChanList != 0)
  58655. {
  58656. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58657. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58658. y += bh + space;
  58659. }
  58660. if (inputChanList != 0)
  58661. {
  58662. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58663. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58664. y += bh + space;
  58665. }
  58666. y += space * 2;
  58667. if (showAdvancedSettingsButton != 0)
  58668. {
  58669. showAdvancedSettingsButton->changeWidthToFitText (h);
  58670. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58671. }
  58672. if (sampleRateDropDown != 0)
  58673. {
  58674. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58675. || ! showAdvancedSettingsButton->isVisible());
  58676. sampleRateDropDown->setBounds (lx, y, w, h);
  58677. y += dh;
  58678. }
  58679. if (bufferSizeDropDown != 0)
  58680. {
  58681. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58682. || ! showAdvancedSettingsButton->isVisible());
  58683. bufferSizeDropDown->setBounds (lx, y, w, h);
  58684. y += dh;
  58685. }
  58686. if (showUIButton != 0)
  58687. {
  58688. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58689. || ! showAdvancedSettingsButton->isVisible());
  58690. showUIButton->changeWidthToFitText (h);
  58691. showUIButton->setTopLeftPosition (lx, y);
  58692. }
  58693. }
  58694. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58695. {
  58696. if (comboBoxThatHasChanged == 0)
  58697. return;
  58698. AudioDeviceManager::AudioDeviceSetup config;
  58699. setup.manager->getAudioDeviceSetup (config);
  58700. String error;
  58701. if (comboBoxThatHasChanged == outputDeviceDropDown
  58702. || comboBoxThatHasChanged == inputDeviceDropDown)
  58703. {
  58704. if (outputDeviceDropDown != 0)
  58705. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58706. : outputDeviceDropDown->getText();
  58707. if (inputDeviceDropDown != 0)
  58708. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58709. : inputDeviceDropDown->getText();
  58710. if (! type->hasSeparateInputsAndOutputs())
  58711. config.inputDeviceName = config.outputDeviceName;
  58712. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58713. config.useDefaultInputChannels = true;
  58714. else
  58715. config.useDefaultOutputChannels = true;
  58716. error = setup.manager->setAudioDeviceSetup (config, true);
  58717. showCorrectDeviceName (inputDeviceDropDown, true);
  58718. showCorrectDeviceName (outputDeviceDropDown, false);
  58719. updateControlPanelButton();
  58720. resized();
  58721. }
  58722. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58723. {
  58724. if (sampleRateDropDown->getSelectedId() > 0)
  58725. {
  58726. config.sampleRate = sampleRateDropDown->getSelectedId();
  58727. error = setup.manager->setAudioDeviceSetup (config, true);
  58728. }
  58729. }
  58730. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58731. {
  58732. if (bufferSizeDropDown->getSelectedId() > 0)
  58733. {
  58734. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58735. error = setup.manager->setAudioDeviceSetup (config, true);
  58736. }
  58737. }
  58738. if (error.isNotEmpty())
  58739. {
  58740. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58741. "Error when trying to open audio device!",
  58742. error);
  58743. }
  58744. }
  58745. void buttonClicked (Button* button)
  58746. {
  58747. if (button == showAdvancedSettingsButton)
  58748. {
  58749. showAdvancedSettingsButton->setVisible (false);
  58750. resized();
  58751. }
  58752. else if (button == showUIButton)
  58753. {
  58754. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58755. if (device != 0 && device->showControlPanel())
  58756. {
  58757. setup.manager->closeAudioDevice();
  58758. setup.manager->restartLastAudioDevice();
  58759. getTopLevelComponent()->toFront (true);
  58760. }
  58761. }
  58762. else if (button == testButton && testButton != 0)
  58763. {
  58764. setup.manager->playTestSound();
  58765. }
  58766. }
  58767. void updateControlPanelButton()
  58768. {
  58769. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58770. showUIButton = 0;
  58771. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58772. {
  58773. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58774. TRANS ("opens the device's own control panel")));
  58775. showUIButton->addListener (this);
  58776. }
  58777. resized();
  58778. }
  58779. void changeListenerCallback (ChangeBroadcaster*)
  58780. {
  58781. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58782. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58783. {
  58784. if (outputDeviceDropDown == 0)
  58785. {
  58786. outputDeviceDropDown = new ComboBox (String::empty);
  58787. outputDeviceDropDown->addListener (this);
  58788. addAndMakeVisible (outputDeviceDropDown);
  58789. outputDeviceLabel = new Label (String::empty,
  58790. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58791. : TRANS ("device:"));
  58792. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58793. if (setup.maxNumOutputChannels > 0)
  58794. {
  58795. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58796. testButton->addListener (this);
  58797. }
  58798. }
  58799. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58800. }
  58801. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58802. {
  58803. if (inputDeviceDropDown == 0)
  58804. {
  58805. inputDeviceDropDown = new ComboBox (String::empty);
  58806. inputDeviceDropDown->addListener (this);
  58807. addAndMakeVisible (inputDeviceDropDown);
  58808. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58809. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58810. addAndMakeVisible (inputLevelMeter
  58811. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58812. }
  58813. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58814. }
  58815. updateControlPanelButton();
  58816. showCorrectDeviceName (inputDeviceDropDown, true);
  58817. showCorrectDeviceName (outputDeviceDropDown, false);
  58818. if (currentDevice != 0)
  58819. {
  58820. if (setup.maxNumOutputChannels > 0
  58821. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58822. {
  58823. if (outputChanList == 0)
  58824. {
  58825. addAndMakeVisible (outputChanList
  58826. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58827. TRANS ("(no audio output channels found)")));
  58828. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58829. outputChanLabel->attachToComponent (outputChanList, true);
  58830. }
  58831. outputChanList->refresh();
  58832. }
  58833. else
  58834. {
  58835. outputChanLabel = 0;
  58836. outputChanList = 0;
  58837. }
  58838. if (setup.maxNumInputChannels > 0
  58839. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58840. {
  58841. if (inputChanList == 0)
  58842. {
  58843. addAndMakeVisible (inputChanList
  58844. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58845. TRANS ("(no audio input channels found)")));
  58846. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58847. inputChanLabel->attachToComponent (inputChanList, true);
  58848. }
  58849. inputChanList->refresh();
  58850. }
  58851. else
  58852. {
  58853. inputChanLabel = 0;
  58854. inputChanList = 0;
  58855. }
  58856. // sample rate..
  58857. {
  58858. if (sampleRateDropDown == 0)
  58859. {
  58860. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58861. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58862. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58863. }
  58864. else
  58865. {
  58866. sampleRateDropDown->clear();
  58867. sampleRateDropDown->removeListener (this);
  58868. }
  58869. const int numRates = currentDevice->getNumSampleRates();
  58870. for (int i = 0; i < numRates; ++i)
  58871. {
  58872. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58873. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58874. }
  58875. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58876. sampleRateDropDown->addListener (this);
  58877. }
  58878. // buffer size
  58879. {
  58880. if (bufferSizeDropDown == 0)
  58881. {
  58882. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58883. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58884. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58885. }
  58886. else
  58887. {
  58888. bufferSizeDropDown->clear();
  58889. bufferSizeDropDown->removeListener (this);
  58890. }
  58891. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58892. double currentRate = currentDevice->getCurrentSampleRate();
  58893. if (currentRate == 0)
  58894. currentRate = 48000.0;
  58895. for (int i = 0; i < numBufferSizes; ++i)
  58896. {
  58897. const int bs = currentDevice->getBufferSizeSamples (i);
  58898. bufferSizeDropDown->addItem (String (bs)
  58899. + " samples ("
  58900. + String (bs * 1000.0 / currentRate, 1)
  58901. + " ms)",
  58902. bs);
  58903. }
  58904. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58905. bufferSizeDropDown->addListener (this);
  58906. }
  58907. }
  58908. else
  58909. {
  58910. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58911. sampleRateLabel = 0;
  58912. bufferSizeLabel = 0;
  58913. sampleRateDropDown = 0;
  58914. bufferSizeDropDown = 0;
  58915. if (outputDeviceDropDown != 0)
  58916. outputDeviceDropDown->setSelectedId (-1, true);
  58917. if (inputDeviceDropDown != 0)
  58918. inputDeviceDropDown->setSelectedId (-1, true);
  58919. }
  58920. resized();
  58921. setSize (getWidth(), getLowestY() + 4);
  58922. }
  58923. private:
  58924. AudioIODeviceType* const type;
  58925. const AudioIODeviceType::DeviceSetupDetails setup;
  58926. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58927. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58928. ScopedPointer<TextButton> testButton;
  58929. ScopedPointer<Component> inputLevelMeter;
  58930. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58931. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58932. {
  58933. if (box != 0)
  58934. {
  58935. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58936. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58937. box->setSelectedId (index + 1, true);
  58938. if (testButton != 0 && ! isInput)
  58939. testButton->setEnabled (index >= 0);
  58940. }
  58941. }
  58942. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58943. {
  58944. const StringArray devs (type->getDeviceNames (isInputs));
  58945. combo.clear (true);
  58946. for (int i = 0; i < devs.size(); ++i)
  58947. combo.addItem (devs[i], i + 1);
  58948. combo.addItem (TRANS("<< none >>"), -1);
  58949. combo.setSelectedId (-1, true);
  58950. }
  58951. int getLowestY() const
  58952. {
  58953. int y = 0;
  58954. for (int i = getNumChildComponents(); --i >= 0;)
  58955. y = jmax (y, getChildComponent (i)->getBottom());
  58956. return y;
  58957. }
  58958. public:
  58959. class ChannelSelectorListBox : public ListBox,
  58960. public ListBoxModel
  58961. {
  58962. public:
  58963. enum BoxType
  58964. {
  58965. audioInputType,
  58966. audioOutputType
  58967. };
  58968. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58969. const BoxType type_,
  58970. const String& noItemsMessage_)
  58971. : ListBox (String::empty, 0),
  58972. setup (setup_),
  58973. type (type_),
  58974. noItemsMessage (noItemsMessage_)
  58975. {
  58976. refresh();
  58977. setModel (this);
  58978. setOutlineThickness (1);
  58979. }
  58980. ~ChannelSelectorListBox()
  58981. {
  58982. }
  58983. void refresh()
  58984. {
  58985. items.clear();
  58986. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58987. if (currentDevice != 0)
  58988. {
  58989. if (type == audioInputType)
  58990. items = currentDevice->getInputChannelNames();
  58991. else if (type == audioOutputType)
  58992. items = currentDevice->getOutputChannelNames();
  58993. if (setup.useStereoPairs)
  58994. {
  58995. StringArray pairs;
  58996. for (int i = 0; i < items.size(); i += 2)
  58997. {
  58998. const String name (items[i]);
  58999. const String name2 (items[i + 1]);
  59000. String commonBit;
  59001. for (int j = 0; j < name.length(); ++j)
  59002. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59003. commonBit = name.substring (0, j);
  59004. // Make sure we only split the name at a space, because otherwise, things
  59005. // like "input 11" + "input 12" would become "input 11 + 2"
  59006. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59007. commonBit = commonBit.dropLastCharacters (1);
  59008. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59009. }
  59010. items = pairs;
  59011. }
  59012. }
  59013. updateContent();
  59014. repaint();
  59015. }
  59016. int getNumRows()
  59017. {
  59018. return items.size();
  59019. }
  59020. void paintListBoxItem (int row,
  59021. Graphics& g,
  59022. int width, int height,
  59023. bool rowIsSelected)
  59024. {
  59025. if (isPositiveAndBelow (row, items.size()))
  59026. {
  59027. if (rowIsSelected)
  59028. g.fillAll (findColour (TextEditor::highlightColourId)
  59029. .withMultipliedAlpha (0.3f));
  59030. const String item (items [row]);
  59031. bool enabled = false;
  59032. AudioDeviceManager::AudioDeviceSetup config;
  59033. setup.manager->getAudioDeviceSetup (config);
  59034. if (setup.useStereoPairs)
  59035. {
  59036. if (type == audioInputType)
  59037. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59038. else if (type == audioOutputType)
  59039. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59040. }
  59041. else
  59042. {
  59043. if (type == audioInputType)
  59044. enabled = config.inputChannels [row];
  59045. else if (type == audioOutputType)
  59046. enabled = config.outputChannels [row];
  59047. }
  59048. const int x = getTickX();
  59049. const float tickW = height * 0.75f;
  59050. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59051. enabled, true, true, false);
  59052. g.setFont (height * 0.6f);
  59053. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59054. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59055. }
  59056. }
  59057. void listBoxItemClicked (int row, const MouseEvent& e)
  59058. {
  59059. selectRow (row);
  59060. if (e.x < getTickX())
  59061. flipEnablement (row);
  59062. }
  59063. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59064. {
  59065. flipEnablement (row);
  59066. }
  59067. void returnKeyPressed (int row)
  59068. {
  59069. flipEnablement (row);
  59070. }
  59071. void paint (Graphics& g)
  59072. {
  59073. ListBox::paint (g);
  59074. if (items.size() == 0)
  59075. {
  59076. g.setColour (Colours::grey);
  59077. g.setFont (13.0f);
  59078. g.drawText (noItemsMessage,
  59079. 0, 0, getWidth(), getHeight() / 2,
  59080. Justification::centred, true);
  59081. }
  59082. }
  59083. int getBestHeight (int maxHeight)
  59084. {
  59085. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59086. getNumRows())
  59087. + getOutlineThickness() * 2;
  59088. }
  59089. private:
  59090. const AudioIODeviceType::DeviceSetupDetails setup;
  59091. const BoxType type;
  59092. const String noItemsMessage;
  59093. StringArray items;
  59094. void flipEnablement (const int row)
  59095. {
  59096. jassert (type == audioInputType || type == audioOutputType);
  59097. if (isPositiveAndBelow (row, items.size()))
  59098. {
  59099. AudioDeviceManager::AudioDeviceSetup config;
  59100. setup.manager->getAudioDeviceSetup (config);
  59101. if (setup.useStereoPairs)
  59102. {
  59103. BigInteger bits;
  59104. BigInteger& original = (type == audioInputType ? config.inputChannels
  59105. : config.outputChannels);
  59106. int i;
  59107. for (i = 0; i < 256; i += 2)
  59108. bits.setBit (i / 2, original [i] || original [i + 1]);
  59109. if (type == audioInputType)
  59110. {
  59111. config.useDefaultInputChannels = false;
  59112. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59113. }
  59114. else
  59115. {
  59116. config.useDefaultOutputChannels = false;
  59117. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59118. }
  59119. for (i = 0; i < 256; ++i)
  59120. original.setBit (i, bits [i / 2]);
  59121. }
  59122. else
  59123. {
  59124. if (type == audioInputType)
  59125. {
  59126. config.useDefaultInputChannels = false;
  59127. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59128. }
  59129. else
  59130. {
  59131. config.useDefaultOutputChannels = false;
  59132. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59133. }
  59134. }
  59135. String error (setup.manager->setAudioDeviceSetup (config, true));
  59136. if (! error.isEmpty())
  59137. {
  59138. //xxx
  59139. }
  59140. }
  59141. }
  59142. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59143. {
  59144. const int numActive = chans.countNumberOfSetBits();
  59145. if (chans [index])
  59146. {
  59147. if (numActive > minNumber)
  59148. chans.setBit (index, false);
  59149. }
  59150. else
  59151. {
  59152. if (numActive >= maxNumber)
  59153. {
  59154. const int firstActiveChan = chans.findNextSetBit();
  59155. chans.setBit (index > firstActiveChan
  59156. ? firstActiveChan : chans.getHighestBit(),
  59157. false);
  59158. }
  59159. chans.setBit (index, true);
  59160. }
  59161. }
  59162. int getTickX() const
  59163. {
  59164. return getRowHeight() + 5;
  59165. }
  59166. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59167. };
  59168. private:
  59169. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59170. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59171. };
  59172. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59173. const int minInputChannels_,
  59174. const int maxInputChannels_,
  59175. const int minOutputChannels_,
  59176. const int maxOutputChannels_,
  59177. const bool showMidiInputOptions,
  59178. const bool showMidiOutputSelector,
  59179. const bool showChannelsAsStereoPairs_,
  59180. const bool hideAdvancedOptionsWithButton_)
  59181. : deviceManager (deviceManager_),
  59182. deviceTypeDropDown (0),
  59183. deviceTypeDropDownLabel (0),
  59184. minOutputChannels (minOutputChannels_),
  59185. maxOutputChannels (maxOutputChannels_),
  59186. minInputChannels (minInputChannels_),
  59187. maxInputChannels (maxInputChannels_),
  59188. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59189. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59190. {
  59191. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59192. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59193. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59194. {
  59195. deviceTypeDropDown = new ComboBox (String::empty);
  59196. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59197. {
  59198. deviceTypeDropDown
  59199. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59200. i + 1);
  59201. }
  59202. addAndMakeVisible (deviceTypeDropDown);
  59203. deviceTypeDropDown->addListener (this);
  59204. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59205. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59206. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59207. }
  59208. if (showMidiInputOptions)
  59209. {
  59210. addAndMakeVisible (midiInputsList
  59211. = new MidiInputSelectorComponentListBox (deviceManager,
  59212. TRANS("(no midi inputs available)"),
  59213. 0, 0));
  59214. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59215. midiInputsLabel->setJustificationType (Justification::topRight);
  59216. midiInputsLabel->attachToComponent (midiInputsList, true);
  59217. }
  59218. else
  59219. {
  59220. midiInputsList = 0;
  59221. midiInputsLabel = 0;
  59222. }
  59223. if (showMidiOutputSelector)
  59224. {
  59225. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59226. midiOutputSelector->addListener (this);
  59227. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59228. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59229. }
  59230. else
  59231. {
  59232. midiOutputSelector = 0;
  59233. midiOutputLabel = 0;
  59234. }
  59235. deviceManager_.addChangeListener (this);
  59236. changeListenerCallback (0);
  59237. }
  59238. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59239. {
  59240. deviceManager.removeChangeListener (this);
  59241. }
  59242. void AudioDeviceSelectorComponent::resized()
  59243. {
  59244. const int lx = proportionOfWidth (0.35f);
  59245. const int w = proportionOfWidth (0.4f);
  59246. const int h = 24;
  59247. const int space = 6;
  59248. const int dh = h + space;
  59249. int y = 15;
  59250. if (deviceTypeDropDown != 0)
  59251. {
  59252. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59253. y += dh + space * 2;
  59254. }
  59255. if (audioDeviceSettingsComp != 0)
  59256. {
  59257. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59258. y += audioDeviceSettingsComp->getHeight() + space;
  59259. }
  59260. if (midiInputsList != 0)
  59261. {
  59262. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59263. midiInputsList->setBounds (lx, y, w, bh);
  59264. y += bh + space;
  59265. }
  59266. if (midiOutputSelector != 0)
  59267. midiOutputSelector->setBounds (lx, y, w, h);
  59268. }
  59269. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59270. {
  59271. if (child == audioDeviceSettingsComp)
  59272. resized();
  59273. }
  59274. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59275. {
  59276. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59277. if (device != 0 && device->hasControlPanel())
  59278. {
  59279. if (device->showControlPanel())
  59280. deviceManager.restartLastAudioDevice();
  59281. getTopLevelComponent()->toFront (true);
  59282. }
  59283. }
  59284. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59285. {
  59286. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59287. {
  59288. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59289. if (type != 0)
  59290. {
  59291. audioDeviceSettingsComp = 0;
  59292. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59293. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59294. }
  59295. }
  59296. else if (comboBoxThatHasChanged == midiOutputSelector)
  59297. {
  59298. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59299. }
  59300. }
  59301. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59302. {
  59303. if (deviceTypeDropDown != 0)
  59304. {
  59305. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59306. }
  59307. if (audioDeviceSettingsComp == 0
  59308. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59309. {
  59310. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59311. audioDeviceSettingsComp = 0;
  59312. AudioIODeviceType* const type
  59313. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59314. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59315. if (type != 0)
  59316. {
  59317. AudioIODeviceType::DeviceSetupDetails details;
  59318. details.manager = &deviceManager;
  59319. details.minNumInputChannels = minInputChannels;
  59320. details.maxNumInputChannels = maxInputChannels;
  59321. details.minNumOutputChannels = minOutputChannels;
  59322. details.maxNumOutputChannels = maxOutputChannels;
  59323. details.useStereoPairs = showChannelsAsStereoPairs;
  59324. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59325. if (audioDeviceSettingsComp != 0)
  59326. {
  59327. addAndMakeVisible (audioDeviceSettingsComp);
  59328. audioDeviceSettingsComp->resized();
  59329. }
  59330. }
  59331. }
  59332. if (midiInputsList != 0)
  59333. {
  59334. midiInputsList->updateContent();
  59335. midiInputsList->repaint();
  59336. }
  59337. if (midiOutputSelector != 0)
  59338. {
  59339. midiOutputSelector->clear();
  59340. const StringArray midiOuts (MidiOutput::getDevices());
  59341. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59342. midiOutputSelector->addSeparator();
  59343. for (int i = 0; i < midiOuts.size(); ++i)
  59344. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59345. int current = -1;
  59346. if (deviceManager.getDefaultMidiOutput() != 0)
  59347. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59348. midiOutputSelector->setSelectedId (current, true);
  59349. }
  59350. resized();
  59351. }
  59352. END_JUCE_NAMESPACE
  59353. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59354. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59355. BEGIN_JUCE_NAMESPACE
  59356. BubbleComponent::BubbleComponent()
  59357. : side (0),
  59358. allowablePlacements (above | below | left | right),
  59359. arrowTipX (0.0f),
  59360. arrowTipY (0.0f)
  59361. {
  59362. setInterceptsMouseClicks (false, false);
  59363. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59364. setComponentEffect (&shadow);
  59365. }
  59366. BubbleComponent::~BubbleComponent()
  59367. {
  59368. }
  59369. void BubbleComponent::paint (Graphics& g)
  59370. {
  59371. int x = content.getX();
  59372. int y = content.getY();
  59373. int w = content.getWidth();
  59374. int h = content.getHeight();
  59375. int cw, ch;
  59376. getContentSize (cw, ch);
  59377. if (side == 3)
  59378. x += w - cw;
  59379. else if (side != 1)
  59380. x += (w - cw) / 2;
  59381. w = cw;
  59382. if (side == 2)
  59383. y += h - ch;
  59384. else if (side != 0)
  59385. y += (h - ch) / 2;
  59386. h = ch;
  59387. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59388. (float) x, (float) y,
  59389. (float) w, (float) h);
  59390. const int cx = x + (w - cw) / 2;
  59391. const int cy = y + (h - ch) / 2;
  59392. const int indent = 3;
  59393. g.setOrigin (cx + indent, cy + indent);
  59394. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59395. paintContent (g, cw - indent * 2, ch - indent * 2);
  59396. }
  59397. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59398. {
  59399. allowablePlacements = newPlacement;
  59400. }
  59401. void BubbleComponent::setPosition (Component* componentToPointTo)
  59402. {
  59403. jassert (componentToPointTo != 0);
  59404. Point<int> pos;
  59405. if (getParentComponent() != 0)
  59406. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59407. else
  59408. pos = componentToPointTo->localPointToGlobal (pos);
  59409. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59410. }
  59411. void BubbleComponent::setPosition (const int arrowTipX_,
  59412. const int arrowTipY_)
  59413. {
  59414. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59415. }
  59416. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59417. {
  59418. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59419. : getParentMonitorArea());
  59420. int x = 0;
  59421. int y = 0;
  59422. int w = 150;
  59423. int h = 30;
  59424. getContentSize (w, h);
  59425. w += 30;
  59426. h += 30;
  59427. const float edgeIndent = 2.0f;
  59428. const int arrowLength = jmin (10, h / 3, w / 3);
  59429. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59430. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59431. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59432. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59433. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59434. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59435. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59436. {
  59437. spaceLeft = spaceRight = 0;
  59438. }
  59439. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59440. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59441. {
  59442. spaceAbove = spaceBelow = 0;
  59443. }
  59444. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59445. {
  59446. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59447. arrowTipX = w * 0.5f;
  59448. content.setSize (w, h - arrowLength);
  59449. if (spaceAbove >= spaceBelow)
  59450. {
  59451. // above
  59452. y = rectangleToPointTo.getY() - h;
  59453. content.setPosition (0, 0);
  59454. arrowTipY = h - edgeIndent;
  59455. side = 2;
  59456. }
  59457. else
  59458. {
  59459. // below
  59460. y = rectangleToPointTo.getBottom();
  59461. content.setPosition (0, arrowLength);
  59462. arrowTipY = edgeIndent;
  59463. side = 0;
  59464. }
  59465. }
  59466. else
  59467. {
  59468. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59469. arrowTipY = h * 0.5f;
  59470. content.setSize (w - arrowLength, h);
  59471. if (spaceLeft > spaceRight)
  59472. {
  59473. // on the left
  59474. x = rectangleToPointTo.getX() - w;
  59475. content.setPosition (0, 0);
  59476. arrowTipX = w - edgeIndent;
  59477. side = 3;
  59478. }
  59479. else
  59480. {
  59481. // on the right
  59482. x = rectangleToPointTo.getRight();
  59483. content.setPosition (arrowLength, 0);
  59484. arrowTipX = edgeIndent;
  59485. side = 1;
  59486. }
  59487. }
  59488. setBounds (x, y, w, h);
  59489. }
  59490. END_JUCE_NAMESPACE
  59491. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59492. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59493. BEGIN_JUCE_NAMESPACE
  59494. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59495. : fadeOutLength (fadeOutLengthMs),
  59496. deleteAfterUse (false)
  59497. {
  59498. }
  59499. BubbleMessageComponent::~BubbleMessageComponent()
  59500. {
  59501. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59502. }
  59503. void BubbleMessageComponent::showAt (int x, int y,
  59504. const String& text,
  59505. const int numMillisecondsBeforeRemoving,
  59506. const bool removeWhenMouseClicked,
  59507. const bool deleteSelfAfterUse)
  59508. {
  59509. textLayout.clear();
  59510. textLayout.setText (text, Font (14.0f));
  59511. textLayout.layout (256, Justification::centredLeft, true);
  59512. setPosition (x, y);
  59513. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59514. }
  59515. void BubbleMessageComponent::showAt (Component* const component,
  59516. const String& text,
  59517. const int numMillisecondsBeforeRemoving,
  59518. const bool removeWhenMouseClicked,
  59519. const bool deleteSelfAfterUse)
  59520. {
  59521. textLayout.clear();
  59522. textLayout.setText (text, Font (14.0f));
  59523. textLayout.layout (256, Justification::centredLeft, true);
  59524. setPosition (component);
  59525. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59526. }
  59527. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59528. const bool removeWhenMouseClicked,
  59529. const bool deleteSelfAfterUse)
  59530. {
  59531. setVisible (true);
  59532. deleteAfterUse = deleteSelfAfterUse;
  59533. if (numMillisecondsBeforeRemoving > 0)
  59534. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59535. else
  59536. expiryTime = 0;
  59537. startTimer (77);
  59538. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59539. if (! (removeWhenMouseClicked && isShowing()))
  59540. mouseClickCounter += 0xfffff;
  59541. repaint();
  59542. }
  59543. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59544. {
  59545. w = textLayout.getWidth() + 16;
  59546. h = textLayout.getHeight() + 16;
  59547. }
  59548. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59549. {
  59550. g.setColour (findColour (TooltipWindow::textColourId));
  59551. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59552. }
  59553. void BubbleMessageComponent::timerCallback()
  59554. {
  59555. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59556. {
  59557. stopTimer();
  59558. setVisible (false);
  59559. if (deleteAfterUse)
  59560. delete this;
  59561. }
  59562. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59563. {
  59564. stopTimer();
  59565. if (deleteAfterUse)
  59566. delete this;
  59567. else
  59568. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59569. }
  59570. }
  59571. END_JUCE_NAMESPACE
  59572. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59573. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59574. BEGIN_JUCE_NAMESPACE
  59575. class ColourComponentSlider : public Slider
  59576. {
  59577. public:
  59578. ColourComponentSlider (const String& name)
  59579. : Slider (name)
  59580. {
  59581. setRange (0.0, 255.0, 1.0);
  59582. }
  59583. const String getTextFromValue (double value)
  59584. {
  59585. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59586. }
  59587. double getValueFromText (const String& text)
  59588. {
  59589. return (double) text.getHexValue32();
  59590. }
  59591. private:
  59592. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59593. };
  59594. class ColourSpaceMarker : public Component
  59595. {
  59596. public:
  59597. ColourSpaceMarker()
  59598. {
  59599. setInterceptsMouseClicks (false, false);
  59600. }
  59601. void paint (Graphics& g)
  59602. {
  59603. g.setColour (Colour::greyLevel (0.1f));
  59604. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59605. g.setColour (Colour::greyLevel (0.9f));
  59606. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59607. }
  59608. private:
  59609. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59610. };
  59611. class ColourSelector::ColourSpaceView : public Component
  59612. {
  59613. public:
  59614. ColourSpaceView (ColourSelector& owner_,
  59615. float& h_, float& s_, float& v_,
  59616. const int edgeSize)
  59617. : owner (owner_),
  59618. h (h_), s (s_), v (v_),
  59619. lastHue (0.0f),
  59620. edge (edgeSize)
  59621. {
  59622. addAndMakeVisible (&marker);
  59623. setMouseCursor (MouseCursor::CrosshairCursor);
  59624. }
  59625. void paint (Graphics& g)
  59626. {
  59627. if (colours.isNull())
  59628. {
  59629. const int width = getWidth() / 2;
  59630. const int height = getHeight() / 2;
  59631. colours = Image (Image::RGB, width, height, false);
  59632. Image::BitmapData pixels (colours, true);
  59633. for (int y = 0; y < height; ++y)
  59634. {
  59635. const float val = 1.0f - y / (float) height;
  59636. for (int x = 0; x < width; ++x)
  59637. {
  59638. const float sat = x / (float) width;
  59639. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59640. }
  59641. }
  59642. }
  59643. g.setOpacity (1.0f);
  59644. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59645. 0, 0, colours.getWidth(), colours.getHeight());
  59646. }
  59647. void mouseDown (const MouseEvent& e)
  59648. {
  59649. mouseDrag (e);
  59650. }
  59651. void mouseDrag (const MouseEvent& e)
  59652. {
  59653. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59654. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59655. owner.setSV (sat, val);
  59656. }
  59657. void updateIfNeeded()
  59658. {
  59659. if (lastHue != h)
  59660. {
  59661. lastHue = h;
  59662. colours = Image::null;
  59663. repaint();
  59664. }
  59665. updateMarker();
  59666. }
  59667. void resized()
  59668. {
  59669. colours = Image::null;
  59670. updateMarker();
  59671. }
  59672. private:
  59673. ColourSelector& owner;
  59674. float& h;
  59675. float& s;
  59676. float& v;
  59677. float lastHue;
  59678. ColourSpaceMarker marker;
  59679. const int edge;
  59680. Image colours;
  59681. void updateMarker()
  59682. {
  59683. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59684. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59685. edge * 2, edge * 2);
  59686. }
  59687. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59688. };
  59689. class HueSelectorMarker : public Component
  59690. {
  59691. public:
  59692. HueSelectorMarker()
  59693. {
  59694. setInterceptsMouseClicks (false, false);
  59695. }
  59696. void paint (Graphics& g)
  59697. {
  59698. Path p;
  59699. p.addTriangle (1.0f, 1.0f,
  59700. getWidth() * 0.3f, getHeight() * 0.5f,
  59701. 1.0f, getHeight() - 1.0f);
  59702. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59703. getWidth() * 0.7f, getHeight() * 0.5f,
  59704. getWidth() - 1.0f, getHeight() - 1.0f);
  59705. g.setColour (Colours::white.withAlpha (0.75f));
  59706. g.fillPath (p);
  59707. g.setColour (Colours::black.withAlpha (0.75f));
  59708. g.strokePath (p, PathStrokeType (1.2f));
  59709. }
  59710. private:
  59711. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59712. };
  59713. class ColourSelector::HueSelectorComp : public Component
  59714. {
  59715. public:
  59716. HueSelectorComp (ColourSelector& owner_,
  59717. float& h_, float& s_, float& v_,
  59718. const int edgeSize)
  59719. : owner (owner_),
  59720. h (h_), s (s_), v (v_),
  59721. lastHue (0.0f),
  59722. edge (edgeSize)
  59723. {
  59724. addAndMakeVisible (&marker);
  59725. }
  59726. void paint (Graphics& g)
  59727. {
  59728. const float yScale = 1.0f / (getHeight() - edge * 2);
  59729. const Rectangle<int> clip (g.getClipBounds());
  59730. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59731. {
  59732. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59733. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59734. }
  59735. }
  59736. void resized()
  59737. {
  59738. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59739. getWidth(), edge * 2);
  59740. }
  59741. void mouseDown (const MouseEvent& e)
  59742. {
  59743. mouseDrag (e);
  59744. }
  59745. void mouseDrag (const MouseEvent& e)
  59746. {
  59747. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59748. }
  59749. void updateIfNeeded()
  59750. {
  59751. resized();
  59752. }
  59753. private:
  59754. ColourSelector& owner;
  59755. float& h;
  59756. float& s;
  59757. float& v;
  59758. float lastHue;
  59759. HueSelectorMarker marker;
  59760. const int edge;
  59761. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  59762. };
  59763. class ColourSelector::SwatchComponent : public Component
  59764. {
  59765. public:
  59766. SwatchComponent (ColourSelector& owner_, int index_)
  59767. : owner (owner_), index (index_)
  59768. {
  59769. }
  59770. void paint (Graphics& g)
  59771. {
  59772. const Colour colour (owner.getSwatchColour (index));
  59773. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59774. Colour (0xffdddddd).overlaidWith (colour),
  59775. Colour (0xffffffff).overlaidWith (colour));
  59776. }
  59777. void mouseDown (const MouseEvent&)
  59778. {
  59779. PopupMenu m;
  59780. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59781. m.addSeparator();
  59782. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59783. const int r = m.showAt (this);
  59784. if (r == 1)
  59785. {
  59786. owner.setCurrentColour (owner.getSwatchColour (index));
  59787. }
  59788. else if (r == 2)
  59789. {
  59790. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59791. {
  59792. owner.setSwatchColour (index, owner.getCurrentColour());
  59793. repaint();
  59794. }
  59795. }
  59796. }
  59797. private:
  59798. ColourSelector& owner;
  59799. const int index;
  59800. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  59801. };
  59802. ColourSelector::ColourSelector (const int flags_,
  59803. const int edgeGap_,
  59804. const int gapAroundColourSpaceComponent)
  59805. : colour (Colours::white),
  59806. flags (flags_),
  59807. edgeGap (edgeGap_)
  59808. {
  59809. // not much point having a selector with no components in it!
  59810. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59811. updateHSV();
  59812. if ((flags & showSliders) != 0)
  59813. {
  59814. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59815. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59816. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59817. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59818. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59819. for (int i = 4; --i >= 0;)
  59820. sliders[i]->addListener (this);
  59821. }
  59822. if ((flags & showColourspace) != 0)
  59823. {
  59824. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59825. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59826. }
  59827. update();
  59828. }
  59829. ColourSelector::~ColourSelector()
  59830. {
  59831. dispatchPendingMessages();
  59832. swatchComponents.clear();
  59833. }
  59834. const Colour ColourSelector::getCurrentColour() const
  59835. {
  59836. return ((flags & showAlphaChannel) != 0) ? colour
  59837. : colour.withAlpha ((uint8) 0xff);
  59838. }
  59839. void ColourSelector::setCurrentColour (const Colour& c)
  59840. {
  59841. if (c != colour)
  59842. {
  59843. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59844. updateHSV();
  59845. update();
  59846. }
  59847. }
  59848. void ColourSelector::setHue (float newH)
  59849. {
  59850. newH = jlimit (0.0f, 1.0f, newH);
  59851. if (h != newH)
  59852. {
  59853. h = newH;
  59854. colour = Colour (h, s, v, colour.getFloatAlpha());
  59855. update();
  59856. }
  59857. }
  59858. void ColourSelector::setSV (float newS, float newV)
  59859. {
  59860. newS = jlimit (0.0f, 1.0f, newS);
  59861. newV = jlimit (0.0f, 1.0f, newV);
  59862. if (s != newS || v != newV)
  59863. {
  59864. s = newS;
  59865. v = newV;
  59866. colour = Colour (h, s, v, colour.getFloatAlpha());
  59867. update();
  59868. }
  59869. }
  59870. void ColourSelector::updateHSV()
  59871. {
  59872. colour.getHSB (h, s, v);
  59873. }
  59874. void ColourSelector::update()
  59875. {
  59876. if (sliders[0] != 0)
  59877. {
  59878. sliders[0]->setValue ((int) colour.getRed());
  59879. sliders[1]->setValue ((int) colour.getGreen());
  59880. sliders[2]->setValue ((int) colour.getBlue());
  59881. sliders[3]->setValue ((int) colour.getAlpha());
  59882. }
  59883. if (colourSpace != 0)
  59884. {
  59885. colourSpace->updateIfNeeded();
  59886. hueSelector->updateIfNeeded();
  59887. }
  59888. if ((flags & showColourAtTop) != 0)
  59889. repaint (previewArea);
  59890. sendChangeMessage();
  59891. }
  59892. void ColourSelector::paint (Graphics& g)
  59893. {
  59894. g.fillAll (findColour (backgroundColourId));
  59895. if ((flags & showColourAtTop) != 0)
  59896. {
  59897. const Colour currentColour (getCurrentColour());
  59898. g.fillCheckerBoard (previewArea, 10, 10,
  59899. Colour (0xffdddddd).overlaidWith (currentColour),
  59900. Colour (0xffffffff).overlaidWith (currentColour));
  59901. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59902. g.setFont (14.0f, true);
  59903. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59904. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59905. Justification::centred, false);
  59906. }
  59907. if ((flags & showSliders) != 0)
  59908. {
  59909. g.setColour (findColour (labelTextColourId));
  59910. g.setFont (11.0f);
  59911. for (int i = 4; --i >= 0;)
  59912. {
  59913. if (sliders[i]->isVisible())
  59914. g.drawText (sliders[i]->getName() + ":",
  59915. 0, sliders[i]->getY(),
  59916. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59917. Justification::centredRight, false);
  59918. }
  59919. }
  59920. }
  59921. void ColourSelector::resized()
  59922. {
  59923. const int swatchesPerRow = 8;
  59924. const int swatchHeight = 22;
  59925. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59926. const int numSwatches = getNumSwatches();
  59927. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59928. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59929. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59930. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59931. int y = topSpace;
  59932. if ((flags & showColourspace) != 0)
  59933. {
  59934. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59935. colourSpace->setBounds (edgeGap, y,
  59936. getWidth() - hueWidth - edgeGap - 4,
  59937. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59938. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59939. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59940. colourSpace->getHeight());
  59941. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59942. }
  59943. if ((flags & showSliders) != 0)
  59944. {
  59945. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59946. for (int i = 0; i < numSliders; ++i)
  59947. {
  59948. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59949. proportionOfWidth (0.72f), sliderHeight - 2);
  59950. y += sliderHeight;
  59951. }
  59952. }
  59953. if (numSwatches > 0)
  59954. {
  59955. const int startX = 8;
  59956. const int xGap = 4;
  59957. const int yGap = 4;
  59958. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59959. y += edgeGap;
  59960. if (swatchComponents.size() != numSwatches)
  59961. {
  59962. swatchComponents.clear();
  59963. for (int i = 0; i < numSwatches; ++i)
  59964. {
  59965. SwatchComponent* const sc = new SwatchComponent (*this, i);
  59966. swatchComponents.add (sc);
  59967. addAndMakeVisible (sc);
  59968. }
  59969. }
  59970. int x = startX;
  59971. for (int i = 0; i < swatchComponents.size(); ++i)
  59972. {
  59973. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59974. sc->setBounds (x + xGap / 2,
  59975. y + yGap / 2,
  59976. swatchWidth - xGap,
  59977. swatchHeight - yGap);
  59978. if (((i + 1) % swatchesPerRow) == 0)
  59979. {
  59980. x = startX;
  59981. y += swatchHeight;
  59982. }
  59983. else
  59984. {
  59985. x += swatchWidth;
  59986. }
  59987. }
  59988. }
  59989. }
  59990. void ColourSelector::sliderValueChanged (Slider*)
  59991. {
  59992. if (sliders[0] != 0)
  59993. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59994. (uint8) sliders[1]->getValue(),
  59995. (uint8) sliders[2]->getValue(),
  59996. (uint8) sliders[3]->getValue()));
  59997. }
  59998. int ColourSelector::getNumSwatches() const
  59999. {
  60000. return 0;
  60001. }
  60002. const Colour ColourSelector::getSwatchColour (const int) const
  60003. {
  60004. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60005. return Colours::black;
  60006. }
  60007. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60008. {
  60009. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60010. }
  60011. END_JUCE_NAMESPACE
  60012. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60013. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60014. BEGIN_JUCE_NAMESPACE
  60015. class ShadowWindow : public Component
  60016. {
  60017. public:
  60018. ShadowWindow (Component& owner, const int type_, const Image shadowImageSections [12])
  60019. : topLeft (shadowImageSections [type_ * 3]),
  60020. bottomRight (shadowImageSections [type_ * 3 + 1]),
  60021. filler (shadowImageSections [type_ * 3 + 2]),
  60022. type (type_)
  60023. {
  60024. setInterceptsMouseClicks (false, false);
  60025. if (owner.isOnDesktop())
  60026. {
  60027. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60028. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60029. | ComponentPeer::windowIsTemporary
  60030. | ComponentPeer::windowIgnoresKeyPresses);
  60031. }
  60032. else if (owner.getParentComponent() != 0)
  60033. {
  60034. owner.getParentComponent()->addChildComponent (this);
  60035. }
  60036. }
  60037. void paint (Graphics& g)
  60038. {
  60039. g.setOpacity (1.0f);
  60040. if (type < 2)
  60041. {
  60042. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60043. g.drawImage (topLeft,
  60044. 0, 0, topLeft.getWidth(), imH,
  60045. 0, 0, topLeft.getWidth(), imH);
  60046. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60047. g.drawImage (bottomRight,
  60048. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60049. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60050. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60051. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60052. }
  60053. else
  60054. {
  60055. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60056. g.drawImage (topLeft,
  60057. 0, 0, imW, topLeft.getHeight(),
  60058. 0, 0, imW, topLeft.getHeight());
  60059. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60060. g.drawImage (bottomRight,
  60061. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60062. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60063. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60064. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60065. }
  60066. }
  60067. void resized()
  60068. {
  60069. repaint(); // (needed for correct repainting)
  60070. }
  60071. private:
  60072. const Image topLeft, bottomRight, filler;
  60073. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60074. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  60075. };
  60076. DropShadower::DropShadower (const float alpha_,
  60077. const int xOffset_,
  60078. const int yOffset_,
  60079. const float blurRadius_)
  60080. : owner (0),
  60081. xOffset (xOffset_),
  60082. yOffset (yOffset_),
  60083. alpha (alpha_),
  60084. blurRadius (blurRadius_),
  60085. reentrant (false)
  60086. {
  60087. }
  60088. DropShadower::~DropShadower()
  60089. {
  60090. if (owner != 0)
  60091. owner->removeComponentListener (this);
  60092. reentrant = true;
  60093. shadowWindows.clear();
  60094. }
  60095. void DropShadower::setOwner (Component* componentToFollow)
  60096. {
  60097. if (componentToFollow != owner)
  60098. {
  60099. if (owner != 0)
  60100. owner->removeComponentListener (this);
  60101. // (the component can't be null)
  60102. jassert (componentToFollow != 0);
  60103. owner = componentToFollow;
  60104. jassert (owner != 0);
  60105. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60106. owner->addComponentListener (this);
  60107. updateShadows();
  60108. }
  60109. }
  60110. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60111. {
  60112. updateShadows();
  60113. }
  60114. void DropShadower::componentBroughtToFront (Component&)
  60115. {
  60116. bringShadowWindowsToFront();
  60117. }
  60118. void DropShadower::componentParentHierarchyChanged (Component&)
  60119. {
  60120. shadowWindows.clear();
  60121. updateShadows();
  60122. }
  60123. void DropShadower::componentVisibilityChanged (Component&)
  60124. {
  60125. updateShadows();
  60126. }
  60127. void DropShadower::updateShadows()
  60128. {
  60129. if (reentrant || owner == 0)
  60130. return;
  60131. ComponentPeer* const peer = owner->getPeer();
  60132. const bool isOwnerVisible = owner->isVisible() && (peer == 0 || ! peer->isMinimised());
  60133. const bool createShadowWindows = shadowWindows.size() == 0
  60134. && owner->getWidth() > 0
  60135. && owner->getHeight() > 0
  60136. && isOwnerVisible
  60137. && (Desktop::canUseSemiTransparentWindows()
  60138. || owner->getParentComponent() != 0);
  60139. {
  60140. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60141. const int shadowEdge = jmax (xOffset, yOffset) + (int) blurRadius;
  60142. if (createShadowWindows)
  60143. {
  60144. // keep a cached version of the image to save doing the gaussian too often
  60145. String imageId;
  60146. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60147. const int hash = imageId.hashCode();
  60148. Image bigIm (ImageCache::getFromHashCode (hash));
  60149. if (bigIm.isNull())
  60150. {
  60151. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60152. Graphics bigG (bigIm);
  60153. bigG.setColour (Colours::black.withAlpha (alpha));
  60154. bigG.fillRect (shadowEdge + xOffset,
  60155. shadowEdge + yOffset,
  60156. bigIm.getWidth() - (shadowEdge * 2),
  60157. bigIm.getHeight() - (shadowEdge * 2));
  60158. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60159. blurKernel.createGaussianBlur (blurRadius);
  60160. blurKernel.applyToImage (bigIm, bigIm,
  60161. Rectangle<int> (xOffset, yOffset,
  60162. bigIm.getWidth(), bigIm.getHeight()));
  60163. ImageCache::addImageToCache (bigIm, hash);
  60164. }
  60165. const int iw = bigIm.getWidth();
  60166. const int ih = bigIm.getHeight();
  60167. const int shadowEdge2 = shadowEdge * 2;
  60168. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60169. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60170. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60171. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60172. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60173. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60174. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60175. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60176. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60177. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60178. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60179. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60180. for (int i = 0; i < 4; ++i)
  60181. shadowWindows.add (new ShadowWindow (*owner, i, shadowImageSections));
  60182. }
  60183. if (shadowWindows.size() >= 4)
  60184. {
  60185. for (int i = shadowWindows.size(); --i >= 0;)
  60186. {
  60187. shadowWindows.getUnchecked(i)->setAlwaysOnTop (owner->isAlwaysOnTop());
  60188. shadowWindows.getUnchecked(i)->setVisible (isOwnerVisible);
  60189. }
  60190. const int x = owner->getX();
  60191. const int y = owner->getY() - shadowEdge;
  60192. const int w = owner->getWidth();
  60193. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60194. shadowWindows.getUnchecked(0)->setBounds (x - shadowEdge, y, shadowEdge, h);
  60195. shadowWindows.getUnchecked(1)->setBounds (x + w, y, shadowEdge, h);
  60196. shadowWindows.getUnchecked(2)->setBounds (x, y, w, shadowEdge);
  60197. shadowWindows.getUnchecked(3)->setBounds (x, owner->getBottom(), w, shadowEdge);
  60198. }
  60199. }
  60200. if (createShadowWindows)
  60201. bringShadowWindowsToFront();
  60202. }
  60203. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60204. const int sx, const int sy)
  60205. {
  60206. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60207. Graphics g (shadowImageSections[num]);
  60208. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60209. }
  60210. void DropShadower::bringShadowWindowsToFront()
  60211. {
  60212. if (! reentrant)
  60213. {
  60214. updateShadows();
  60215. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60216. for (int i = shadowWindows.size(); --i >= 0;)
  60217. shadowWindows.getUnchecked(i)->toBehind (owner);
  60218. }
  60219. }
  60220. END_JUCE_NAMESPACE
  60221. /*** End of inlined file: juce_DropShadower.cpp ***/
  60222. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60223. BEGIN_JUCE_NAMESPACE
  60224. class MidiKeyboardUpDownButton : public Button
  60225. {
  60226. public:
  60227. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60228. : Button (String::empty),
  60229. owner (owner_),
  60230. delta (delta_)
  60231. {
  60232. setOpaque (true);
  60233. }
  60234. void clicked()
  60235. {
  60236. int note = owner.getLowestVisibleKey();
  60237. if (delta < 0)
  60238. note = (note - 1) / 12;
  60239. else
  60240. note = note / 12 + 1;
  60241. owner.setLowestVisibleKey (note * 12);
  60242. }
  60243. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60244. {
  60245. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60246. isMouseOverButton, isButtonDown,
  60247. delta > 0);
  60248. }
  60249. private:
  60250. MidiKeyboardComponent& owner;
  60251. const int delta;
  60252. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60253. };
  60254. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60255. const Orientation orientation_)
  60256. : state (state_),
  60257. xOffset (0),
  60258. blackNoteLength (1),
  60259. keyWidth (16.0f),
  60260. orientation (orientation_),
  60261. midiChannel (1),
  60262. midiInChannelMask (0xffff),
  60263. velocity (1.0f),
  60264. noteUnderMouse (-1),
  60265. mouseDownNote (-1),
  60266. rangeStart (0),
  60267. rangeEnd (127),
  60268. firstKey (12 * 4),
  60269. canScroll (true),
  60270. mouseDragging (false),
  60271. useMousePositionForVelocity (true),
  60272. keyMappingOctave (6),
  60273. octaveNumForMiddleC (3)
  60274. {
  60275. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60276. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60277. // initialise with a default set of querty key-mappings..
  60278. const char* const keymap = "awsedftgyhujkolp;";
  60279. for (int i = String (keymap).length(); --i >= 0;)
  60280. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60281. setOpaque (true);
  60282. setWantsKeyboardFocus (true);
  60283. state.addListener (this);
  60284. }
  60285. MidiKeyboardComponent::~MidiKeyboardComponent()
  60286. {
  60287. state.removeListener (this);
  60288. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60289. }
  60290. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60291. {
  60292. keyWidth = widthInPixels;
  60293. resized();
  60294. }
  60295. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60296. {
  60297. if (orientation != newOrientation)
  60298. {
  60299. orientation = newOrientation;
  60300. resized();
  60301. }
  60302. }
  60303. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60304. const int highestNote)
  60305. {
  60306. jassert (lowestNote >= 0 && lowestNote <= 127);
  60307. jassert (highestNote >= 0 && highestNote <= 127);
  60308. jassert (lowestNote <= highestNote);
  60309. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60310. {
  60311. rangeStart = jlimit (0, 127, lowestNote);
  60312. rangeEnd = jlimit (0, 127, highestNote);
  60313. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60314. resized();
  60315. }
  60316. }
  60317. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60318. {
  60319. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60320. if (noteNumber != firstKey)
  60321. {
  60322. firstKey = noteNumber;
  60323. sendChangeMessage();
  60324. resized();
  60325. }
  60326. }
  60327. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60328. {
  60329. if (canScroll != canScroll_)
  60330. {
  60331. canScroll = canScroll_;
  60332. resized();
  60333. }
  60334. }
  60335. void MidiKeyboardComponent::colourChanged()
  60336. {
  60337. repaint();
  60338. }
  60339. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60340. {
  60341. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60342. if (midiChannel != midiChannelNumber)
  60343. {
  60344. resetAnyKeysInUse();
  60345. midiChannel = jlimit (1, 16, midiChannelNumber);
  60346. }
  60347. }
  60348. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60349. {
  60350. midiInChannelMask = midiChannelMask;
  60351. triggerAsyncUpdate();
  60352. }
  60353. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60354. {
  60355. velocity = jlimit (0.0f, 1.0f, velocity_);
  60356. useMousePositionForVelocity = useMousePositionForVelocity_;
  60357. }
  60358. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60359. {
  60360. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60361. static const float blackNoteWidth = 0.7f;
  60362. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60363. 1.0f, 2 - blackNoteWidth * 0.4f,
  60364. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60365. 4.0f, 5 - blackNoteWidth * 0.5f,
  60366. 5.0f, 6 - blackNoteWidth * 0.3f,
  60367. 6.0f };
  60368. static const float widths[] = { 1.0f, blackNoteWidth,
  60369. 1.0f, blackNoteWidth,
  60370. 1.0f, 1.0f, blackNoteWidth,
  60371. 1.0f, blackNoteWidth,
  60372. 1.0f, blackNoteWidth,
  60373. 1.0f };
  60374. const int octave = midiNoteNumber / 12;
  60375. const int note = midiNoteNumber % 12;
  60376. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60377. w = roundToInt (widths [note] * keyWidth_);
  60378. }
  60379. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60380. {
  60381. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60382. int rx, rw;
  60383. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60384. x -= xOffset + rx;
  60385. }
  60386. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60387. {
  60388. int x, y;
  60389. getKeyPos (midiNoteNumber, x, y);
  60390. return x;
  60391. }
  60392. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60393. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60394. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60395. {
  60396. if (! reallyContains (pos, false))
  60397. return -1;
  60398. Point<int> p (pos);
  60399. if (orientation != horizontalKeyboard)
  60400. {
  60401. p = Point<int> (p.getY(), p.getX());
  60402. if (orientation == verticalKeyboardFacingLeft)
  60403. p = Point<int> (p.getX(), getWidth() - p.getY());
  60404. else
  60405. p = Point<int> (getHeight() - p.getX(), p.getY());
  60406. }
  60407. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60408. }
  60409. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60410. {
  60411. if (pos.getY() < blackNoteLength)
  60412. {
  60413. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60414. {
  60415. for (int i = 0; i < 5; ++i)
  60416. {
  60417. const int note = octaveStart + blackNotes [i];
  60418. if (note >= rangeStart && note <= rangeEnd)
  60419. {
  60420. int kx, kw;
  60421. getKeyPos (note, kx, kw);
  60422. kx += xOffset;
  60423. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60424. {
  60425. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60426. return note;
  60427. }
  60428. }
  60429. }
  60430. }
  60431. }
  60432. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60433. {
  60434. for (int i = 0; i < 7; ++i)
  60435. {
  60436. const int note = octaveStart + whiteNotes [i];
  60437. if (note >= rangeStart && note <= rangeEnd)
  60438. {
  60439. int kx, kw;
  60440. getKeyPos (note, kx, kw);
  60441. kx += xOffset;
  60442. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60443. {
  60444. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60445. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60446. return note;
  60447. }
  60448. }
  60449. }
  60450. }
  60451. mousePositionVelocity = 0;
  60452. return -1;
  60453. }
  60454. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60455. {
  60456. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60457. {
  60458. int x, w;
  60459. getKeyPos (noteNum, x, w);
  60460. if (orientation == horizontalKeyboard)
  60461. repaint (x, 0, w, getHeight());
  60462. else if (orientation == verticalKeyboardFacingLeft)
  60463. repaint (0, x, getWidth(), w);
  60464. else if (orientation == verticalKeyboardFacingRight)
  60465. repaint (0, getHeight() - x - w, getWidth(), w);
  60466. }
  60467. }
  60468. void MidiKeyboardComponent::paint (Graphics& g)
  60469. {
  60470. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60471. const Colour lineColour (findColour (keySeparatorLineColourId));
  60472. const Colour textColour (findColour (textLabelColourId));
  60473. int x, w, octave;
  60474. for (octave = 0; octave < 128; octave += 12)
  60475. {
  60476. for (int white = 0; white < 7; ++white)
  60477. {
  60478. const int noteNum = octave + whiteNotes [white];
  60479. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60480. {
  60481. getKeyPos (noteNum, x, w);
  60482. if (orientation == horizontalKeyboard)
  60483. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60484. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60485. noteUnderMouse == noteNum,
  60486. lineColour, textColour);
  60487. else if (orientation == verticalKeyboardFacingLeft)
  60488. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60489. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60490. noteUnderMouse == noteNum,
  60491. lineColour, textColour);
  60492. else if (orientation == verticalKeyboardFacingRight)
  60493. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60494. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60495. noteUnderMouse == noteNum,
  60496. lineColour, textColour);
  60497. }
  60498. }
  60499. }
  60500. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60501. if (orientation == verticalKeyboardFacingLeft)
  60502. {
  60503. x1 = getWidth() - 1.0f;
  60504. x2 = getWidth() - 5.0f;
  60505. }
  60506. else if (orientation == verticalKeyboardFacingRight)
  60507. x2 = 5.0f;
  60508. else
  60509. y2 = 5.0f;
  60510. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60511. Colours::transparentBlack, x2, y2, false));
  60512. getKeyPos (rangeEnd, x, w);
  60513. x += w;
  60514. if (orientation == verticalKeyboardFacingLeft)
  60515. g.fillRect (getWidth() - 5, 0, 5, x);
  60516. else if (orientation == verticalKeyboardFacingRight)
  60517. g.fillRect (0, 0, 5, x);
  60518. else
  60519. g.fillRect (0, 0, x, 5);
  60520. g.setColour (lineColour);
  60521. if (orientation == verticalKeyboardFacingLeft)
  60522. g.fillRect (0, 0, 1, x);
  60523. else if (orientation == verticalKeyboardFacingRight)
  60524. g.fillRect (getWidth() - 1, 0, 1, x);
  60525. else
  60526. g.fillRect (0, getHeight() - 1, x, 1);
  60527. const Colour blackNoteColour (findColour (blackNoteColourId));
  60528. for (octave = 0; octave < 128; octave += 12)
  60529. {
  60530. for (int black = 0; black < 5; ++black)
  60531. {
  60532. const int noteNum = octave + blackNotes [black];
  60533. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60534. {
  60535. getKeyPos (noteNum, x, w);
  60536. if (orientation == horizontalKeyboard)
  60537. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60538. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60539. noteUnderMouse == noteNum,
  60540. blackNoteColour);
  60541. else if (orientation == verticalKeyboardFacingLeft)
  60542. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60543. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60544. noteUnderMouse == noteNum,
  60545. blackNoteColour);
  60546. else if (orientation == verticalKeyboardFacingRight)
  60547. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60548. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60549. noteUnderMouse == noteNum,
  60550. blackNoteColour);
  60551. }
  60552. }
  60553. }
  60554. }
  60555. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60556. Graphics& g, int x, int y, int w, int h,
  60557. bool isDown, bool isOver,
  60558. const Colour& lineColour,
  60559. const Colour& textColour)
  60560. {
  60561. Colour c (Colours::transparentWhite);
  60562. if (isDown)
  60563. c = findColour (keyDownOverlayColourId);
  60564. if (isOver)
  60565. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60566. g.setColour (c);
  60567. g.fillRect (x, y, w, h);
  60568. const String text (getWhiteNoteText (midiNoteNumber));
  60569. if (! text.isEmpty())
  60570. {
  60571. g.setColour (textColour);
  60572. Font f (jmin (12.0f, keyWidth * 0.9f));
  60573. f.setHorizontalScale (0.8f);
  60574. g.setFont (f);
  60575. Justification justification (Justification::centredBottom);
  60576. if (orientation == verticalKeyboardFacingLeft)
  60577. justification = Justification::centredLeft;
  60578. else if (orientation == verticalKeyboardFacingRight)
  60579. justification = Justification::centredRight;
  60580. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60581. }
  60582. g.setColour (lineColour);
  60583. if (orientation == horizontalKeyboard)
  60584. g.fillRect (x, y, 1, h);
  60585. else if (orientation == verticalKeyboardFacingLeft)
  60586. g.fillRect (x, y, w, 1);
  60587. else if (orientation == verticalKeyboardFacingRight)
  60588. g.fillRect (x, y + h - 1, w, 1);
  60589. if (midiNoteNumber == rangeEnd)
  60590. {
  60591. if (orientation == horizontalKeyboard)
  60592. g.fillRect (x + w, y, 1, h);
  60593. else if (orientation == verticalKeyboardFacingLeft)
  60594. g.fillRect (x, y + h, w, 1);
  60595. else if (orientation == verticalKeyboardFacingRight)
  60596. g.fillRect (x, y - 1, w, 1);
  60597. }
  60598. }
  60599. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60600. Graphics& g, int x, int y, int w, int h,
  60601. bool isDown, bool isOver,
  60602. const Colour& noteFillColour)
  60603. {
  60604. Colour c (noteFillColour);
  60605. if (isDown)
  60606. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60607. if (isOver)
  60608. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60609. g.setColour (c);
  60610. g.fillRect (x, y, w, h);
  60611. if (isDown)
  60612. {
  60613. g.setColour (noteFillColour);
  60614. g.drawRect (x, y, w, h);
  60615. }
  60616. else
  60617. {
  60618. const int xIndent = jmax (1, jmin (w, h) / 8);
  60619. g.setColour (c.brighter());
  60620. if (orientation == horizontalKeyboard)
  60621. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60622. else if (orientation == verticalKeyboardFacingLeft)
  60623. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60624. else if (orientation == verticalKeyboardFacingRight)
  60625. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60626. }
  60627. }
  60628. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60629. {
  60630. octaveNumForMiddleC = octaveNumForMiddleC_;
  60631. repaint();
  60632. }
  60633. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60634. {
  60635. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60636. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60637. return String::empty;
  60638. }
  60639. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60640. const bool isMouseOver_,
  60641. const bool isButtonDown,
  60642. const bool movesOctavesUp)
  60643. {
  60644. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60645. float angle;
  60646. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60647. angle = movesOctavesUp ? 0.0f : 0.5f;
  60648. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60649. angle = movesOctavesUp ? 0.25f : 0.75f;
  60650. else
  60651. angle = movesOctavesUp ? 0.75f : 0.25f;
  60652. Path path;
  60653. path.lineTo (0.0f, 1.0f);
  60654. path.lineTo (1.0f, 0.5f);
  60655. path.closeSubPath();
  60656. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60657. g.setColour (findColour (upDownButtonArrowColourId)
  60658. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60659. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60660. w - 2.0f,
  60661. h - 2.0f,
  60662. true));
  60663. }
  60664. void MidiKeyboardComponent::resized()
  60665. {
  60666. int w = getWidth();
  60667. int h = getHeight();
  60668. if (w > 0 && h > 0)
  60669. {
  60670. if (orientation != horizontalKeyboard)
  60671. swapVariables (w, h);
  60672. blackNoteLength = roundToInt (h * 0.7f);
  60673. int kx2, kw2;
  60674. getKeyPos (rangeEnd, kx2, kw2);
  60675. kx2 += kw2;
  60676. if (firstKey != rangeStart)
  60677. {
  60678. int kx1, kw1;
  60679. getKeyPos (rangeStart, kx1, kw1);
  60680. if (kx2 - kx1 <= w)
  60681. {
  60682. firstKey = rangeStart;
  60683. sendChangeMessage();
  60684. repaint();
  60685. }
  60686. }
  60687. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60688. scrollDown->setVisible (showScrollButtons);
  60689. scrollUp->setVisible (showScrollButtons);
  60690. xOffset = 0;
  60691. if (showScrollButtons)
  60692. {
  60693. const int scrollButtonW = jmin (12, w / 2);
  60694. if (orientation == horizontalKeyboard)
  60695. {
  60696. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60697. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60698. }
  60699. else if (orientation == verticalKeyboardFacingLeft)
  60700. {
  60701. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60702. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60703. }
  60704. else if (orientation == verticalKeyboardFacingRight)
  60705. {
  60706. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60707. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60708. }
  60709. int endOfLastKey, kw;
  60710. getKeyPos (rangeEnd, endOfLastKey, kw);
  60711. endOfLastKey += kw;
  60712. float mousePositionVelocity;
  60713. const int spaceAvailable = w - scrollButtonW * 2;
  60714. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60715. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60716. {
  60717. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60718. sendChangeMessage();
  60719. }
  60720. int newOffset = 0;
  60721. getKeyPos (firstKey, newOffset, kw);
  60722. xOffset = newOffset - scrollButtonW;
  60723. }
  60724. else
  60725. {
  60726. firstKey = rangeStart;
  60727. }
  60728. timerCallback();
  60729. repaint();
  60730. }
  60731. }
  60732. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60733. {
  60734. triggerAsyncUpdate();
  60735. }
  60736. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60737. {
  60738. triggerAsyncUpdate();
  60739. }
  60740. void MidiKeyboardComponent::handleAsyncUpdate()
  60741. {
  60742. for (int i = rangeStart; i <= rangeEnd; ++i)
  60743. {
  60744. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60745. {
  60746. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60747. repaintNote (i);
  60748. }
  60749. }
  60750. }
  60751. void MidiKeyboardComponent::resetAnyKeysInUse()
  60752. {
  60753. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60754. {
  60755. state.allNotesOff (midiChannel);
  60756. keysPressed.clear();
  60757. mouseDownNote = -1;
  60758. }
  60759. }
  60760. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60761. {
  60762. float mousePositionVelocity = 0.0f;
  60763. const int newNote = (mouseDragging || isMouseOver())
  60764. ? xyToNote (pos, mousePositionVelocity) : -1;
  60765. if (noteUnderMouse != newNote)
  60766. {
  60767. if (mouseDownNote >= 0)
  60768. {
  60769. state.noteOff (midiChannel, mouseDownNote);
  60770. mouseDownNote = -1;
  60771. }
  60772. if (mouseDragging && newNote >= 0)
  60773. {
  60774. if (! useMousePositionForVelocity)
  60775. mousePositionVelocity = 1.0f;
  60776. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60777. mouseDownNote = newNote;
  60778. }
  60779. repaintNote (noteUnderMouse);
  60780. noteUnderMouse = newNote;
  60781. repaintNote (noteUnderMouse);
  60782. }
  60783. else if (mouseDownNote >= 0 && ! mouseDragging)
  60784. {
  60785. state.noteOff (midiChannel, mouseDownNote);
  60786. mouseDownNote = -1;
  60787. }
  60788. }
  60789. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60790. {
  60791. updateNoteUnderMouse (e.getPosition());
  60792. stopTimer();
  60793. }
  60794. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60795. {
  60796. float mousePositionVelocity;
  60797. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60798. if (newNote >= 0)
  60799. mouseDraggedToKey (newNote, e);
  60800. updateNoteUnderMouse (e.getPosition());
  60801. }
  60802. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60803. {
  60804. return true;
  60805. }
  60806. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60807. {
  60808. }
  60809. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60810. {
  60811. float mousePositionVelocity;
  60812. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60813. mouseDragging = false;
  60814. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60815. {
  60816. repaintNote (noteUnderMouse);
  60817. noteUnderMouse = -1;
  60818. mouseDragging = true;
  60819. updateNoteUnderMouse (e.getPosition());
  60820. startTimer (500);
  60821. }
  60822. }
  60823. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60824. {
  60825. mouseDragging = false;
  60826. updateNoteUnderMouse (e.getPosition());
  60827. stopTimer();
  60828. }
  60829. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60830. {
  60831. updateNoteUnderMouse (e.getPosition());
  60832. }
  60833. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60834. {
  60835. updateNoteUnderMouse (e.getPosition());
  60836. }
  60837. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60838. {
  60839. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60840. }
  60841. void MidiKeyboardComponent::timerCallback()
  60842. {
  60843. updateNoteUnderMouse (getMouseXYRelative());
  60844. }
  60845. void MidiKeyboardComponent::clearKeyMappings()
  60846. {
  60847. resetAnyKeysInUse();
  60848. keyPressNotes.clear();
  60849. keyPresses.clear();
  60850. }
  60851. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60852. const int midiNoteOffsetFromC)
  60853. {
  60854. removeKeyPressForNote (midiNoteOffsetFromC);
  60855. keyPressNotes.add (midiNoteOffsetFromC);
  60856. keyPresses.add (key);
  60857. }
  60858. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60859. {
  60860. for (int i = keyPressNotes.size(); --i >= 0;)
  60861. {
  60862. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60863. {
  60864. keyPressNotes.remove (i);
  60865. keyPresses.remove (i);
  60866. }
  60867. }
  60868. }
  60869. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60870. {
  60871. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60872. keyMappingOctave = newOctaveNumber;
  60873. }
  60874. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60875. {
  60876. bool keyPressUsed = false;
  60877. for (int i = keyPresses.size(); --i >= 0;)
  60878. {
  60879. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60880. if (keyPresses.getReference(i).isCurrentlyDown())
  60881. {
  60882. if (! keysPressed [note])
  60883. {
  60884. keysPressed.setBit (note);
  60885. state.noteOn (midiChannel, note, velocity);
  60886. keyPressUsed = true;
  60887. }
  60888. }
  60889. else
  60890. {
  60891. if (keysPressed [note])
  60892. {
  60893. keysPressed.clearBit (note);
  60894. state.noteOff (midiChannel, note);
  60895. keyPressUsed = true;
  60896. }
  60897. }
  60898. }
  60899. return keyPressUsed;
  60900. }
  60901. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60902. {
  60903. resetAnyKeysInUse();
  60904. }
  60905. END_JUCE_NAMESPACE
  60906. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60907. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60908. #if JUCE_OPENGL
  60909. BEGIN_JUCE_NAMESPACE
  60910. extern void juce_glViewport (const int w, const int h);
  60911. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60912. const int alphaBits_,
  60913. const int depthBufferBits_,
  60914. const int stencilBufferBits_)
  60915. : redBits (bitsPerRGBComponent),
  60916. greenBits (bitsPerRGBComponent),
  60917. blueBits (bitsPerRGBComponent),
  60918. alphaBits (alphaBits_),
  60919. depthBufferBits (depthBufferBits_),
  60920. stencilBufferBits (stencilBufferBits_),
  60921. accumulationBufferRedBits (0),
  60922. accumulationBufferGreenBits (0),
  60923. accumulationBufferBlueBits (0),
  60924. accumulationBufferAlphaBits (0),
  60925. fullSceneAntiAliasingNumSamples (0)
  60926. {
  60927. }
  60928. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60929. : redBits (other.redBits),
  60930. greenBits (other.greenBits),
  60931. blueBits (other.blueBits),
  60932. alphaBits (other.alphaBits),
  60933. depthBufferBits (other.depthBufferBits),
  60934. stencilBufferBits (other.stencilBufferBits),
  60935. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60936. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60937. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60938. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60939. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60940. {
  60941. }
  60942. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60943. {
  60944. redBits = other.redBits;
  60945. greenBits = other.greenBits;
  60946. blueBits = other.blueBits;
  60947. alphaBits = other.alphaBits;
  60948. depthBufferBits = other.depthBufferBits;
  60949. stencilBufferBits = other.stencilBufferBits;
  60950. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60951. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60952. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60953. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60954. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60955. return *this;
  60956. }
  60957. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60958. {
  60959. return redBits == other.redBits
  60960. && greenBits == other.greenBits
  60961. && blueBits == other.blueBits
  60962. && alphaBits == other.alphaBits
  60963. && depthBufferBits == other.depthBufferBits
  60964. && stencilBufferBits == other.stencilBufferBits
  60965. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60966. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60967. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60968. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60969. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60970. }
  60971. static Array<OpenGLContext*> knownContexts;
  60972. OpenGLContext::OpenGLContext() throw()
  60973. {
  60974. knownContexts.add (this);
  60975. }
  60976. OpenGLContext::~OpenGLContext()
  60977. {
  60978. knownContexts.removeValue (this);
  60979. }
  60980. OpenGLContext* OpenGLContext::getCurrentContext()
  60981. {
  60982. for (int i = knownContexts.size(); --i >= 0;)
  60983. {
  60984. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60985. if (oglc->isActive())
  60986. return oglc;
  60987. }
  60988. return 0;
  60989. }
  60990. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60991. {
  60992. public:
  60993. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60994. : ComponentMovementWatcher (owner_),
  60995. owner (owner_)
  60996. {
  60997. }
  60998. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60999. {
  61000. owner->updateContextPosition();
  61001. }
  61002. void componentPeerChanged()
  61003. {
  61004. const ScopedLock sl (owner->getContextLock());
  61005. owner->deleteContext();
  61006. }
  61007. void componentVisibilityChanged()
  61008. {
  61009. if (! owner->isShowing())
  61010. {
  61011. const ScopedLock sl (owner->getContextLock());
  61012. owner->deleteContext();
  61013. }
  61014. }
  61015. private:
  61016. OpenGLComponent* const owner;
  61017. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  61018. };
  61019. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61020. : type (type_),
  61021. contextToShareListsWith (0),
  61022. needToUpdateViewport (true)
  61023. {
  61024. setOpaque (true);
  61025. componentWatcher = new OpenGLComponentWatcher (this);
  61026. }
  61027. OpenGLComponent::~OpenGLComponent()
  61028. {
  61029. deleteContext();
  61030. componentWatcher = 0;
  61031. }
  61032. void OpenGLComponent::deleteContext()
  61033. {
  61034. const ScopedLock sl (contextLock);
  61035. context = 0;
  61036. }
  61037. void OpenGLComponent::updateContextPosition()
  61038. {
  61039. needToUpdateViewport = true;
  61040. if (getWidth() > 0 && getHeight() > 0)
  61041. {
  61042. Component* const topComp = getTopLevelComponent();
  61043. if (topComp->getPeer() != 0)
  61044. {
  61045. const ScopedLock sl (contextLock);
  61046. if (context != 0)
  61047. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61048. getScreenY() - topComp->getScreenY(),
  61049. getWidth(),
  61050. getHeight(),
  61051. topComp->getHeight());
  61052. }
  61053. }
  61054. }
  61055. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61056. {
  61057. OpenGLPixelFormat pf;
  61058. const ScopedLock sl (contextLock);
  61059. if (context != 0)
  61060. pf = context->getPixelFormat();
  61061. return pf;
  61062. }
  61063. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61064. {
  61065. if (! (preferredPixelFormat == formatToUse))
  61066. {
  61067. const ScopedLock sl (contextLock);
  61068. deleteContext();
  61069. preferredPixelFormat = formatToUse;
  61070. }
  61071. }
  61072. void OpenGLComponent::shareWith (OpenGLContext* c)
  61073. {
  61074. if (contextToShareListsWith != c)
  61075. {
  61076. const ScopedLock sl (contextLock);
  61077. deleteContext();
  61078. contextToShareListsWith = c;
  61079. }
  61080. }
  61081. bool OpenGLComponent::makeCurrentContextActive()
  61082. {
  61083. if (context == 0)
  61084. {
  61085. const ScopedLock sl (contextLock);
  61086. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61087. {
  61088. context = createContext();
  61089. if (context != 0)
  61090. {
  61091. updateContextPosition();
  61092. if (context->makeActive())
  61093. newOpenGLContextCreated();
  61094. }
  61095. }
  61096. }
  61097. return context != 0 && context->makeActive();
  61098. }
  61099. void OpenGLComponent::makeCurrentContextInactive()
  61100. {
  61101. if (context != 0)
  61102. context->makeInactive();
  61103. }
  61104. bool OpenGLComponent::isActiveContext() const throw()
  61105. {
  61106. return context != 0 && context->isActive();
  61107. }
  61108. void OpenGLComponent::swapBuffers()
  61109. {
  61110. if (context != 0)
  61111. context->swapBuffers();
  61112. }
  61113. void OpenGLComponent::paint (Graphics&)
  61114. {
  61115. if (renderAndSwapBuffers())
  61116. {
  61117. ComponentPeer* const peer = getPeer();
  61118. if (peer != 0)
  61119. {
  61120. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61121. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61122. }
  61123. }
  61124. }
  61125. bool OpenGLComponent::renderAndSwapBuffers()
  61126. {
  61127. const ScopedLock sl (contextLock);
  61128. if (! makeCurrentContextActive())
  61129. return false;
  61130. if (needToUpdateViewport)
  61131. {
  61132. needToUpdateViewport = false;
  61133. juce_glViewport (getWidth(), getHeight());
  61134. }
  61135. renderOpenGL();
  61136. swapBuffers();
  61137. return true;
  61138. }
  61139. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61140. {
  61141. Component::internalRepaint (x, y, w, h);
  61142. if (context != 0)
  61143. context->repaint();
  61144. }
  61145. END_JUCE_NAMESPACE
  61146. #endif
  61147. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61148. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61149. BEGIN_JUCE_NAMESPACE
  61150. PreferencesPanel::PreferencesPanel()
  61151. : buttonSize (70)
  61152. {
  61153. }
  61154. PreferencesPanel::~PreferencesPanel()
  61155. {
  61156. }
  61157. void PreferencesPanel::addSettingsPage (const String& title,
  61158. const Drawable* icon,
  61159. const Drawable* overIcon,
  61160. const Drawable* downIcon)
  61161. {
  61162. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61163. buttons.add (button);
  61164. button->setImages (icon, overIcon, downIcon);
  61165. button->setRadioGroupId (1);
  61166. button->addListener (this);
  61167. button->setClickingTogglesState (true);
  61168. button->setWantsKeyboardFocus (false);
  61169. addAndMakeVisible (button);
  61170. resized();
  61171. if (currentPage == 0)
  61172. setCurrentPage (title);
  61173. }
  61174. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61175. {
  61176. DrawableImage icon, iconOver, iconDown;
  61177. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61178. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61179. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61180. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61181. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61182. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61183. }
  61184. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61185. {
  61186. setSize (dialogWidth, dialogHeight);
  61187. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61188. }
  61189. void PreferencesPanel::resized()
  61190. {
  61191. for (int i = 0; i < buttons.size(); ++i)
  61192. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61193. if (currentPage != 0)
  61194. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61195. }
  61196. void PreferencesPanel::paint (Graphics& g)
  61197. {
  61198. g.setColour (Colours::grey);
  61199. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61200. }
  61201. void PreferencesPanel::setCurrentPage (const String& pageName)
  61202. {
  61203. if (currentPageName != pageName)
  61204. {
  61205. currentPageName = pageName;
  61206. currentPage = 0;
  61207. currentPage = createComponentForPage (pageName);
  61208. if (currentPage != 0)
  61209. {
  61210. addAndMakeVisible (currentPage);
  61211. currentPage->toBack();
  61212. resized();
  61213. }
  61214. for (int i = 0; i < buttons.size(); ++i)
  61215. {
  61216. if (buttons.getUnchecked(i)->getName() == pageName)
  61217. {
  61218. buttons.getUnchecked(i)->setToggleState (true, false);
  61219. break;
  61220. }
  61221. }
  61222. }
  61223. }
  61224. void PreferencesPanel::buttonClicked (Button*)
  61225. {
  61226. for (int i = 0; i < buttons.size(); ++i)
  61227. {
  61228. if (buttons.getUnchecked(i)->getToggleState())
  61229. {
  61230. setCurrentPage (buttons.getUnchecked(i)->getName());
  61231. break;
  61232. }
  61233. }
  61234. }
  61235. END_JUCE_NAMESPACE
  61236. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61237. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61238. #if JUCE_WINDOWS || JUCE_LINUX
  61239. BEGIN_JUCE_NAMESPACE
  61240. SystemTrayIconComponent::SystemTrayIconComponent()
  61241. {
  61242. addToDesktop (0);
  61243. }
  61244. SystemTrayIconComponent::~SystemTrayIconComponent()
  61245. {
  61246. }
  61247. END_JUCE_NAMESPACE
  61248. #endif
  61249. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61250. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61251. BEGIN_JUCE_NAMESPACE
  61252. class AlertWindowTextEditor : public TextEditor
  61253. {
  61254. public:
  61255. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61256. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61257. {
  61258. setSelectAllWhenFocused (true);
  61259. }
  61260. void returnPressed()
  61261. {
  61262. // pass these up the component hierarchy to be trigger the buttons
  61263. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61264. }
  61265. void escapePressed()
  61266. {
  61267. // pass these up the component hierarchy to be trigger the buttons
  61268. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61269. }
  61270. private:
  61271. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61272. static juce_wchar getDefaultPasswordChar() throw()
  61273. {
  61274. #if JUCE_LINUX
  61275. return 0x2022;
  61276. #else
  61277. return 0x25cf;
  61278. #endif
  61279. }
  61280. };
  61281. AlertWindow::AlertWindow (const String& title,
  61282. const String& message,
  61283. AlertIconType iconType,
  61284. Component* associatedComponent_)
  61285. : TopLevelWindow (title, true),
  61286. alertIconType (iconType),
  61287. associatedComponent (associatedComponent_)
  61288. {
  61289. if (message.isEmpty())
  61290. text = " "; // to force an update if the message is empty
  61291. setMessage (message);
  61292. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61293. {
  61294. Component* const c = Desktop::getInstance().getComponent (i);
  61295. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61296. {
  61297. setAlwaysOnTop (true);
  61298. break;
  61299. }
  61300. }
  61301. if (! JUCEApplication::isStandaloneApp())
  61302. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61303. lookAndFeelChanged();
  61304. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61305. }
  61306. AlertWindow::~AlertWindow()
  61307. {
  61308. removeAllChildren();
  61309. }
  61310. void AlertWindow::userTriedToCloseWindow()
  61311. {
  61312. exitModalState (0);
  61313. }
  61314. void AlertWindow::setMessage (const String& message)
  61315. {
  61316. const String newMessage (message.substring (0, 2048));
  61317. if (text != newMessage)
  61318. {
  61319. text = newMessage;
  61320. font = getLookAndFeel().getAlertWindowMessageFont();
  61321. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61322. textLayout.setText (getName() + "\n\n", titleFont);
  61323. textLayout.appendText (text, font);
  61324. updateLayout (true);
  61325. repaint();
  61326. }
  61327. }
  61328. void AlertWindow::buttonClicked (Button* button)
  61329. {
  61330. if (button->getParentComponent() != 0)
  61331. button->getParentComponent()->exitModalState (button->getCommandID());
  61332. }
  61333. void AlertWindow::addButton (const String& name,
  61334. const int returnValue,
  61335. const KeyPress& shortcutKey1,
  61336. const KeyPress& shortcutKey2)
  61337. {
  61338. TextButton* const b = new TextButton (name, String::empty);
  61339. buttons.add (b);
  61340. b->setWantsKeyboardFocus (true);
  61341. b->setMouseClickGrabsKeyboardFocus (false);
  61342. b->setCommandToTrigger (0, returnValue, false);
  61343. b->addShortcut (shortcutKey1);
  61344. b->addShortcut (shortcutKey2);
  61345. b->addListener (this);
  61346. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61347. addAndMakeVisible (b, 0);
  61348. updateLayout (false);
  61349. }
  61350. int AlertWindow::getNumButtons() const
  61351. {
  61352. return buttons.size();
  61353. }
  61354. void AlertWindow::triggerButtonClick (const String& buttonName)
  61355. {
  61356. for (int i = buttons.size(); --i >= 0;)
  61357. {
  61358. TextButton* const b = buttons.getUnchecked(i);
  61359. if (buttonName == b->getName())
  61360. {
  61361. b->triggerClick();
  61362. break;
  61363. }
  61364. }
  61365. }
  61366. void AlertWindow::addTextEditor (const String& name,
  61367. const String& initialContents,
  61368. const String& onScreenLabel,
  61369. const bool isPasswordBox)
  61370. {
  61371. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61372. textBoxes.add (tc);
  61373. allComps.add (tc);
  61374. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61375. tc->setFont (font);
  61376. tc->setText (initialContents);
  61377. tc->setCaretPosition (initialContents.length());
  61378. addAndMakeVisible (tc);
  61379. textboxNames.add (onScreenLabel);
  61380. updateLayout (false);
  61381. }
  61382. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61383. {
  61384. for (int i = textBoxes.size(); --i >= 0;)
  61385. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61386. return textBoxes.getUnchecked(i);
  61387. return 0;
  61388. }
  61389. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61390. {
  61391. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61392. return t != 0 ? t->getText() : String::empty;
  61393. }
  61394. void AlertWindow::addComboBox (const String& name,
  61395. const StringArray& items,
  61396. const String& onScreenLabel)
  61397. {
  61398. ComboBox* const cb = new ComboBox (name);
  61399. comboBoxes.add (cb);
  61400. allComps.add (cb);
  61401. for (int i = 0; i < items.size(); ++i)
  61402. cb->addItem (items[i], i + 1);
  61403. addAndMakeVisible (cb);
  61404. cb->setSelectedItemIndex (0);
  61405. comboBoxNames.add (onScreenLabel);
  61406. updateLayout (false);
  61407. }
  61408. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61409. {
  61410. for (int i = comboBoxes.size(); --i >= 0;)
  61411. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61412. return comboBoxes.getUnchecked(i);
  61413. return 0;
  61414. }
  61415. class AlertTextComp : public TextEditor
  61416. {
  61417. public:
  61418. AlertTextComp (const String& message,
  61419. const Font& font)
  61420. {
  61421. setReadOnly (true);
  61422. setMultiLine (true, true);
  61423. setCaretVisible (false);
  61424. setScrollbarsShown (true);
  61425. lookAndFeelChanged();
  61426. setWantsKeyboardFocus (false);
  61427. setFont (font);
  61428. setText (message, false);
  61429. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61430. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61431. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61432. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61433. }
  61434. ~AlertTextComp()
  61435. {
  61436. }
  61437. int getPreferredWidth() const throw() { return bestWidth; }
  61438. void updateLayout (const int width)
  61439. {
  61440. TextLayout text;
  61441. text.appendText (getText(), getFont());
  61442. text.layout (width - 8, Justification::topLeft, true);
  61443. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61444. }
  61445. private:
  61446. int bestWidth;
  61447. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61448. };
  61449. void AlertWindow::addTextBlock (const String& textBlock)
  61450. {
  61451. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61452. textBlocks.add (c);
  61453. allComps.add (c);
  61454. addAndMakeVisible (c);
  61455. updateLayout (false);
  61456. }
  61457. void AlertWindow::addProgressBarComponent (double& progressValue)
  61458. {
  61459. ProgressBar* const pb = new ProgressBar (progressValue);
  61460. progressBars.add (pb);
  61461. allComps.add (pb);
  61462. addAndMakeVisible (pb);
  61463. updateLayout (false);
  61464. }
  61465. void AlertWindow::addCustomComponent (Component* const component)
  61466. {
  61467. customComps.add (component);
  61468. allComps.add (component);
  61469. addAndMakeVisible (component);
  61470. updateLayout (false);
  61471. }
  61472. int AlertWindow::getNumCustomComponents() const
  61473. {
  61474. return customComps.size();
  61475. }
  61476. Component* AlertWindow::getCustomComponent (const int index) const
  61477. {
  61478. return customComps [index];
  61479. }
  61480. Component* AlertWindow::removeCustomComponent (const int index)
  61481. {
  61482. Component* const c = getCustomComponent (index);
  61483. if (c != 0)
  61484. {
  61485. customComps.removeValue (c);
  61486. allComps.removeValue (c);
  61487. removeChildComponent (c);
  61488. updateLayout (false);
  61489. }
  61490. return c;
  61491. }
  61492. void AlertWindow::paint (Graphics& g)
  61493. {
  61494. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61495. g.setColour (findColour (textColourId));
  61496. g.setFont (getLookAndFeel().getAlertWindowFont());
  61497. int i;
  61498. for (i = textBoxes.size(); --i >= 0;)
  61499. {
  61500. const TextEditor* const te = textBoxes.getUnchecked(i);
  61501. g.drawFittedText (textboxNames[i],
  61502. te->getX(), te->getY() - 14,
  61503. te->getWidth(), 14,
  61504. Justification::centredLeft, 1);
  61505. }
  61506. for (i = comboBoxNames.size(); --i >= 0;)
  61507. {
  61508. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61509. g.drawFittedText (comboBoxNames[i],
  61510. cb->getX(), cb->getY() - 14,
  61511. cb->getWidth(), 14,
  61512. Justification::centredLeft, 1);
  61513. }
  61514. for (i = customComps.size(); --i >= 0;)
  61515. {
  61516. const Component* const c = customComps.getUnchecked(i);
  61517. g.drawFittedText (c->getName(),
  61518. c->getX(), c->getY() - 14,
  61519. c->getWidth(), 14,
  61520. Justification::centredLeft, 1);
  61521. }
  61522. }
  61523. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61524. {
  61525. const int titleH = 24;
  61526. const int iconWidth = 80;
  61527. const int wid = jmax (font.getStringWidth (text),
  61528. font.getStringWidth (getName()));
  61529. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61530. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61531. const int edgeGap = 10;
  61532. const int labelHeight = 18;
  61533. int iconSpace;
  61534. if (alertIconType == NoIcon)
  61535. {
  61536. textLayout.layout (w, Justification::horizontallyCentred, true);
  61537. iconSpace = 0;
  61538. }
  61539. else
  61540. {
  61541. textLayout.layout (w, Justification::left, true);
  61542. iconSpace = iconWidth;
  61543. }
  61544. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61545. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61546. const int textLayoutH = textLayout.getHeight();
  61547. const int textBottom = 16 + titleH + textLayoutH;
  61548. int h = textBottom;
  61549. int buttonW = 40;
  61550. int i;
  61551. for (i = 0; i < buttons.size(); ++i)
  61552. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61553. w = jmax (buttonW, w);
  61554. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61555. if (buttons.size() > 0)
  61556. h += 20 + buttons.getUnchecked(0)->getHeight();
  61557. for (i = customComps.size(); --i >= 0;)
  61558. {
  61559. Component* c = customComps.getUnchecked(i);
  61560. w = jmax (w, (c->getWidth() * 100) / 80);
  61561. h += 10 + c->getHeight();
  61562. if (c->getName().isNotEmpty())
  61563. h += labelHeight;
  61564. }
  61565. for (i = textBlocks.size(); --i >= 0;)
  61566. {
  61567. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61568. w = jmax (w, ac->getPreferredWidth());
  61569. }
  61570. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61571. for (i = textBlocks.size(); --i >= 0;)
  61572. {
  61573. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61574. ac->updateLayout ((int) (w * 0.8f));
  61575. h += ac->getHeight() + 10;
  61576. }
  61577. h = jmin (getParentHeight() - 50, h);
  61578. if (onlyIncreaseSize)
  61579. {
  61580. w = jmax (w, getWidth());
  61581. h = jmax (h, getHeight());
  61582. }
  61583. if (! isVisible())
  61584. {
  61585. centreAroundComponent (associatedComponent, w, h);
  61586. }
  61587. else
  61588. {
  61589. const int cx = getX() + getWidth() / 2;
  61590. const int cy = getY() + getHeight() / 2;
  61591. setBounds (cx - w / 2,
  61592. cy - h / 2,
  61593. w, h);
  61594. }
  61595. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61596. const int spacer = 16;
  61597. int totalWidth = -spacer;
  61598. for (i = buttons.size(); --i >= 0;)
  61599. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61600. int x = (w - totalWidth) / 2;
  61601. int y = (int) (getHeight() * 0.95f);
  61602. for (i = 0; i < buttons.size(); ++i)
  61603. {
  61604. TextButton* const c = buttons.getUnchecked(i);
  61605. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61606. c->setTopLeftPosition (x, ny);
  61607. if (ny < y)
  61608. y = ny;
  61609. x += c->getWidth() + spacer;
  61610. c->toFront (false);
  61611. }
  61612. y = textBottom;
  61613. for (i = 0; i < allComps.size(); ++i)
  61614. {
  61615. Component* const c = allComps.getUnchecked(i);
  61616. h = 22;
  61617. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61618. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61619. y += labelHeight;
  61620. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61621. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61622. y += labelHeight;
  61623. if (customComps.contains (c))
  61624. {
  61625. if (c->getName().isNotEmpty())
  61626. y += labelHeight;
  61627. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61628. h = c->getHeight();
  61629. }
  61630. else if (textBlocks.contains (c))
  61631. {
  61632. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61633. h = c->getHeight();
  61634. }
  61635. else
  61636. {
  61637. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61638. }
  61639. y += h + 10;
  61640. }
  61641. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61642. }
  61643. bool AlertWindow::containsAnyExtraComponents() const
  61644. {
  61645. return allComps.size() > 0;
  61646. }
  61647. void AlertWindow::mouseDown (const MouseEvent& e)
  61648. {
  61649. dragger.startDraggingComponent (this, e);
  61650. }
  61651. void AlertWindow::mouseDrag (const MouseEvent& e)
  61652. {
  61653. dragger.dragComponent (this, e, &constrainer);
  61654. }
  61655. bool AlertWindow::keyPressed (const KeyPress& key)
  61656. {
  61657. for (int i = buttons.size(); --i >= 0;)
  61658. {
  61659. TextButton* const b = buttons.getUnchecked(i);
  61660. if (b->isRegisteredForShortcut (key))
  61661. {
  61662. b->triggerClick();
  61663. return true;
  61664. }
  61665. }
  61666. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61667. {
  61668. exitModalState (0);
  61669. return true;
  61670. }
  61671. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61672. {
  61673. buttons.getUnchecked(0)->triggerClick();
  61674. return true;
  61675. }
  61676. return false;
  61677. }
  61678. void AlertWindow::lookAndFeelChanged()
  61679. {
  61680. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61681. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61682. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61683. }
  61684. int AlertWindow::getDesktopWindowStyleFlags() const
  61685. {
  61686. return getLookAndFeel().getAlertBoxWindowFlags();
  61687. }
  61688. class AlertWindowInfo
  61689. {
  61690. public:
  61691. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61692. AlertWindow::AlertIconType iconType_, int numButtons_)
  61693. : title (title_), message (message_), iconType (iconType_),
  61694. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  61695. {
  61696. }
  61697. String title, message, button1, button2, button3;
  61698. AlertWindow::AlertIconType iconType;
  61699. int numButtons, returnValue;
  61700. WeakReference<Component> associatedComponent;
  61701. int showModal() const
  61702. {
  61703. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61704. return returnValue;
  61705. }
  61706. private:
  61707. void show()
  61708. {
  61709. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61710. : LookAndFeel::getDefaultLookAndFeel();
  61711. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61712. iconType, numButtons, associatedComponent));
  61713. jassert (alertBox != 0); // you have to return one of these!
  61714. returnValue = alertBox->runModalLoop();
  61715. }
  61716. static void* showCallback (void* userData)
  61717. {
  61718. static_cast <AlertWindowInfo*> (userData)->show();
  61719. return 0;
  61720. }
  61721. };
  61722. void AlertWindow::showMessageBox (AlertIconType iconType,
  61723. const String& title,
  61724. const String& message,
  61725. const String& buttonText,
  61726. Component* associatedComponent)
  61727. {
  61728. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  61729. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61730. info.showModal();
  61731. }
  61732. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61733. const String& title,
  61734. const String& message,
  61735. const String& button1Text,
  61736. const String& button2Text,
  61737. Component* associatedComponent)
  61738. {
  61739. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  61740. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61741. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61742. return info.showModal() != 0;
  61743. }
  61744. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61745. const String& title,
  61746. const String& message,
  61747. const String& button1Text,
  61748. const String& button2Text,
  61749. const String& button3Text,
  61750. Component* associatedComponent)
  61751. {
  61752. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  61753. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61754. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61755. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61756. return info.showModal();
  61757. }
  61758. END_JUCE_NAMESPACE
  61759. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61760. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61761. BEGIN_JUCE_NAMESPACE
  61762. CallOutBox::CallOutBox (Component& contentComponent,
  61763. Component& componentToPointTo,
  61764. Component* const parentComponent)
  61765. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61766. {
  61767. addAndMakeVisible (&content);
  61768. if (parentComponent != 0)
  61769. {
  61770. parentComponent->addChildComponent (this);
  61771. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  61772. parentComponent->getLocalBounds());
  61773. setVisible (true);
  61774. }
  61775. else
  61776. {
  61777. if (! JUCEApplication::isStandaloneApp())
  61778. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61779. updatePosition (componentToPointTo.getScreenBounds(),
  61780. componentToPointTo.getParentMonitorArea());
  61781. addToDesktop (ComponentPeer::windowIsTemporary);
  61782. }
  61783. }
  61784. CallOutBox::~CallOutBox()
  61785. {
  61786. }
  61787. void CallOutBox::setArrowSize (const float newSize)
  61788. {
  61789. arrowSize = newSize;
  61790. borderSpace = jmax (20, (int) arrowSize);
  61791. refreshPath();
  61792. }
  61793. void CallOutBox::paint (Graphics& g)
  61794. {
  61795. if (background.isNull())
  61796. {
  61797. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61798. Graphics g2 (background);
  61799. getLookAndFeel().drawCallOutBoxBackground (*this, g2, outline);
  61800. }
  61801. g.setColour (Colours::black);
  61802. g.drawImageAt (background, 0, 0);
  61803. }
  61804. void CallOutBox::resized()
  61805. {
  61806. content.setTopLeftPosition (borderSpace, borderSpace);
  61807. refreshPath();
  61808. }
  61809. void CallOutBox::moved()
  61810. {
  61811. refreshPath();
  61812. }
  61813. void CallOutBox::childBoundsChanged (Component*)
  61814. {
  61815. updatePosition (targetArea, availableArea);
  61816. }
  61817. bool CallOutBox::hitTest (int x, int y)
  61818. {
  61819. return outline.contains ((float) x, (float) y);
  61820. }
  61821. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61822. void CallOutBox::inputAttemptWhenModal()
  61823. {
  61824. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61825. if (targetArea.contains (mousePos))
  61826. {
  61827. // if you click on the area that originally popped-up the callout, you expect it
  61828. // to get rid of the box, but deleting the box here allows the click to pass through and
  61829. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61830. postCommandMessage (callOutBoxDismissCommandId);
  61831. }
  61832. else
  61833. {
  61834. exitModalState (0);
  61835. setVisible (false);
  61836. }
  61837. }
  61838. void CallOutBox::handleCommandMessage (int commandId)
  61839. {
  61840. Component::handleCommandMessage (commandId);
  61841. if (commandId == callOutBoxDismissCommandId)
  61842. {
  61843. exitModalState (0);
  61844. setVisible (false);
  61845. }
  61846. }
  61847. bool CallOutBox::keyPressed (const KeyPress& key)
  61848. {
  61849. if (key.isKeyCode (KeyPress::escapeKey))
  61850. {
  61851. inputAttemptWhenModal();
  61852. return true;
  61853. }
  61854. return false;
  61855. }
  61856. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61857. {
  61858. targetArea = newAreaToPointTo;
  61859. availableArea = newAreaToFitIn;
  61860. Rectangle<int> bounds (0, 0,
  61861. content.getWidth() + borderSpace * 2,
  61862. content.getHeight() + borderSpace * 2);
  61863. const int hw = bounds.getWidth() / 2;
  61864. const int hh = bounds.getHeight() / 2;
  61865. const float hwReduced = (float) (hw - borderSpace * 3);
  61866. const float hhReduced = (float) (hh - borderSpace * 3);
  61867. const float arrowIndent = borderSpace - arrowSize;
  61868. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61869. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61870. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61871. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61872. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61873. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61874. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61875. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61876. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61877. float nearest = 1.0e9f;
  61878. for (int i = 0; i < 4; ++i)
  61879. {
  61880. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61881. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61882. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61883. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61884. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61885. distanceFromCentre *= 2.0f;
  61886. if (distanceFromCentre < nearest)
  61887. {
  61888. nearest = distanceFromCentre;
  61889. targetPoint = targets[i];
  61890. bounds.setPosition ((int) (centre.getX() - hw),
  61891. (int) (centre.getY() - hh));
  61892. }
  61893. }
  61894. setBounds (bounds);
  61895. }
  61896. void CallOutBox::refreshPath()
  61897. {
  61898. repaint();
  61899. background = Image::null;
  61900. outline.clear();
  61901. const float gap = 4.5f;
  61902. const float cornerSize = 9.0f;
  61903. const float cornerSize2 = 2.0f * cornerSize;
  61904. const float arrowBaseWidth = arrowSize * 0.7f;
  61905. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61906. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61907. outline.startNewSubPath (left + cornerSize, top);
  61908. if (targetY <= top)
  61909. {
  61910. outline.lineTo (targetX - arrowBaseWidth, top);
  61911. outline.lineTo (targetX, targetY);
  61912. outline.lineTo (targetX + arrowBaseWidth, top);
  61913. }
  61914. outline.lineTo (right - cornerSize, top);
  61915. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61916. if (targetX >= right)
  61917. {
  61918. outline.lineTo (right, targetY - arrowBaseWidth);
  61919. outline.lineTo (targetX, targetY);
  61920. outline.lineTo (right, targetY + arrowBaseWidth);
  61921. }
  61922. outline.lineTo (right, bottom - cornerSize);
  61923. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61924. if (targetY >= bottom)
  61925. {
  61926. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61927. outline.lineTo (targetX, targetY);
  61928. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61929. }
  61930. outline.lineTo (left + cornerSize, bottom);
  61931. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61932. if (targetX <= left)
  61933. {
  61934. outline.lineTo (left, targetY + arrowBaseWidth);
  61935. outline.lineTo (targetX, targetY);
  61936. outline.lineTo (left, targetY - arrowBaseWidth);
  61937. }
  61938. outline.lineTo (left, top + cornerSize);
  61939. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61940. outline.closeSubPath();
  61941. }
  61942. END_JUCE_NAMESPACE
  61943. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61944. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61945. BEGIN_JUCE_NAMESPACE
  61946. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61947. static Array <ComponentPeer*> heavyweightPeers;
  61948. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61949. : component (component_),
  61950. styleFlags (styleFlags_),
  61951. lastPaintTime (0),
  61952. constrainer (0),
  61953. lastDragAndDropCompUnderMouse (0),
  61954. fakeMouseMessageSent (false),
  61955. isWindowMinimised (false)
  61956. {
  61957. heavyweightPeers.add (this);
  61958. }
  61959. ComponentPeer::~ComponentPeer()
  61960. {
  61961. heavyweightPeers.removeValue (this);
  61962. Desktop::getInstance().triggerFocusCallback();
  61963. }
  61964. int ComponentPeer::getNumPeers() throw()
  61965. {
  61966. return heavyweightPeers.size();
  61967. }
  61968. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61969. {
  61970. return heavyweightPeers [index];
  61971. }
  61972. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61973. {
  61974. for (int i = heavyweightPeers.size(); --i >= 0;)
  61975. {
  61976. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61977. if (peer->getComponent() == component)
  61978. return peer;
  61979. }
  61980. return 0;
  61981. }
  61982. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61983. {
  61984. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61985. }
  61986. void ComponentPeer::updateCurrentModifiers() throw()
  61987. {
  61988. ModifierKeys::updateCurrentModifiers();
  61989. }
  61990. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61991. {
  61992. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61993. jassert (mouse != 0); // not enough sources!
  61994. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61995. }
  61996. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61997. {
  61998. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61999. jassert (mouse != 0); // not enough sources!
  62000. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62001. }
  62002. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62003. {
  62004. Graphics g (&contextToPaintTo);
  62005. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62006. g.saveState();
  62007. #endif
  62008. JUCE_TRY
  62009. {
  62010. component->paintEntireComponent (g, true);
  62011. }
  62012. JUCE_CATCH_EXCEPTION
  62013. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62014. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62015. // clearly when things are being repainted.
  62016. g.restoreState();
  62017. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62018. (uint8) Random::getSystemRandom().nextInt (255),
  62019. (uint8) Random::getSystemRandom().nextInt (255),
  62020. (uint8) 0x50));
  62021. #endif
  62022. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62023. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62024. mess up a lot of the calculations that the library needs to do.
  62025. */
  62026. jassert (roundToInt (10.1f) == 10);
  62027. }
  62028. bool ComponentPeer::handleKeyPress (const int keyCode,
  62029. const juce_wchar textCharacter)
  62030. {
  62031. updateCurrentModifiers();
  62032. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62033. ? Component::getCurrentlyFocusedComponent()
  62034. : component;
  62035. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62036. {
  62037. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62038. if (currentModalComp != 0)
  62039. target = currentModalComp;
  62040. }
  62041. const KeyPress keyInfo (keyCode,
  62042. ModifierKeys::getCurrentModifiers().getRawFlags()
  62043. & ModifierKeys::allKeyboardModifiers,
  62044. textCharacter);
  62045. bool keyWasUsed = false;
  62046. while (target != 0)
  62047. {
  62048. const WeakReference<Component> deletionChecker (target);
  62049. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  62050. if (keyListeners != 0)
  62051. {
  62052. for (int i = keyListeners->size(); --i >= 0;)
  62053. {
  62054. keyWasUsed = keyListeners->getUnchecked(i)->keyPressed (keyInfo, target);
  62055. if (keyWasUsed || deletionChecker == 0)
  62056. return keyWasUsed;
  62057. i = jmin (i, keyListeners->size());
  62058. }
  62059. }
  62060. keyWasUsed = target->keyPressed (keyInfo);
  62061. if (keyWasUsed || deletionChecker == 0)
  62062. break;
  62063. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62064. {
  62065. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62066. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62067. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62068. break;
  62069. }
  62070. target = target->getParentComponent();
  62071. }
  62072. return keyWasUsed;
  62073. }
  62074. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62075. {
  62076. updateCurrentModifiers();
  62077. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62078. ? Component::getCurrentlyFocusedComponent()
  62079. : component;
  62080. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62081. {
  62082. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62083. if (currentModalComp != 0)
  62084. target = currentModalComp;
  62085. }
  62086. bool keyWasUsed = false;
  62087. while (target != 0)
  62088. {
  62089. const WeakReference<Component> deletionChecker (target);
  62090. keyWasUsed = target->keyStateChanged (isKeyDown);
  62091. if (keyWasUsed || deletionChecker == 0)
  62092. break;
  62093. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  62094. if (keyListeners != 0)
  62095. {
  62096. for (int i = keyListeners->size(); --i >= 0;)
  62097. {
  62098. keyWasUsed = keyListeners->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62099. if (keyWasUsed || deletionChecker == 0)
  62100. return keyWasUsed;
  62101. i = jmin (i, keyListeners->size());
  62102. }
  62103. }
  62104. target = target->getParentComponent();
  62105. }
  62106. return keyWasUsed;
  62107. }
  62108. void ComponentPeer::handleModifierKeysChange()
  62109. {
  62110. updateCurrentModifiers();
  62111. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62112. if (target == 0)
  62113. target = Component::getCurrentlyFocusedComponent();
  62114. if (target == 0)
  62115. target = component;
  62116. if (target != 0)
  62117. target->internalModifierKeysChanged();
  62118. }
  62119. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62120. {
  62121. Component* const c = Component::getCurrentlyFocusedComponent();
  62122. if (component->isParentOf (c))
  62123. {
  62124. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62125. if (ti != 0 && ti->isTextInputActive())
  62126. return ti;
  62127. }
  62128. return 0;
  62129. }
  62130. void ComponentPeer::handleBroughtToFront()
  62131. {
  62132. updateCurrentModifiers();
  62133. if (component != 0)
  62134. component->internalBroughtToFront();
  62135. }
  62136. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62137. {
  62138. constrainer = newConstrainer;
  62139. }
  62140. void ComponentPeer::handleMovedOrResized()
  62141. {
  62142. updateCurrentModifiers();
  62143. const bool nowMinimised = isMinimised();
  62144. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62145. {
  62146. const WeakReference<Component> deletionChecker (component);
  62147. const Rectangle<int> newBounds (getBounds());
  62148. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62149. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62150. if (wasMoved || wasResized)
  62151. {
  62152. component->bounds = newBounds;
  62153. if (wasResized)
  62154. component->repaint();
  62155. component->sendMovedResizedMessages (wasMoved, wasResized);
  62156. if (deletionChecker == 0)
  62157. return;
  62158. }
  62159. }
  62160. if (isWindowMinimised != nowMinimised)
  62161. {
  62162. isWindowMinimised = nowMinimised;
  62163. component->minimisationStateChanged (nowMinimised);
  62164. component->sendVisibilityChangeMessage();
  62165. }
  62166. if (! isFullScreen())
  62167. lastNonFullscreenBounds = component->getBounds();
  62168. }
  62169. void ComponentPeer::handleFocusGain()
  62170. {
  62171. updateCurrentModifiers();
  62172. if (component->isParentOf (lastFocusedComponent))
  62173. {
  62174. Component::currentlyFocusedComponent = lastFocusedComponent;
  62175. Desktop::getInstance().triggerFocusCallback();
  62176. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62177. }
  62178. else
  62179. {
  62180. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62181. component->grabKeyboardFocus();
  62182. else
  62183. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62184. }
  62185. }
  62186. void ComponentPeer::handleFocusLoss()
  62187. {
  62188. updateCurrentModifiers();
  62189. if (component->hasKeyboardFocus (true))
  62190. {
  62191. lastFocusedComponent = Component::currentlyFocusedComponent;
  62192. if (lastFocusedComponent != 0)
  62193. {
  62194. Component::currentlyFocusedComponent = 0;
  62195. Desktop::getInstance().triggerFocusCallback();
  62196. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62197. }
  62198. }
  62199. }
  62200. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62201. {
  62202. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62203. ? static_cast <Component*> (lastFocusedComponent)
  62204. : component;
  62205. }
  62206. void ComponentPeer::handleScreenSizeChange()
  62207. {
  62208. updateCurrentModifiers();
  62209. component->parentSizeChanged();
  62210. handleMovedOrResized();
  62211. }
  62212. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62213. {
  62214. lastNonFullscreenBounds = newBounds;
  62215. }
  62216. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62217. {
  62218. return lastNonFullscreenBounds;
  62219. }
  62220. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62221. {
  62222. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62223. }
  62224. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62225. {
  62226. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62227. }
  62228. namespace ComponentPeerHelpers
  62229. {
  62230. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62231. const StringArray& files,
  62232. FileDragAndDropTarget* const lastOne)
  62233. {
  62234. while (c != 0)
  62235. {
  62236. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62237. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62238. return t;
  62239. c = c->getParentComponent();
  62240. }
  62241. return 0;
  62242. }
  62243. }
  62244. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62245. {
  62246. updateCurrentModifiers();
  62247. FileDragAndDropTarget* lastTarget
  62248. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62249. FileDragAndDropTarget* newTarget = 0;
  62250. Component* const compUnderMouse = component->getComponentAt (position);
  62251. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62252. {
  62253. lastDragAndDropCompUnderMouse = compUnderMouse;
  62254. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62255. if (newTarget != lastTarget)
  62256. {
  62257. if (lastTarget != 0)
  62258. lastTarget->fileDragExit (files);
  62259. dragAndDropTargetComponent = 0;
  62260. if (newTarget != 0)
  62261. {
  62262. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62263. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62264. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62265. }
  62266. }
  62267. }
  62268. else
  62269. {
  62270. newTarget = lastTarget;
  62271. }
  62272. if (newTarget != 0)
  62273. {
  62274. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62275. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62276. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62277. }
  62278. }
  62279. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62280. {
  62281. handleFileDragMove (files, Point<int> (-1, -1));
  62282. jassert (dragAndDropTargetComponent == 0);
  62283. lastDragAndDropCompUnderMouse = 0;
  62284. }
  62285. // We'll use an async message to deliver the drop, because if the target decides
  62286. // to run a modal loop, it can gum-up the operating system..
  62287. class AsyncFileDropMessage : public CallbackMessage
  62288. {
  62289. public:
  62290. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62291. const Point<int>& position_, const StringArray& files_)
  62292. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62293. {
  62294. }
  62295. void messageCallback()
  62296. {
  62297. if (target != 0)
  62298. dropTarget->filesDropped (files, position.getX(), position.getY());
  62299. }
  62300. private:
  62301. WeakReference<Component> target;
  62302. FileDragAndDropTarget* const dropTarget;
  62303. const Point<int> position;
  62304. const StringArray files;
  62305. JUCE_DECLARE_NON_COPYABLE (AsyncFileDropMessage);
  62306. };
  62307. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62308. {
  62309. handleFileDragMove (files, position);
  62310. if (dragAndDropTargetComponent != 0)
  62311. {
  62312. FileDragAndDropTarget* const target
  62313. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62314. dragAndDropTargetComponent = 0;
  62315. lastDragAndDropCompUnderMouse = 0;
  62316. if (target != 0)
  62317. {
  62318. Component* const targetComp = dynamic_cast <Component*> (target);
  62319. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62320. {
  62321. targetComp->internalModalInputAttempt();
  62322. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62323. return;
  62324. }
  62325. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62326. }
  62327. }
  62328. }
  62329. void ComponentPeer::handleUserClosingWindow()
  62330. {
  62331. updateCurrentModifiers();
  62332. component->userTriedToCloseWindow();
  62333. }
  62334. void ComponentPeer::clearMaskedRegion()
  62335. {
  62336. maskedRegion.clear();
  62337. }
  62338. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62339. {
  62340. maskedRegion.add (x, y, w, h);
  62341. }
  62342. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62343. {
  62344. StringArray s;
  62345. s.add ("Software Renderer");
  62346. return s;
  62347. }
  62348. int ComponentPeer::getCurrentRenderingEngine() throw()
  62349. {
  62350. return 0;
  62351. }
  62352. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62353. {
  62354. }
  62355. END_JUCE_NAMESPACE
  62356. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62357. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62358. BEGIN_JUCE_NAMESPACE
  62359. DialogWindow::DialogWindow (const String& name,
  62360. const Colour& backgroundColour_,
  62361. const bool escapeKeyTriggersCloseButton_,
  62362. const bool addToDesktop_)
  62363. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62364. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62365. {
  62366. }
  62367. DialogWindow::~DialogWindow()
  62368. {
  62369. }
  62370. void DialogWindow::resized()
  62371. {
  62372. DocumentWindow::resized();
  62373. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62374. if (escapeKeyTriggersCloseButton
  62375. && getCloseButton() != 0
  62376. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62377. {
  62378. getCloseButton()->addShortcut (esc);
  62379. }
  62380. }
  62381. // (Sadly, this can't be made a local class inside the showModalDialog function, because the
  62382. // VC compiler complains about the undefined copy constructor)
  62383. class TempDialogWindow : public DialogWindow
  62384. {
  62385. public:
  62386. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62387. : DialogWindow (title, colour, escapeCloses, true)
  62388. {
  62389. if (! JUCEApplication::isStandaloneApp())
  62390. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62391. }
  62392. void closeButtonPressed()
  62393. {
  62394. setVisible (false);
  62395. }
  62396. private:
  62397. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62398. };
  62399. int DialogWindow::showModalDialog (const String& dialogTitle,
  62400. Component* contentComponent,
  62401. Component* componentToCentreAround,
  62402. const Colour& colour,
  62403. const bool escapeKeyTriggersCloseButton,
  62404. const bool shouldBeResizable,
  62405. const bool useBottomRightCornerResizer)
  62406. {
  62407. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62408. dw.setContentComponent (contentComponent, true, true);
  62409. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62410. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62411. const int result = dw.runModalLoop();
  62412. dw.setContentComponent (0, false);
  62413. return result;
  62414. }
  62415. END_JUCE_NAMESPACE
  62416. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62417. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62418. BEGIN_JUCE_NAMESPACE
  62419. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62420. {
  62421. public:
  62422. ButtonListenerProxy (DocumentWindow& owner_)
  62423. : owner (owner_)
  62424. {
  62425. }
  62426. void buttonClicked (Button* button)
  62427. {
  62428. if (button == owner.getMinimiseButton())
  62429. owner.minimiseButtonPressed();
  62430. else if (button == owner.getMaximiseButton())
  62431. owner.maximiseButtonPressed();
  62432. else if (button == owner.getCloseButton())
  62433. owner.closeButtonPressed();
  62434. }
  62435. private:
  62436. DocumentWindow& owner;
  62437. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62438. };
  62439. DocumentWindow::DocumentWindow (const String& title,
  62440. const Colour& backgroundColour,
  62441. const int requiredButtons_,
  62442. const bool addToDesktop_)
  62443. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62444. titleBarHeight (26),
  62445. menuBarHeight (24),
  62446. requiredButtons (requiredButtons_),
  62447. #if JUCE_MAC
  62448. positionTitleBarButtonsOnLeft (true),
  62449. #else
  62450. positionTitleBarButtonsOnLeft (false),
  62451. #endif
  62452. drawTitleTextCentred (true),
  62453. menuBarModel (0)
  62454. {
  62455. setResizeLimits (128, 128, 32768, 32768);
  62456. lookAndFeelChanged();
  62457. }
  62458. DocumentWindow::~DocumentWindow()
  62459. {
  62460. // Don't delete or remove the resizer components yourself! They're managed by the
  62461. // DocumentWindow, and you should leave them alone! You may have deleted them
  62462. // accidentally by careless use of deleteAllChildren()..?
  62463. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62464. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62465. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62466. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62467. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62468. titleBarButtons[i] = 0;
  62469. menuBar = 0;
  62470. }
  62471. void DocumentWindow::repaintTitleBar()
  62472. {
  62473. repaint (getTitleBarArea());
  62474. }
  62475. void DocumentWindow::setName (const String& newName)
  62476. {
  62477. if (newName != getName())
  62478. {
  62479. Component::setName (newName);
  62480. repaintTitleBar();
  62481. }
  62482. }
  62483. void DocumentWindow::setIcon (const Image& imageToUse)
  62484. {
  62485. titleBarIcon = imageToUse;
  62486. repaintTitleBar();
  62487. }
  62488. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62489. {
  62490. titleBarHeight = newHeight;
  62491. resized();
  62492. repaintTitleBar();
  62493. }
  62494. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62495. const bool positionTitleBarButtonsOnLeft_)
  62496. {
  62497. requiredButtons = requiredButtons_;
  62498. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62499. lookAndFeelChanged();
  62500. }
  62501. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62502. {
  62503. drawTitleTextCentred = textShouldBeCentred;
  62504. repaintTitleBar();
  62505. }
  62506. void DocumentWindow::setMenuBar (MenuBarModel* newMenuBarModel, const int newMenuBarHeight)
  62507. {
  62508. if (menuBarModel != newMenuBarModel)
  62509. {
  62510. menuBar = 0;
  62511. menuBarModel = newMenuBarModel;
  62512. menuBarHeight = newMenuBarHeight > 0 ? newMenuBarHeight
  62513. : getLookAndFeel().getDefaultMenuBarHeight();
  62514. if (menuBarModel != 0)
  62515. setMenuBarComponent (new MenuBarComponent (menuBarModel));
  62516. resized();
  62517. }
  62518. }
  62519. Component* DocumentWindow::getMenuBarComponent() const throw()
  62520. {
  62521. return menuBar;
  62522. }
  62523. void DocumentWindow::setMenuBarComponent (Component* newMenuBarComponent)
  62524. {
  62525. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62526. Component::addAndMakeVisible (menuBar = newMenuBarComponent);
  62527. if (menuBar != 0)
  62528. menuBar->setEnabled (isActiveWindow());
  62529. resized();
  62530. }
  62531. void DocumentWindow::closeButtonPressed()
  62532. {
  62533. /* If you've got a close button, you have to override this method to get
  62534. rid of your window!
  62535. If the window is just a pop-up, you should override this method and make
  62536. it delete the window in whatever way is appropriate for your app. E.g. you
  62537. might just want to call "delete this".
  62538. If your app is centred around this window such that the whole app should quit when
  62539. the window is closed, then you will probably want to use this method as an opportunity
  62540. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62541. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62542. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62543. or closing it via the taskbar icon on Windows).
  62544. */
  62545. jassertfalse;
  62546. }
  62547. void DocumentWindow::minimiseButtonPressed()
  62548. {
  62549. setMinimised (true);
  62550. }
  62551. void DocumentWindow::maximiseButtonPressed()
  62552. {
  62553. setFullScreen (! isFullScreen());
  62554. }
  62555. void DocumentWindow::paint (Graphics& g)
  62556. {
  62557. ResizableWindow::paint (g);
  62558. if (resizableBorder == 0)
  62559. {
  62560. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62561. const BorderSize<int> border (getBorderThickness());
  62562. g.fillRect (0, 0, getWidth(), border.getTop());
  62563. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62564. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62565. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62566. }
  62567. const Rectangle<int> titleBarArea (getTitleBarArea());
  62568. g.reduceClipRegion (titleBarArea);
  62569. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62570. int titleSpaceX1 = 6;
  62571. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62572. for (int i = 0; i < 3; ++i)
  62573. {
  62574. if (titleBarButtons[i] != 0)
  62575. {
  62576. if (positionTitleBarButtonsOnLeft)
  62577. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62578. else
  62579. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62580. }
  62581. }
  62582. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62583. titleBarArea.getWidth(),
  62584. titleBarArea.getHeight(),
  62585. titleSpaceX1,
  62586. jmax (1, titleSpaceX2 - titleSpaceX1),
  62587. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62588. ! drawTitleTextCentred);
  62589. }
  62590. void DocumentWindow::resized()
  62591. {
  62592. ResizableWindow::resized();
  62593. if (titleBarButtons[1] != 0)
  62594. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62595. const Rectangle<int> titleBarArea (getTitleBarArea());
  62596. getLookAndFeel()
  62597. .positionDocumentWindowButtons (*this,
  62598. titleBarArea.getX(), titleBarArea.getY(),
  62599. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62600. titleBarButtons[0],
  62601. titleBarButtons[1],
  62602. titleBarButtons[2],
  62603. positionTitleBarButtonsOnLeft);
  62604. if (menuBar != 0)
  62605. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62606. titleBarArea.getWidth(), menuBarHeight);
  62607. }
  62608. const BorderSize<int> DocumentWindow::getBorderThickness()
  62609. {
  62610. return BorderSize<int> ((isFullScreen() || isUsingNativeTitleBar())
  62611. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62612. }
  62613. const BorderSize<int> DocumentWindow::getContentComponentBorder()
  62614. {
  62615. BorderSize<int> border (getBorderThickness());
  62616. border.setTop (border.getTop()
  62617. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62618. + (menuBar != 0 ? menuBarHeight : 0));
  62619. return border;
  62620. }
  62621. int DocumentWindow::getTitleBarHeight() const
  62622. {
  62623. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62624. }
  62625. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62626. {
  62627. const BorderSize<int> border (getBorderThickness());
  62628. return Rectangle<int> (border.getLeft(), border.getTop(),
  62629. getWidth() - border.getLeftAndRight(),
  62630. getTitleBarHeight());
  62631. }
  62632. Button* DocumentWindow::getCloseButton() const throw() { return titleBarButtons[2]; }
  62633. Button* DocumentWindow::getMinimiseButton() const throw() { return titleBarButtons[0]; }
  62634. Button* DocumentWindow::getMaximiseButton() const throw() { return titleBarButtons[1]; }
  62635. int DocumentWindow::getDesktopWindowStyleFlags() const
  62636. {
  62637. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62638. if ((requiredButtons & minimiseButton) != 0)
  62639. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62640. if ((requiredButtons & maximiseButton) != 0)
  62641. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62642. if ((requiredButtons & closeButton) != 0)
  62643. styleFlags |= ComponentPeer::windowHasCloseButton;
  62644. return styleFlags;
  62645. }
  62646. void DocumentWindow::lookAndFeelChanged()
  62647. {
  62648. int i;
  62649. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62650. titleBarButtons[i] = 0;
  62651. if (! isUsingNativeTitleBar())
  62652. {
  62653. LookAndFeel& lf = getLookAndFeel();
  62654. if ((requiredButtons & minimiseButton) != 0)
  62655. titleBarButtons[0] = lf.createDocumentWindowButton (minimiseButton);
  62656. if ((requiredButtons & maximiseButton) != 0)
  62657. titleBarButtons[1] = lf.createDocumentWindowButton (maximiseButton);
  62658. if ((requiredButtons & closeButton) != 0)
  62659. titleBarButtons[2] = lf.createDocumentWindowButton (closeButton);
  62660. for (i = 0; i < 3; ++i)
  62661. {
  62662. if (titleBarButtons[i] != 0)
  62663. {
  62664. if (buttonListener == 0)
  62665. buttonListener = new ButtonListenerProxy (*this);
  62666. titleBarButtons[i]->addListener (buttonListener);
  62667. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62668. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62669. Component::addAndMakeVisible (titleBarButtons[i]);
  62670. }
  62671. }
  62672. if (getCloseButton() != 0)
  62673. {
  62674. #if JUCE_MAC
  62675. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62676. #else
  62677. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62678. #endif
  62679. }
  62680. }
  62681. activeWindowStatusChanged();
  62682. ResizableWindow::lookAndFeelChanged();
  62683. }
  62684. void DocumentWindow::parentHierarchyChanged()
  62685. {
  62686. lookAndFeelChanged();
  62687. }
  62688. void DocumentWindow::activeWindowStatusChanged()
  62689. {
  62690. ResizableWindow::activeWindowStatusChanged();
  62691. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62692. if (titleBarButtons[i] != 0)
  62693. titleBarButtons[i]->setEnabled (isActiveWindow());
  62694. if (menuBar != 0)
  62695. menuBar->setEnabled (isActiveWindow());
  62696. }
  62697. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62698. {
  62699. if (getTitleBarArea().contains (e.x, e.y)
  62700. && getMaximiseButton() != 0)
  62701. {
  62702. getMaximiseButton()->triggerClick();
  62703. }
  62704. }
  62705. void DocumentWindow::userTriedToCloseWindow()
  62706. {
  62707. closeButtonPressed();
  62708. }
  62709. END_JUCE_NAMESPACE
  62710. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62711. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62712. BEGIN_JUCE_NAMESPACE
  62713. ResizableWindow::ResizableWindow (const String& name,
  62714. const bool addToDesktop_)
  62715. : TopLevelWindow (name, addToDesktop_),
  62716. resizeToFitContent (false),
  62717. fullscreen (false),
  62718. lastNonFullScreenPos (50, 50, 256, 256),
  62719. constrainer (0)
  62720. #if JUCE_DEBUG
  62721. , hasBeenResized (false)
  62722. #endif
  62723. {
  62724. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62725. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62726. if (addToDesktop_)
  62727. Component::addToDesktop (getDesktopWindowStyleFlags());
  62728. }
  62729. ResizableWindow::ResizableWindow (const String& name,
  62730. const Colour& backgroundColour_,
  62731. const bool addToDesktop_)
  62732. : TopLevelWindow (name, addToDesktop_),
  62733. resizeToFitContent (false),
  62734. fullscreen (false),
  62735. lastNonFullScreenPos (50, 50, 256, 256),
  62736. constrainer (0)
  62737. #if JUCE_DEBUG
  62738. , hasBeenResized (false)
  62739. #endif
  62740. {
  62741. setBackgroundColour (backgroundColour_);
  62742. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62743. if (addToDesktop_)
  62744. Component::addToDesktop (getDesktopWindowStyleFlags());
  62745. }
  62746. ResizableWindow::~ResizableWindow()
  62747. {
  62748. // Don't delete or remove the resizer components yourself! They're managed by the
  62749. // ResizableWindow, and you should leave them alone! You may have deleted them
  62750. // accidentally by careless use of deleteAllChildren()..?
  62751. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  62752. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  62753. resizableCorner = 0;
  62754. resizableBorder = 0;
  62755. contentComponent.deleteAndZero();
  62756. // have you been adding your own components directly to this window..? tut tut tut.
  62757. // Read the instructions for using a ResizableWindow!
  62758. jassert (getNumChildComponents() == 0);
  62759. }
  62760. int ResizableWindow::getDesktopWindowStyleFlags() const
  62761. {
  62762. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62763. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62764. styleFlags |= ComponentPeer::windowIsResizable;
  62765. return styleFlags;
  62766. }
  62767. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62768. const bool deleteOldOne,
  62769. const bool resizeToFit)
  62770. {
  62771. resizeToFitContent = resizeToFit;
  62772. if (newContentComponent != static_cast <Component*> (contentComponent))
  62773. {
  62774. if (deleteOldOne)
  62775. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  62776. // external deletion of the content comp)
  62777. else
  62778. removeChildComponent (contentComponent);
  62779. contentComponent = newContentComponent;
  62780. Component::addAndMakeVisible (contentComponent);
  62781. }
  62782. if (resizeToFit)
  62783. childBoundsChanged (contentComponent);
  62784. resized(); // must always be called to position the new content comp
  62785. }
  62786. void ResizableWindow::setContentComponentSize (int width, int height)
  62787. {
  62788. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62789. const BorderSize<int> border (getContentComponentBorder());
  62790. setSize (width + border.getLeftAndRight(),
  62791. height + border.getTopAndBottom());
  62792. }
  62793. const BorderSize<int> ResizableWindow::getBorderThickness()
  62794. {
  62795. return BorderSize<int> (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62796. }
  62797. const BorderSize<int> ResizableWindow::getContentComponentBorder()
  62798. {
  62799. return getBorderThickness();
  62800. }
  62801. void ResizableWindow::moved()
  62802. {
  62803. updateLastPos();
  62804. }
  62805. void ResizableWindow::visibilityChanged()
  62806. {
  62807. TopLevelWindow::visibilityChanged();
  62808. updateLastPos();
  62809. }
  62810. void ResizableWindow::resized()
  62811. {
  62812. if (resizableBorder != 0)
  62813. {
  62814. #if JUCE_WINDOWS || JUCE_LINUX
  62815. // hide the resizable border if the OS already provides one..
  62816. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62817. #else
  62818. resizableBorder->setVisible (! isFullScreen());
  62819. #endif
  62820. resizableBorder->setBorderThickness (getBorderThickness());
  62821. resizableBorder->setSize (getWidth(), getHeight());
  62822. resizableBorder->toBack();
  62823. }
  62824. if (resizableCorner != 0)
  62825. {
  62826. #if JUCE_MAC
  62827. // hide the resizable border if the OS already provides one..
  62828. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62829. #else
  62830. resizableCorner->setVisible (! isFullScreen());
  62831. #endif
  62832. const int resizerSize = 18;
  62833. resizableCorner->setBounds (getWidth() - resizerSize,
  62834. getHeight() - resizerSize,
  62835. resizerSize, resizerSize);
  62836. }
  62837. if (contentComponent != 0)
  62838. contentComponent->setBoundsInset (getContentComponentBorder());
  62839. updateLastPos();
  62840. #if JUCE_DEBUG
  62841. hasBeenResized = true;
  62842. #endif
  62843. }
  62844. void ResizableWindow::childBoundsChanged (Component* child)
  62845. {
  62846. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62847. {
  62848. // not going to look very good if this component has a zero size..
  62849. jassert (child->getWidth() > 0);
  62850. jassert (child->getHeight() > 0);
  62851. const BorderSize<int> borders (getContentComponentBorder());
  62852. setSize (child->getWidth() + borders.getLeftAndRight(),
  62853. child->getHeight() + borders.getTopAndBottom());
  62854. }
  62855. }
  62856. void ResizableWindow::activeWindowStatusChanged()
  62857. {
  62858. const BorderSize<int> border (getContentComponentBorder());
  62859. Rectangle<int> area (getLocalBounds());
  62860. repaint (area.removeFromTop (border.getTop()));
  62861. repaint (area.removeFromLeft (border.getLeft()));
  62862. repaint (area.removeFromRight (border.getRight()));
  62863. repaint (area.removeFromBottom (border.getBottom()));
  62864. }
  62865. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62866. const bool useBottomRightCornerResizer)
  62867. {
  62868. if (shouldBeResizable)
  62869. {
  62870. if (useBottomRightCornerResizer)
  62871. {
  62872. resizableBorder = 0;
  62873. if (resizableCorner == 0)
  62874. {
  62875. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62876. resizableCorner->setAlwaysOnTop (true);
  62877. }
  62878. }
  62879. else
  62880. {
  62881. resizableCorner = 0;
  62882. if (resizableBorder == 0)
  62883. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62884. }
  62885. }
  62886. else
  62887. {
  62888. resizableCorner = 0;
  62889. resizableBorder = 0;
  62890. }
  62891. if (isUsingNativeTitleBar())
  62892. recreateDesktopWindow();
  62893. childBoundsChanged (contentComponent);
  62894. resized();
  62895. }
  62896. bool ResizableWindow::isResizable() const throw()
  62897. {
  62898. return resizableCorner != 0
  62899. || resizableBorder != 0;
  62900. }
  62901. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62902. const int newMinimumHeight,
  62903. const int newMaximumWidth,
  62904. const int newMaximumHeight) throw()
  62905. {
  62906. // if you've set up a custom constrainer then these settings won't have any effect..
  62907. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62908. if (constrainer == 0)
  62909. setConstrainer (&defaultConstrainer);
  62910. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62911. newMaximumWidth, newMaximumHeight);
  62912. setBoundsConstrained (getBounds());
  62913. }
  62914. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62915. {
  62916. if (constrainer != newConstrainer)
  62917. {
  62918. constrainer = newConstrainer;
  62919. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62920. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62921. resizableCorner = 0;
  62922. resizableBorder = 0;
  62923. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62924. ComponentPeer* const peer = getPeer();
  62925. if (peer != 0)
  62926. peer->setConstrainer (newConstrainer);
  62927. }
  62928. }
  62929. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62930. {
  62931. if (constrainer != 0)
  62932. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62933. else
  62934. setBounds (bounds);
  62935. }
  62936. void ResizableWindow::paint (Graphics& g)
  62937. {
  62938. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62939. getBorderThickness(), *this);
  62940. if (! isFullScreen())
  62941. {
  62942. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62943. getBorderThickness(), *this);
  62944. }
  62945. #if JUCE_DEBUG
  62946. /* If this fails, then you've probably written a subclass with a resized()
  62947. callback but forgotten to make it call its parent class's resized() method.
  62948. It's important when you override methods like resized(), moved(),
  62949. etc., that you make sure the base class methods also get called.
  62950. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62951. because your content should all be inside the content component - and it's the
  62952. content component's resized() method that you should be using to do your
  62953. layout.
  62954. */
  62955. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62956. #endif
  62957. }
  62958. void ResizableWindow::lookAndFeelChanged()
  62959. {
  62960. resized();
  62961. if (isOnDesktop())
  62962. {
  62963. Component::addToDesktop (getDesktopWindowStyleFlags());
  62964. ComponentPeer* const peer = getPeer();
  62965. if (peer != 0)
  62966. peer->setConstrainer (constrainer);
  62967. }
  62968. }
  62969. const Colour ResizableWindow::getBackgroundColour() const throw()
  62970. {
  62971. return findColour (backgroundColourId, false);
  62972. }
  62973. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62974. {
  62975. Colour backgroundColour (newColour);
  62976. if (! Desktop::canUseSemiTransparentWindows())
  62977. backgroundColour = newColour.withAlpha (1.0f);
  62978. setColour (backgroundColourId, backgroundColour);
  62979. setOpaque (backgroundColour.isOpaque());
  62980. repaint();
  62981. }
  62982. bool ResizableWindow::isFullScreen() const
  62983. {
  62984. if (isOnDesktop())
  62985. {
  62986. ComponentPeer* const peer = getPeer();
  62987. return peer != 0 && peer->isFullScreen();
  62988. }
  62989. return fullscreen;
  62990. }
  62991. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62992. {
  62993. if (shouldBeFullScreen != isFullScreen())
  62994. {
  62995. updateLastPos();
  62996. fullscreen = shouldBeFullScreen;
  62997. if (isOnDesktop())
  62998. {
  62999. ComponentPeer* const peer = getPeer();
  63000. if (peer != 0)
  63001. {
  63002. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63003. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63004. peer->setFullScreen (shouldBeFullScreen);
  63005. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63006. setBounds (lastPos);
  63007. }
  63008. else
  63009. {
  63010. jassertfalse;
  63011. }
  63012. }
  63013. else
  63014. {
  63015. if (shouldBeFullScreen)
  63016. setBounds (0, 0, getParentWidth(), getParentHeight());
  63017. else
  63018. setBounds (lastNonFullScreenPos);
  63019. }
  63020. resized();
  63021. }
  63022. }
  63023. bool ResizableWindow::isMinimised() const
  63024. {
  63025. ComponentPeer* const peer = getPeer();
  63026. return (peer != 0) && peer->isMinimised();
  63027. }
  63028. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63029. {
  63030. if (shouldMinimise != isMinimised())
  63031. {
  63032. ComponentPeer* const peer = getPeer();
  63033. if (peer != 0)
  63034. {
  63035. updateLastPos();
  63036. peer->setMinimised (shouldMinimise);
  63037. }
  63038. else
  63039. {
  63040. jassertfalse;
  63041. }
  63042. }
  63043. }
  63044. void ResizableWindow::updateLastPos()
  63045. {
  63046. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63047. {
  63048. lastNonFullScreenPos = getBounds();
  63049. }
  63050. }
  63051. void ResizableWindow::parentSizeChanged()
  63052. {
  63053. if (isFullScreen() && getParentComponent() != 0)
  63054. {
  63055. setBounds (0, 0, getParentWidth(), getParentHeight());
  63056. }
  63057. }
  63058. const String ResizableWindow::getWindowStateAsString()
  63059. {
  63060. updateLastPos();
  63061. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63062. }
  63063. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63064. {
  63065. StringArray tokens;
  63066. tokens.addTokens (s, false);
  63067. tokens.removeEmptyStrings();
  63068. tokens.trim();
  63069. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63070. const int firstCoord = fs ? 1 : 0;
  63071. if (tokens.size() != firstCoord + 4)
  63072. return false;
  63073. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63074. tokens[firstCoord + 1].getIntValue(),
  63075. tokens[firstCoord + 2].getIntValue(),
  63076. tokens[firstCoord + 3].getIntValue());
  63077. if (newPos.isEmpty())
  63078. return false;
  63079. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63080. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63081. if (peer != 0)
  63082. peer->getFrameSize().addTo (newPos);
  63083. if (! screen.contains (newPos))
  63084. {
  63085. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63086. jmin (newPos.getHeight(), screen.getHeight()));
  63087. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63088. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63089. }
  63090. if (peer != 0)
  63091. {
  63092. peer->getFrameSize().subtractFrom (newPos);
  63093. peer->setNonFullScreenBounds (newPos);
  63094. }
  63095. lastNonFullScreenPos = newPos;
  63096. setFullScreen (fs);
  63097. if (! fs)
  63098. setBoundsConstrained (newPos);
  63099. return true;
  63100. }
  63101. void ResizableWindow::mouseDown (const MouseEvent& e)
  63102. {
  63103. if (! isFullScreen())
  63104. dragger.startDraggingComponent (this, e);
  63105. }
  63106. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63107. {
  63108. if (! isFullScreen())
  63109. dragger.dragComponent (this, e, constrainer);
  63110. }
  63111. #if JUCE_DEBUG
  63112. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63113. {
  63114. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63115. manages its child components automatically, and if you add your own it'll cause
  63116. trouble. Instead, use setContentComponent() to give it a component which
  63117. will be automatically resized and kept in the right place - then you can add
  63118. subcomponents to the content comp. See the notes for the ResizableWindow class
  63119. for more info.
  63120. If you really know what you're doing and want to avoid this assertion, just call
  63121. Component::addChildComponent directly.
  63122. */
  63123. jassertfalse;
  63124. Component::addChildComponent (child, zOrder);
  63125. }
  63126. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63127. {
  63128. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63129. manages its child components automatically, and if you add your own it'll cause
  63130. trouble. Instead, use setContentComponent() to give it a component which
  63131. will be automatically resized and kept in the right place - then you can add
  63132. subcomponents to the content comp. See the notes for the ResizableWindow class
  63133. for more info.
  63134. If you really know what you're doing and want to avoid this assertion, just call
  63135. Component::addAndMakeVisible directly.
  63136. */
  63137. jassertfalse;
  63138. Component::addAndMakeVisible (child, zOrder);
  63139. }
  63140. #endif
  63141. END_JUCE_NAMESPACE
  63142. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63143. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63144. BEGIN_JUCE_NAMESPACE
  63145. SplashScreen::SplashScreen()
  63146. {
  63147. setOpaque (true);
  63148. }
  63149. SplashScreen::~SplashScreen()
  63150. {
  63151. }
  63152. void SplashScreen::show (const String& title,
  63153. const Image& backgroundImage_,
  63154. const int minimumTimeToDisplayFor,
  63155. const bool useDropShadow,
  63156. const bool removeOnMouseClick)
  63157. {
  63158. backgroundImage = backgroundImage_;
  63159. jassert (backgroundImage_.isValid());
  63160. if (backgroundImage_.isValid())
  63161. {
  63162. setOpaque (! backgroundImage_.hasAlphaChannel());
  63163. show (title,
  63164. backgroundImage_.getWidth(),
  63165. backgroundImage_.getHeight(),
  63166. minimumTimeToDisplayFor,
  63167. useDropShadow,
  63168. removeOnMouseClick);
  63169. }
  63170. }
  63171. void SplashScreen::show (const String& title,
  63172. const int width,
  63173. const int height,
  63174. const int minimumTimeToDisplayFor,
  63175. const bool useDropShadow,
  63176. const bool removeOnMouseClick)
  63177. {
  63178. setName (title);
  63179. setAlwaysOnTop (true);
  63180. setVisible (true);
  63181. centreWithSize (width, height);
  63182. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63183. toFront (false);
  63184. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63185. repaint();
  63186. originalClickCounter = removeOnMouseClick
  63187. ? Desktop::getMouseButtonClickCounter()
  63188. : std::numeric_limits<int>::max();
  63189. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63190. startTimer (50);
  63191. }
  63192. void SplashScreen::paint (Graphics& g)
  63193. {
  63194. g.setOpacity (1.0f);
  63195. g.drawImage (backgroundImage,
  63196. 0, 0, getWidth(), getHeight(),
  63197. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63198. }
  63199. void SplashScreen::timerCallback()
  63200. {
  63201. if (Time::getCurrentTime() > earliestTimeToDelete
  63202. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63203. {
  63204. delete this;
  63205. }
  63206. }
  63207. END_JUCE_NAMESPACE
  63208. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63209. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63210. BEGIN_JUCE_NAMESPACE
  63211. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63212. const bool hasProgressBar,
  63213. const bool hasCancelButton,
  63214. const int timeOutMsWhenCancelling_,
  63215. const String& cancelButtonText)
  63216. : Thread ("Juce Progress Window"),
  63217. progress (0.0),
  63218. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63219. {
  63220. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63221. .createAlertWindow (title, String::empty, cancelButtonText,
  63222. String::empty, String::empty,
  63223. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63224. if (hasProgressBar)
  63225. alertWindow->addProgressBarComponent (progress);
  63226. }
  63227. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63228. {
  63229. stopThread (timeOutMsWhenCancelling);
  63230. }
  63231. bool ThreadWithProgressWindow::runThread (const int priority)
  63232. {
  63233. startThread (priority);
  63234. startTimer (100);
  63235. {
  63236. const ScopedLock sl (messageLock);
  63237. alertWindow->setMessage (message);
  63238. }
  63239. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63240. stopThread (timeOutMsWhenCancelling);
  63241. alertWindow->setVisible (false);
  63242. return finishedNaturally;
  63243. }
  63244. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63245. {
  63246. progress = newProgress;
  63247. }
  63248. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63249. {
  63250. const ScopedLock sl (messageLock);
  63251. message = newStatusMessage;
  63252. }
  63253. void ThreadWithProgressWindow::timerCallback()
  63254. {
  63255. if (! isThreadRunning())
  63256. {
  63257. // thread has finished normally..
  63258. alertWindow->exitModalState (1);
  63259. alertWindow->setVisible (false);
  63260. }
  63261. else
  63262. {
  63263. const ScopedLock sl (messageLock);
  63264. alertWindow->setMessage (message);
  63265. }
  63266. }
  63267. END_JUCE_NAMESPACE
  63268. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63269. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63270. BEGIN_JUCE_NAMESPACE
  63271. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63272. const int millisecondsBeforeTipAppears_)
  63273. : Component ("tooltip"),
  63274. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63275. mouseClicks (0),
  63276. lastHideTime (0),
  63277. lastComponentUnderMouse (0),
  63278. changedCompsSinceShown (true)
  63279. {
  63280. if (Desktop::getInstance().getMainMouseSource().canHover())
  63281. startTimer (123);
  63282. setAlwaysOnTop (true);
  63283. setOpaque (true);
  63284. if (parentComponent != 0)
  63285. parentComponent->addChildComponent (this);
  63286. }
  63287. TooltipWindow::~TooltipWindow()
  63288. {
  63289. hide();
  63290. }
  63291. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63292. {
  63293. millisecondsBeforeTipAppears = newTimeMs;
  63294. }
  63295. void TooltipWindow::paint (Graphics& g)
  63296. {
  63297. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63298. }
  63299. void TooltipWindow::mouseEnter (const MouseEvent&)
  63300. {
  63301. hide();
  63302. }
  63303. void TooltipWindow::showFor (const String& tip)
  63304. {
  63305. jassert (tip.isNotEmpty());
  63306. if (tipShowing != tip)
  63307. repaint();
  63308. tipShowing = tip;
  63309. Point<int> mousePos (Desktop::getMousePosition());
  63310. if (getParentComponent() != 0)
  63311. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63312. int x, y, w, h;
  63313. getLookAndFeel().getTooltipSize (tip, w, h);
  63314. if (mousePos.getX() > getParentWidth() / 2)
  63315. x = mousePos.getX() - (w + 12);
  63316. else
  63317. x = mousePos.getX() + 24;
  63318. if (mousePos.getY() > getParentHeight() / 2)
  63319. y = mousePos.getY() - (h + 6);
  63320. else
  63321. y = mousePos.getY() + 6;
  63322. setBounds (x, y, w, h);
  63323. setVisible (true);
  63324. if (getParentComponent() == 0)
  63325. {
  63326. addToDesktop (ComponentPeer::windowHasDropShadow
  63327. | ComponentPeer::windowIsTemporary
  63328. | ComponentPeer::windowIgnoresKeyPresses);
  63329. }
  63330. toFront (false);
  63331. }
  63332. const String TooltipWindow::getTipFor (Component* const c)
  63333. {
  63334. if (c != 0
  63335. && Process::isForegroundProcess()
  63336. && ! Component::isMouseButtonDownAnywhere())
  63337. {
  63338. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63339. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63340. return ttc->getTooltip();
  63341. }
  63342. return String::empty;
  63343. }
  63344. void TooltipWindow::hide()
  63345. {
  63346. tipShowing = String::empty;
  63347. removeFromDesktop();
  63348. setVisible (false);
  63349. }
  63350. void TooltipWindow::timerCallback()
  63351. {
  63352. const unsigned int now = Time::getApproximateMillisecondCounter();
  63353. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63354. const String newTip (getTipFor (newComp));
  63355. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63356. lastComponentUnderMouse = newComp;
  63357. lastTipUnderMouse = newTip;
  63358. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63359. const bool mouseWasClicked = clickCount > mouseClicks;
  63360. mouseClicks = clickCount;
  63361. const Point<int> mousePos (Desktop::getMousePosition());
  63362. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63363. lastMousePos = mousePos;
  63364. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63365. lastCompChangeTime = now;
  63366. if (isVisible() || now < lastHideTime + 500)
  63367. {
  63368. // if a tip is currently visible (or has just disappeared), update to a new one
  63369. // immediately if needed..
  63370. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63371. {
  63372. if (isVisible())
  63373. {
  63374. lastHideTime = now;
  63375. hide();
  63376. }
  63377. }
  63378. else if (tipChanged)
  63379. {
  63380. showFor (newTip);
  63381. }
  63382. }
  63383. else
  63384. {
  63385. // if there isn't currently a tip, but one is needed, only let it
  63386. // appear after a timeout..
  63387. if (newTip.isNotEmpty()
  63388. && newTip != tipShowing
  63389. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63390. {
  63391. showFor (newTip);
  63392. }
  63393. }
  63394. }
  63395. END_JUCE_NAMESPACE
  63396. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63397. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63398. BEGIN_JUCE_NAMESPACE
  63399. /** Keeps track of the active top level window.
  63400. */
  63401. class TopLevelWindowManager : public Timer,
  63402. public DeletedAtShutdown
  63403. {
  63404. public:
  63405. TopLevelWindowManager()
  63406. : currentActive (0)
  63407. {
  63408. }
  63409. ~TopLevelWindowManager()
  63410. {
  63411. clearSingletonInstance();
  63412. }
  63413. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63414. void timerCallback()
  63415. {
  63416. startTimer (jmin (1731, getTimerInterval() * 2));
  63417. TopLevelWindow* active = 0;
  63418. if (Process::isForegroundProcess())
  63419. {
  63420. active = currentActive;
  63421. Component* const c = Component::getCurrentlyFocusedComponent();
  63422. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63423. if (tlw == 0 && c != 0)
  63424. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63425. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63426. if (tlw != 0)
  63427. active = tlw;
  63428. }
  63429. if (active != currentActive)
  63430. {
  63431. currentActive = active;
  63432. for (int i = windows.size(); --i >= 0;)
  63433. {
  63434. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63435. tlw->setWindowActive (isWindowActive (tlw));
  63436. i = jmin (i, windows.size() - 1);
  63437. }
  63438. Desktop::getInstance().triggerFocusCallback();
  63439. }
  63440. }
  63441. bool addWindow (TopLevelWindow* const w)
  63442. {
  63443. windows.add (w);
  63444. startTimer (10);
  63445. return isWindowActive (w);
  63446. }
  63447. void removeWindow (TopLevelWindow* const w)
  63448. {
  63449. startTimer (10);
  63450. if (currentActive == w)
  63451. currentActive = 0;
  63452. windows.removeValue (w);
  63453. if (windows.size() == 0)
  63454. deleteInstance();
  63455. }
  63456. Array <TopLevelWindow*> windows;
  63457. private:
  63458. TopLevelWindow* currentActive;
  63459. bool isWindowActive (TopLevelWindow* const tlw) const
  63460. {
  63461. return (tlw == currentActive
  63462. || tlw->isParentOf (currentActive)
  63463. || tlw->hasKeyboardFocus (true))
  63464. && tlw->isShowing();
  63465. }
  63466. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63467. };
  63468. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63469. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63470. {
  63471. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63472. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63473. }
  63474. TopLevelWindow::TopLevelWindow (const String& name,
  63475. const bool addToDesktop_)
  63476. : Component (name),
  63477. useDropShadow (true),
  63478. useNativeTitleBar (false),
  63479. windowIsActive_ (false)
  63480. {
  63481. setOpaque (true);
  63482. if (addToDesktop_)
  63483. Component::addToDesktop (getDesktopWindowStyleFlags());
  63484. else
  63485. setDropShadowEnabled (true);
  63486. setWantsKeyboardFocus (true);
  63487. setBroughtToFrontOnMouseClick (true);
  63488. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63489. }
  63490. TopLevelWindow::~TopLevelWindow()
  63491. {
  63492. shadower = 0;
  63493. TopLevelWindowManager::getInstance()->removeWindow (this);
  63494. }
  63495. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63496. {
  63497. if (hasKeyboardFocus (true))
  63498. TopLevelWindowManager::getInstance()->timerCallback();
  63499. else
  63500. TopLevelWindowManager::getInstance()->startTimer (10);
  63501. }
  63502. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63503. {
  63504. if (windowIsActive_ != isNowActive)
  63505. {
  63506. windowIsActive_ = isNowActive;
  63507. activeWindowStatusChanged();
  63508. }
  63509. }
  63510. void TopLevelWindow::activeWindowStatusChanged()
  63511. {
  63512. }
  63513. void TopLevelWindow::visibilityChanged()
  63514. {
  63515. if (isShowing()
  63516. && (getPeer()->getStyleFlags() & (ComponentPeer::windowIsTemporary
  63517. | ComponentPeer::windowIgnoresKeyPresses)) == 0)
  63518. {
  63519. toFront (true);
  63520. }
  63521. }
  63522. void TopLevelWindow::parentHierarchyChanged()
  63523. {
  63524. setDropShadowEnabled (useDropShadow);
  63525. }
  63526. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63527. {
  63528. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63529. if (useDropShadow)
  63530. styleFlags |= ComponentPeer::windowHasDropShadow;
  63531. if (useNativeTitleBar)
  63532. styleFlags |= ComponentPeer::windowHasTitleBar;
  63533. return styleFlags;
  63534. }
  63535. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63536. {
  63537. useDropShadow = useShadow;
  63538. if (isOnDesktop())
  63539. {
  63540. shadower = 0;
  63541. Component::addToDesktop (getDesktopWindowStyleFlags());
  63542. }
  63543. else
  63544. {
  63545. if (useShadow && isOpaque())
  63546. {
  63547. if (shadower == 0)
  63548. {
  63549. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63550. if (shadower != 0)
  63551. shadower->setOwner (this);
  63552. }
  63553. }
  63554. else
  63555. {
  63556. shadower = 0;
  63557. }
  63558. }
  63559. }
  63560. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63561. {
  63562. if (useNativeTitleBar != useNativeTitleBar_)
  63563. {
  63564. useNativeTitleBar = useNativeTitleBar_;
  63565. recreateDesktopWindow();
  63566. sendLookAndFeelChange();
  63567. }
  63568. }
  63569. void TopLevelWindow::recreateDesktopWindow()
  63570. {
  63571. if (isOnDesktop())
  63572. {
  63573. Component::addToDesktop (getDesktopWindowStyleFlags());
  63574. toFront (true);
  63575. }
  63576. }
  63577. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63578. {
  63579. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63580. because this class needs to make sure its layout corresponds with settings like whether
  63581. it's got a native title bar or not.
  63582. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63583. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63584. method, then add or remove whatever flags are necessary from this value before returning it.
  63585. */
  63586. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63587. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63588. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63589. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63590. sendLookAndFeelChange();
  63591. }
  63592. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63593. {
  63594. if (c == 0)
  63595. c = TopLevelWindow::getActiveTopLevelWindow();
  63596. if (c == 0)
  63597. {
  63598. centreWithSize (width, height);
  63599. }
  63600. else
  63601. {
  63602. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63603. Rectangle<int> parentArea (c->getParentMonitorArea());
  63604. if (getParentComponent() != 0)
  63605. {
  63606. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63607. parentArea = getParentComponent()->getLocalBounds();
  63608. }
  63609. parentArea.reduce (12, 12);
  63610. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63611. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63612. width, height);
  63613. }
  63614. }
  63615. int TopLevelWindow::getNumTopLevelWindows() throw()
  63616. {
  63617. return TopLevelWindowManager::getInstance()->windows.size();
  63618. }
  63619. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63620. {
  63621. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63622. }
  63623. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63624. {
  63625. TopLevelWindow* best = 0;
  63626. int bestNumTWLParents = -1;
  63627. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63628. {
  63629. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63630. if (tlw->isActiveWindow())
  63631. {
  63632. int numTWLParents = 0;
  63633. const Component* c = tlw->getParentComponent();
  63634. while (c != 0)
  63635. {
  63636. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63637. ++numTWLParents;
  63638. c = c->getParentComponent();
  63639. }
  63640. if (bestNumTWLParents < numTWLParents)
  63641. {
  63642. best = tlw;
  63643. bestNumTWLParents = numTWLParents;
  63644. }
  63645. }
  63646. }
  63647. return best;
  63648. }
  63649. END_JUCE_NAMESPACE
  63650. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63651. /*** Start of inlined file: juce_MarkerList.cpp ***/
  63652. BEGIN_JUCE_NAMESPACE
  63653. MarkerList::MarkerList()
  63654. {
  63655. }
  63656. MarkerList::MarkerList (const MarkerList& other)
  63657. {
  63658. operator= (other);
  63659. }
  63660. MarkerList& MarkerList::operator= (const MarkerList& other)
  63661. {
  63662. if (other != *this)
  63663. {
  63664. markers.clear();
  63665. markers.addCopiesOf (other.markers);
  63666. markersHaveChanged();
  63667. }
  63668. return *this;
  63669. }
  63670. MarkerList::~MarkerList()
  63671. {
  63672. listeners.call (&MarkerList::Listener::markerListBeingDeleted, this);
  63673. }
  63674. bool MarkerList::operator== (const MarkerList& other) const throw()
  63675. {
  63676. if (other.markers.size() != markers.size())
  63677. return false;
  63678. for (int i = markers.size(); --i >= 0;)
  63679. {
  63680. const Marker* const m1 = markers.getUnchecked(i);
  63681. jassert (m1 != 0);
  63682. const Marker* const m2 = other.getMarker (m1->name);
  63683. if (m2 == 0 || *m1 != *m2)
  63684. return false;
  63685. }
  63686. return true;
  63687. }
  63688. bool MarkerList::operator!= (const MarkerList& other) const throw()
  63689. {
  63690. return ! operator== (other);
  63691. }
  63692. int MarkerList::getNumMarkers() const throw()
  63693. {
  63694. return markers.size();
  63695. }
  63696. const MarkerList::Marker* MarkerList::getMarker (const int index) const throw()
  63697. {
  63698. return markers [index];
  63699. }
  63700. const MarkerList::Marker* MarkerList::getMarker (const String& name) const throw()
  63701. {
  63702. for (int i = 0; i < markers.size(); ++i)
  63703. {
  63704. const Marker* const m = markers.getUnchecked(i);
  63705. if (m->name == name)
  63706. return m;
  63707. }
  63708. return 0;
  63709. }
  63710. void MarkerList::setMarker (const String& name, const RelativeCoordinate& position)
  63711. {
  63712. Marker* const m = const_cast <Marker*> (getMarker (name));
  63713. if (m != 0)
  63714. {
  63715. if (m->position != position)
  63716. {
  63717. m->position = position;
  63718. markersHaveChanged();
  63719. }
  63720. return;
  63721. }
  63722. markers.add (new Marker (name, position));
  63723. markersHaveChanged();
  63724. }
  63725. void MarkerList::removeMarker (const int index)
  63726. {
  63727. if (isPositiveAndBelow (index, markers.size()))
  63728. {
  63729. markers.remove (index);
  63730. markersHaveChanged();
  63731. }
  63732. }
  63733. void MarkerList::removeMarker (const String& name)
  63734. {
  63735. for (int i = 0; i < markers.size(); ++i)
  63736. {
  63737. const Marker* const m = markers.getUnchecked(i);
  63738. if (m->name == name)
  63739. {
  63740. markers.remove (i);
  63741. markersHaveChanged();
  63742. }
  63743. }
  63744. }
  63745. void MarkerList::markersHaveChanged()
  63746. {
  63747. listeners.call (&MarkerList::Listener::markersChanged, this);
  63748. }
  63749. void MarkerList::Listener::markerListBeingDeleted (MarkerList*)
  63750. {
  63751. }
  63752. void MarkerList::addListener (Listener* listener)
  63753. {
  63754. listeners.add (listener);
  63755. }
  63756. void MarkerList::removeListener (Listener* listener)
  63757. {
  63758. listeners.remove (listener);
  63759. }
  63760. MarkerList::Marker::Marker (const Marker& other)
  63761. : name (other.name), position (other.position)
  63762. {
  63763. }
  63764. MarkerList::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  63765. : name (name_), position (position_)
  63766. {
  63767. }
  63768. bool MarkerList::Marker::operator== (const Marker& other) const throw()
  63769. {
  63770. return name == other.name && position == other.position;
  63771. }
  63772. bool MarkerList::Marker::operator!= (const Marker& other) const throw()
  63773. {
  63774. return ! operator== (other);
  63775. }
  63776. const Identifier MarkerList::ValueTreeWrapper::markerTag ("Marker");
  63777. const Identifier MarkerList::ValueTreeWrapper::nameProperty ("name");
  63778. const Identifier MarkerList::ValueTreeWrapper::posProperty ("position");
  63779. MarkerList::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  63780. : state (state_)
  63781. {
  63782. }
  63783. int MarkerList::ValueTreeWrapper::getNumMarkers() const
  63784. {
  63785. return state.getNumChildren();
  63786. }
  63787. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (int index) const
  63788. {
  63789. return state.getChild (index);
  63790. }
  63791. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (const String& name) const
  63792. {
  63793. return state.getChildWithProperty (nameProperty, name);
  63794. }
  63795. bool MarkerList::ValueTreeWrapper::containsMarker (const ValueTree& marker) const
  63796. {
  63797. return marker.isAChildOf (state);
  63798. }
  63799. const MarkerList::Marker MarkerList::ValueTreeWrapper::getMarker (const ValueTree& marker) const
  63800. {
  63801. jassert (containsMarker (marker));
  63802. return MarkerList::Marker (marker [nameProperty], RelativeCoordinate (marker [posProperty].toString()));
  63803. }
  63804. void MarkerList::ValueTreeWrapper::setMarker (const MarkerList::Marker& m, UndoManager* undoManager)
  63805. {
  63806. ValueTree marker (state.getChildWithProperty (nameProperty, m.name));
  63807. if (marker.isValid())
  63808. {
  63809. marker.setProperty (posProperty, m.position.toString(), undoManager);
  63810. }
  63811. else
  63812. {
  63813. marker = ValueTree (markerTag);
  63814. marker.setProperty (nameProperty, m.name, 0);
  63815. marker.setProperty (posProperty, m.position.toString(), 0);
  63816. state.addChild (marker, -1, undoManager);
  63817. }
  63818. }
  63819. void MarkerList::ValueTreeWrapper::removeMarker (const ValueTree& marker, UndoManager* undoManager)
  63820. {
  63821. state.removeChild (marker, undoManager);
  63822. }
  63823. class MarkerListEvaluator : public Expression::EvaluationContext
  63824. {
  63825. public:
  63826. MarkerListEvaluator (const MarkerList& markerList_, Component* const parentComponent_)
  63827. : markerList (markerList_), parentComponent (parentComponent_)
  63828. {
  63829. }
  63830. const Expression getSymbolValue (const String& objectName, const String& member) const
  63831. {
  63832. if (member.isEmpty())
  63833. {
  63834. const MarkerList::Marker* const marker = markerList.getMarker (objectName);
  63835. if (marker != 0)
  63836. return Expression (marker->position.resolve (this));
  63837. }
  63838. else if (parentComponent != 0 && objectName == RelativeCoordinate::Strings::parent)
  63839. {
  63840. if (member == RelativeCoordinate::Strings::right) return Expression ((double) parentComponent->getWidth());
  63841. if (member == RelativeCoordinate::Strings::bottom) return Expression ((double) parentComponent->getHeight());
  63842. }
  63843. return Expression::EvaluationContext::getSymbolValue (objectName, member);
  63844. }
  63845. private:
  63846. const MarkerList& markerList;
  63847. Component* parentComponent;
  63848. JUCE_DECLARE_NON_COPYABLE (MarkerListEvaluator);
  63849. };
  63850. double MarkerList::getMarkerPosition (const Marker& marker, Component* const parentComponent) const
  63851. {
  63852. MarkerListEvaluator context (*this, parentComponent);
  63853. return marker.position.resolve (&context);
  63854. }
  63855. void MarkerList::ValueTreeWrapper::applyTo (MarkerList& markerList)
  63856. {
  63857. const int numMarkers = getNumMarkers();
  63858. StringArray updatedMarkers;
  63859. int i;
  63860. for (i = 0; i < numMarkers; ++i)
  63861. {
  63862. const ValueTree marker (state.getChild (i));
  63863. const String name (marker [nameProperty].toString());
  63864. markerList.setMarker (name, RelativeCoordinate (marker [posProperty].toString()));
  63865. updatedMarkers.add (name);
  63866. }
  63867. for (i = markerList.getNumMarkers(); --i >= 0;)
  63868. if (! updatedMarkers.contains (markerList.getMarker (i)->name))
  63869. markerList.removeMarker (i);
  63870. }
  63871. void MarkerList::ValueTreeWrapper::readFrom (const MarkerList& markerList, UndoManager* undoManager)
  63872. {
  63873. state.removeAllChildren (undoManager);
  63874. for (int i = 0; i < markerList.getNumMarkers(); ++i)
  63875. setMarker (*markerList.getMarker(i), undoManager);
  63876. }
  63877. END_JUCE_NAMESPACE
  63878. /*** End of inlined file: juce_MarkerList.cpp ***/
  63879. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63880. BEGIN_JUCE_NAMESPACE
  63881. const String RelativeCoordinate::Strings::parent ("parent");
  63882. const String RelativeCoordinate::Strings::this_ ("this");
  63883. const String RelativeCoordinate::Strings::left ("left");
  63884. const String RelativeCoordinate::Strings::right ("right");
  63885. const String RelativeCoordinate::Strings::top ("top");
  63886. const String RelativeCoordinate::Strings::bottom ("bottom");
  63887. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  63888. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  63889. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  63890. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  63891. RelativeCoordinate::RelativeCoordinate()
  63892. {
  63893. }
  63894. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  63895. : term (term_)
  63896. {
  63897. }
  63898. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  63899. : term (other.term)
  63900. {
  63901. }
  63902. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  63903. {
  63904. term = other.term;
  63905. return *this;
  63906. }
  63907. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63908. : term (absoluteDistanceFromOrigin)
  63909. {
  63910. }
  63911. RelativeCoordinate::RelativeCoordinate (const String& s)
  63912. {
  63913. try
  63914. {
  63915. term = Expression (s);
  63916. }
  63917. catch (...)
  63918. {}
  63919. }
  63920. RelativeCoordinate::~RelativeCoordinate()
  63921. {
  63922. }
  63923. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63924. {
  63925. return term.toString() == other.term.toString();
  63926. }
  63927. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63928. {
  63929. return ! operator== (other);
  63930. }
  63931. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  63932. {
  63933. try
  63934. {
  63935. if (context != 0)
  63936. return term.evaluate (*context);
  63937. else
  63938. return term.evaluate();
  63939. }
  63940. catch (...)
  63941. {}
  63942. return 0.0;
  63943. }
  63944. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  63945. {
  63946. try
  63947. {
  63948. if (context != 0)
  63949. term.evaluate (*context);
  63950. else
  63951. term.evaluate();
  63952. }
  63953. catch (...)
  63954. {
  63955. return true;
  63956. }
  63957. return false;
  63958. }
  63959. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  63960. {
  63961. try
  63962. {
  63963. if (context != 0)
  63964. {
  63965. term = term.adjustedToGiveNewResult (newPos, *context);
  63966. }
  63967. else
  63968. {
  63969. Expression::EvaluationContext defaultContext;
  63970. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  63971. }
  63972. }
  63973. catch (...)
  63974. {}
  63975. }
  63976. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  63977. {
  63978. try
  63979. {
  63980. return term.referencesSymbol (coordName, context);
  63981. }
  63982. catch (...)
  63983. {}
  63984. return false;
  63985. }
  63986. bool RelativeCoordinate::isDynamic() const
  63987. {
  63988. return term.usesAnySymbols();
  63989. }
  63990. const String RelativeCoordinate::toString() const
  63991. {
  63992. return term.toString();
  63993. }
  63994. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  63995. {
  63996. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  63997. if (term.referencesSymbol (oldName, 0))
  63998. term = term.withRenamedSymbol (oldName, newName);
  63999. }
  64000. END_JUCE_NAMESPACE
  64001. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64002. /*** Start of inlined file: juce_RelativePoint.cpp ***/
  64003. BEGIN_JUCE_NAMESPACE
  64004. namespace RelativePointHelpers
  64005. {
  64006. void skipComma (const juce_wchar* const s, int& i)
  64007. {
  64008. while (CharacterFunctions::isWhitespace (s[i]))
  64009. ++i;
  64010. if (s[i] == ',')
  64011. ++i;
  64012. }
  64013. }
  64014. RelativePoint::RelativePoint()
  64015. {
  64016. }
  64017. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64018. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64019. {
  64020. }
  64021. RelativePoint::RelativePoint (const float x_, const float y_)
  64022. : x (x_), y (y_)
  64023. {
  64024. }
  64025. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64026. : x (x_), y (y_)
  64027. {
  64028. }
  64029. RelativePoint::RelativePoint (const String& s)
  64030. {
  64031. int i = 0;
  64032. x = RelativeCoordinate (Expression::parse (s, i));
  64033. RelativePointHelpers::skipComma (s, i);
  64034. y = RelativeCoordinate (Expression::parse (s, i));
  64035. }
  64036. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64037. {
  64038. return x == other.x && y == other.y;
  64039. }
  64040. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64041. {
  64042. return ! operator== (other);
  64043. }
  64044. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64045. {
  64046. return Point<float> ((float) x.resolve (context),
  64047. (float) y.resolve (context));
  64048. }
  64049. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64050. {
  64051. x.moveToAbsolute (newPos.getX(), context);
  64052. y.moveToAbsolute (newPos.getY(), context);
  64053. }
  64054. const String RelativePoint::toString() const
  64055. {
  64056. return x.toString() + ", " + y.toString();
  64057. }
  64058. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64059. {
  64060. x.renameSymbolIfUsed (oldName, newName);
  64061. y.renameSymbolIfUsed (oldName, newName);
  64062. }
  64063. bool RelativePoint::isDynamic() const
  64064. {
  64065. return x.isDynamic() || y.isDynamic();
  64066. }
  64067. END_JUCE_NAMESPACE
  64068. /*** End of inlined file: juce_RelativePoint.cpp ***/
  64069. /*** Start of inlined file: juce_RelativeRectangle.cpp ***/
  64070. BEGIN_JUCE_NAMESPACE
  64071. namespace RelativeRectangleHelpers
  64072. {
  64073. inline void skipComma (const juce_wchar* const s, int& i)
  64074. {
  64075. while (CharacterFunctions::isWhitespace (s[i]))
  64076. ++i;
  64077. if (s[i] == ',')
  64078. ++i;
  64079. }
  64080. bool dependsOnSymbolsOtherThanThis (const Expression& e)
  64081. {
  64082. if (e.getType() == Expression::symbolType)
  64083. {
  64084. String objectName, memberName;
  64085. e.getSymbolParts (objectName, memberName);
  64086. if (objectName != RelativeCoordinate::Strings::this_)
  64087. return true;
  64088. }
  64089. else
  64090. {
  64091. for (int i = e.getNumInputs(); --i >= 0;)
  64092. if (dependsOnSymbolsOtherThanThis (e.getInput(i)))
  64093. return true;
  64094. }
  64095. return false;
  64096. }
  64097. }
  64098. RelativeRectangle::RelativeRectangle()
  64099. {
  64100. }
  64101. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64102. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64103. : left (left_), right (right_), top (top_), bottom (bottom_)
  64104. {
  64105. }
  64106. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect)
  64107. : left (rect.getX()),
  64108. right (Expression::symbol (RelativeCoordinate::Strings::this_ + "." + RelativeCoordinate::Strings::left)
  64109. + Expression ((double) rect.getWidth())),
  64110. top (rect.getY()),
  64111. bottom (Expression::symbol (RelativeCoordinate::Strings::this_ + "." + RelativeCoordinate::Strings::top)
  64112. + Expression ((double) rect.getHeight()))
  64113. {
  64114. }
  64115. RelativeRectangle::RelativeRectangle (const String& s)
  64116. {
  64117. int i = 0;
  64118. left = RelativeCoordinate (Expression::parse (s, i));
  64119. RelativeRectangleHelpers::skipComma (s, i);
  64120. top = RelativeCoordinate (Expression::parse (s, i));
  64121. RelativeRectangleHelpers::skipComma (s, i);
  64122. right = RelativeCoordinate (Expression::parse (s, i));
  64123. RelativeRectangleHelpers::skipComma (s, i);
  64124. bottom = RelativeCoordinate (Expression::parse (s, i));
  64125. }
  64126. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64127. {
  64128. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64129. }
  64130. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64131. {
  64132. return ! operator== (other);
  64133. }
  64134. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64135. {
  64136. const double l = left.resolve (context);
  64137. const double r = right.resolve (context);
  64138. const double t = top.resolve (context);
  64139. const double b = bottom.resolve (context);
  64140. return Rectangle<float> ((float) l, (float) t, (float) jmax (0.0, r - l), (float) jmax (0.0, b - t));
  64141. }
  64142. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64143. {
  64144. left.moveToAbsolute (newPos.getX(), context);
  64145. right.moveToAbsolute (newPos.getRight(), context);
  64146. top.moveToAbsolute (newPos.getY(), context);
  64147. bottom.moveToAbsolute (newPos.getBottom(), context);
  64148. }
  64149. bool RelativeRectangle::isDynamic() const
  64150. {
  64151. using namespace RelativeRectangleHelpers;
  64152. return dependsOnSymbolsOtherThanThis (left.getExpression())
  64153. || dependsOnSymbolsOtherThanThis (right.getExpression())
  64154. || dependsOnSymbolsOtherThanThis (top.getExpression())
  64155. || dependsOnSymbolsOtherThanThis (bottom.getExpression());
  64156. }
  64157. const String RelativeRectangle::toString() const
  64158. {
  64159. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64160. }
  64161. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64162. {
  64163. left.renameSymbolIfUsed (oldName, newName);
  64164. right.renameSymbolIfUsed (oldName, newName);
  64165. top.renameSymbolIfUsed (oldName, newName);
  64166. bottom.renameSymbolIfUsed (oldName, newName);
  64167. }
  64168. class RelativeRectangleComponentPositioner : public RelativeCoordinatePositionerBase
  64169. {
  64170. public:
  64171. RelativeRectangleComponentPositioner (Component& component_, const RelativeRectangle& rectangle_)
  64172. : RelativeCoordinatePositionerBase (component_),
  64173. rectangle (rectangle_)
  64174. {
  64175. }
  64176. bool registerCoordinates()
  64177. {
  64178. bool ok = addCoordinate (rectangle.left);
  64179. ok = addCoordinate (rectangle.right) && ok;
  64180. ok = addCoordinate (rectangle.top) && ok;
  64181. ok = addCoordinate (rectangle.bottom) && ok;
  64182. return ok;
  64183. }
  64184. bool isUsingRectangle (const RelativeRectangle& other) const throw()
  64185. {
  64186. return rectangle == other;
  64187. }
  64188. void applyToComponentBounds()
  64189. {
  64190. for (int i = 4; --i >= 0;)
  64191. {
  64192. const Rectangle<int> newBounds (rectangle.resolve (this).getSmallestIntegerContainer());
  64193. if (newBounds == getComponent().getBounds())
  64194. return;
  64195. getComponent().setBounds (newBounds);
  64196. }
  64197. jassertfalse; // must be a recursive reference!
  64198. }
  64199. private:
  64200. const RelativeRectangle rectangle;
  64201. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeRectangleComponentPositioner);
  64202. };
  64203. // An expression context that can evaluate expressions using "this"
  64204. class TemporaryRectangleContext : public Expression::EvaluationContext
  64205. {
  64206. public:
  64207. TemporaryRectangleContext (const RelativeRectangle& rect_) : rect (rect_) {}
  64208. const Expression getSymbolValue (const String& objectName, const String& edge) const
  64209. {
  64210. if (objectName == RelativeCoordinate::Strings::this_)
  64211. {
  64212. if (edge == RelativeCoordinate::Strings::left) return rect.left.getExpression();
  64213. if (edge == RelativeCoordinate::Strings::right) return rect.right.getExpression();
  64214. if (edge == RelativeCoordinate::Strings::top) return rect.top.getExpression();
  64215. if (edge == RelativeCoordinate::Strings::bottom) return rect.bottom.getExpression();
  64216. }
  64217. return Expression::EvaluationContext::getSymbolValue (objectName, edge);
  64218. }
  64219. private:
  64220. const RelativeRectangle& rect;
  64221. JUCE_DECLARE_NON_COPYABLE (TemporaryRectangleContext);
  64222. };
  64223. void RelativeRectangle::applyToComponent (Component& component) const
  64224. {
  64225. if (isDynamic())
  64226. {
  64227. RelativeRectangleComponentPositioner* current = dynamic_cast <RelativeRectangleComponentPositioner*> (component.getPositioner());
  64228. if (current == 0 || ! current->isUsingRectangle (*this))
  64229. {
  64230. RelativeRectangleComponentPositioner* p = new RelativeRectangleComponentPositioner (component, *this);
  64231. component.setPositioner (p);
  64232. p->apply();
  64233. }
  64234. }
  64235. else
  64236. {
  64237. component.setPositioner (0);
  64238. TemporaryRectangleContext context (*this);
  64239. component.setBounds (resolve (&context).getSmallestIntegerContainer());
  64240. }
  64241. }
  64242. END_JUCE_NAMESPACE
  64243. /*** End of inlined file: juce_RelativeRectangle.cpp ***/
  64244. /*** Start of inlined file: juce_RelativePointPath.cpp ***/
  64245. BEGIN_JUCE_NAMESPACE
  64246. RelativePointPath::RelativePointPath()
  64247. : usesNonZeroWinding (true),
  64248. containsDynamicPoints (false)
  64249. {
  64250. }
  64251. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64252. : usesNonZeroWinding (true),
  64253. containsDynamicPoints (false)
  64254. {
  64255. for (int i = 0; i < other.elements.size(); ++i)
  64256. elements.add (other.elements.getUnchecked(i)->clone());
  64257. }
  64258. RelativePointPath::RelativePointPath (const Path& path)
  64259. : usesNonZeroWinding (path.isUsingNonZeroWinding()),
  64260. containsDynamicPoints (false)
  64261. {
  64262. for (Path::Iterator i (path); i.next();)
  64263. {
  64264. switch (i.elementType)
  64265. {
  64266. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64267. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64268. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64269. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64270. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64271. default: jassertfalse; break;
  64272. }
  64273. }
  64274. }
  64275. RelativePointPath::~RelativePointPath()
  64276. {
  64277. }
  64278. bool RelativePointPath::operator== (const RelativePointPath& other) const throw()
  64279. {
  64280. if (elements.size() != other.elements.size()
  64281. || usesNonZeroWinding != other.usesNonZeroWinding
  64282. || containsDynamicPoints != other.containsDynamicPoints)
  64283. return false;
  64284. for (int i = 0; i < elements.size(); ++i)
  64285. {
  64286. ElementBase* const e1 = elements.getUnchecked(i);
  64287. ElementBase* const e2 = other.elements.getUnchecked(i);
  64288. if (e1->type != e2->type)
  64289. return false;
  64290. int numPoints1, numPoints2;
  64291. const RelativePoint* const points1 = e1->getControlPoints (numPoints1);
  64292. const RelativePoint* const points2 = e2->getControlPoints (numPoints2);
  64293. jassert (numPoints1 == numPoints2);
  64294. for (int j = numPoints1; --j >= 0;)
  64295. if (points1[j] != points2[j])
  64296. return false;
  64297. }
  64298. return true;
  64299. }
  64300. bool RelativePointPath::operator!= (const RelativePointPath& other) const throw()
  64301. {
  64302. return ! operator== (other);
  64303. }
  64304. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64305. {
  64306. elements.swapWithArray (other.elements);
  64307. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64308. swapVariables (containsDynamicPoints, other.containsDynamicPoints);
  64309. }
  64310. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64311. {
  64312. for (int i = 0; i < elements.size(); ++i)
  64313. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64314. }
  64315. bool RelativePointPath::containsAnyDynamicPoints() const
  64316. {
  64317. return containsDynamicPoints;
  64318. }
  64319. void RelativePointPath::addElement (ElementBase* newElement)
  64320. {
  64321. if (newElement != 0)
  64322. {
  64323. elements.add (newElement);
  64324. containsDynamicPoints = containsDynamicPoints || newElement->isDynamic();
  64325. }
  64326. }
  64327. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64328. {
  64329. }
  64330. bool RelativePointPath::ElementBase::isDynamic()
  64331. {
  64332. int numPoints;
  64333. const RelativePoint* const points = getControlPoints (numPoints);
  64334. for (int i = numPoints; --i >= 0;)
  64335. if (points[i].isDynamic())
  64336. return true;
  64337. return false;
  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::ElementBase* RelativePointPath::StartSubPath::clone() const
  64359. {
  64360. return new StartSubPath (startPos);
  64361. }
  64362. RelativePointPath::CloseSubPath::CloseSubPath()
  64363. : ElementBase (closeSubPathElement)
  64364. {
  64365. }
  64366. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64367. {
  64368. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64369. }
  64370. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64371. {
  64372. path.closeSubPath();
  64373. }
  64374. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64375. {
  64376. numPoints = 0;
  64377. return 0;
  64378. }
  64379. RelativePointPath::ElementBase* RelativePointPath::CloseSubPath::clone() const
  64380. {
  64381. return new CloseSubPath();
  64382. }
  64383. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64384. : ElementBase (lineToElement), endPoint (endPoint_)
  64385. {
  64386. }
  64387. const ValueTree RelativePointPath::LineTo::createTree() const
  64388. {
  64389. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64390. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64391. return v;
  64392. }
  64393. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64394. {
  64395. path.lineTo (endPoint.resolve (coordFinder));
  64396. }
  64397. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64398. {
  64399. numPoints = 1;
  64400. return &endPoint;
  64401. }
  64402. RelativePointPath::ElementBase* RelativePointPath::LineTo::clone() const
  64403. {
  64404. return new LineTo (endPoint);
  64405. }
  64406. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64407. : ElementBase (quadraticToElement)
  64408. {
  64409. controlPoints[0] = controlPoint;
  64410. controlPoints[1] = endPoint;
  64411. }
  64412. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64413. {
  64414. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64415. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64416. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64417. return v;
  64418. }
  64419. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64420. {
  64421. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64422. controlPoints[1].resolve (coordFinder));
  64423. }
  64424. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64425. {
  64426. numPoints = 2;
  64427. return controlPoints;
  64428. }
  64429. RelativePointPath::ElementBase* RelativePointPath::QuadraticTo::clone() const
  64430. {
  64431. return new QuadraticTo (controlPoints[0], controlPoints[1]);
  64432. }
  64433. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64434. : ElementBase (cubicToElement)
  64435. {
  64436. controlPoints[0] = controlPoint1;
  64437. controlPoints[1] = controlPoint2;
  64438. controlPoints[2] = endPoint;
  64439. }
  64440. const ValueTree RelativePointPath::CubicTo::createTree() const
  64441. {
  64442. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64443. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64444. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64445. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64446. return v;
  64447. }
  64448. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64449. {
  64450. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64451. controlPoints[1].resolve (coordFinder),
  64452. controlPoints[2].resolve (coordFinder));
  64453. }
  64454. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64455. {
  64456. numPoints = 3;
  64457. return controlPoints;
  64458. }
  64459. RelativePointPath::ElementBase* RelativePointPath::CubicTo::clone() const
  64460. {
  64461. return new CubicTo (controlPoints[0], controlPoints[1], controlPoints[2]);
  64462. }
  64463. END_JUCE_NAMESPACE
  64464. /*** End of inlined file: juce_RelativePointPath.cpp ***/
  64465. /*** Start of inlined file: juce_RelativeParallelogram.cpp ***/
  64466. BEGIN_JUCE_NAMESPACE
  64467. RelativeParallelogram::RelativeParallelogram()
  64468. {
  64469. }
  64470. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64471. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64472. {
  64473. }
  64474. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64475. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64476. {
  64477. }
  64478. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64479. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64480. {
  64481. }
  64482. RelativeParallelogram::~RelativeParallelogram()
  64483. {
  64484. }
  64485. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64486. {
  64487. points[0] = topLeft.resolve (coordFinder);
  64488. points[1] = topRight.resolve (coordFinder);
  64489. points[2] = bottomLeft.resolve (coordFinder);
  64490. }
  64491. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64492. {
  64493. resolveThreePoints (points, coordFinder);
  64494. points[3] = points[1] + (points[2] - points[0]);
  64495. }
  64496. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64497. {
  64498. Point<float> points[4];
  64499. resolveFourCorners (points, coordFinder);
  64500. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64501. }
  64502. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64503. {
  64504. Point<float> points[4];
  64505. resolveFourCorners (points, coordFinder);
  64506. path.startNewSubPath (points[0]);
  64507. path.lineTo (points[1]);
  64508. path.lineTo (points[3]);
  64509. path.lineTo (points[2]);
  64510. path.closeSubPath();
  64511. }
  64512. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64513. {
  64514. Point<float> corners[3];
  64515. resolveThreePoints (corners, coordFinder);
  64516. const Line<float> top (corners[0], corners[1]);
  64517. const Line<float> left (corners[0], corners[2]);
  64518. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64519. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64520. topRight.moveToAbsolute (newTopRight, coordFinder);
  64521. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64522. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64523. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64524. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64525. }
  64526. bool RelativeParallelogram::isDynamic() const
  64527. {
  64528. return topLeft.isDynamic() || topRight.isDynamic() || bottomLeft.isDynamic();
  64529. }
  64530. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64531. {
  64532. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64533. }
  64534. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64535. {
  64536. return ! operator== (other);
  64537. }
  64538. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64539. {
  64540. const Point<float> tr (corners[1] - corners[0]);
  64541. const Point<float> bl (corners[2] - corners[0]);
  64542. target -= corners[0];
  64543. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64544. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64545. }
  64546. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64547. {
  64548. return corners[0]
  64549. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64550. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64551. }
  64552. const Rectangle<float> RelativeParallelogram::getBoundingBox (const Point<float>* const p) throw()
  64553. {
  64554. const Point<float> points[] = { p[0], p[1], p[2], p[1] + (p[2] - p[0]) };
  64555. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64556. }
  64557. END_JUCE_NAMESPACE
  64558. /*** End of inlined file: juce_RelativeParallelogram.cpp ***/
  64559. /*** Start of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64560. BEGIN_JUCE_NAMESPACE
  64561. RelativeCoordinatePositionerBase::RelativeCoordinatePositionerBase (Component& component_)
  64562. : Component::Positioner (component_), registeredOk (false)
  64563. {
  64564. }
  64565. RelativeCoordinatePositionerBase::~RelativeCoordinatePositionerBase()
  64566. {
  64567. unregisterListeners();
  64568. }
  64569. const Expression RelativeCoordinatePositionerBase::getSymbolValue (const String& objectName, const String& member) const
  64570. {
  64571. jassert (objectName.isNotEmpty());
  64572. if (member.isNotEmpty())
  64573. {
  64574. const Component* comp = getSourceComponent (objectName);
  64575. if (comp == 0)
  64576. {
  64577. if (objectName == RelativeCoordinate::Strings::parent)
  64578. comp = getComponent().getParentComponent();
  64579. else if (objectName == RelativeCoordinate::Strings::this_ || objectName == getComponent().getComponentID())
  64580. comp = &getComponent();
  64581. }
  64582. if (comp != 0)
  64583. {
  64584. if (member == RelativeCoordinate::Strings::left) return xToExpression (comp, 0);
  64585. if (member == RelativeCoordinate::Strings::right) return xToExpression (comp, comp->getWidth());
  64586. if (member == RelativeCoordinate::Strings::top) return yToExpression (comp, 0);
  64587. if (member == RelativeCoordinate::Strings::bottom) return yToExpression (comp, comp->getHeight());
  64588. }
  64589. }
  64590. for (int i = sourceMarkerLists.size(); --i >= 0;)
  64591. {
  64592. MarkerList* const markerList = sourceMarkerLists.getUnchecked(i);
  64593. const MarkerList::Marker* const marker = markerList->getMarker (objectName);
  64594. if (marker != 0)
  64595. return Expression (markerList->getMarkerPosition (*marker, getComponent().getParentComponent()));
  64596. }
  64597. return Expression::EvaluationContext::getSymbolValue (objectName, member);
  64598. }
  64599. void RelativeCoordinatePositionerBase::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  64600. {
  64601. apply();
  64602. }
  64603. void RelativeCoordinatePositionerBase::componentParentHierarchyChanged (Component&)
  64604. {
  64605. apply();
  64606. }
  64607. void RelativeCoordinatePositionerBase::componentBeingDeleted (Component& component)
  64608. {
  64609. jassert (sourceComponents.contains (&component));
  64610. sourceComponents.removeValue (&component);
  64611. }
  64612. void RelativeCoordinatePositionerBase::markersChanged (MarkerList*)
  64613. {
  64614. apply();
  64615. }
  64616. void RelativeCoordinatePositionerBase::markerListBeingDeleted (MarkerList* markerList)
  64617. {
  64618. jassert (sourceMarkerLists.contains (markerList));
  64619. sourceMarkerLists.removeValue (markerList);
  64620. }
  64621. void RelativeCoordinatePositionerBase::apply()
  64622. {
  64623. if (! registeredOk)
  64624. {
  64625. unregisterListeners();
  64626. registeredOk = registerCoordinates();
  64627. }
  64628. applyToComponentBounds();
  64629. }
  64630. bool RelativeCoordinatePositionerBase::addCoordinate (const RelativeCoordinate& coord)
  64631. {
  64632. return registerListeners (coord.getExpression());
  64633. }
  64634. bool RelativeCoordinatePositionerBase::addPoint (const RelativePoint& point)
  64635. {
  64636. const bool ok = addCoordinate (point.x);
  64637. return addCoordinate (point.y) && ok;
  64638. }
  64639. bool RelativeCoordinatePositionerBase::registerListeners (const Expression& e)
  64640. {
  64641. bool ok = true;
  64642. if (e.getType() == Expression::symbolType)
  64643. {
  64644. String objectName, memberName;
  64645. e.getSymbolParts (objectName, memberName);
  64646. if (memberName.isNotEmpty())
  64647. ok = registerComponent (objectName) && ok;
  64648. else
  64649. ok = registerMarker (objectName) && ok;
  64650. }
  64651. else
  64652. {
  64653. for (int i = e.getNumInputs(); --i >= 0;)
  64654. ok = registerListeners (e.getInput (i)) && ok;
  64655. }
  64656. return ok;
  64657. }
  64658. bool RelativeCoordinatePositionerBase::registerComponent (const String& componentID)
  64659. {
  64660. Component* comp = findComponent (componentID);
  64661. if (comp == 0)
  64662. {
  64663. if (componentID == RelativeCoordinate::Strings::parent)
  64664. comp = getComponent().getParentComponent();
  64665. else if (componentID == RelativeCoordinate::Strings::this_ || componentID == getComponent().getComponentID())
  64666. comp = &getComponent();
  64667. }
  64668. if (comp != 0)
  64669. {
  64670. if (comp != &getComponent())
  64671. registerComponentListener (comp);
  64672. return true;
  64673. }
  64674. else
  64675. {
  64676. // The component we want doesn't exist, so watch the parent in case the hierarchy changes and it appears later..
  64677. Component* const parent = getComponent().getParentComponent();
  64678. if (parent != 0)
  64679. registerComponentListener (parent);
  64680. else
  64681. registerComponentListener (&getComponent());
  64682. return false;
  64683. }
  64684. }
  64685. bool RelativeCoordinatePositionerBase::registerMarker (const String markerName)
  64686. {
  64687. Component* const parent = getComponent().getParentComponent();
  64688. if (parent != 0)
  64689. {
  64690. MarkerList* list = parent->getMarkers (true);
  64691. if (list == 0 || list->getMarker (markerName) == 0)
  64692. list = parent->getMarkers (false);
  64693. if (list != 0 && list->getMarker (markerName) != 0)
  64694. {
  64695. registerMarkerListListener (list);
  64696. return true;
  64697. }
  64698. else
  64699. {
  64700. // The marker we want doesn't exist, so watch all lists in case they change and the marker appears later..
  64701. registerMarkerListListener (parent->getMarkers (true));
  64702. registerMarkerListListener (parent->getMarkers (false));
  64703. }
  64704. }
  64705. return false;
  64706. }
  64707. void RelativeCoordinatePositionerBase::registerComponentListener (Component* const comp)
  64708. {
  64709. if (comp != 0 && ! sourceComponents.contains (comp))
  64710. {
  64711. comp->addComponentListener (this);
  64712. sourceComponents.add (comp);
  64713. }
  64714. }
  64715. void RelativeCoordinatePositionerBase::registerMarkerListListener (MarkerList* const list)
  64716. {
  64717. if (list != 0 && ! sourceMarkerLists.contains (list))
  64718. {
  64719. list->addListener (this);
  64720. sourceMarkerLists.add (list);
  64721. }
  64722. }
  64723. void RelativeCoordinatePositionerBase::unregisterListeners()
  64724. {
  64725. int i;
  64726. for (i = sourceComponents.size(); --i >= 0;)
  64727. sourceComponents.getUnchecked(i)->removeComponentListener (this);
  64728. for (i = sourceMarkerLists.size(); --i >= 0;)
  64729. sourceMarkerLists.getUnchecked(i)->removeListener (this);
  64730. sourceComponents.clear();
  64731. sourceMarkerLists.clear();
  64732. }
  64733. Component* RelativeCoordinatePositionerBase::findComponent (const String& componentID) const
  64734. {
  64735. Component* const parent = getComponent().getParentComponent();
  64736. if (parent != 0)
  64737. {
  64738. for (int i = parent->getNumChildComponents(); --i >= 0;)
  64739. {
  64740. Component* const c = parent->getChildComponent(i);
  64741. if (c->getComponentID() == componentID)
  64742. return c;
  64743. }
  64744. }
  64745. return 0;
  64746. }
  64747. Component* RelativeCoordinatePositionerBase::getSourceComponent (const String& objectName) const
  64748. {
  64749. for (int i = sourceComponents.size(); --i >= 0;)
  64750. {
  64751. Component* const comp = sourceComponents.getUnchecked(i);
  64752. if (comp->getComponentID() == objectName)
  64753. return comp;
  64754. }
  64755. return 0;
  64756. }
  64757. const Expression RelativeCoordinatePositionerBase::xToExpression (const Component* const source, const int x) const
  64758. {
  64759. return Expression ((double) (getComponent().getLocalPoint (source, Point<int> (x, 0)).getX() + getComponent().getX()));
  64760. }
  64761. const Expression RelativeCoordinatePositionerBase::yToExpression (const Component* const source, const int y) const
  64762. {
  64763. return Expression ((double) (getComponent().getLocalPoint (source, Point<int> (0, y)).getY() + getComponent().getY()));
  64764. }
  64765. END_JUCE_NAMESPACE
  64766. /*** End of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64767. #endif
  64768. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64769. /*** Start of inlined file: juce_Colour.cpp ***/
  64770. BEGIN_JUCE_NAMESPACE
  64771. namespace ColourHelpers
  64772. {
  64773. uint8 floatAlphaToInt (const float alpha) throw()
  64774. {
  64775. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64776. }
  64777. void convertHSBtoRGB (float h, float s, float v,
  64778. uint8& r, uint8& g, uint8& b) throw()
  64779. {
  64780. v = jlimit (0.0f, 1.0f, v);
  64781. v *= 255.0f;
  64782. const uint8 intV = (uint8) roundToInt (v);
  64783. if (s <= 0)
  64784. {
  64785. r = intV;
  64786. g = intV;
  64787. b = intV;
  64788. }
  64789. else
  64790. {
  64791. s = jmin (1.0f, s);
  64792. h = jlimit (0.0f, 1.0f, h);
  64793. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64794. const float f = h - std::floor (h);
  64795. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64796. const float y = v * (1.0f - s * f);
  64797. const float z = v * (1.0f - (s * (1.0f - f)));
  64798. if (h < 1.0f)
  64799. {
  64800. r = intV;
  64801. g = (uint8) roundToInt (z);
  64802. b = x;
  64803. }
  64804. else if (h < 2.0f)
  64805. {
  64806. r = (uint8) roundToInt (y);
  64807. g = intV;
  64808. b = x;
  64809. }
  64810. else if (h < 3.0f)
  64811. {
  64812. r = x;
  64813. g = intV;
  64814. b = (uint8) roundToInt (z);
  64815. }
  64816. else if (h < 4.0f)
  64817. {
  64818. r = x;
  64819. g = (uint8) roundToInt (y);
  64820. b = intV;
  64821. }
  64822. else if (h < 5.0f)
  64823. {
  64824. r = (uint8) roundToInt (z);
  64825. g = x;
  64826. b = intV;
  64827. }
  64828. else if (h < 6.0f)
  64829. {
  64830. r = intV;
  64831. g = x;
  64832. b = (uint8) roundToInt (y);
  64833. }
  64834. else
  64835. {
  64836. r = 0;
  64837. g = 0;
  64838. b = 0;
  64839. }
  64840. }
  64841. }
  64842. }
  64843. Colour::Colour() throw()
  64844. : argb (0)
  64845. {
  64846. }
  64847. Colour::Colour (const Colour& other) throw()
  64848. : argb (other.argb)
  64849. {
  64850. }
  64851. Colour& Colour::operator= (const Colour& other) throw()
  64852. {
  64853. argb = other.argb;
  64854. return *this;
  64855. }
  64856. bool Colour::operator== (const Colour& other) const throw()
  64857. {
  64858. return argb.getARGB() == other.argb.getARGB();
  64859. }
  64860. bool Colour::operator!= (const Colour& other) const throw()
  64861. {
  64862. return argb.getARGB() != other.argb.getARGB();
  64863. }
  64864. Colour::Colour (const uint32 argb_) throw()
  64865. : argb (argb_)
  64866. {
  64867. }
  64868. Colour::Colour (const uint8 red,
  64869. const uint8 green,
  64870. const uint8 blue) throw()
  64871. {
  64872. argb.setARGB (0xff, red, green, blue);
  64873. }
  64874. const Colour Colour::fromRGB (const uint8 red,
  64875. const uint8 green,
  64876. const uint8 blue) throw()
  64877. {
  64878. return Colour (red, green, blue);
  64879. }
  64880. Colour::Colour (const uint8 red,
  64881. const uint8 green,
  64882. const uint8 blue,
  64883. const uint8 alpha) throw()
  64884. {
  64885. argb.setARGB (alpha, red, green, blue);
  64886. }
  64887. const Colour Colour::fromRGBA (const uint8 red,
  64888. const uint8 green,
  64889. const uint8 blue,
  64890. const uint8 alpha) throw()
  64891. {
  64892. return Colour (red, green, blue, alpha);
  64893. }
  64894. Colour::Colour (const uint8 red,
  64895. const uint8 green,
  64896. const uint8 blue,
  64897. const float alpha) throw()
  64898. {
  64899. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64900. }
  64901. const Colour Colour::fromRGBAFloat (const uint8 red,
  64902. const uint8 green,
  64903. const uint8 blue,
  64904. const float alpha) throw()
  64905. {
  64906. return Colour (red, green, blue, alpha);
  64907. }
  64908. Colour::Colour (const float hue,
  64909. const float saturation,
  64910. const float brightness,
  64911. const float alpha) throw()
  64912. {
  64913. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64914. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64915. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64916. }
  64917. const Colour Colour::fromHSV (const float hue,
  64918. const float saturation,
  64919. const float brightness,
  64920. const float alpha) throw()
  64921. {
  64922. return Colour (hue, saturation, brightness, alpha);
  64923. }
  64924. Colour::Colour (const float hue,
  64925. const float saturation,
  64926. const float brightness,
  64927. const uint8 alpha) throw()
  64928. {
  64929. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64930. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64931. argb.setARGB (alpha, r, g, b);
  64932. }
  64933. Colour::~Colour() throw()
  64934. {
  64935. }
  64936. const PixelARGB Colour::getPixelARGB() const throw()
  64937. {
  64938. PixelARGB p (argb);
  64939. p.premultiply();
  64940. return p;
  64941. }
  64942. uint32 Colour::getARGB() const throw()
  64943. {
  64944. return argb.getARGB();
  64945. }
  64946. bool Colour::isTransparent() const throw()
  64947. {
  64948. return getAlpha() == 0;
  64949. }
  64950. bool Colour::isOpaque() const throw()
  64951. {
  64952. return getAlpha() == 0xff;
  64953. }
  64954. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64955. {
  64956. PixelARGB newCol (argb);
  64957. newCol.setAlpha (newAlpha);
  64958. return Colour (newCol.getARGB());
  64959. }
  64960. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64961. {
  64962. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64963. PixelARGB newCol (argb);
  64964. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64965. return Colour (newCol.getARGB());
  64966. }
  64967. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64968. {
  64969. jassert (alphaMultiplier >= 0);
  64970. PixelARGB newCol (argb);
  64971. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64972. return Colour (newCol.getARGB());
  64973. }
  64974. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64975. {
  64976. const int destAlpha = getAlpha();
  64977. if (destAlpha > 0)
  64978. {
  64979. const int invA = 0xff - (int) src.getAlpha();
  64980. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64981. if (resA > 0)
  64982. {
  64983. const int da = (invA * destAlpha) / resA;
  64984. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64985. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64986. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64987. (uint8) resA);
  64988. }
  64989. return *this;
  64990. }
  64991. else
  64992. {
  64993. return src;
  64994. }
  64995. }
  64996. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64997. {
  64998. if (proportionOfOther <= 0)
  64999. return *this;
  65000. if (proportionOfOther >= 1.0f)
  65001. return other;
  65002. PixelARGB c1 (getPixelARGB());
  65003. const PixelARGB c2 (other.getPixelARGB());
  65004. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65005. c1.unpremultiply();
  65006. return Colour (c1.getARGB());
  65007. }
  65008. float Colour::getFloatRed() const throw()
  65009. {
  65010. return getRed() / 255.0f;
  65011. }
  65012. float Colour::getFloatGreen() const throw()
  65013. {
  65014. return getGreen() / 255.0f;
  65015. }
  65016. float Colour::getFloatBlue() const throw()
  65017. {
  65018. return getBlue() / 255.0f;
  65019. }
  65020. float Colour::getFloatAlpha() const throw()
  65021. {
  65022. return getAlpha() / 255.0f;
  65023. }
  65024. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65025. {
  65026. const int r = getRed();
  65027. const int g = getGreen();
  65028. const int b = getBlue();
  65029. const int hi = jmax (r, g, b);
  65030. const int lo = jmin (r, g, b);
  65031. if (hi != 0)
  65032. {
  65033. s = (hi - lo) / (float) hi;
  65034. if (s != 0)
  65035. {
  65036. const float invDiff = 1.0f / (hi - lo);
  65037. const float red = (hi - r) * invDiff;
  65038. const float green = (hi - g) * invDiff;
  65039. const float blue = (hi - b) * invDiff;
  65040. if (r == hi)
  65041. h = blue - green;
  65042. else if (g == hi)
  65043. h = 2.0f + red - blue;
  65044. else
  65045. h = 4.0f + green - red;
  65046. h *= 1.0f / 6.0f;
  65047. if (h < 0)
  65048. ++h;
  65049. }
  65050. else
  65051. {
  65052. h = 0;
  65053. }
  65054. }
  65055. else
  65056. {
  65057. s = 0;
  65058. h = 0;
  65059. }
  65060. v = hi / 255.0f;
  65061. }
  65062. float Colour::getHue() const throw()
  65063. {
  65064. float h, s, b;
  65065. getHSB (h, s, b);
  65066. return h;
  65067. }
  65068. const Colour Colour::withHue (const float hue) const throw()
  65069. {
  65070. float h, s, b;
  65071. getHSB (h, s, b);
  65072. return Colour (hue, s, b, getAlpha());
  65073. }
  65074. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65075. {
  65076. float h, s, b;
  65077. getHSB (h, s, b);
  65078. h += amountToRotate;
  65079. h -= std::floor (h);
  65080. return Colour (h, s, b, getAlpha());
  65081. }
  65082. float Colour::getSaturation() const throw()
  65083. {
  65084. float h, s, b;
  65085. getHSB (h, s, b);
  65086. return s;
  65087. }
  65088. const Colour Colour::withSaturation (const float saturation) const throw()
  65089. {
  65090. float h, s, b;
  65091. getHSB (h, s, b);
  65092. return Colour (h, saturation, b, getAlpha());
  65093. }
  65094. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65095. {
  65096. float h, s, b;
  65097. getHSB (h, s, b);
  65098. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65099. }
  65100. float Colour::getBrightness() const throw()
  65101. {
  65102. float h, s, b;
  65103. getHSB (h, s, b);
  65104. return b;
  65105. }
  65106. const Colour Colour::withBrightness (const float brightness) const throw()
  65107. {
  65108. float h, s, b;
  65109. getHSB (h, s, b);
  65110. return Colour (h, s, brightness, getAlpha());
  65111. }
  65112. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65113. {
  65114. float h, s, b;
  65115. getHSB (h, s, b);
  65116. b *= amount;
  65117. if (b > 1.0f)
  65118. b = 1.0f;
  65119. return Colour (h, s, b, getAlpha());
  65120. }
  65121. const Colour Colour::brighter (float amount) const throw()
  65122. {
  65123. amount = 1.0f / (1.0f + amount);
  65124. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65125. (uint8) (255 - (amount * (255 - getGreen()))),
  65126. (uint8) (255 - (amount * (255 - getBlue()))),
  65127. getAlpha());
  65128. }
  65129. const Colour Colour::darker (float amount) const throw()
  65130. {
  65131. amount = 1.0f / (1.0f + amount);
  65132. return Colour ((uint8) (amount * getRed()),
  65133. (uint8) (amount * getGreen()),
  65134. (uint8) (amount * getBlue()),
  65135. getAlpha());
  65136. }
  65137. const Colour Colour::greyLevel (const float brightness) throw()
  65138. {
  65139. const uint8 level
  65140. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65141. return Colour (level, level, level);
  65142. }
  65143. const Colour Colour::contrasting (const float amount) const throw()
  65144. {
  65145. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65146. ? Colours::black
  65147. : Colours::white).withAlpha (amount));
  65148. }
  65149. const Colour Colour::contrasting (const Colour& colour1,
  65150. const Colour& colour2) throw()
  65151. {
  65152. const float b1 = colour1.getBrightness();
  65153. const float b2 = colour2.getBrightness();
  65154. float best = 0.0f;
  65155. float bestDist = 0.0f;
  65156. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65157. {
  65158. const float d1 = std::abs (i - b1);
  65159. const float d2 = std::abs (i - b2);
  65160. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65161. if (dist > bestDist)
  65162. {
  65163. best = i;
  65164. bestDist = dist;
  65165. }
  65166. }
  65167. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65168. .withBrightness (best);
  65169. }
  65170. const String Colour::toString() const
  65171. {
  65172. return String::toHexString ((int) argb.getARGB());
  65173. }
  65174. const Colour Colour::fromString (const String& encodedColourString)
  65175. {
  65176. return Colour ((uint32) encodedColourString.getHexValue32());
  65177. }
  65178. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65179. {
  65180. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65181. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65182. .toUpperCase();
  65183. }
  65184. END_JUCE_NAMESPACE
  65185. /*** End of inlined file: juce_Colour.cpp ***/
  65186. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65187. BEGIN_JUCE_NAMESPACE
  65188. ColourGradient::ColourGradient() throw()
  65189. {
  65190. #if JUCE_DEBUG
  65191. point1.setX (987654.0f);
  65192. #endif
  65193. }
  65194. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65195. const Colour& colour2, const float x2_, const float y2_,
  65196. const bool isRadial_)
  65197. : point1 (x1_, y1_),
  65198. point2 (x2_, y2_),
  65199. isRadial (isRadial_)
  65200. {
  65201. colours.add (ColourPoint (0.0, colour1));
  65202. colours.add (ColourPoint (1.0, colour2));
  65203. }
  65204. ColourGradient::~ColourGradient()
  65205. {
  65206. }
  65207. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65208. {
  65209. return point1 == other.point1 && point2 == other.point2
  65210. && isRadial == other.isRadial
  65211. && colours == other.colours;
  65212. }
  65213. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65214. {
  65215. return ! operator== (other);
  65216. }
  65217. void ColourGradient::clearColours()
  65218. {
  65219. colours.clear();
  65220. }
  65221. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65222. {
  65223. // must be within the two end-points
  65224. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65225. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65226. int i;
  65227. for (i = 0; i < colours.size(); ++i)
  65228. if (colours.getReference(i).position > pos)
  65229. break;
  65230. colours.insert (i, ColourPoint (pos, colour));
  65231. return i;
  65232. }
  65233. void ColourGradient::removeColour (int index)
  65234. {
  65235. jassert (index > 0 && index < colours.size() - 1);
  65236. colours.remove (index);
  65237. }
  65238. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65239. {
  65240. for (int i = 0; i < colours.size(); ++i)
  65241. {
  65242. Colour& c = colours.getReference(i).colour;
  65243. c = c.withMultipliedAlpha (multiplier);
  65244. }
  65245. }
  65246. int ColourGradient::getNumColours() const throw()
  65247. {
  65248. return colours.size();
  65249. }
  65250. double ColourGradient::getColourPosition (const int index) const throw()
  65251. {
  65252. if (isPositiveAndBelow (index, colours.size()))
  65253. return colours.getReference (index).position;
  65254. return 0;
  65255. }
  65256. const Colour ColourGradient::getColour (const int index) const throw()
  65257. {
  65258. if (isPositiveAndBelow (index, colours.size()))
  65259. return colours.getReference (index).colour;
  65260. return Colour();
  65261. }
  65262. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65263. {
  65264. if (isPositiveAndBelow (index, colours.size()))
  65265. colours.getReference (index).colour = newColour;
  65266. }
  65267. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65268. {
  65269. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65270. if (position <= 0 || colours.size() <= 1)
  65271. return colours.getReference(0).colour;
  65272. int i = colours.size() - 1;
  65273. while (position < colours.getReference(i).position)
  65274. --i;
  65275. const ColourPoint& p1 = colours.getReference (i);
  65276. if (i >= colours.size() - 1)
  65277. return p1.colour;
  65278. const ColourPoint& p2 = colours.getReference (i + 1);
  65279. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65280. }
  65281. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65282. {
  65283. #if JUCE_DEBUG
  65284. // trying to use the object without setting its co-ordinates? Have a careful read of
  65285. // the comments for the constructors.
  65286. jassert (point1.getX() != 987654.0f);
  65287. #endif
  65288. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65289. 3 * (int) point1.transformedBy (transform)
  65290. .getDistanceFrom (point2.transformedBy (transform)));
  65291. lookupTable.malloc (numEntries);
  65292. if (colours.size() >= 2)
  65293. {
  65294. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65295. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65296. int index = 0;
  65297. for (int j = 1; j < colours.size(); ++j)
  65298. {
  65299. const ColourPoint& p = colours.getReference (j);
  65300. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65301. const PixelARGB pix2 (p.colour.getPixelARGB());
  65302. for (int i = 0; i < numToDo; ++i)
  65303. {
  65304. jassert (index >= 0 && index < numEntries);
  65305. lookupTable[index] = pix1;
  65306. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65307. ++index;
  65308. }
  65309. pix1 = pix2;
  65310. }
  65311. while (index < numEntries)
  65312. lookupTable [index++] = pix1;
  65313. }
  65314. else
  65315. {
  65316. jassertfalse; // no colours specified!
  65317. }
  65318. return numEntries;
  65319. }
  65320. bool ColourGradient::isOpaque() const throw()
  65321. {
  65322. for (int i = 0; i < colours.size(); ++i)
  65323. if (! colours.getReference(i).colour.isOpaque())
  65324. return false;
  65325. return true;
  65326. }
  65327. bool ColourGradient::isInvisible() const throw()
  65328. {
  65329. for (int i = 0; i < colours.size(); ++i)
  65330. if (! colours.getReference(i).colour.isTransparent())
  65331. return false;
  65332. return true;
  65333. }
  65334. END_JUCE_NAMESPACE
  65335. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65336. /*** Start of inlined file: juce_Colours.cpp ***/
  65337. BEGIN_JUCE_NAMESPACE
  65338. const Colour Colours::transparentBlack (0);
  65339. const Colour Colours::transparentWhite (0x00ffffff);
  65340. const Colour Colours::aliceblue (0xfff0f8ff);
  65341. const Colour Colours::antiquewhite (0xfffaebd7);
  65342. const Colour Colours::aqua (0xff00ffff);
  65343. const Colour Colours::aquamarine (0xff7fffd4);
  65344. const Colour Colours::azure (0xfff0ffff);
  65345. const Colour Colours::beige (0xfff5f5dc);
  65346. const Colour Colours::bisque (0xffffe4c4);
  65347. const Colour Colours::black (0xff000000);
  65348. const Colour Colours::blanchedalmond (0xffffebcd);
  65349. const Colour Colours::blue (0xff0000ff);
  65350. const Colour Colours::blueviolet (0xff8a2be2);
  65351. const Colour Colours::brown (0xffa52a2a);
  65352. const Colour Colours::burlywood (0xffdeb887);
  65353. const Colour Colours::cadetblue (0xff5f9ea0);
  65354. const Colour Colours::chartreuse (0xff7fff00);
  65355. const Colour Colours::chocolate (0xffd2691e);
  65356. const Colour Colours::coral (0xffff7f50);
  65357. const Colour Colours::cornflowerblue (0xff6495ed);
  65358. const Colour Colours::cornsilk (0xfffff8dc);
  65359. const Colour Colours::crimson (0xffdc143c);
  65360. const Colour Colours::cyan (0xff00ffff);
  65361. const Colour Colours::darkblue (0xff00008b);
  65362. const Colour Colours::darkcyan (0xff008b8b);
  65363. const Colour Colours::darkgoldenrod (0xffb8860b);
  65364. const Colour Colours::darkgrey (0xff555555);
  65365. const Colour Colours::darkgreen (0xff006400);
  65366. const Colour Colours::darkkhaki (0xffbdb76b);
  65367. const Colour Colours::darkmagenta (0xff8b008b);
  65368. const Colour Colours::darkolivegreen (0xff556b2f);
  65369. const Colour Colours::darkorange (0xffff8c00);
  65370. const Colour Colours::darkorchid (0xff9932cc);
  65371. const Colour Colours::darkred (0xff8b0000);
  65372. const Colour Colours::darksalmon (0xffe9967a);
  65373. const Colour Colours::darkseagreen (0xff8fbc8f);
  65374. const Colour Colours::darkslateblue (0xff483d8b);
  65375. const Colour Colours::darkslategrey (0xff2f4f4f);
  65376. const Colour Colours::darkturquoise (0xff00ced1);
  65377. const Colour Colours::darkviolet (0xff9400d3);
  65378. const Colour Colours::deeppink (0xffff1493);
  65379. const Colour Colours::deepskyblue (0xff00bfff);
  65380. const Colour Colours::dimgrey (0xff696969);
  65381. const Colour Colours::dodgerblue (0xff1e90ff);
  65382. const Colour Colours::firebrick (0xffb22222);
  65383. const Colour Colours::floralwhite (0xfffffaf0);
  65384. const Colour Colours::forestgreen (0xff228b22);
  65385. const Colour Colours::fuchsia (0xffff00ff);
  65386. const Colour Colours::gainsboro (0xffdcdcdc);
  65387. const Colour Colours::gold (0xffffd700);
  65388. const Colour Colours::goldenrod (0xffdaa520);
  65389. const Colour Colours::grey (0xff808080);
  65390. const Colour Colours::green (0xff008000);
  65391. const Colour Colours::greenyellow (0xffadff2f);
  65392. const Colour Colours::honeydew (0xfff0fff0);
  65393. const Colour Colours::hotpink (0xffff69b4);
  65394. const Colour Colours::indianred (0xffcd5c5c);
  65395. const Colour Colours::indigo (0xff4b0082);
  65396. const Colour Colours::ivory (0xfffffff0);
  65397. const Colour Colours::khaki (0xfff0e68c);
  65398. const Colour Colours::lavender (0xffe6e6fa);
  65399. const Colour Colours::lavenderblush (0xfffff0f5);
  65400. const Colour Colours::lemonchiffon (0xfffffacd);
  65401. const Colour Colours::lightblue (0xffadd8e6);
  65402. const Colour Colours::lightcoral (0xfff08080);
  65403. const Colour Colours::lightcyan (0xffe0ffff);
  65404. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65405. const Colour Colours::lightgreen (0xff90ee90);
  65406. const Colour Colours::lightgrey (0xffd3d3d3);
  65407. const Colour Colours::lightpink (0xffffb6c1);
  65408. const Colour Colours::lightsalmon (0xffffa07a);
  65409. const Colour Colours::lightseagreen (0xff20b2aa);
  65410. const Colour Colours::lightskyblue (0xff87cefa);
  65411. const Colour Colours::lightslategrey (0xff778899);
  65412. const Colour Colours::lightsteelblue (0xffb0c4de);
  65413. const Colour Colours::lightyellow (0xffffffe0);
  65414. const Colour Colours::lime (0xff00ff00);
  65415. const Colour Colours::limegreen (0xff32cd32);
  65416. const Colour Colours::linen (0xfffaf0e6);
  65417. const Colour Colours::magenta (0xffff00ff);
  65418. const Colour Colours::maroon (0xff800000);
  65419. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65420. const Colour Colours::mediumblue (0xff0000cd);
  65421. const Colour Colours::mediumorchid (0xffba55d3);
  65422. const Colour Colours::mediumpurple (0xff9370db);
  65423. const Colour Colours::mediumseagreen (0xff3cb371);
  65424. const Colour Colours::mediumslateblue (0xff7b68ee);
  65425. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65426. const Colour Colours::mediumturquoise (0xff48d1cc);
  65427. const Colour Colours::mediumvioletred (0xffc71585);
  65428. const Colour Colours::midnightblue (0xff191970);
  65429. const Colour Colours::mintcream (0xfff5fffa);
  65430. const Colour Colours::mistyrose (0xffffe4e1);
  65431. const Colour Colours::navajowhite (0xffffdead);
  65432. const Colour Colours::navy (0xff000080);
  65433. const Colour Colours::oldlace (0xfffdf5e6);
  65434. const Colour Colours::olive (0xff808000);
  65435. const Colour Colours::olivedrab (0xff6b8e23);
  65436. const Colour Colours::orange (0xffffa500);
  65437. const Colour Colours::orangered (0xffff4500);
  65438. const Colour Colours::orchid (0xffda70d6);
  65439. const Colour Colours::palegoldenrod (0xffeee8aa);
  65440. const Colour Colours::palegreen (0xff98fb98);
  65441. const Colour Colours::paleturquoise (0xffafeeee);
  65442. const Colour Colours::palevioletred (0xffdb7093);
  65443. const Colour Colours::papayawhip (0xffffefd5);
  65444. const Colour Colours::peachpuff (0xffffdab9);
  65445. const Colour Colours::peru (0xffcd853f);
  65446. const Colour Colours::pink (0xffffc0cb);
  65447. const Colour Colours::plum (0xffdda0dd);
  65448. const Colour Colours::powderblue (0xffb0e0e6);
  65449. const Colour Colours::purple (0xff800080);
  65450. const Colour Colours::red (0xffff0000);
  65451. const Colour Colours::rosybrown (0xffbc8f8f);
  65452. const Colour Colours::royalblue (0xff4169e1);
  65453. const Colour Colours::saddlebrown (0xff8b4513);
  65454. const Colour Colours::salmon (0xfffa8072);
  65455. const Colour Colours::sandybrown (0xfff4a460);
  65456. const Colour Colours::seagreen (0xff2e8b57);
  65457. const Colour Colours::seashell (0xfffff5ee);
  65458. const Colour Colours::sienna (0xffa0522d);
  65459. const Colour Colours::silver (0xffc0c0c0);
  65460. const Colour Colours::skyblue (0xff87ceeb);
  65461. const Colour Colours::slateblue (0xff6a5acd);
  65462. const Colour Colours::slategrey (0xff708090);
  65463. const Colour Colours::snow (0xfffffafa);
  65464. const Colour Colours::springgreen (0xff00ff7f);
  65465. const Colour Colours::steelblue (0xff4682b4);
  65466. const Colour Colours::tan (0xffd2b48c);
  65467. const Colour Colours::teal (0xff008080);
  65468. const Colour Colours::thistle (0xffd8bfd8);
  65469. const Colour Colours::tomato (0xffff6347);
  65470. const Colour Colours::turquoise (0xff40e0d0);
  65471. const Colour Colours::violet (0xffee82ee);
  65472. const Colour Colours::wheat (0xfff5deb3);
  65473. const Colour Colours::white (0xffffffff);
  65474. const Colour Colours::whitesmoke (0xfff5f5f5);
  65475. const Colour Colours::yellow (0xffffff00);
  65476. const Colour Colours::yellowgreen (0xff9acd32);
  65477. const Colour Colours::findColourForName (const String& colourName,
  65478. const Colour& defaultColour)
  65479. {
  65480. static const int presets[] =
  65481. {
  65482. // (first value is the string's hashcode, second is ARGB)
  65483. 0x05978fff, 0xff000000, /* black */
  65484. 0x06bdcc29, 0xffffffff, /* white */
  65485. 0x002e305a, 0xff0000ff, /* blue */
  65486. 0x00308adf, 0xff808080, /* grey */
  65487. 0x05e0cf03, 0xff008000, /* green */
  65488. 0x0001b891, 0xffff0000, /* red */
  65489. 0xd43c6474, 0xffffff00, /* yellow */
  65490. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65491. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65492. 0x002dcebc, 0xff00ffff, /* aqua */
  65493. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65494. 0x0590228f, 0xfff0ffff, /* azure */
  65495. 0x05947fe4, 0xfff5f5dc, /* beige */
  65496. 0xad388e35, 0xffffe4c4, /* bisque */
  65497. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65498. 0x39129959, 0xff8a2be2, /* blueviolet */
  65499. 0x059a8136, 0xffa52a2a, /* brown */
  65500. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65501. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65502. 0x6b748956, 0xff7fff00, /* chartreuse */
  65503. 0x2903623c, 0xffd2691e, /* chocolate */
  65504. 0x05a74431, 0xffff7f50, /* coral */
  65505. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65506. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65507. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65508. 0x002ed323, 0xff00ffff, /* cyan */
  65509. 0x67cc74d0, 0xff00008b, /* darkblue */
  65510. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65511. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65512. 0x67cecf55, 0xff555555, /* darkgrey */
  65513. 0x920b194d, 0xff006400, /* darkgreen */
  65514. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65515. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65516. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65517. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65518. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65519. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65520. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65521. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65522. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65523. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65524. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65525. 0xc8769375, 0xff9400d3, /* darkviolet */
  65526. 0x25832862, 0xffff1493, /* deeppink */
  65527. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65528. 0x634c8b67, 0xff696969, /* dimgrey */
  65529. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65530. 0xef19e3cb, 0xffb22222, /* firebrick */
  65531. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65532. 0xd086fd06, 0xff228b22, /* forestgreen */
  65533. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65534. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65535. 0x00308060, 0xffffd700, /* gold */
  65536. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65537. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65538. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65539. 0x41892743, 0xffff69b4, /* hotpink */
  65540. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65541. 0xb969fed2, 0xff4b0082, /* indigo */
  65542. 0x05fef6a9, 0xfffffff0, /* ivory */
  65543. 0x06149302, 0xfff0e68c, /* khaki */
  65544. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65545. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65546. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65547. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65548. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65549. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65550. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65551. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65552. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65553. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65554. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65555. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65556. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65557. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65558. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65559. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65560. 0x0032afd5, 0xff00ff00, /* lime */
  65561. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65562. 0x06234efa, 0xfffaf0e6, /* linen */
  65563. 0x316858a9, 0xffff00ff, /* magenta */
  65564. 0xbf8ca470, 0xff800000, /* maroon */
  65565. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65566. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65567. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65568. 0x07556b71, 0xff9370db, /* mediumpurple */
  65569. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65570. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65571. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65572. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65573. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65574. 0x168eb32a, 0xff191970, /* midnightblue */
  65575. 0x4306b960, 0xfff5fffa, /* mintcream */
  65576. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65577. 0xe97218a6, 0xffffdead, /* navajowhite */
  65578. 0x00337bb6, 0xff000080, /* navy */
  65579. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65580. 0x064ee1db, 0xff808000, /* olive */
  65581. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65582. 0xc3de262e, 0xffffa500, /* orange */
  65583. 0x58bebba3, 0xffff4500, /* orangered */
  65584. 0xc3def8a3, 0xffda70d6, /* orchid */
  65585. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65586. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65587. 0x74022737, 0xffafeeee, /* paleturquoise */
  65588. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65589. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65590. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65591. 0x003472f8, 0xffcd853f, /* peru */
  65592. 0x00348176, 0xffffc0cb, /* pink */
  65593. 0x00348d94, 0xffdda0dd, /* plum */
  65594. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65595. 0xc5c507bc, 0xff800080, /* purple */
  65596. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65597. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65598. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65599. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65600. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65601. 0x34636c14, 0xff2e8b57, /* seagreen */
  65602. 0x3507fb41, 0xfffff5ee, /* seashell */
  65603. 0xca348772, 0xffa0522d, /* sienna */
  65604. 0xca37d30d, 0xffc0c0c0, /* silver */
  65605. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65606. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65607. 0x44ab37f8, 0xff708090, /* slategrey */
  65608. 0x0035f183, 0xfffffafa, /* snow */
  65609. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65610. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65611. 0x0001bfa1, 0xffd2b48c, /* tan */
  65612. 0x0036425c, 0xff008080, /* teal */
  65613. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65614. 0xcc41600a, 0xffff6347, /* tomato */
  65615. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65616. 0xcf57947f, 0xffee82ee, /* violet */
  65617. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65618. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65619. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65620. };
  65621. const int hash = colourName.trim().toLowerCase().hashCode();
  65622. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65623. if (presets [i] == hash)
  65624. return Colour (presets [i + 1]);
  65625. return defaultColour;
  65626. }
  65627. END_JUCE_NAMESPACE
  65628. /*** End of inlined file: juce_Colours.cpp ***/
  65629. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65630. BEGIN_JUCE_NAMESPACE
  65631. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65632. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65633. const Path& path, const AffineTransform& transform)
  65634. : bounds (bounds_),
  65635. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65636. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65637. needToCheckEmptinesss (true)
  65638. {
  65639. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65640. int* t = table;
  65641. for (int i = bounds.getHeight(); --i >= 0;)
  65642. {
  65643. *t = 0;
  65644. t += lineStrideElements;
  65645. }
  65646. const int topLimit = bounds.getY() << 8;
  65647. const int heightLimit = bounds.getHeight() << 8;
  65648. const int leftLimit = bounds.getX() << 8;
  65649. const int rightLimit = bounds.getRight() << 8;
  65650. PathFlatteningIterator iter (path, transform);
  65651. while (iter.next())
  65652. {
  65653. int y1 = roundToInt (iter.y1 * 256.0f);
  65654. int y2 = roundToInt (iter.y2 * 256.0f);
  65655. if (y1 != y2)
  65656. {
  65657. y1 -= topLimit;
  65658. y2 -= topLimit;
  65659. const int startY = y1;
  65660. int direction = -1;
  65661. if (y1 > y2)
  65662. {
  65663. swapVariables (y1, y2);
  65664. direction = 1;
  65665. }
  65666. if (y1 < 0)
  65667. y1 = 0;
  65668. if (y2 > heightLimit)
  65669. y2 = heightLimit;
  65670. if (y1 < y2)
  65671. {
  65672. const double startX = 256.0f * iter.x1;
  65673. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65674. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65675. do
  65676. {
  65677. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65678. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65679. if (x < leftLimit)
  65680. x = leftLimit;
  65681. else if (x >= rightLimit)
  65682. x = rightLimit - 1;
  65683. addEdgePoint (x, y1 >> 8, direction * step);
  65684. y1 += step;
  65685. }
  65686. while (y1 < y2);
  65687. }
  65688. }
  65689. }
  65690. sanitiseLevels (path.isUsingNonZeroWinding());
  65691. }
  65692. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65693. : bounds (rectangleToAdd),
  65694. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65695. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65696. needToCheckEmptinesss (true)
  65697. {
  65698. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65699. table[0] = 0;
  65700. const int x1 = rectangleToAdd.getX() << 8;
  65701. const int x2 = rectangleToAdd.getRight() << 8;
  65702. int* t = table;
  65703. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65704. {
  65705. t[0] = 2;
  65706. t[1] = x1;
  65707. t[2] = 255;
  65708. t[3] = x2;
  65709. t[4] = 0;
  65710. t += lineStrideElements;
  65711. }
  65712. }
  65713. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65714. : bounds (rectanglesToAdd.getBounds()),
  65715. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65716. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65717. needToCheckEmptinesss (true)
  65718. {
  65719. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65720. int* t = table;
  65721. for (int i = bounds.getHeight(); --i >= 0;)
  65722. {
  65723. *t = 0;
  65724. t += lineStrideElements;
  65725. }
  65726. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65727. {
  65728. const Rectangle<int>* const r = iter.getRectangle();
  65729. const int x1 = r->getX() << 8;
  65730. const int x2 = r->getRight() << 8;
  65731. int y = r->getY() - bounds.getY();
  65732. for (int j = r->getHeight(); --j >= 0;)
  65733. {
  65734. addEdgePoint (x1, y, 255);
  65735. addEdgePoint (x2, y, -255);
  65736. ++y;
  65737. }
  65738. }
  65739. sanitiseLevels (true);
  65740. }
  65741. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65742. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65743. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65744. 2 + (int) rectangleToAdd.getWidth(),
  65745. 2 + (int) rectangleToAdd.getHeight())),
  65746. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65747. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65748. needToCheckEmptinesss (true)
  65749. {
  65750. jassert (! rectangleToAdd.isEmpty());
  65751. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65752. table[0] = 0;
  65753. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65754. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65755. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65756. jassert (y1 < 256);
  65757. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65758. if (x2 <= x1 || y2 <= y1)
  65759. {
  65760. bounds.setHeight (0);
  65761. return;
  65762. }
  65763. int lineY = 0;
  65764. int* t = table;
  65765. if ((y1 >> 8) == (y2 >> 8))
  65766. {
  65767. t[0] = 2;
  65768. t[1] = x1;
  65769. t[2] = y2 - y1;
  65770. t[3] = x2;
  65771. t[4] = 0;
  65772. ++lineY;
  65773. t += lineStrideElements;
  65774. }
  65775. else
  65776. {
  65777. t[0] = 2;
  65778. t[1] = x1;
  65779. t[2] = 255 - (y1 & 255);
  65780. t[3] = x2;
  65781. t[4] = 0;
  65782. ++lineY;
  65783. t += lineStrideElements;
  65784. while (lineY < (y2 >> 8))
  65785. {
  65786. t[0] = 2;
  65787. t[1] = x1;
  65788. t[2] = 255;
  65789. t[3] = x2;
  65790. t[4] = 0;
  65791. ++lineY;
  65792. t += lineStrideElements;
  65793. }
  65794. jassert (lineY < bounds.getHeight());
  65795. t[0] = 2;
  65796. t[1] = x1;
  65797. t[2] = y2 & 255;
  65798. t[3] = x2;
  65799. t[4] = 0;
  65800. ++lineY;
  65801. t += lineStrideElements;
  65802. }
  65803. while (lineY < bounds.getHeight())
  65804. {
  65805. t[0] = 0;
  65806. t += lineStrideElements;
  65807. ++lineY;
  65808. }
  65809. }
  65810. EdgeTable::EdgeTable (const EdgeTable& other)
  65811. {
  65812. operator= (other);
  65813. }
  65814. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65815. {
  65816. bounds = other.bounds;
  65817. maxEdgesPerLine = other.maxEdgesPerLine;
  65818. lineStrideElements = other.lineStrideElements;
  65819. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65820. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65821. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65822. return *this;
  65823. }
  65824. EdgeTable::~EdgeTable()
  65825. {
  65826. }
  65827. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65828. {
  65829. while (--numLines >= 0)
  65830. {
  65831. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65832. src += srcLineStride;
  65833. dest += destLineStride;
  65834. }
  65835. }
  65836. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65837. {
  65838. // Convert the table from relative windings to absolute levels..
  65839. int* lineStart = table;
  65840. for (int i = bounds.getHeight(); --i >= 0;)
  65841. {
  65842. int* line = lineStart;
  65843. lineStart += lineStrideElements;
  65844. int num = *line;
  65845. if (num == 0)
  65846. continue;
  65847. int level = 0;
  65848. if (useNonZeroWinding)
  65849. {
  65850. while (--num > 0)
  65851. {
  65852. line += 2;
  65853. level += *line;
  65854. int corrected = abs (level);
  65855. if (corrected >> 8)
  65856. corrected = 255;
  65857. *line = corrected;
  65858. }
  65859. }
  65860. else
  65861. {
  65862. while (--num > 0)
  65863. {
  65864. line += 2;
  65865. level += *line;
  65866. int corrected = abs (level);
  65867. if (corrected >> 8)
  65868. {
  65869. corrected &= 511;
  65870. if (corrected >> 8)
  65871. corrected = 511 - corrected;
  65872. }
  65873. *line = corrected;
  65874. }
  65875. }
  65876. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65877. }
  65878. }
  65879. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  65880. {
  65881. if (newNumEdgesPerLine != maxEdgesPerLine)
  65882. {
  65883. maxEdgesPerLine = newNumEdgesPerLine;
  65884. jassert (bounds.getHeight() > 0);
  65885. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65886. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65887. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65888. table.swapWith (newTable);
  65889. lineStrideElements = newLineStrideElements;
  65890. }
  65891. }
  65892. void EdgeTable::optimiseTable()
  65893. {
  65894. int maxLineElements = 0;
  65895. for (int i = bounds.getHeight(); --i >= 0;)
  65896. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65897. remapTableForNumEdges (maxLineElements);
  65898. }
  65899. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  65900. {
  65901. jassert (y >= 0 && y < bounds.getHeight());
  65902. int* line = table + lineStrideElements * y;
  65903. const int numPoints = line[0];
  65904. int n = numPoints << 1;
  65905. if (n > 0)
  65906. {
  65907. while (n > 0)
  65908. {
  65909. const int cx = line [n - 1];
  65910. if (cx <= x)
  65911. {
  65912. if (cx == x)
  65913. {
  65914. line [n] += winding;
  65915. return;
  65916. }
  65917. break;
  65918. }
  65919. n -= 2;
  65920. }
  65921. if (numPoints >= maxEdgesPerLine)
  65922. {
  65923. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65924. jassert (numPoints < maxEdgesPerLine);
  65925. line = table + lineStrideElements * y;
  65926. }
  65927. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65928. }
  65929. line [n + 1] = x;
  65930. line [n + 2] = winding;
  65931. line[0]++;
  65932. }
  65933. void EdgeTable::translate (float dx, const int dy) throw()
  65934. {
  65935. bounds.translate ((int) std::floor (dx), dy);
  65936. int* lineStart = table;
  65937. const int intDx = (int) (dx * 256.0f);
  65938. for (int i = bounds.getHeight(); --i >= 0;)
  65939. {
  65940. int* line = lineStart;
  65941. lineStart += lineStrideElements;
  65942. int num = *line++;
  65943. while (--num >= 0)
  65944. {
  65945. *line += intDx;
  65946. line += 2;
  65947. }
  65948. }
  65949. }
  65950. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  65951. {
  65952. jassert (y >= 0 && y < bounds.getHeight());
  65953. int* dest = table + lineStrideElements * y;
  65954. if (dest[0] == 0)
  65955. return;
  65956. int otherNumPoints = *otherLine;
  65957. if (otherNumPoints == 0)
  65958. {
  65959. *dest = 0;
  65960. return;
  65961. }
  65962. const int right = bounds.getRight() << 8;
  65963. // optimise for the common case where our line lies entirely within a
  65964. // single pair of points, as happens when clipping to a simple rect.
  65965. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65966. {
  65967. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65968. return;
  65969. }
  65970. ++otherLine;
  65971. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65972. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65973. memcpy (temp, dest, lineSizeBytes);
  65974. const int* src1 = temp;
  65975. int srcNum1 = *src1++;
  65976. int x1 = *src1++;
  65977. const int* src2 = otherLine;
  65978. int srcNum2 = otherNumPoints;
  65979. int x2 = *src2++;
  65980. int destIndex = 0, destTotal = 0;
  65981. int level1 = 0, level2 = 0;
  65982. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65983. while (srcNum1 > 0 && srcNum2 > 0)
  65984. {
  65985. int nextX;
  65986. if (x1 < x2)
  65987. {
  65988. nextX = x1;
  65989. level1 = *src1++;
  65990. x1 = *src1++;
  65991. --srcNum1;
  65992. }
  65993. else if (x1 == x2)
  65994. {
  65995. nextX = x1;
  65996. level1 = *src1++;
  65997. level2 = *src2++;
  65998. x1 = *src1++;
  65999. x2 = *src2++;
  66000. --srcNum1;
  66001. --srcNum2;
  66002. }
  66003. else
  66004. {
  66005. nextX = x2;
  66006. level2 = *src2++;
  66007. x2 = *src2++;
  66008. --srcNum2;
  66009. }
  66010. if (nextX > lastX)
  66011. {
  66012. if (nextX >= right)
  66013. break;
  66014. lastX = nextX;
  66015. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66016. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  66017. if (nextLevel != lastLevel)
  66018. {
  66019. if (destTotal >= maxEdgesPerLine)
  66020. {
  66021. dest[0] = destTotal;
  66022. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66023. dest = table + lineStrideElements * y;
  66024. }
  66025. ++destTotal;
  66026. lastLevel = nextLevel;
  66027. dest[++destIndex] = nextX;
  66028. dest[++destIndex] = nextLevel;
  66029. }
  66030. }
  66031. }
  66032. if (lastLevel > 0)
  66033. {
  66034. if (destTotal >= maxEdgesPerLine)
  66035. {
  66036. dest[0] = destTotal;
  66037. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66038. dest = table + lineStrideElements * y;
  66039. }
  66040. ++destTotal;
  66041. dest[++destIndex] = right;
  66042. dest[++destIndex] = 0;
  66043. }
  66044. dest[0] = destTotal;
  66045. #if JUCE_DEBUG
  66046. int last = std::numeric_limits<int>::min();
  66047. for (int i = 0; i < dest[0]; ++i)
  66048. {
  66049. jassert (dest[i * 2 + 1] > last);
  66050. last = dest[i * 2 + 1];
  66051. }
  66052. jassert (dest [dest[0] * 2] == 0);
  66053. #endif
  66054. }
  66055. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66056. {
  66057. int* lastItem = dest + (dest[0] * 2 - 1);
  66058. if (x2 < lastItem[0])
  66059. {
  66060. if (x2 <= dest[1])
  66061. {
  66062. dest[0] = 0;
  66063. return;
  66064. }
  66065. while (x2 < lastItem[-2])
  66066. {
  66067. --(dest[0]);
  66068. lastItem -= 2;
  66069. }
  66070. lastItem[0] = x2;
  66071. lastItem[1] = 0;
  66072. }
  66073. if (x1 > dest[1])
  66074. {
  66075. while (lastItem[0] > x1)
  66076. lastItem -= 2;
  66077. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66078. if (itemsRemoved > 0)
  66079. {
  66080. dest[0] -= itemsRemoved;
  66081. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66082. }
  66083. dest[1] = x1;
  66084. }
  66085. }
  66086. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  66087. {
  66088. const Rectangle<int> clipped (r.getIntersection (bounds));
  66089. if (clipped.isEmpty())
  66090. {
  66091. needToCheckEmptinesss = false;
  66092. bounds.setHeight (0);
  66093. }
  66094. else
  66095. {
  66096. const int top = clipped.getY() - bounds.getY();
  66097. const int bottom = clipped.getBottom() - bounds.getY();
  66098. if (bottom < bounds.getHeight())
  66099. bounds.setHeight (bottom);
  66100. if (clipped.getRight() < bounds.getRight())
  66101. bounds.setRight (clipped.getRight());
  66102. for (int i = top; --i >= 0;)
  66103. table [lineStrideElements * i] = 0;
  66104. if (clipped.getX() > bounds.getX())
  66105. {
  66106. const int x1 = clipped.getX() << 8;
  66107. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66108. int* line = table + lineStrideElements * top;
  66109. for (int i = bottom - top; --i >= 0;)
  66110. {
  66111. if (line[0] != 0)
  66112. clipEdgeTableLineToRange (line, x1, x2);
  66113. line += lineStrideElements;
  66114. }
  66115. }
  66116. needToCheckEmptinesss = true;
  66117. }
  66118. }
  66119. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  66120. {
  66121. const Rectangle<int> clipped (r.getIntersection (bounds));
  66122. if (! clipped.isEmpty())
  66123. {
  66124. const int top = clipped.getY() - bounds.getY();
  66125. const int bottom = clipped.getBottom() - bounds.getY();
  66126. //XXX optimise here by shortening the table if it fills top or bottom
  66127. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66128. clipped.getX() << 8, 0,
  66129. clipped.getRight() << 8, 255,
  66130. std::numeric_limits<int>::max(), 0 };
  66131. for (int i = top; i < bottom; ++i)
  66132. intersectWithEdgeTableLine (i, rectLine);
  66133. needToCheckEmptinesss = true;
  66134. }
  66135. }
  66136. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66137. {
  66138. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66139. if (clipped.isEmpty())
  66140. {
  66141. needToCheckEmptinesss = false;
  66142. bounds.setHeight (0);
  66143. }
  66144. else
  66145. {
  66146. const int top = clipped.getY() - bounds.getY();
  66147. const int bottom = clipped.getBottom() - bounds.getY();
  66148. if (bottom < bounds.getHeight())
  66149. bounds.setHeight (bottom);
  66150. if (clipped.getRight() < bounds.getRight())
  66151. bounds.setRight (clipped.getRight());
  66152. int i = 0;
  66153. for (i = top; --i >= 0;)
  66154. table [lineStrideElements * i] = 0;
  66155. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66156. for (i = top; i < bottom; ++i)
  66157. {
  66158. intersectWithEdgeTableLine (i, otherLine);
  66159. otherLine += other.lineStrideElements;
  66160. }
  66161. needToCheckEmptinesss = true;
  66162. }
  66163. }
  66164. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  66165. {
  66166. y -= bounds.getY();
  66167. if (y < 0 || y >= bounds.getHeight())
  66168. return;
  66169. needToCheckEmptinesss = true;
  66170. if (numPixels <= 0)
  66171. {
  66172. table [lineStrideElements * y] = 0;
  66173. return;
  66174. }
  66175. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66176. int destIndex = 0, lastLevel = 0;
  66177. while (--numPixels >= 0)
  66178. {
  66179. const int alpha = *mask;
  66180. mask += maskStride;
  66181. if (alpha != lastLevel)
  66182. {
  66183. tempLine[++destIndex] = (x << 8);
  66184. tempLine[++destIndex] = alpha;
  66185. lastLevel = alpha;
  66186. }
  66187. ++x;
  66188. }
  66189. if (lastLevel > 0)
  66190. {
  66191. tempLine[++destIndex] = (x << 8);
  66192. tempLine[++destIndex] = 0;
  66193. }
  66194. tempLine[0] = destIndex >> 1;
  66195. intersectWithEdgeTableLine (y, tempLine);
  66196. }
  66197. bool EdgeTable::isEmpty() throw()
  66198. {
  66199. if (needToCheckEmptinesss)
  66200. {
  66201. needToCheckEmptinesss = false;
  66202. int* t = table;
  66203. for (int i = bounds.getHeight(); --i >= 0;)
  66204. {
  66205. if (t[0] > 1)
  66206. return false;
  66207. t += lineStrideElements;
  66208. }
  66209. bounds.setHeight (0);
  66210. }
  66211. return bounds.getHeight() == 0;
  66212. }
  66213. END_JUCE_NAMESPACE
  66214. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66215. /*** Start of inlined file: juce_FillType.cpp ***/
  66216. BEGIN_JUCE_NAMESPACE
  66217. FillType::FillType() throw()
  66218. : colour (0xff000000), image (0)
  66219. {
  66220. }
  66221. FillType::FillType (const Colour& colour_) throw()
  66222. : colour (colour_), image (0)
  66223. {
  66224. }
  66225. FillType::FillType (const ColourGradient& gradient_)
  66226. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66227. {
  66228. }
  66229. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66230. : colour (0xff000000), image (image_), transform (transform_)
  66231. {
  66232. }
  66233. FillType::FillType (const FillType& other)
  66234. : colour (other.colour),
  66235. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66236. image (other.image), transform (other.transform)
  66237. {
  66238. }
  66239. FillType& FillType::operator= (const FillType& other)
  66240. {
  66241. if (this != &other)
  66242. {
  66243. colour = other.colour;
  66244. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66245. image = other.image;
  66246. transform = other.transform;
  66247. }
  66248. return *this;
  66249. }
  66250. FillType::~FillType() throw()
  66251. {
  66252. }
  66253. bool FillType::operator== (const FillType& other) const
  66254. {
  66255. return colour == other.colour && image == other.image
  66256. && transform == other.transform
  66257. && (gradient == other.gradient
  66258. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66259. }
  66260. bool FillType::operator!= (const FillType& other) const
  66261. {
  66262. return ! operator== (other);
  66263. }
  66264. void FillType::setColour (const Colour& newColour) throw()
  66265. {
  66266. gradient = 0;
  66267. image = Image::null;
  66268. colour = newColour;
  66269. }
  66270. void FillType::setGradient (const ColourGradient& newGradient)
  66271. {
  66272. if (gradient != 0)
  66273. {
  66274. *gradient = newGradient;
  66275. }
  66276. else
  66277. {
  66278. image = Image::null;
  66279. gradient = new ColourGradient (newGradient);
  66280. colour = Colours::black;
  66281. }
  66282. }
  66283. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66284. {
  66285. gradient = 0;
  66286. image = image_;
  66287. transform = transform_;
  66288. colour = Colours::black;
  66289. }
  66290. void FillType::setOpacity (const float newOpacity) throw()
  66291. {
  66292. colour = colour.withAlpha (newOpacity);
  66293. }
  66294. bool FillType::isInvisible() const throw()
  66295. {
  66296. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66297. }
  66298. END_JUCE_NAMESPACE
  66299. /*** End of inlined file: juce_FillType.cpp ***/
  66300. /*** Start of inlined file: juce_Graphics.cpp ***/
  66301. BEGIN_JUCE_NAMESPACE
  66302. namespace
  66303. {
  66304. template <typename Type>
  66305. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66306. {
  66307. const int maxVal = 0x3fffffff;
  66308. return (int) x >= -maxVal && (int) x <= maxVal
  66309. && (int) y >= -maxVal && (int) y <= maxVal
  66310. && (int) w >= -maxVal && (int) w <= maxVal
  66311. && (int) h >= -maxVal && (int) h <= maxVal;
  66312. }
  66313. }
  66314. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66315. {
  66316. }
  66317. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66318. {
  66319. }
  66320. Graphics::Graphics (const Image& imageToDrawOnto)
  66321. : context (imageToDrawOnto.createLowLevelContext()),
  66322. contextToDelete (context),
  66323. saveStatePending (false)
  66324. {
  66325. }
  66326. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66327. : context (internalContext),
  66328. saveStatePending (false)
  66329. {
  66330. }
  66331. Graphics::~Graphics()
  66332. {
  66333. }
  66334. void Graphics::resetToDefaultState()
  66335. {
  66336. saveStateIfPending();
  66337. context->setFill (FillType());
  66338. context->setFont (Font());
  66339. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66340. }
  66341. bool Graphics::isVectorDevice() const
  66342. {
  66343. return context->isVectorDevice();
  66344. }
  66345. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66346. {
  66347. saveStateIfPending();
  66348. return context->clipToRectangle (area);
  66349. }
  66350. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66351. {
  66352. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66353. }
  66354. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66355. {
  66356. saveStateIfPending();
  66357. return context->clipToRectangleList (clipRegion);
  66358. }
  66359. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66360. {
  66361. saveStateIfPending();
  66362. context->clipToPath (path, transform);
  66363. return ! context->isClipEmpty();
  66364. }
  66365. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66366. {
  66367. saveStateIfPending();
  66368. context->clipToImageAlpha (image, transform);
  66369. return ! context->isClipEmpty();
  66370. }
  66371. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66372. {
  66373. saveStateIfPending();
  66374. context->excludeClipRectangle (rectangleToExclude);
  66375. }
  66376. bool Graphics::isClipEmpty() const
  66377. {
  66378. return context->isClipEmpty();
  66379. }
  66380. const Rectangle<int> Graphics::getClipBounds() const
  66381. {
  66382. return context->getClipBounds();
  66383. }
  66384. void Graphics::saveState()
  66385. {
  66386. saveStateIfPending();
  66387. saveStatePending = true;
  66388. }
  66389. void Graphics::restoreState()
  66390. {
  66391. if (saveStatePending)
  66392. saveStatePending = false;
  66393. else
  66394. context->restoreState();
  66395. }
  66396. void Graphics::saveStateIfPending()
  66397. {
  66398. if (saveStatePending)
  66399. {
  66400. saveStatePending = false;
  66401. context->saveState();
  66402. }
  66403. }
  66404. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66405. {
  66406. saveStateIfPending();
  66407. context->setOrigin (newOriginX, newOriginY);
  66408. }
  66409. void Graphics::addTransform (const AffineTransform& transform)
  66410. {
  66411. saveStateIfPending();
  66412. context->addTransform (transform);
  66413. }
  66414. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66415. {
  66416. return context->clipRegionIntersects (area);
  66417. }
  66418. void Graphics::beginTransparencyLayer (float layerOpacity)
  66419. {
  66420. saveStateIfPending();
  66421. context->beginTransparencyLayer (layerOpacity);
  66422. }
  66423. void Graphics::endTransparencyLayer()
  66424. {
  66425. context->endTransparencyLayer();
  66426. }
  66427. void Graphics::setColour (const Colour& newColour)
  66428. {
  66429. saveStateIfPending();
  66430. context->setFill (newColour);
  66431. }
  66432. void Graphics::setOpacity (const float newOpacity)
  66433. {
  66434. saveStateIfPending();
  66435. context->setOpacity (newOpacity);
  66436. }
  66437. void Graphics::setGradientFill (const ColourGradient& gradient)
  66438. {
  66439. setFillType (gradient);
  66440. }
  66441. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66442. {
  66443. saveStateIfPending();
  66444. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66445. context->setOpacity (opacity);
  66446. }
  66447. void Graphics::setFillType (const FillType& newFill)
  66448. {
  66449. saveStateIfPending();
  66450. context->setFill (newFill);
  66451. }
  66452. void Graphics::setFont (const Font& newFont)
  66453. {
  66454. saveStateIfPending();
  66455. context->setFont (newFont);
  66456. }
  66457. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66458. {
  66459. saveStateIfPending();
  66460. Font f (context->getFont());
  66461. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66462. context->setFont (f);
  66463. }
  66464. const Font Graphics::getCurrentFont() const
  66465. {
  66466. return context->getFont();
  66467. }
  66468. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66469. {
  66470. if (text.isNotEmpty()
  66471. && startX < context->getClipBounds().getRight())
  66472. {
  66473. GlyphArrangement arr;
  66474. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66475. arr.draw (*this);
  66476. }
  66477. }
  66478. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66479. {
  66480. if (text.isNotEmpty())
  66481. {
  66482. GlyphArrangement arr;
  66483. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66484. arr.draw (*this, transform);
  66485. }
  66486. }
  66487. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66488. {
  66489. if (text.isNotEmpty()
  66490. && startX < context->getClipBounds().getRight())
  66491. {
  66492. GlyphArrangement arr;
  66493. arr.addJustifiedText (context->getFont(), text,
  66494. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66495. Justification::left);
  66496. arr.draw (*this);
  66497. }
  66498. }
  66499. void Graphics::drawText (const String& text,
  66500. const int x, const int y, const int width, const int height,
  66501. const Justification& justificationType,
  66502. const bool useEllipsesIfTooBig) const
  66503. {
  66504. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66505. {
  66506. GlyphArrangement arr;
  66507. arr.addCurtailedLineOfText (context->getFont(), text,
  66508. 0.0f, 0.0f, (float) width,
  66509. useEllipsesIfTooBig);
  66510. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66511. (float) x, (float) y, (float) width, (float) height,
  66512. justificationType);
  66513. arr.draw (*this);
  66514. }
  66515. }
  66516. void Graphics::drawFittedText (const String& text,
  66517. const int x, const int y, const int width, const int height,
  66518. const Justification& justification,
  66519. const int maximumNumberOfLines,
  66520. const float minimumHorizontalScale) const
  66521. {
  66522. if (text.isNotEmpty()
  66523. && width > 0 && height > 0
  66524. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66525. {
  66526. GlyphArrangement arr;
  66527. arr.addFittedText (context->getFont(), text,
  66528. (float) x, (float) y, (float) width, (float) height,
  66529. justification,
  66530. maximumNumberOfLines,
  66531. minimumHorizontalScale);
  66532. arr.draw (*this);
  66533. }
  66534. }
  66535. void Graphics::fillRect (int x, int y, int width, int height) const
  66536. {
  66537. // passing in a silly number can cause maths problems in rendering!
  66538. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66539. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66540. }
  66541. void Graphics::fillRect (const Rectangle<int>& r) const
  66542. {
  66543. context->fillRect (r, false);
  66544. }
  66545. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66546. {
  66547. // passing in a silly number can cause maths problems in rendering!
  66548. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66549. Path p;
  66550. p.addRectangle (x, y, width, height);
  66551. fillPath (p);
  66552. }
  66553. void Graphics::setPixel (int x, int y) const
  66554. {
  66555. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66556. }
  66557. void Graphics::fillAll() const
  66558. {
  66559. fillRect (context->getClipBounds());
  66560. }
  66561. void Graphics::fillAll (const Colour& colourToUse) const
  66562. {
  66563. if (! colourToUse.isTransparent())
  66564. {
  66565. const Rectangle<int> clip (context->getClipBounds());
  66566. context->saveState();
  66567. context->setFill (colourToUse);
  66568. context->fillRect (clip, false);
  66569. context->restoreState();
  66570. }
  66571. }
  66572. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66573. {
  66574. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66575. context->fillPath (path, transform);
  66576. }
  66577. void Graphics::strokePath (const Path& path,
  66578. const PathStrokeType& strokeType,
  66579. const AffineTransform& transform) const
  66580. {
  66581. Path stroke;
  66582. strokeType.createStrokedPath (stroke, path, transform, context->getScaleFactor());
  66583. fillPath (stroke);
  66584. }
  66585. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66586. const int lineThickness) const
  66587. {
  66588. // passing in a silly number can cause maths problems in rendering!
  66589. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66590. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66591. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66592. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66593. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66594. }
  66595. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66596. {
  66597. // passing in a silly number can cause maths problems in rendering!
  66598. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66599. Path p;
  66600. p.addRectangle (x, y, width, lineThickness);
  66601. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66602. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66603. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66604. fillPath (p);
  66605. }
  66606. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66607. {
  66608. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66609. }
  66610. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66611. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66612. const bool useGradient, const bool sharpEdgeOnOutside) const
  66613. {
  66614. // passing in a silly number can cause maths problems in rendering!
  66615. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66616. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66617. {
  66618. context->saveState();
  66619. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66620. const float ramp = oldOpacity / bevelThickness;
  66621. for (int i = bevelThickness; --i >= 0;)
  66622. {
  66623. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66624. : oldOpacity;
  66625. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66626. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66627. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66628. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66629. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66630. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66631. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66632. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66633. }
  66634. context->restoreState();
  66635. }
  66636. }
  66637. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66638. {
  66639. // passing in a silly number can cause maths problems in rendering!
  66640. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66641. Path p;
  66642. p.addEllipse (x, y, width, height);
  66643. fillPath (p);
  66644. }
  66645. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66646. const float lineThickness) const
  66647. {
  66648. // passing in a silly number can cause maths problems in rendering!
  66649. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66650. Path p;
  66651. p.addEllipse (x, y, width, height);
  66652. strokePath (p, PathStrokeType (lineThickness));
  66653. }
  66654. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66655. {
  66656. // passing in a silly number can cause maths problems in rendering!
  66657. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66658. Path p;
  66659. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66660. fillPath (p);
  66661. }
  66662. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66663. {
  66664. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66665. }
  66666. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66667. const float cornerSize, const float lineThickness) const
  66668. {
  66669. // passing in a silly number can cause maths problems in rendering!
  66670. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66671. Path p;
  66672. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66673. strokePath (p, PathStrokeType (lineThickness));
  66674. }
  66675. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66676. {
  66677. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66678. }
  66679. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66680. {
  66681. Path p;
  66682. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66683. fillPath (p);
  66684. }
  66685. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66686. const int checkWidth, const int checkHeight,
  66687. const Colour& colour1, const Colour& colour2) const
  66688. {
  66689. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66690. if (checkWidth > 0 && checkHeight > 0)
  66691. {
  66692. context->saveState();
  66693. if (colour1 == colour2)
  66694. {
  66695. context->setFill (colour1);
  66696. context->fillRect (area, false);
  66697. }
  66698. else
  66699. {
  66700. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66701. if (! clipped.isEmpty())
  66702. {
  66703. context->clipToRectangle (clipped);
  66704. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66705. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66706. const int startX = area.getX() + checkNumX * checkWidth;
  66707. const int startY = area.getY() + checkNumY * checkHeight;
  66708. const int right = clipped.getRight();
  66709. const int bottom = clipped.getBottom();
  66710. for (int i = 0; i < 2; ++i)
  66711. {
  66712. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66713. int cy = i;
  66714. for (int y = startY; y < bottom; y += checkHeight)
  66715. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66716. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66717. }
  66718. }
  66719. }
  66720. context->restoreState();
  66721. }
  66722. }
  66723. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66724. {
  66725. context->drawVerticalLine (x, top, bottom);
  66726. }
  66727. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66728. {
  66729. context->drawHorizontalLine (y, left, right);
  66730. }
  66731. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2) const
  66732. {
  66733. context->drawLine (Line<float> (x1, y1, x2, y2));
  66734. }
  66735. void Graphics::drawLine (const Line<float>& line) const
  66736. {
  66737. context->drawLine (line);
  66738. }
  66739. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2, const float lineThickness) const
  66740. {
  66741. drawLine (Line<float> (x1, y1, x2, y2), lineThickness);
  66742. }
  66743. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66744. {
  66745. Path p;
  66746. p.addLineSegment (line, lineThickness);
  66747. fillPath (p);
  66748. }
  66749. void Graphics::drawDashedLine (const Line<float>& line, const float* const dashLengths,
  66750. const int numDashLengths, const float lineThickness, int n) const
  66751. {
  66752. jassert (n >= 0 && n < numDashLengths); // your start index must be valid!
  66753. const Point<double> delta ((line.getEnd() - line.getStart()).toDouble());
  66754. const double totalLen = delta.getDistanceFromOrigin();
  66755. if (totalLen >= 0.1)
  66756. {
  66757. const double onePixAlpha = 1.0 / totalLen;
  66758. for (double alpha = 0.0; alpha < 1.0;)
  66759. {
  66760. jassert (dashLengths[n] > 0); // can't have zero-length dashes!
  66761. const double lastAlpha = alpha;
  66762. alpha = jmin (1.0, alpha + dashLengths [n] * onePixAlpha);
  66763. n = (n + 1) % numDashLengths;
  66764. if ((n & 1) != 0)
  66765. {
  66766. const Line<float> segment (line.getStart() + (delta * lastAlpha).toFloat(),
  66767. line.getStart() + (delta * alpha).toFloat());
  66768. if (lineThickness != 1.0f)
  66769. drawLine (segment, lineThickness);
  66770. else
  66771. context->drawLine (segment);
  66772. }
  66773. }
  66774. }
  66775. }
  66776. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66777. {
  66778. saveStateIfPending();
  66779. context->setInterpolationQuality (newQuality);
  66780. }
  66781. void Graphics::drawImageAt (const Image& imageToDraw,
  66782. const int topLeftX, const int topLeftY,
  66783. const bool fillAlphaChannelWithCurrentBrush) const
  66784. {
  66785. const int imageW = imageToDraw.getWidth();
  66786. const int imageH = imageToDraw.getHeight();
  66787. drawImage (imageToDraw,
  66788. topLeftX, topLeftY, imageW, imageH,
  66789. 0, 0, imageW, imageH,
  66790. fillAlphaChannelWithCurrentBrush);
  66791. }
  66792. void Graphics::drawImageWithin (const Image& imageToDraw,
  66793. const int destX, const int destY,
  66794. const int destW, const int destH,
  66795. const RectanglePlacement& placementWithinTarget,
  66796. const bool fillAlphaChannelWithCurrentBrush) const
  66797. {
  66798. // passing in a silly number can cause maths problems in rendering!
  66799. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66800. if (imageToDraw.isValid())
  66801. {
  66802. const int imageW = imageToDraw.getWidth();
  66803. const int imageH = imageToDraw.getHeight();
  66804. if (imageW > 0 && imageH > 0)
  66805. {
  66806. double newX = 0.0, newY = 0.0;
  66807. double newW = imageW;
  66808. double newH = imageH;
  66809. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66810. destX, destY, destW, destH);
  66811. if (newW > 0 && newH > 0)
  66812. {
  66813. drawImage (imageToDraw,
  66814. roundToInt (newX), roundToInt (newY),
  66815. roundToInt (newW), roundToInt (newH),
  66816. 0, 0, imageW, imageH,
  66817. fillAlphaChannelWithCurrentBrush);
  66818. }
  66819. }
  66820. }
  66821. }
  66822. void Graphics::drawImage (const Image& imageToDraw,
  66823. int dx, int dy, int dw, int dh,
  66824. int sx, int sy, int sw, int sh,
  66825. const bool fillAlphaChannelWithCurrentBrush) const
  66826. {
  66827. // passing in a silly number can cause maths problems in rendering!
  66828. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66829. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66830. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66831. {
  66832. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66833. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66834. .translated ((float) dx, (float) dy),
  66835. fillAlphaChannelWithCurrentBrush);
  66836. }
  66837. }
  66838. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66839. const AffineTransform& transform,
  66840. const bool fillAlphaChannelWithCurrentBrush) const
  66841. {
  66842. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66843. {
  66844. if (fillAlphaChannelWithCurrentBrush)
  66845. {
  66846. context->saveState();
  66847. context->clipToImageAlpha (imageToDraw, transform);
  66848. fillAll();
  66849. context->restoreState();
  66850. }
  66851. else
  66852. {
  66853. context->drawImage (imageToDraw, transform, false);
  66854. }
  66855. }
  66856. }
  66857. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  66858. : context (g)
  66859. {
  66860. context.saveState();
  66861. }
  66862. Graphics::ScopedSaveState::~ScopedSaveState()
  66863. {
  66864. context.restoreState();
  66865. }
  66866. END_JUCE_NAMESPACE
  66867. /*** End of inlined file: juce_Graphics.cpp ***/
  66868. /*** Start of inlined file: juce_Justification.cpp ***/
  66869. BEGIN_JUCE_NAMESPACE
  66870. Justification::Justification (const Justification& other) throw()
  66871. : flags (other.flags)
  66872. {
  66873. }
  66874. Justification& Justification::operator= (const Justification& other) throw()
  66875. {
  66876. flags = other.flags;
  66877. return *this;
  66878. }
  66879. int Justification::getOnlyVerticalFlags() const throw()
  66880. {
  66881. return flags & (top | bottom | verticallyCentred);
  66882. }
  66883. int Justification::getOnlyHorizontalFlags() const throw()
  66884. {
  66885. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66886. }
  66887. END_JUCE_NAMESPACE
  66888. /*** End of inlined file: juce_Justification.cpp ***/
  66889. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66890. BEGIN_JUCE_NAMESPACE
  66891. // this will throw an assertion if you try to draw something that's not
  66892. // possible in postscript
  66893. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66894. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66895. #define notPossibleInPostscriptAssert jassertfalse
  66896. #else
  66897. #define notPossibleInPostscriptAssert
  66898. #endif
  66899. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66900. const String& documentTitle,
  66901. const int totalWidth_,
  66902. const int totalHeight_)
  66903. : out (resultingPostScript),
  66904. totalWidth (totalWidth_),
  66905. totalHeight (totalHeight_),
  66906. needToClip (true)
  66907. {
  66908. stateStack.add (new SavedState());
  66909. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66910. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66911. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66912. "\n%%BoundingBox: 0 0 600 824"
  66913. "\n%%Pages: 0"
  66914. "\n%%Creator: Raw Material Software JUCE"
  66915. "\n%%Title: " << documentTitle <<
  66916. "\n%%CreationDate: none"
  66917. "\n%%LanguageLevel: 2"
  66918. "\n%%EndComments"
  66919. "\n%%BeginProlog"
  66920. "\n%%BeginResource: JRes"
  66921. "\n/bd {bind def} bind def"
  66922. "\n/c {setrgbcolor} bd"
  66923. "\n/m {moveto} bd"
  66924. "\n/l {lineto} bd"
  66925. "\n/rl {rlineto} bd"
  66926. "\n/ct {curveto} bd"
  66927. "\n/cp {closepath} bd"
  66928. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66929. "\n/doclip {initclip newpath} bd"
  66930. "\n/endclip {clip newpath} bd"
  66931. "\n%%EndResource"
  66932. "\n%%EndProlog"
  66933. "\n%%BeginSetup"
  66934. "\n%%EndSetup"
  66935. "\n%%Page: 1 1"
  66936. "\n%%BeginPageSetup"
  66937. "\n%%EndPageSetup\n\n"
  66938. << "40 800 translate\n"
  66939. << scale << ' ' << scale << " scale\n\n";
  66940. }
  66941. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66942. {
  66943. }
  66944. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66945. {
  66946. return true;
  66947. }
  66948. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66949. {
  66950. if (x != 0 || y != 0)
  66951. {
  66952. stateStack.getLast()->xOffset += x;
  66953. stateStack.getLast()->yOffset += y;
  66954. needToClip = true;
  66955. }
  66956. }
  66957. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66958. {
  66959. //xxx
  66960. jassertfalse;
  66961. }
  66962. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  66963. {
  66964. jassertfalse; //xxx
  66965. return 1.0f;
  66966. }
  66967. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66968. {
  66969. needToClip = true;
  66970. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66971. }
  66972. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66973. {
  66974. needToClip = true;
  66975. return stateStack.getLast()->clip.clipTo (clipRegion);
  66976. }
  66977. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66978. {
  66979. needToClip = true;
  66980. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66981. }
  66982. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66983. {
  66984. writeClip();
  66985. Path p (path);
  66986. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66987. writePath (p);
  66988. out << "clip\n";
  66989. }
  66990. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66991. {
  66992. needToClip = true;
  66993. jassertfalse; // xxx
  66994. }
  66995. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66996. {
  66997. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66998. }
  66999. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67000. {
  67001. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67002. -stateStack.getLast()->yOffset);
  67003. }
  67004. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67005. {
  67006. return stateStack.getLast()->clip.isEmpty();
  67007. }
  67008. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67009. : xOffset (0),
  67010. yOffset (0)
  67011. {
  67012. }
  67013. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67014. {
  67015. }
  67016. void LowLevelGraphicsPostScriptRenderer::saveState()
  67017. {
  67018. stateStack.add (new SavedState (*stateStack.getLast()));
  67019. }
  67020. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67021. {
  67022. jassert (stateStack.size() > 0);
  67023. if (stateStack.size() > 0)
  67024. stateStack.removeLast();
  67025. }
  67026. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  67027. {
  67028. }
  67029. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  67030. {
  67031. }
  67032. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67033. {
  67034. if (needToClip)
  67035. {
  67036. needToClip = false;
  67037. out << "doclip ";
  67038. int itemsOnLine = 0;
  67039. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67040. {
  67041. if (++itemsOnLine == 6)
  67042. {
  67043. itemsOnLine = 0;
  67044. out << '\n';
  67045. }
  67046. const Rectangle<int>& r = *i.getRectangle();
  67047. out << r.getX() << ' ' << -r.getY() << ' '
  67048. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67049. }
  67050. out << "endclip\n";
  67051. }
  67052. }
  67053. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67054. {
  67055. Colour c (Colours::white.overlaidWith (colour));
  67056. if (lastColour != c)
  67057. {
  67058. lastColour = c;
  67059. out << String (c.getFloatRed(), 3) << ' '
  67060. << String (c.getFloatGreen(), 3) << ' '
  67061. << String (c.getFloatBlue(), 3) << " c\n";
  67062. }
  67063. }
  67064. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67065. {
  67066. out << String (x, 2) << ' '
  67067. << String (-y, 2) << ' ';
  67068. }
  67069. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67070. {
  67071. out << "newpath ";
  67072. float lastX = 0.0f;
  67073. float lastY = 0.0f;
  67074. int itemsOnLine = 0;
  67075. Path::Iterator i (path);
  67076. while (i.next())
  67077. {
  67078. if (++itemsOnLine == 4)
  67079. {
  67080. itemsOnLine = 0;
  67081. out << '\n';
  67082. }
  67083. switch (i.elementType)
  67084. {
  67085. case Path::Iterator::startNewSubPath:
  67086. writeXY (i.x1, i.y1);
  67087. lastX = i.x1;
  67088. lastY = i.y1;
  67089. out << "m ";
  67090. break;
  67091. case Path::Iterator::lineTo:
  67092. writeXY (i.x1, i.y1);
  67093. lastX = i.x1;
  67094. lastY = i.y1;
  67095. out << "l ";
  67096. break;
  67097. case Path::Iterator::quadraticTo:
  67098. {
  67099. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67100. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67101. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67102. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67103. writeXY (cp1x, cp1y);
  67104. writeXY (cp2x, cp2y);
  67105. writeXY (i.x2, i.y2);
  67106. out << "ct ";
  67107. lastX = i.x2;
  67108. lastY = i.y2;
  67109. }
  67110. break;
  67111. case Path::Iterator::cubicTo:
  67112. writeXY (i.x1, i.y1);
  67113. writeXY (i.x2, i.y2);
  67114. writeXY (i.x3, i.y3);
  67115. out << "ct ";
  67116. lastX = i.x3;
  67117. lastY = i.y3;
  67118. break;
  67119. case Path::Iterator::closePath:
  67120. out << "cp ";
  67121. break;
  67122. default:
  67123. jassertfalse;
  67124. break;
  67125. }
  67126. }
  67127. out << '\n';
  67128. }
  67129. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67130. {
  67131. out << "[ "
  67132. << trans.mat00 << ' '
  67133. << trans.mat10 << ' '
  67134. << trans.mat01 << ' '
  67135. << trans.mat11 << ' '
  67136. << trans.mat02 << ' '
  67137. << trans.mat12 << " ] concat ";
  67138. }
  67139. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67140. {
  67141. stateStack.getLast()->fillType = fillType;
  67142. }
  67143. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67144. {
  67145. }
  67146. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67147. {
  67148. }
  67149. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67150. {
  67151. if (stateStack.getLast()->fillType.isColour())
  67152. {
  67153. writeClip();
  67154. writeColour (stateStack.getLast()->fillType.colour);
  67155. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67156. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67157. }
  67158. else
  67159. {
  67160. Path p;
  67161. p.addRectangle (r);
  67162. fillPath (p, AffineTransform::identity);
  67163. }
  67164. }
  67165. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67166. {
  67167. if (stateStack.getLast()->fillType.isColour())
  67168. {
  67169. writeClip();
  67170. Path p (path);
  67171. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67172. (float) stateStack.getLast()->yOffset));
  67173. writePath (p);
  67174. writeColour (stateStack.getLast()->fillType.colour);
  67175. out << "fill\n";
  67176. }
  67177. else if (stateStack.getLast()->fillType.isGradient())
  67178. {
  67179. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67180. // postscript can't do semi-transparent ones.
  67181. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67182. writeClip();
  67183. out << "gsave ";
  67184. {
  67185. Path p (path);
  67186. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67187. writePath (p);
  67188. out << "clip\n";
  67189. }
  67190. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67191. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67192. // time-being, this just fills it with the average colour..
  67193. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67194. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67195. out << "grestore\n";
  67196. }
  67197. }
  67198. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67199. const int sx, const int sy,
  67200. const int maxW, const int maxH) const
  67201. {
  67202. out << "{<\n";
  67203. const int w = jmin (maxW, im.getWidth());
  67204. const int h = jmin (maxH, im.getHeight());
  67205. int charsOnLine = 0;
  67206. const Image::BitmapData srcData (im, 0, 0, w, h);
  67207. Colour pixel;
  67208. for (int y = h; --y >= 0;)
  67209. {
  67210. for (int x = 0; x < w; ++x)
  67211. {
  67212. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67213. if (x >= sx && y >= sy)
  67214. {
  67215. if (im.isARGB())
  67216. {
  67217. PixelARGB p (*(const PixelARGB*) pixelData);
  67218. p.unpremultiply();
  67219. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67220. }
  67221. else if (im.isRGB())
  67222. {
  67223. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67224. }
  67225. else
  67226. {
  67227. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67228. }
  67229. }
  67230. else
  67231. {
  67232. pixel = Colours::transparentWhite;
  67233. }
  67234. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67235. out << String::toHexString (pixelValues, 3, 0);
  67236. charsOnLine += 3;
  67237. if (charsOnLine > 100)
  67238. {
  67239. out << '\n';
  67240. charsOnLine = 0;
  67241. }
  67242. }
  67243. }
  67244. out << "\n>}\n";
  67245. }
  67246. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67247. {
  67248. const int w = sourceImage.getWidth();
  67249. const int h = sourceImage.getHeight();
  67250. writeClip();
  67251. out << "gsave ";
  67252. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67253. .scaled (1.0f, -1.0f));
  67254. RectangleList imageClip;
  67255. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67256. out << "newpath ";
  67257. int itemsOnLine = 0;
  67258. for (RectangleList::Iterator i (imageClip); i.next();)
  67259. {
  67260. if (++itemsOnLine == 6)
  67261. {
  67262. out << '\n';
  67263. itemsOnLine = 0;
  67264. }
  67265. const Rectangle<int>& r = *i.getRectangle();
  67266. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67267. }
  67268. out << " clip newpath\n";
  67269. out << w << ' ' << h << " scale\n";
  67270. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67271. writeImage (sourceImage, 0, 0, w, h);
  67272. out << "false 3 colorimage grestore\n";
  67273. needToClip = true;
  67274. }
  67275. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67276. {
  67277. Path p;
  67278. p.addLineSegment (line, 1.0f);
  67279. fillPath (p, AffineTransform::identity);
  67280. }
  67281. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67282. {
  67283. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67284. }
  67285. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67286. {
  67287. drawLine (Line<float> (left, (float) y, right, (float) y));
  67288. }
  67289. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67290. {
  67291. stateStack.getLast()->font = newFont;
  67292. }
  67293. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67294. {
  67295. return stateStack.getLast()->font;
  67296. }
  67297. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67298. {
  67299. Path p;
  67300. Font& font = stateStack.getLast()->font;
  67301. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67302. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67303. }
  67304. END_JUCE_NAMESPACE
  67305. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67306. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67307. BEGIN_JUCE_NAMESPACE
  67308. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67309. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67310. #endif
  67311. #if JUCE_MSVC
  67312. #pragma warning (push)
  67313. #pragma warning (disable: 4127) // "expression is constant" warning
  67314. #if JUCE_DEBUG
  67315. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67316. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67317. #endif
  67318. #endif
  67319. namespace SoftwareRendererClasses
  67320. {
  67321. template <class PixelType, bool replaceExisting = false>
  67322. class SolidColourEdgeTableRenderer
  67323. {
  67324. public:
  67325. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67326. : data (data_),
  67327. sourceColour (colour)
  67328. {
  67329. if (sizeof (PixelType) == 3)
  67330. {
  67331. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67332. && sourceColour.getGreen() == sourceColour.getBlue();
  67333. filler[0].set (sourceColour);
  67334. filler[1].set (sourceColour);
  67335. filler[2].set (sourceColour);
  67336. filler[3].set (sourceColour);
  67337. }
  67338. }
  67339. forcedinline void setEdgeTableYPos (const int y) throw()
  67340. {
  67341. linePixels = (PixelType*) data.getLinePointer (y);
  67342. }
  67343. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67344. {
  67345. if (replaceExisting)
  67346. linePixels[x].set (sourceColour);
  67347. else
  67348. linePixels[x].blend (sourceColour, alphaLevel);
  67349. }
  67350. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67351. {
  67352. if (replaceExisting)
  67353. linePixels[x].set (sourceColour);
  67354. else
  67355. linePixels[x].blend (sourceColour);
  67356. }
  67357. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67358. {
  67359. PixelARGB p (sourceColour);
  67360. p.multiplyAlpha (alphaLevel);
  67361. PixelType* dest = linePixels + x;
  67362. if (replaceExisting || p.getAlpha() >= 0xff)
  67363. replaceLine (dest, p, width);
  67364. else
  67365. blendLine (dest, p, width);
  67366. }
  67367. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67368. {
  67369. PixelType* dest = linePixels + x;
  67370. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67371. replaceLine (dest, sourceColour, width);
  67372. else
  67373. blendLine (dest, sourceColour, width);
  67374. }
  67375. private:
  67376. const Image::BitmapData& data;
  67377. PixelType* linePixels;
  67378. PixelARGB sourceColour;
  67379. PixelRGB filler [4];
  67380. bool areRGBComponentsEqual;
  67381. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67382. {
  67383. do
  67384. {
  67385. dest->blend (colour);
  67386. ++dest;
  67387. } while (--width > 0);
  67388. }
  67389. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67390. {
  67391. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67392. {
  67393. memset (dest, colour.getRed(), width * 3);
  67394. }
  67395. else
  67396. {
  67397. if (width >> 5)
  67398. {
  67399. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67400. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67401. {
  67402. dest->set (colour);
  67403. ++dest;
  67404. --width;
  67405. }
  67406. while (width > 4)
  67407. {
  67408. int* d = reinterpret_cast<int*> (dest);
  67409. *d++ = intFiller[0];
  67410. *d++ = intFiller[1];
  67411. *d++ = intFiller[2];
  67412. dest = reinterpret_cast<PixelRGB*> (d);
  67413. width -= 4;
  67414. }
  67415. }
  67416. while (--width >= 0)
  67417. {
  67418. dest->set (colour);
  67419. ++dest;
  67420. }
  67421. }
  67422. }
  67423. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67424. {
  67425. memset (dest, colour.getAlpha(), width);
  67426. }
  67427. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67428. {
  67429. do
  67430. {
  67431. dest->set (colour);
  67432. ++dest;
  67433. } while (--width > 0);
  67434. }
  67435. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67436. };
  67437. class LinearGradientPixelGenerator
  67438. {
  67439. public:
  67440. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67441. : lookupTable (lookupTable_), numEntries (numEntries_)
  67442. {
  67443. jassert (numEntries_ >= 0);
  67444. Point<float> p1 (gradient.point1);
  67445. Point<float> p2 (gradient.point2);
  67446. if (! transform.isIdentity())
  67447. {
  67448. const Line<float> l (p2, p1);
  67449. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67450. p1.applyTransform (transform);
  67451. p2.applyTransform (transform);
  67452. p3.applyTransform (transform);
  67453. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67454. }
  67455. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67456. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67457. if (vertical)
  67458. {
  67459. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67460. start = roundToInt (p1.getY() * scale);
  67461. }
  67462. else if (horizontal)
  67463. {
  67464. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67465. start = roundToInt (p1.getX() * scale);
  67466. }
  67467. else
  67468. {
  67469. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67470. yTerm = p1.getY() - p1.getX() / grad;
  67471. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67472. grad *= scale;
  67473. }
  67474. }
  67475. forcedinline void setY (const int y) throw()
  67476. {
  67477. if (vertical)
  67478. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67479. else if (! horizontal)
  67480. start = roundToInt ((y - yTerm) * grad);
  67481. }
  67482. inline const PixelARGB getPixel (const int x) const throw()
  67483. {
  67484. return vertical ? linePix
  67485. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67486. }
  67487. private:
  67488. const PixelARGB* const lookupTable;
  67489. const int numEntries;
  67490. PixelARGB linePix;
  67491. int start, scale;
  67492. double grad, yTerm;
  67493. bool vertical, horizontal;
  67494. enum { numScaleBits = 12 };
  67495. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67496. };
  67497. class RadialGradientPixelGenerator
  67498. {
  67499. public:
  67500. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67501. const PixelARGB* const lookupTable_, const int numEntries_)
  67502. : lookupTable (lookupTable_),
  67503. numEntries (numEntries_),
  67504. gx1 (gradient.point1.getX()),
  67505. gy1 (gradient.point1.getY())
  67506. {
  67507. jassert (numEntries_ >= 0);
  67508. const Point<float> diff (gradient.point1 - gradient.point2);
  67509. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67510. invScale = numEntries / std::sqrt (maxDist);
  67511. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67512. }
  67513. forcedinline void setY (const int y) throw()
  67514. {
  67515. dy = y - gy1;
  67516. dy *= dy;
  67517. }
  67518. inline const PixelARGB getPixel (const int px) const throw()
  67519. {
  67520. double x = px - gx1;
  67521. x *= x;
  67522. x += dy;
  67523. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67524. }
  67525. protected:
  67526. const PixelARGB* const lookupTable;
  67527. const int numEntries;
  67528. const double gx1, gy1;
  67529. double maxDist, invScale, dy;
  67530. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67531. };
  67532. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67533. {
  67534. public:
  67535. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67536. const PixelARGB* const lookupTable_, const int numEntries_)
  67537. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67538. inverseTransform (transform.inverted())
  67539. {
  67540. tM10 = inverseTransform.mat10;
  67541. tM00 = inverseTransform.mat00;
  67542. }
  67543. forcedinline void setY (const int y) throw()
  67544. {
  67545. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67546. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67547. }
  67548. inline const PixelARGB getPixel (const int px) const throw()
  67549. {
  67550. double x = px;
  67551. const double y = tM10 * x + lineYM11;
  67552. x = tM00 * x + lineYM01;
  67553. x *= x;
  67554. x += y * y;
  67555. if (x >= maxDist)
  67556. return lookupTable [numEntries];
  67557. else
  67558. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67559. }
  67560. private:
  67561. double tM10, tM00, lineYM01, lineYM11;
  67562. const AffineTransform inverseTransform;
  67563. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67564. };
  67565. template <class PixelType, class GradientType>
  67566. class GradientEdgeTableRenderer : public GradientType
  67567. {
  67568. public:
  67569. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67570. const PixelARGB* const lookupTable_, const int numEntries_)
  67571. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67572. destData (destData_)
  67573. {
  67574. }
  67575. forcedinline void setEdgeTableYPos (const int y) throw()
  67576. {
  67577. linePixels = (PixelType*) destData.getLinePointer (y);
  67578. GradientType::setY (y);
  67579. }
  67580. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67581. {
  67582. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67583. }
  67584. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67585. {
  67586. linePixels[x].blend (GradientType::getPixel (x));
  67587. }
  67588. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67589. {
  67590. PixelType* dest = linePixels + x;
  67591. if (alphaLevel < 0xff)
  67592. {
  67593. do
  67594. {
  67595. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67596. } while (--width > 0);
  67597. }
  67598. else
  67599. {
  67600. do
  67601. {
  67602. (dest++)->blend (GradientType::getPixel (x++));
  67603. } while (--width > 0);
  67604. }
  67605. }
  67606. void handleEdgeTableLineFull (int x, int width) const throw()
  67607. {
  67608. PixelType* dest = linePixels + x;
  67609. do
  67610. {
  67611. (dest++)->blend (GradientType::getPixel (x++));
  67612. } while (--width > 0);
  67613. }
  67614. private:
  67615. const Image::BitmapData& destData;
  67616. PixelType* linePixels;
  67617. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67618. };
  67619. namespace RenderingHelpers
  67620. {
  67621. forcedinline int safeModulo (int n, const int divisor) throw()
  67622. {
  67623. jassert (divisor > 0);
  67624. n %= divisor;
  67625. return (n < 0) ? (n + divisor) : n;
  67626. }
  67627. }
  67628. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67629. class ImageFillEdgeTableRenderer
  67630. {
  67631. public:
  67632. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67633. const Image::BitmapData& srcData_,
  67634. const int extraAlpha_,
  67635. const int x, const int y)
  67636. : destData (destData_),
  67637. srcData (srcData_),
  67638. extraAlpha (extraAlpha_ + 1),
  67639. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67640. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67641. {
  67642. }
  67643. forcedinline void setEdgeTableYPos (int y) throw()
  67644. {
  67645. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67646. y -= yOffset;
  67647. if (repeatPattern)
  67648. {
  67649. jassert (y >= 0);
  67650. y %= srcData.height;
  67651. }
  67652. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67653. }
  67654. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67655. {
  67656. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67657. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67658. }
  67659. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67660. {
  67661. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67662. }
  67663. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67664. {
  67665. DestPixelType* dest = linePixels + x;
  67666. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67667. x -= xOffset;
  67668. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67669. if (alphaLevel < 0xfe)
  67670. {
  67671. do
  67672. {
  67673. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67674. } while (--width > 0);
  67675. }
  67676. else
  67677. {
  67678. if (repeatPattern)
  67679. {
  67680. do
  67681. {
  67682. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67683. } while (--width > 0);
  67684. }
  67685. else
  67686. {
  67687. copyRow (dest, sourceLineStart + x, width);
  67688. }
  67689. }
  67690. }
  67691. void handleEdgeTableLineFull (int x, int width) const throw()
  67692. {
  67693. DestPixelType* dest = linePixels + x;
  67694. x -= xOffset;
  67695. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67696. if (extraAlpha < 0xfe)
  67697. {
  67698. do
  67699. {
  67700. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67701. } while (--width > 0);
  67702. }
  67703. else
  67704. {
  67705. if (repeatPattern)
  67706. {
  67707. do
  67708. {
  67709. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67710. } while (--width > 0);
  67711. }
  67712. else
  67713. {
  67714. copyRow (dest, sourceLineStart + x, width);
  67715. }
  67716. }
  67717. }
  67718. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67719. {
  67720. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67721. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67722. uint8* mask = (uint8*) (s + x - xOffset);
  67723. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67724. mask += PixelARGB::indexA;
  67725. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67726. }
  67727. private:
  67728. const Image::BitmapData& destData;
  67729. const Image::BitmapData& srcData;
  67730. const int extraAlpha, xOffset, yOffset;
  67731. DestPixelType* linePixels;
  67732. SrcPixelType* sourceLineStart;
  67733. template <class PixelType1, class PixelType2>
  67734. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67735. {
  67736. do
  67737. {
  67738. dest++ ->blend (*src++);
  67739. } while (--width > 0);
  67740. }
  67741. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67742. {
  67743. memcpy (dest, src, width * sizeof (PixelRGB));
  67744. }
  67745. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  67746. };
  67747. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67748. class TransformedImageFillEdgeTableRenderer
  67749. {
  67750. public:
  67751. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67752. const Image::BitmapData& srcData_,
  67753. const AffineTransform& transform,
  67754. const int extraAlpha_,
  67755. const bool betterQuality_)
  67756. : interpolator (transform,
  67757. betterQuality_ ? 0.5f : 0.0f,
  67758. betterQuality_ ? -128 : 0),
  67759. destData (destData_),
  67760. srcData (srcData_),
  67761. extraAlpha (extraAlpha_ + 1),
  67762. betterQuality (betterQuality_),
  67763. maxX (srcData_.width - 1),
  67764. maxY (srcData_.height - 1),
  67765. scratchSize (2048)
  67766. {
  67767. scratchBuffer.malloc (scratchSize);
  67768. }
  67769. forcedinline void setEdgeTableYPos (const int newY) throw()
  67770. {
  67771. y = newY;
  67772. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67773. }
  67774. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67775. {
  67776. SrcPixelType p;
  67777. generate (&p, x, 1);
  67778. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  67779. }
  67780. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67781. {
  67782. SrcPixelType p;
  67783. generate (&p, x, 1);
  67784. linePixels[x].blend (p, extraAlpha);
  67785. }
  67786. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67787. {
  67788. if (width > scratchSize)
  67789. {
  67790. scratchSize = width;
  67791. scratchBuffer.malloc (scratchSize);
  67792. }
  67793. SrcPixelType* span = scratchBuffer;
  67794. generate (span, x, width);
  67795. DestPixelType* dest = linePixels + x;
  67796. alphaLevel *= extraAlpha;
  67797. alphaLevel >>= 8;
  67798. if (alphaLevel < 0xfe)
  67799. {
  67800. do
  67801. {
  67802. dest++ ->blend (*span++, alphaLevel);
  67803. } while (--width > 0);
  67804. }
  67805. else
  67806. {
  67807. do
  67808. {
  67809. dest++ ->blend (*span++);
  67810. } while (--width > 0);
  67811. }
  67812. }
  67813. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67814. {
  67815. handleEdgeTableLine (x, width, 255);
  67816. }
  67817. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67818. {
  67819. if (width > scratchSize)
  67820. {
  67821. scratchSize = width;
  67822. scratchBuffer.malloc (scratchSize);
  67823. }
  67824. y = y_;
  67825. generate (scratchBuffer.getData(), x, width);
  67826. et.clipLineToMask (x, y_,
  67827. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67828. sizeof (SrcPixelType), width);
  67829. }
  67830. private:
  67831. template <class PixelType>
  67832. void generate (PixelType* dest, const int x, int numPixels) throw()
  67833. {
  67834. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67835. do
  67836. {
  67837. int hiResX, hiResY;
  67838. this->interpolator.next (hiResX, hiResY);
  67839. int loResX = hiResX >> 8;
  67840. int loResY = hiResY >> 8;
  67841. if (repeatPattern)
  67842. {
  67843. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67844. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67845. }
  67846. if (betterQuality)
  67847. {
  67848. if (isPositiveAndBelow (loResX, maxX))
  67849. {
  67850. if (isPositiveAndBelow (loResY, maxY))
  67851. {
  67852. // In the centre of the image..
  67853. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67854. hiResX & 255, hiResY & 255);
  67855. ++dest;
  67856. continue;
  67857. }
  67858. else
  67859. {
  67860. // At a top or bottom edge..
  67861. if (! repeatPattern)
  67862. {
  67863. if (loResY < 0)
  67864. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67865. else
  67866. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67867. ++dest;
  67868. continue;
  67869. }
  67870. }
  67871. }
  67872. else
  67873. {
  67874. if (isPositiveAndBelow (loResY, maxY))
  67875. {
  67876. // At a left or right hand edge..
  67877. if (! repeatPattern)
  67878. {
  67879. if (loResX < 0)
  67880. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67881. else
  67882. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67883. ++dest;
  67884. continue;
  67885. }
  67886. }
  67887. }
  67888. }
  67889. if (! repeatPattern)
  67890. {
  67891. if (loResX < 0) loResX = 0;
  67892. if (loResY < 0) loResY = 0;
  67893. if (loResX > maxX) loResX = maxX;
  67894. if (loResY > maxY) loResY = maxY;
  67895. }
  67896. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67897. ++dest;
  67898. } while (--numPixels > 0);
  67899. }
  67900. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67901. {
  67902. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67903. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67904. c[0] += weight * src[0];
  67905. c[1] += weight * src[1];
  67906. c[2] += weight * src[2];
  67907. c[3] += weight * src[3];
  67908. weight = subPixelX * (256 - subPixelY);
  67909. c[0] += weight * src[4];
  67910. c[1] += weight * src[5];
  67911. c[2] += weight * src[6];
  67912. c[3] += weight * src[7];
  67913. src += this->srcData.lineStride;
  67914. weight = (256 - subPixelX) * subPixelY;
  67915. c[0] += weight * src[0];
  67916. c[1] += weight * src[1];
  67917. c[2] += weight * src[2];
  67918. c[3] += weight * src[3];
  67919. weight = subPixelX * subPixelY;
  67920. c[0] += weight * src[4];
  67921. c[1] += weight * src[5];
  67922. c[2] += weight * src[6];
  67923. c[3] += weight * src[7];
  67924. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67925. (uint8) (c[PixelARGB::indexR] >> 16),
  67926. (uint8) (c[PixelARGB::indexG] >> 16),
  67927. (uint8) (c[PixelARGB::indexB] >> 16));
  67928. }
  67929. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67930. {
  67931. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67932. uint32 weight = (256 - subPixelX) * alpha;
  67933. c[0] += weight * src[0];
  67934. c[1] += weight * src[1];
  67935. c[2] += weight * src[2];
  67936. c[3] += weight * src[3];
  67937. weight = subPixelX * alpha;
  67938. c[0] += weight * src[4];
  67939. c[1] += weight * src[5];
  67940. c[2] += weight * src[6];
  67941. c[3] += weight * src[7];
  67942. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67943. (uint8) (c[PixelARGB::indexR] >> 16),
  67944. (uint8) (c[PixelARGB::indexG] >> 16),
  67945. (uint8) (c[PixelARGB::indexB] >> 16));
  67946. }
  67947. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67948. {
  67949. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67950. uint32 weight = (256 - subPixelY) * alpha;
  67951. c[0] += weight * src[0];
  67952. c[1] += weight * src[1];
  67953. c[2] += weight * src[2];
  67954. c[3] += weight * src[3];
  67955. src += this->srcData.lineStride;
  67956. weight = subPixelY * alpha;
  67957. c[0] += weight * src[0];
  67958. c[1] += weight * src[1];
  67959. c[2] += weight * src[2];
  67960. c[3] += weight * src[3];
  67961. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67962. (uint8) (c[PixelARGB::indexR] >> 16),
  67963. (uint8) (c[PixelARGB::indexG] >> 16),
  67964. (uint8) (c[PixelARGB::indexB] >> 16));
  67965. }
  67966. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67967. {
  67968. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67969. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67970. c[0] += weight * src[0];
  67971. c[1] += weight * src[1];
  67972. c[2] += weight * src[2];
  67973. weight = subPixelX * (256 - subPixelY);
  67974. c[0] += weight * src[3];
  67975. c[1] += weight * src[4];
  67976. c[2] += weight * src[5];
  67977. src += this->srcData.lineStride;
  67978. weight = (256 - subPixelX) * subPixelY;
  67979. c[0] += weight * src[0];
  67980. c[1] += weight * src[1];
  67981. c[2] += weight * src[2];
  67982. weight = subPixelX * subPixelY;
  67983. c[0] += weight * src[3];
  67984. c[1] += weight * src[4];
  67985. c[2] += weight * src[5];
  67986. dest->setARGB ((uint8) 255,
  67987. (uint8) (c[PixelRGB::indexR] >> 16),
  67988. (uint8) (c[PixelRGB::indexG] >> 16),
  67989. (uint8) (c[PixelRGB::indexB] >> 16));
  67990. }
  67991. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67992. {
  67993. uint32 c[3] = { 128, 128, 128 };
  67994. uint32 weight = (256 - subPixelX);
  67995. c[0] += weight * src[0];
  67996. c[1] += weight * src[1];
  67997. c[2] += weight * src[2];
  67998. c[0] += subPixelX * src[3];
  67999. c[1] += subPixelX * src[4];
  68000. c[2] += subPixelX * src[5];
  68001. dest->setARGB ((uint8) 255,
  68002. (uint8) (c[PixelRGB::indexR] >> 8),
  68003. (uint8) (c[PixelRGB::indexG] >> 8),
  68004. (uint8) (c[PixelRGB::indexB] >> 8));
  68005. }
  68006. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  68007. {
  68008. uint32 c[3] = { 128, 128, 128 };
  68009. uint32 weight = (256 - subPixelY);
  68010. c[0] += weight * src[0];
  68011. c[1] += weight * src[1];
  68012. c[2] += weight * src[2];
  68013. src += this->srcData.lineStride;
  68014. c[0] += subPixelY * src[0];
  68015. c[1] += subPixelY * src[1];
  68016. c[2] += subPixelY * src[2];
  68017. dest->setARGB ((uint8) 255,
  68018. (uint8) (c[PixelRGB::indexR] >> 8),
  68019. (uint8) (c[PixelRGB::indexG] >> 8),
  68020. (uint8) (c[PixelRGB::indexB] >> 8));
  68021. }
  68022. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  68023. {
  68024. uint32 c = 256 * 128;
  68025. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  68026. c += src[1] * (subPixelX * (256 - subPixelY));
  68027. src += this->srcData.lineStride;
  68028. c += src[0] * ((256 - subPixelX) * subPixelY);
  68029. c += src[1] * (subPixelX * subPixelY);
  68030. *((uint8*) dest) = (uint8) (c >> 16);
  68031. }
  68032. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  68033. {
  68034. uint32 c = 256 * 128;
  68035. c += src[0] * (256 - subPixelX) * alpha;
  68036. c += src[1] * subPixelX * alpha;
  68037. *((uint8*) dest) = (uint8) (c >> 16);
  68038. }
  68039. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  68040. {
  68041. uint32 c = 256 * 128;
  68042. c += src[0] * (256 - subPixelY) * alpha;
  68043. src += this->srcData.lineStride;
  68044. c += src[0] * subPixelY * alpha;
  68045. *((uint8*) dest) = (uint8) (c >> 16);
  68046. }
  68047. class TransformedImageSpanInterpolator
  68048. {
  68049. public:
  68050. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  68051. : inverseTransform (transform.inverted()),
  68052. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  68053. {}
  68054. void setStartOfLine (float x, float y, const int numPixels) throw()
  68055. {
  68056. jassert (numPixels > 0);
  68057. x += pixelOffset;
  68058. y += pixelOffset;
  68059. float x1 = x, y1 = y;
  68060. x += numPixels;
  68061. inverseTransform.transformPoints (x1, y1, x, y);
  68062. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  68063. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  68064. }
  68065. void next (int& x, int& y) throw()
  68066. {
  68067. x = xBresenham.n;
  68068. xBresenham.stepToNext();
  68069. y = yBresenham.n;
  68070. yBresenham.stepToNext();
  68071. }
  68072. private:
  68073. class BresenhamInterpolator
  68074. {
  68075. public:
  68076. BresenhamInterpolator() throw() {}
  68077. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  68078. {
  68079. numSteps = numSteps_;
  68080. step = (n2 - n1) / numSteps;
  68081. remainder = modulo = (n2 - n1) % numSteps;
  68082. n = n1 + pixelOffsetInt;
  68083. if (modulo <= 0)
  68084. {
  68085. modulo += numSteps;
  68086. remainder += numSteps;
  68087. --step;
  68088. }
  68089. modulo -= numSteps;
  68090. }
  68091. forcedinline void stepToNext() throw()
  68092. {
  68093. modulo += remainder;
  68094. n += step;
  68095. if (modulo > 0)
  68096. {
  68097. modulo -= numSteps;
  68098. ++n;
  68099. }
  68100. }
  68101. int n;
  68102. private:
  68103. int numSteps, step, modulo, remainder;
  68104. };
  68105. const AffineTransform inverseTransform;
  68106. BresenhamInterpolator xBresenham, yBresenham;
  68107. const float pixelOffset;
  68108. const int pixelOffsetInt;
  68109. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  68110. };
  68111. TransformedImageSpanInterpolator interpolator;
  68112. const Image::BitmapData& destData;
  68113. const Image::BitmapData& srcData;
  68114. const int extraAlpha;
  68115. const bool betterQuality;
  68116. const int maxX, maxY;
  68117. int y;
  68118. DestPixelType* linePixels;
  68119. HeapBlock <SrcPixelType> scratchBuffer;
  68120. int scratchSize;
  68121. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  68122. };
  68123. class ClipRegionBase : public ReferenceCountedObject
  68124. {
  68125. public:
  68126. ClipRegionBase() {}
  68127. virtual ~ClipRegionBase() {}
  68128. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68129. virtual const Ptr clone() const = 0;
  68130. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68131. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68132. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68133. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68134. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68135. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68136. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68137. virtual const Ptr translated (const Point<int>& delta) = 0;
  68138. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68139. virtual const Rectangle<int> getClipBounds() const = 0;
  68140. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68141. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68142. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68143. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68144. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68145. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68146. protected:
  68147. template <class Iterator>
  68148. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68149. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68150. {
  68151. switch (destData.pixelFormat)
  68152. {
  68153. case Image::ARGB:
  68154. switch (srcData.pixelFormat)
  68155. {
  68156. case Image::ARGB:
  68157. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68158. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68159. break;
  68160. case Image::RGB:
  68161. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68162. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68163. break;
  68164. default:
  68165. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68166. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68167. break;
  68168. }
  68169. break;
  68170. case Image::RGB:
  68171. switch (srcData.pixelFormat)
  68172. {
  68173. case Image::ARGB:
  68174. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68175. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68176. break;
  68177. case Image::RGB:
  68178. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68179. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68180. break;
  68181. default:
  68182. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68183. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68184. break;
  68185. }
  68186. break;
  68187. default:
  68188. switch (srcData.pixelFormat)
  68189. {
  68190. case Image::ARGB:
  68191. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68192. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68193. break;
  68194. case Image::RGB:
  68195. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68196. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68197. break;
  68198. default:
  68199. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68200. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68201. break;
  68202. }
  68203. break;
  68204. }
  68205. }
  68206. template <class Iterator>
  68207. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68208. {
  68209. switch (destData.pixelFormat)
  68210. {
  68211. case Image::ARGB:
  68212. switch (srcData.pixelFormat)
  68213. {
  68214. case Image::ARGB:
  68215. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68216. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68217. break;
  68218. case Image::RGB:
  68219. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68220. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68221. break;
  68222. default:
  68223. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68224. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68225. break;
  68226. }
  68227. break;
  68228. case Image::RGB:
  68229. switch (srcData.pixelFormat)
  68230. {
  68231. case Image::ARGB:
  68232. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68233. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68234. break;
  68235. case Image::RGB:
  68236. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68237. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68238. break;
  68239. default:
  68240. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68241. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68242. break;
  68243. }
  68244. break;
  68245. default:
  68246. switch (srcData.pixelFormat)
  68247. {
  68248. case Image::ARGB:
  68249. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68250. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68251. break;
  68252. case Image::RGB:
  68253. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68254. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68255. break;
  68256. default:
  68257. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68258. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68259. break;
  68260. }
  68261. break;
  68262. }
  68263. }
  68264. template <class Iterator, class DestPixelType>
  68265. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68266. {
  68267. jassert (destData.pixelStride == sizeof (DestPixelType));
  68268. if (replaceContents)
  68269. {
  68270. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68271. iter.iterate (r);
  68272. }
  68273. else
  68274. {
  68275. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68276. iter.iterate (r);
  68277. }
  68278. }
  68279. template <class Iterator, class DestPixelType>
  68280. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68281. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68282. {
  68283. jassert (destData.pixelStride == sizeof (DestPixelType));
  68284. if (g.isRadial)
  68285. {
  68286. if (isIdentity)
  68287. {
  68288. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68289. iter.iterate (renderer);
  68290. }
  68291. else
  68292. {
  68293. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68294. iter.iterate (renderer);
  68295. }
  68296. }
  68297. else
  68298. {
  68299. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68300. iter.iterate (renderer);
  68301. }
  68302. }
  68303. };
  68304. class ClipRegion_EdgeTable : public ClipRegionBase
  68305. {
  68306. public:
  68307. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68308. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68309. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68310. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68311. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68312. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68313. ~ClipRegion_EdgeTable() {}
  68314. const Ptr clone() const
  68315. {
  68316. return new ClipRegion_EdgeTable (*this);
  68317. }
  68318. const Ptr applyClipTo (const Ptr& target) const
  68319. {
  68320. return target->clipToEdgeTable (edgeTable);
  68321. }
  68322. const Ptr clipToRectangle (const Rectangle<int>& r)
  68323. {
  68324. edgeTable.clipToRectangle (r);
  68325. return edgeTable.isEmpty() ? 0 : this;
  68326. }
  68327. const Ptr clipToRectangleList (const RectangleList& r)
  68328. {
  68329. RectangleList inverse (edgeTable.getMaximumBounds());
  68330. if (inverse.subtract (r))
  68331. for (RectangleList::Iterator iter (inverse); iter.next();)
  68332. edgeTable.excludeRectangle (*iter.getRectangle());
  68333. return edgeTable.isEmpty() ? 0 : this;
  68334. }
  68335. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68336. {
  68337. edgeTable.excludeRectangle (r);
  68338. return edgeTable.isEmpty() ? 0 : this;
  68339. }
  68340. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68341. {
  68342. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68343. edgeTable.clipToEdgeTable (et);
  68344. return edgeTable.isEmpty() ? 0 : this;
  68345. }
  68346. const Ptr clipToEdgeTable (const EdgeTable& et)
  68347. {
  68348. edgeTable.clipToEdgeTable (et);
  68349. return edgeTable.isEmpty() ? 0 : this;
  68350. }
  68351. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68352. {
  68353. const Image::BitmapData srcData (image, false);
  68354. if (transform.isOnlyTranslation())
  68355. {
  68356. // If our translation doesn't involve any distortion, just use a simple blit..
  68357. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68358. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68359. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68360. {
  68361. const int imageX = ((tx + 128) >> 8);
  68362. const int imageY = ((ty + 128) >> 8);
  68363. if (image.getFormat() == Image::ARGB)
  68364. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68365. else
  68366. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68367. return edgeTable.isEmpty() ? 0 : this;
  68368. }
  68369. }
  68370. if (transform.isSingularity())
  68371. return 0;
  68372. {
  68373. Path p;
  68374. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68375. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68376. edgeTable.clipToEdgeTable (et2);
  68377. }
  68378. if (! edgeTable.isEmpty())
  68379. {
  68380. if (image.getFormat() == Image::ARGB)
  68381. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68382. else
  68383. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68384. }
  68385. return edgeTable.isEmpty() ? 0 : this;
  68386. }
  68387. const Ptr translated (const Point<int>& delta)
  68388. {
  68389. edgeTable.translate ((float) delta.getX(), delta.getY());
  68390. return edgeTable.isEmpty() ? 0 : this;
  68391. }
  68392. bool clipRegionIntersects (const Rectangle<int>& r) const
  68393. {
  68394. return edgeTable.getMaximumBounds().intersects (r);
  68395. }
  68396. const Rectangle<int> getClipBounds() const
  68397. {
  68398. return edgeTable.getMaximumBounds();
  68399. }
  68400. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68401. {
  68402. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68403. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68404. if (! clipped.isEmpty())
  68405. {
  68406. ClipRegion_EdgeTable et (clipped);
  68407. et.edgeTable.clipToEdgeTable (edgeTable);
  68408. et.fillAllWithColour (destData, colour, replaceContents);
  68409. }
  68410. }
  68411. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68412. {
  68413. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68414. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68415. if (! clipped.isEmpty())
  68416. {
  68417. ClipRegion_EdgeTable et (clipped);
  68418. et.edgeTable.clipToEdgeTable (edgeTable);
  68419. et.fillAllWithColour (destData, colour, false);
  68420. }
  68421. }
  68422. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68423. {
  68424. switch (destData.pixelFormat)
  68425. {
  68426. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68427. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68428. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68429. }
  68430. }
  68431. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68432. {
  68433. HeapBlock <PixelARGB> lookupTable;
  68434. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68435. jassert (numLookupEntries > 0);
  68436. switch (destData.pixelFormat)
  68437. {
  68438. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68439. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68440. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68441. }
  68442. }
  68443. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68444. {
  68445. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68446. }
  68447. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68448. {
  68449. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68450. }
  68451. EdgeTable edgeTable;
  68452. private:
  68453. template <class SrcPixelType>
  68454. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68455. {
  68456. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68457. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68458. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68459. edgeTable.getMaximumBounds().getWidth());
  68460. }
  68461. template <class SrcPixelType>
  68462. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68463. {
  68464. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68465. edgeTable.clipToRectangle (r);
  68466. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68467. for (int y = 0; y < r.getHeight(); ++y)
  68468. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68469. }
  68470. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68471. };
  68472. class ClipRegion_RectangleList : public ClipRegionBase
  68473. {
  68474. public:
  68475. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68476. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68477. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68478. ~ClipRegion_RectangleList() {}
  68479. const Ptr clone() const
  68480. {
  68481. return new ClipRegion_RectangleList (*this);
  68482. }
  68483. const Ptr applyClipTo (const Ptr& target) const
  68484. {
  68485. return target->clipToRectangleList (clip);
  68486. }
  68487. const Ptr clipToRectangle (const Rectangle<int>& r)
  68488. {
  68489. clip.clipTo (r);
  68490. return clip.isEmpty() ? 0 : this;
  68491. }
  68492. const Ptr clipToRectangleList (const RectangleList& r)
  68493. {
  68494. clip.clipTo (r);
  68495. return clip.isEmpty() ? 0 : this;
  68496. }
  68497. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68498. {
  68499. clip.subtract (r);
  68500. return clip.isEmpty() ? 0 : this;
  68501. }
  68502. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68503. {
  68504. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68505. }
  68506. const Ptr clipToEdgeTable (const EdgeTable& et)
  68507. {
  68508. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68509. }
  68510. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68511. {
  68512. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68513. }
  68514. const Ptr translated (const Point<int>& delta)
  68515. {
  68516. clip.offsetAll (delta.getX(), delta.getY());
  68517. return clip.isEmpty() ? 0 : this;
  68518. }
  68519. bool clipRegionIntersects (const Rectangle<int>& r) const
  68520. {
  68521. return clip.intersects (r);
  68522. }
  68523. const Rectangle<int> getClipBounds() const
  68524. {
  68525. return clip.getBounds();
  68526. }
  68527. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68528. {
  68529. SubRectangleIterator iter (clip, area);
  68530. switch (destData.pixelFormat)
  68531. {
  68532. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68533. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68534. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68535. }
  68536. }
  68537. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68538. {
  68539. SubRectangleIteratorFloat iter (clip, area);
  68540. switch (destData.pixelFormat)
  68541. {
  68542. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68543. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68544. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68545. }
  68546. }
  68547. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68548. {
  68549. switch (destData.pixelFormat)
  68550. {
  68551. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68552. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68553. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68554. }
  68555. }
  68556. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68557. {
  68558. HeapBlock <PixelARGB> lookupTable;
  68559. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68560. jassert (numLookupEntries > 0);
  68561. switch (destData.pixelFormat)
  68562. {
  68563. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68564. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68565. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68566. }
  68567. }
  68568. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68569. {
  68570. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68571. }
  68572. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68573. {
  68574. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68575. }
  68576. RectangleList clip;
  68577. template <class Renderer>
  68578. void iterate (Renderer& r) const throw()
  68579. {
  68580. RectangleList::Iterator iter (clip);
  68581. while (iter.next())
  68582. {
  68583. const Rectangle<int> rect (*iter.getRectangle());
  68584. const int x = rect.getX();
  68585. const int w = rect.getWidth();
  68586. jassert (w > 0);
  68587. const int bottom = rect.getBottom();
  68588. for (int y = rect.getY(); y < bottom; ++y)
  68589. {
  68590. r.setEdgeTableYPos (y);
  68591. r.handleEdgeTableLineFull (x, w);
  68592. }
  68593. }
  68594. }
  68595. private:
  68596. class SubRectangleIterator
  68597. {
  68598. public:
  68599. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68600. : clip (clip_), area (area_)
  68601. {
  68602. }
  68603. template <class Renderer>
  68604. void iterate (Renderer& r) const throw()
  68605. {
  68606. RectangleList::Iterator iter (clip);
  68607. while (iter.next())
  68608. {
  68609. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68610. if (! rect.isEmpty())
  68611. {
  68612. const int x = rect.getX();
  68613. const int w = rect.getWidth();
  68614. const int bottom = rect.getBottom();
  68615. for (int y = rect.getY(); y < bottom; ++y)
  68616. {
  68617. r.setEdgeTableYPos (y);
  68618. r.handleEdgeTableLineFull (x, w);
  68619. }
  68620. }
  68621. }
  68622. }
  68623. private:
  68624. const RectangleList& clip;
  68625. const Rectangle<int> area;
  68626. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68627. };
  68628. class SubRectangleIteratorFloat
  68629. {
  68630. public:
  68631. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68632. : clip (clip_), area (area_)
  68633. {
  68634. }
  68635. template <class Renderer>
  68636. void iterate (Renderer& r) const throw()
  68637. {
  68638. int left = roundToInt (area.getX() * 256.0f);
  68639. int top = roundToInt (area.getY() * 256.0f);
  68640. int right = roundToInt (area.getRight() * 256.0f);
  68641. int bottom = roundToInt (area.getBottom() * 256.0f);
  68642. int totalTop, totalLeft, totalBottom, totalRight;
  68643. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68644. if ((top >> 8) == (bottom >> 8))
  68645. {
  68646. topAlpha = bottom - top;
  68647. bottomAlpha = 0;
  68648. totalTop = top >> 8;
  68649. totalBottom = bottom = top = totalTop + 1;
  68650. }
  68651. else
  68652. {
  68653. if ((top & 255) == 0)
  68654. {
  68655. topAlpha = 0;
  68656. top = totalTop = (top >> 8);
  68657. }
  68658. else
  68659. {
  68660. topAlpha = 255 - (top & 255);
  68661. totalTop = (top >> 8);
  68662. top = totalTop + 1;
  68663. }
  68664. bottomAlpha = bottom & 255;
  68665. bottom >>= 8;
  68666. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68667. }
  68668. if ((left >> 8) == (right >> 8))
  68669. {
  68670. leftAlpha = right - left;
  68671. rightAlpha = 0;
  68672. totalLeft = (left >> 8);
  68673. totalRight = right = left = totalLeft + 1;
  68674. }
  68675. else
  68676. {
  68677. if ((left & 255) == 0)
  68678. {
  68679. leftAlpha = 0;
  68680. left = totalLeft = (left >> 8);
  68681. }
  68682. else
  68683. {
  68684. leftAlpha = 255 - (left & 255);
  68685. totalLeft = (left >> 8);
  68686. left = totalLeft + 1;
  68687. }
  68688. rightAlpha = right & 255;
  68689. right >>= 8;
  68690. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68691. }
  68692. RectangleList::Iterator iter (clip);
  68693. while (iter.next())
  68694. {
  68695. const int clipLeft = iter.getRectangle()->getX();
  68696. const int clipRight = iter.getRectangle()->getRight();
  68697. const int clipTop = iter.getRectangle()->getY();
  68698. const int clipBottom = iter.getRectangle()->getBottom();
  68699. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68700. {
  68701. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68702. {
  68703. if (topAlpha != 0 && totalTop >= clipTop)
  68704. {
  68705. r.setEdgeTableYPos (totalTop);
  68706. r.handleEdgeTablePixel (left, topAlpha);
  68707. }
  68708. const int endY = jmin (bottom, clipBottom);
  68709. for (int y = jmax (clipTop, top); y < endY; ++y)
  68710. {
  68711. r.setEdgeTableYPos (y);
  68712. r.handleEdgeTablePixelFull (left);
  68713. }
  68714. if (bottomAlpha != 0 && bottom < clipBottom)
  68715. {
  68716. r.setEdgeTableYPos (bottom);
  68717. r.handleEdgeTablePixel (left, bottomAlpha);
  68718. }
  68719. }
  68720. else
  68721. {
  68722. const int clippedLeft = jmax (left, clipLeft);
  68723. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68724. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68725. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68726. if (topAlpha != 0 && totalTop >= clipTop)
  68727. {
  68728. r.setEdgeTableYPos (totalTop);
  68729. if (doLeftAlpha)
  68730. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68731. if (clippedWidth > 0)
  68732. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68733. if (doRightAlpha)
  68734. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68735. }
  68736. const int endY = jmin (bottom, clipBottom);
  68737. for (int y = jmax (clipTop, top); y < endY; ++y)
  68738. {
  68739. r.setEdgeTableYPos (y);
  68740. if (doLeftAlpha)
  68741. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68742. if (clippedWidth > 0)
  68743. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68744. if (doRightAlpha)
  68745. r.handleEdgeTablePixel (right, rightAlpha);
  68746. }
  68747. if (bottomAlpha != 0 && bottom < clipBottom)
  68748. {
  68749. r.setEdgeTableYPos (bottom);
  68750. if (doLeftAlpha)
  68751. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68752. if (clippedWidth > 0)
  68753. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68754. if (doRightAlpha)
  68755. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68756. }
  68757. }
  68758. }
  68759. }
  68760. }
  68761. private:
  68762. const RectangleList& clip;
  68763. const Rectangle<float>& area;
  68764. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  68765. };
  68766. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68767. };
  68768. }
  68769. class LowLevelGraphicsSoftwareRenderer::SavedState
  68770. {
  68771. public:
  68772. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68773. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68774. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68775. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68776. {
  68777. }
  68778. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68779. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68780. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68781. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68782. {
  68783. }
  68784. SavedState (const SavedState& other)
  68785. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  68786. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  68787. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  68788. interpolationQuality (other.interpolationQuality)
  68789. {
  68790. }
  68791. void setOrigin (const int x, const int y) throw()
  68792. {
  68793. if (isOnlyTranslated)
  68794. {
  68795. xOffset += x;
  68796. yOffset += y;
  68797. }
  68798. else
  68799. {
  68800. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68801. }
  68802. }
  68803. void addTransform (const AffineTransform& t)
  68804. {
  68805. if ((! isOnlyTranslated)
  68806. || (! t.isOnlyTranslation())
  68807. || (int) (t.getTranslationX() * 256.0f) != 0
  68808. || (int) (t.getTranslationY() * 256.0f) != 0)
  68809. {
  68810. complexTransform = getTransformWith (t);
  68811. isOnlyTranslated = false;
  68812. }
  68813. else
  68814. {
  68815. xOffset += (int) t.getTranslationX();
  68816. yOffset += (int) t.getTranslationY();
  68817. }
  68818. }
  68819. float getScaleFactor() const
  68820. {
  68821. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  68822. }
  68823. bool clipToRectangle (const Rectangle<int>& r)
  68824. {
  68825. if (clip != 0)
  68826. {
  68827. if (isOnlyTranslated)
  68828. {
  68829. cloneClipIfMultiplyReferenced();
  68830. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68831. }
  68832. else
  68833. {
  68834. Path p;
  68835. p.addRectangle (r);
  68836. clipToPath (p, AffineTransform::identity);
  68837. }
  68838. }
  68839. return clip != 0;
  68840. }
  68841. bool clipToRectangleList (const RectangleList& r)
  68842. {
  68843. if (clip != 0)
  68844. {
  68845. if (isOnlyTranslated)
  68846. {
  68847. cloneClipIfMultiplyReferenced();
  68848. RectangleList offsetList (r);
  68849. offsetList.offsetAll (xOffset, yOffset);
  68850. clip = clip->clipToRectangleList (offsetList);
  68851. }
  68852. else
  68853. {
  68854. clipToPath (r.toPath(), AffineTransform::identity);
  68855. }
  68856. }
  68857. return clip != 0;
  68858. }
  68859. bool excludeClipRectangle (const Rectangle<int>& r)
  68860. {
  68861. if (clip != 0)
  68862. {
  68863. cloneClipIfMultiplyReferenced();
  68864. if (isOnlyTranslated)
  68865. {
  68866. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68867. }
  68868. else
  68869. {
  68870. Path p;
  68871. p.addRectangle (r.toFloat());
  68872. p.applyTransform (complexTransform);
  68873. p.addRectangle (clip->getClipBounds().toFloat());
  68874. p.setUsingNonZeroWinding (false);
  68875. clip = clip->clipToPath (p, AffineTransform::identity);
  68876. }
  68877. }
  68878. return clip != 0;
  68879. }
  68880. void clipToPath (const Path& p, const AffineTransform& transform)
  68881. {
  68882. if (clip != 0)
  68883. {
  68884. cloneClipIfMultiplyReferenced();
  68885. clip = clip->clipToPath (p, getTransformWith (transform));
  68886. }
  68887. }
  68888. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  68889. {
  68890. if (clip != 0)
  68891. {
  68892. if (sourceImage.hasAlphaChannel())
  68893. {
  68894. cloneClipIfMultiplyReferenced();
  68895. clip = clip->clipToImageAlpha (sourceImage, getTransformWith (t),
  68896. interpolationQuality != Graphics::lowResamplingQuality);
  68897. }
  68898. else
  68899. {
  68900. Path p;
  68901. p.addRectangle (sourceImage.getBounds());
  68902. clipToPath (p, t);
  68903. }
  68904. }
  68905. }
  68906. bool clipRegionIntersects (const Rectangle<int>& r) const
  68907. {
  68908. if (clip != 0)
  68909. {
  68910. if (isOnlyTranslated)
  68911. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68912. else
  68913. return getClipBounds().intersects (r);
  68914. }
  68915. return false;
  68916. }
  68917. const Rectangle<int> getUntransformedClipBounds() const
  68918. {
  68919. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  68920. }
  68921. const Rectangle<int> getClipBounds() const
  68922. {
  68923. if (clip != 0)
  68924. {
  68925. if (isOnlyTranslated)
  68926. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68927. else
  68928. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  68929. }
  68930. return Rectangle<int>();
  68931. }
  68932. SavedState* beginTransparencyLayer (float opacity)
  68933. {
  68934. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68935. SavedState* s = new SavedState (*this);
  68936. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  68937. s->compositionAlpha = opacity;
  68938. if (s->isOnlyTranslated)
  68939. {
  68940. s->xOffset -= layerBounds.getX();
  68941. s->yOffset -= layerBounds.getY();
  68942. }
  68943. else
  68944. {
  68945. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -layerBounds.getX(),
  68946. (float) -layerBounds.getY()));
  68947. }
  68948. s->cloneClipIfMultiplyReferenced();
  68949. s->clip = s->clip->translated (-layerBounds.getPosition());
  68950. return s;
  68951. }
  68952. void endTransparencyLayer (SavedState& layerState)
  68953. {
  68954. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68955. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  68956. g->setOpacity (layerState.compositionAlpha);
  68957. g->drawImage (layerState.image, AffineTransform::translation ((float) layerBounds.getX(),
  68958. (float) layerBounds.getY()), false);
  68959. }
  68960. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  68961. {
  68962. if (clip != 0)
  68963. {
  68964. if (isOnlyTranslated)
  68965. {
  68966. if (fillType.isColour())
  68967. {
  68968. Image::BitmapData destData (image, true);
  68969. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68970. }
  68971. else
  68972. {
  68973. const Rectangle<int> totalClip (clip->getClipBounds());
  68974. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68975. if (! clipped.isEmpty())
  68976. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68977. }
  68978. }
  68979. else
  68980. {
  68981. Path p;
  68982. p.addRectangle (r);
  68983. fillPath (p, AffineTransform::identity);
  68984. }
  68985. }
  68986. }
  68987. void fillRect (const Rectangle<float>& r)
  68988. {
  68989. if (clip != 0)
  68990. {
  68991. if (isOnlyTranslated)
  68992. {
  68993. if (fillType.isColour())
  68994. {
  68995. Image::BitmapData destData (image, true);
  68996. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68997. }
  68998. else
  68999. {
  69000. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  69001. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  69002. if (! clipped.isEmpty())
  69003. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  69004. }
  69005. }
  69006. else
  69007. {
  69008. Path p;
  69009. p.addRectangle (r);
  69010. fillPath (p, AffineTransform::identity);
  69011. }
  69012. }
  69013. }
  69014. void fillPath (const Path& path, const AffineTransform& transform)
  69015. {
  69016. if (clip != 0)
  69017. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  69018. }
  69019. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  69020. {
  69021. jassert (isOnlyTranslated);
  69022. if (clip != 0)
  69023. {
  69024. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  69025. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  69026. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  69027. fillShape (shapeToFill, false);
  69028. }
  69029. }
  69030. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  69031. {
  69032. jassert (clip != 0);
  69033. shapeToFill = clip->applyClipTo (shapeToFill);
  69034. if (shapeToFill != 0)
  69035. {
  69036. Image::BitmapData destData (image, true);
  69037. if (fillType.isGradient())
  69038. {
  69039. jassert (! replaceContents); // that option is just for solid colours
  69040. ColourGradient g2 (*(fillType.gradient));
  69041. g2.multiplyOpacity (fillType.getOpacity());
  69042. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  69043. const bool isIdentity = transform.isOnlyTranslation();
  69044. if (isIdentity)
  69045. {
  69046. // If our translation doesn't involve any distortion, we can speed it up..
  69047. g2.point1.applyTransform (transform);
  69048. g2.point2.applyTransform (transform);
  69049. transform = AffineTransform::identity;
  69050. }
  69051. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  69052. }
  69053. else if (fillType.isTiledImage())
  69054. {
  69055. renderImage (fillType.image, fillType.transform, shapeToFill);
  69056. }
  69057. else
  69058. {
  69059. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  69060. }
  69061. }
  69062. }
  69063. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  69064. {
  69065. const AffineTransform transform (getTransformWith (t));
  69066. const Image::BitmapData destData (image, true);
  69067. const Image::BitmapData srcData (sourceImage, false);
  69068. const int alpha = fillType.colour.getAlpha();
  69069. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69070. if (transform.isOnlyTranslation())
  69071. {
  69072. // If our translation doesn't involve any distortion, just use a simple blit..
  69073. int tx = (int) (transform.getTranslationX() * 256.0f);
  69074. int ty = (int) (transform.getTranslationY() * 256.0f);
  69075. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69076. {
  69077. tx = ((tx + 128) >> 8);
  69078. ty = ((ty + 128) >> 8);
  69079. if (tiledFillClipRegion != 0)
  69080. {
  69081. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69082. }
  69083. else
  69084. {
  69085. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  69086. c = clip->applyClipTo (c);
  69087. if (c != 0)
  69088. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69089. }
  69090. return;
  69091. }
  69092. }
  69093. if (transform.isSingularity())
  69094. return;
  69095. if (tiledFillClipRegion != 0)
  69096. {
  69097. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69098. }
  69099. else
  69100. {
  69101. Path p;
  69102. p.addRectangle (sourceImage.getBounds());
  69103. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69104. c = c->clipToPath (p, transform);
  69105. if (c != 0)
  69106. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69107. }
  69108. }
  69109. Image image;
  69110. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69111. private:
  69112. AffineTransform complexTransform;
  69113. int xOffset, yOffset;
  69114. float compositionAlpha;
  69115. public:
  69116. bool isOnlyTranslated;
  69117. Font font;
  69118. FillType fillType;
  69119. Graphics::ResamplingQuality interpolationQuality;
  69120. private:
  69121. void cloneClipIfMultiplyReferenced()
  69122. {
  69123. if (clip->getReferenceCount() > 1)
  69124. clip = clip->clone();
  69125. }
  69126. const AffineTransform getTransform() const
  69127. {
  69128. if (isOnlyTranslated)
  69129. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  69130. return complexTransform;
  69131. }
  69132. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  69133. {
  69134. if (isOnlyTranslated)
  69135. return userTransform.translated ((float) xOffset, (float) yOffset);
  69136. return userTransform.followedBy (complexTransform);
  69137. }
  69138. SavedState& operator= (const SavedState&);
  69139. };
  69140. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69141. : image (image_),
  69142. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  69143. {
  69144. }
  69145. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69146. const RectangleList& initialClip)
  69147. : image (image_),
  69148. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  69149. {
  69150. }
  69151. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69152. {
  69153. }
  69154. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69155. {
  69156. return false;
  69157. }
  69158. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69159. {
  69160. currentState->setOrigin (x, y);
  69161. }
  69162. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  69163. {
  69164. currentState->addTransform (transform);
  69165. }
  69166. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  69167. {
  69168. return currentState->getScaleFactor();
  69169. }
  69170. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69171. {
  69172. return currentState->clipToRectangle (r);
  69173. }
  69174. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69175. {
  69176. return currentState->clipToRectangleList (clipRegion);
  69177. }
  69178. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69179. {
  69180. currentState->excludeClipRectangle (r);
  69181. }
  69182. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69183. {
  69184. currentState->clipToPath (path, transform);
  69185. }
  69186. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69187. {
  69188. currentState->clipToImageAlpha (sourceImage, transform);
  69189. }
  69190. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69191. {
  69192. return currentState->clipRegionIntersects (r);
  69193. }
  69194. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69195. {
  69196. return currentState->getClipBounds();
  69197. }
  69198. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69199. {
  69200. return currentState->clip == 0;
  69201. }
  69202. void LowLevelGraphicsSoftwareRenderer::saveState()
  69203. {
  69204. stateStack.add (new SavedState (*currentState));
  69205. }
  69206. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69207. {
  69208. SavedState* const top = stateStack.getLast();
  69209. if (top != 0)
  69210. {
  69211. currentState = top;
  69212. stateStack.removeLast (1, false);
  69213. }
  69214. else
  69215. {
  69216. jassertfalse; // trying to pop with an empty stack!
  69217. }
  69218. }
  69219. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  69220. {
  69221. saveState();
  69222. currentState = currentState->beginTransparencyLayer (opacity);
  69223. }
  69224. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  69225. {
  69226. const ScopedPointer<SavedState> layer (currentState);
  69227. restoreState();
  69228. currentState->endTransparencyLayer (*layer);
  69229. }
  69230. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69231. {
  69232. currentState->fillType = fillType;
  69233. }
  69234. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69235. {
  69236. currentState->fillType.setOpacity (newOpacity);
  69237. }
  69238. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69239. {
  69240. currentState->interpolationQuality = quality;
  69241. }
  69242. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69243. {
  69244. currentState->fillRect (r, replaceExistingContents);
  69245. }
  69246. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69247. {
  69248. currentState->fillPath (path, transform);
  69249. }
  69250. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69251. {
  69252. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  69253. }
  69254. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69255. {
  69256. Path p;
  69257. p.addLineSegment (line, 1.0f);
  69258. fillPath (p, AffineTransform::identity);
  69259. }
  69260. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69261. {
  69262. if (bottom > top)
  69263. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69264. }
  69265. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69266. {
  69267. if (right > left)
  69268. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69269. }
  69270. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69271. {
  69272. public:
  69273. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69274. void draw (SavedState& state, float x, const float y) const
  69275. {
  69276. if (snapToIntegerCoordinate)
  69277. x = std::floor (x + 0.5f);
  69278. if (edgeTable != 0)
  69279. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69280. }
  69281. void generate (const Font& newFont, const int glyphNumber)
  69282. {
  69283. font = newFont;
  69284. snapToIntegerCoordinate = newFont.getTypeface()->isHinted();
  69285. glyph = glyphNumber;
  69286. edgeTable = 0;
  69287. Path glyphPath;
  69288. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69289. if (! glyphPath.isEmpty())
  69290. {
  69291. const float fontHeight = font.getHeight();
  69292. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69293. #if JUCE_MAC || JUCE_IOS
  69294. .translated (0.0f, -0.5f)
  69295. #endif
  69296. );
  69297. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69298. glyphPath, transform);
  69299. }
  69300. }
  69301. Font font;
  69302. int glyph, lastAccessCount;
  69303. bool snapToIntegerCoordinate;
  69304. private:
  69305. ScopedPointer <EdgeTable> edgeTable;
  69306. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69307. };
  69308. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69309. {
  69310. public:
  69311. GlyphCache()
  69312. : accessCounter (0), hits (0), misses (0)
  69313. {
  69314. addNewGlyphSlots (120);
  69315. }
  69316. ~GlyphCache()
  69317. {
  69318. clearSingletonInstance();
  69319. }
  69320. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69321. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69322. {
  69323. ++accessCounter;
  69324. int oldestCounter = std::numeric_limits<int>::max();
  69325. CachedGlyph* oldest = 0;
  69326. for (int i = glyphs.size(); --i >= 0;)
  69327. {
  69328. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69329. if (glyph->glyph == glyphNumber && glyph->font == font)
  69330. {
  69331. ++hits;
  69332. glyph->lastAccessCount = accessCounter;
  69333. glyph->draw (state, x, y);
  69334. return;
  69335. }
  69336. if (glyph->lastAccessCount <= oldestCounter)
  69337. {
  69338. oldestCounter = glyph->lastAccessCount;
  69339. oldest = glyph;
  69340. }
  69341. }
  69342. if (hits + ++misses > (glyphs.size() << 4))
  69343. {
  69344. if (misses * 2 > hits)
  69345. addNewGlyphSlots (32);
  69346. hits = misses = 0;
  69347. oldest = glyphs.getLast();
  69348. }
  69349. jassert (oldest != 0);
  69350. oldest->lastAccessCount = accessCounter;
  69351. oldest->generate (font, glyphNumber);
  69352. oldest->draw (state, x, y);
  69353. }
  69354. private:
  69355. friend class OwnedArray <CachedGlyph>;
  69356. OwnedArray <CachedGlyph> glyphs;
  69357. int accessCounter, hits, misses;
  69358. void addNewGlyphSlots (int num)
  69359. {
  69360. while (--num >= 0)
  69361. glyphs.add (new CachedGlyph());
  69362. }
  69363. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69364. };
  69365. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69366. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69367. {
  69368. currentState->font = newFont;
  69369. }
  69370. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69371. {
  69372. return currentState->font;
  69373. }
  69374. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69375. {
  69376. Font& f = currentState->font;
  69377. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69378. {
  69379. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69380. transform.getTranslationX(),
  69381. transform.getTranslationY());
  69382. }
  69383. else
  69384. {
  69385. Path p;
  69386. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69387. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69388. }
  69389. }
  69390. #if JUCE_MSVC
  69391. #pragma warning (pop)
  69392. #if JUCE_DEBUG
  69393. #pragma optimize ("", on) // resets optimisations to the project defaults
  69394. #endif
  69395. #endif
  69396. END_JUCE_NAMESPACE
  69397. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69398. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69399. BEGIN_JUCE_NAMESPACE
  69400. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69401. : flags (other.flags)
  69402. {
  69403. }
  69404. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69405. {
  69406. flags = other.flags;
  69407. return *this;
  69408. }
  69409. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69410. const double dx, const double dy, const double dw, const double dh) const throw()
  69411. {
  69412. if (w == 0 || h == 0)
  69413. return;
  69414. if ((flags & stretchToFit) != 0)
  69415. {
  69416. x = dx;
  69417. y = dy;
  69418. w = dw;
  69419. h = dh;
  69420. }
  69421. else
  69422. {
  69423. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69424. : jmin (dw / w, dh / h);
  69425. if ((flags & onlyReduceInSize) != 0)
  69426. scale = jmin (scale, 1.0);
  69427. if ((flags & onlyIncreaseInSize) != 0)
  69428. scale = jmax (scale, 1.0);
  69429. w *= scale;
  69430. h *= scale;
  69431. if ((flags & xLeft) != 0)
  69432. x = dx;
  69433. else if ((flags & xRight) != 0)
  69434. x = dx + dw - w;
  69435. else
  69436. x = dx + (dw - w) * 0.5;
  69437. if ((flags & yTop) != 0)
  69438. y = dy;
  69439. else if ((flags & yBottom) != 0)
  69440. y = dy + dh - h;
  69441. else
  69442. y = dy + (dh - h) * 0.5;
  69443. }
  69444. }
  69445. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69446. {
  69447. if (source.isEmpty())
  69448. return AffineTransform::identity;
  69449. float newX = destination.getX();
  69450. float newY = destination.getY();
  69451. float scaleX = destination.getWidth() / source.getWidth();
  69452. float scaleY = destination.getHeight() / source.getHeight();
  69453. if ((flags & stretchToFit) == 0)
  69454. {
  69455. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69456. : jmin (scaleX, scaleY);
  69457. if ((flags & onlyReduceInSize) != 0)
  69458. scaleX = jmin (scaleX, 1.0f);
  69459. if ((flags & onlyIncreaseInSize) != 0)
  69460. scaleX = jmax (scaleX, 1.0f);
  69461. scaleY = scaleX;
  69462. if ((flags & xRight) != 0)
  69463. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69464. else if ((flags & xLeft) == 0)
  69465. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69466. if ((flags & yBottom) != 0)
  69467. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69468. else if ((flags & yTop) == 0)
  69469. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69470. }
  69471. return AffineTransform::translation (-source.getX(), -source.getY())
  69472. .scaled (scaleX, scaleY)
  69473. .translated (newX, newY);
  69474. }
  69475. END_JUCE_NAMESPACE
  69476. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69477. /*** Start of inlined file: juce_Drawable.cpp ***/
  69478. BEGIN_JUCE_NAMESPACE
  69479. Drawable::Drawable()
  69480. {
  69481. setInterceptsMouseClicks (false, false);
  69482. setPaintingIsUnclipped (true);
  69483. }
  69484. Drawable::~Drawable()
  69485. {
  69486. }
  69487. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69488. {
  69489. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69490. }
  69491. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69492. {
  69493. Graphics::ScopedSaveState ss (g);
  69494. const float oldOpacity = getAlpha();
  69495. setAlpha (opacity);
  69496. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69497. (float) -originRelativeToComponent.getY())
  69498. .followedBy (getTransform())
  69499. .followedBy (transform));
  69500. if (! g.isClipEmpty())
  69501. paintEntireComponent (g, false);
  69502. setAlpha (oldOpacity);
  69503. }
  69504. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69505. {
  69506. draw (g, opacity, AffineTransform::translation (x, y));
  69507. }
  69508. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69509. {
  69510. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69511. }
  69512. DrawableComposite* Drawable::getParent() const
  69513. {
  69514. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69515. }
  69516. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69517. {
  69518. g.setOrigin (originRelativeToComponent.getX(),
  69519. originRelativeToComponent.getY());
  69520. }
  69521. void Drawable::parentHierarchyChanged()
  69522. {
  69523. setBoundsToEnclose (getDrawableBounds());
  69524. }
  69525. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69526. {
  69527. Drawable* const parent = getParent();
  69528. Point<int> parentOrigin;
  69529. if (parent != 0)
  69530. parentOrigin = parent->originRelativeToComponent;
  69531. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69532. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69533. setBounds (newBounds);
  69534. }
  69535. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69536. {
  69537. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69538. }
  69539. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69540. {
  69541. if (! area.isEmpty())
  69542. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69543. }
  69544. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69545. {
  69546. Drawable* result = 0;
  69547. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69548. if (image.isValid())
  69549. {
  69550. DrawableImage* const di = new DrawableImage();
  69551. di->setImage (image);
  69552. result = di;
  69553. }
  69554. else
  69555. {
  69556. const String asString (String::createStringFromData (data, (int) numBytes));
  69557. XmlDocument doc (asString);
  69558. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69559. if (outer != 0 && outer->hasTagName ("svg"))
  69560. {
  69561. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69562. if (svg != 0)
  69563. result = Drawable::createFromSVG (*svg);
  69564. }
  69565. }
  69566. return result;
  69567. }
  69568. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69569. {
  69570. MemoryOutputStream mo;
  69571. mo.writeFromInputStream (dataSource, -1);
  69572. return createFromImageData (mo.getData(), mo.getDataSize());
  69573. }
  69574. Drawable* Drawable::createFromImageFile (const File& file)
  69575. {
  69576. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69577. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69578. }
  69579. template <class DrawableClass>
  69580. class DrawableTypeHandler : public ComponentBuilder::TypeHandler
  69581. {
  69582. public:
  69583. DrawableTypeHandler()
  69584. : ComponentBuilder::TypeHandler (DrawableClass::valueTreeType)
  69585. {
  69586. }
  69587. Component* addNewComponentFromState (const ValueTree& state, Component* parent)
  69588. {
  69589. DrawableClass* const d = new DrawableClass();
  69590. if (parent != 0)
  69591. parent->addAndMakeVisible (d);
  69592. updateComponentFromState (d, state);
  69593. return d;
  69594. }
  69595. void updateComponentFromState (Component* component, const ValueTree& state)
  69596. {
  69597. DrawableClass* const d = dynamic_cast <DrawableClass*> (component);
  69598. jassert (d != 0);
  69599. d->refreshFromValueTree (state, *this->getBuilder());
  69600. }
  69601. };
  69602. void Drawable::registerDrawableTypeHandlers (ComponentBuilder& builder)
  69603. {
  69604. builder.registerTypeHandler (new DrawableTypeHandler <DrawablePath>());
  69605. builder.registerTypeHandler (new DrawableTypeHandler <DrawableComposite>());
  69606. builder.registerTypeHandler (new DrawableTypeHandler <DrawableRectangle>());
  69607. builder.registerTypeHandler (new DrawableTypeHandler <DrawableImage>());
  69608. builder.registerTypeHandler (new DrawableTypeHandler <DrawableText>());
  69609. }
  69610. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider)
  69611. {
  69612. ComponentBuilder builder (tree);
  69613. builder.setImageProvider (imageProvider);
  69614. registerDrawableTypeHandlers (builder);
  69615. ScopedPointer<Component> comp (builder.createComponent());
  69616. Drawable* const d = dynamic_cast<Drawable*> (static_cast <Component*> (comp));
  69617. if (d != 0)
  69618. comp.release();
  69619. return d;
  69620. }
  69621. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69622. : state (state_)
  69623. {
  69624. }
  69625. const String Drawable::ValueTreeWrapperBase::getID() const
  69626. {
  69627. return state [ComponentBuilder::idProperty];
  69628. }
  69629. void Drawable::ValueTreeWrapperBase::setID (const String& newID)
  69630. {
  69631. if (newID.isEmpty())
  69632. state.removeProperty (ComponentBuilder::idProperty, 0);
  69633. else
  69634. state.setProperty (ComponentBuilder::idProperty, newID, 0);
  69635. }
  69636. END_JUCE_NAMESPACE
  69637. /*** End of inlined file: juce_Drawable.cpp ***/
  69638. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69639. BEGIN_JUCE_NAMESPACE
  69640. DrawableShape::DrawableShape()
  69641. : strokeType (0.0f),
  69642. mainFill (Colours::black),
  69643. strokeFill (Colours::black)
  69644. {
  69645. }
  69646. DrawableShape::DrawableShape (const DrawableShape& other)
  69647. : strokeType (other.strokeType),
  69648. mainFill (other.mainFill),
  69649. strokeFill (other.strokeFill)
  69650. {
  69651. }
  69652. DrawableShape::~DrawableShape()
  69653. {
  69654. }
  69655. class DrawableShape::RelativePositioner : public RelativeCoordinatePositionerBase
  69656. {
  69657. public:
  69658. RelativePositioner (DrawableShape& component_, const DrawableShape::RelativeFillType& fill_, bool isMainFill_)
  69659. : RelativeCoordinatePositionerBase (component_),
  69660. owner (component_),
  69661. fill (fill_),
  69662. isMainFill (isMainFill_)
  69663. {
  69664. }
  69665. bool registerCoordinates()
  69666. {
  69667. bool ok = addPoint (fill.gradientPoint1);
  69668. ok = addPoint (fill.gradientPoint2) && ok;
  69669. return addPoint (fill.gradientPoint3) && ok;
  69670. }
  69671. void applyToComponentBounds()
  69672. {
  69673. if (isMainFill ? owner.mainFill.recalculateCoords (this)
  69674. : owner.strokeFill.recalculateCoords (this))
  69675. owner.repaint();
  69676. }
  69677. private:
  69678. DrawableShape& owner;
  69679. const DrawableShape::RelativeFillType fill;
  69680. const bool isMainFill;
  69681. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  69682. };
  69683. void DrawableShape::setFill (const FillType& newFill)
  69684. {
  69685. setFill (RelativeFillType (newFill));
  69686. }
  69687. void DrawableShape::setStrokeFill (const FillType& newFill)
  69688. {
  69689. setStrokeFill (RelativeFillType (newFill));
  69690. }
  69691. void DrawableShape::setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  69692. ScopedPointer<RelativeCoordinatePositionerBase>& positioner)
  69693. {
  69694. if (fill != newFill)
  69695. {
  69696. fill = newFill;
  69697. positioner = 0;
  69698. if (fill.isDynamic())
  69699. {
  69700. positioner = new RelativePositioner (*this, fill, true);
  69701. positioner->apply();
  69702. }
  69703. else
  69704. {
  69705. fill.recalculateCoords (0);
  69706. }
  69707. repaint();
  69708. }
  69709. }
  69710. void DrawableShape::setFill (const RelativeFillType& newFill)
  69711. {
  69712. setFillInternal (mainFill, newFill, mainFillPositioner);
  69713. }
  69714. void DrawableShape::setStrokeFill (const RelativeFillType& newFill)
  69715. {
  69716. setFillInternal (strokeFill, newFill, strokeFillPositioner);
  69717. }
  69718. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69719. {
  69720. if (strokeType != newStrokeType)
  69721. {
  69722. strokeType = newStrokeType;
  69723. strokeChanged();
  69724. }
  69725. }
  69726. void DrawableShape::setStrokeThickness (const float newThickness)
  69727. {
  69728. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69729. }
  69730. bool DrawableShape::isStrokeVisible() const throw()
  69731. {
  69732. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.fill.isInvisible();
  69733. }
  69734. void DrawableShape::refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider* imageProvider)
  69735. {
  69736. setFill (newState.getFill (FillAndStrokeState::fill, imageProvider));
  69737. setStrokeFill (newState.getFill (FillAndStrokeState::stroke, imageProvider));
  69738. }
  69739. void DrawableShape::writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69740. {
  69741. state.setFill (FillAndStrokeState::fill, mainFill, imageProvider, undoManager);
  69742. state.setFill (FillAndStrokeState::stroke, strokeFill, imageProvider, undoManager);
  69743. state.setStrokeType (strokeType, undoManager);
  69744. }
  69745. void DrawableShape::paint (Graphics& g)
  69746. {
  69747. transformContextToCorrectOrigin (g);
  69748. g.setFillType (mainFill.fill);
  69749. g.fillPath (path);
  69750. if (isStrokeVisible())
  69751. {
  69752. g.setFillType (strokeFill.fill);
  69753. g.fillPath (strokePath);
  69754. }
  69755. }
  69756. void DrawableShape::pathChanged()
  69757. {
  69758. strokeChanged();
  69759. }
  69760. void DrawableShape::strokeChanged()
  69761. {
  69762. strokePath.clear();
  69763. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  69764. setBoundsToEnclose (getDrawableBounds());
  69765. repaint();
  69766. }
  69767. const Rectangle<float> DrawableShape::getDrawableBounds() const
  69768. {
  69769. if (isStrokeVisible())
  69770. return strokePath.getBounds();
  69771. else
  69772. return path.getBounds();
  69773. }
  69774. bool DrawableShape::hitTest (int x, int y) const
  69775. {
  69776. const float globalX = (float) (x - originRelativeToComponent.getX());
  69777. const float globalY = (float) (y - originRelativeToComponent.getY());
  69778. return path.contains (globalX, globalY)
  69779. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  69780. }
  69781. DrawableShape::RelativeFillType::RelativeFillType()
  69782. {
  69783. }
  69784. DrawableShape::RelativeFillType::RelativeFillType (const FillType& fill_)
  69785. : fill (fill_)
  69786. {
  69787. if (fill.isGradient())
  69788. {
  69789. const ColourGradient& g = *fill.gradient;
  69790. gradientPoint1 = g.point1.transformedBy (fill.transform);
  69791. gradientPoint2 = g.point2.transformedBy (fill.transform);
  69792. gradientPoint3 = Point<float> (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69793. g.point1.getY() + g.point1.getX() - g.point2.getX())
  69794. .transformedBy (fill.transform);
  69795. fill.transform = AffineTransform::identity;
  69796. }
  69797. }
  69798. DrawableShape::RelativeFillType::RelativeFillType (const RelativeFillType& other)
  69799. : fill (other.fill),
  69800. gradientPoint1 (other.gradientPoint1),
  69801. gradientPoint2 (other.gradientPoint2),
  69802. gradientPoint3 (other.gradientPoint3)
  69803. {
  69804. }
  69805. DrawableShape::RelativeFillType& DrawableShape::RelativeFillType::operator= (const RelativeFillType& other)
  69806. {
  69807. fill = other.fill;
  69808. gradientPoint1 = other.gradientPoint1;
  69809. gradientPoint2 = other.gradientPoint2;
  69810. gradientPoint3 = other.gradientPoint3;
  69811. return *this;
  69812. }
  69813. bool DrawableShape::RelativeFillType::operator== (const RelativeFillType& other) const
  69814. {
  69815. return fill == other.fill
  69816. && ((! fill.isGradient())
  69817. || (gradientPoint1 == other.gradientPoint1
  69818. && gradientPoint2 == other.gradientPoint2
  69819. && gradientPoint3 == other.gradientPoint3));
  69820. }
  69821. bool DrawableShape::RelativeFillType::operator!= (const RelativeFillType& other) const
  69822. {
  69823. return ! operator== (other);
  69824. }
  69825. bool DrawableShape::RelativeFillType::recalculateCoords (Expression::EvaluationContext* context)
  69826. {
  69827. if (fill.isGradient())
  69828. {
  69829. const Point<float> g1 (gradientPoint1.resolve (context));
  69830. const Point<float> g2 (gradientPoint2.resolve (context));
  69831. AffineTransform t;
  69832. ColourGradient& g = *fill.gradient;
  69833. if (g.isRadial)
  69834. {
  69835. const Point<float> g3 (gradientPoint3.resolve (context));
  69836. const Point<float> g3Source (g1.getX() + g2.getY() - g1.getY(),
  69837. g1.getY() + g1.getX() - g2.getX());
  69838. t = AffineTransform::fromTargetPoints (g1.getX(), g1.getY(), g1.getX(), g1.getY(),
  69839. g2.getX(), g2.getY(), g2.getX(), g2.getY(),
  69840. g3Source.getX(), g3Source.getY(), g3.getX(), g3.getY());
  69841. }
  69842. if (g.point1 != g1 || g.point2 != g2 || fill.transform != t)
  69843. {
  69844. g.point1 = g1;
  69845. g.point2 = g2;
  69846. fill.transform = t;
  69847. return true;
  69848. }
  69849. }
  69850. return false;
  69851. }
  69852. bool DrawableShape::RelativeFillType::isDynamic() const
  69853. {
  69854. return gradientPoint1.isDynamic() || gradientPoint2.isDynamic() || gradientPoint3.isDynamic();
  69855. }
  69856. void DrawableShape::RelativeFillType::writeTo (ValueTree& v, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69857. {
  69858. if (fill.isColour())
  69859. {
  69860. v.setProperty (FillAndStrokeState::type, "solid", undoManager);
  69861. v.setProperty (FillAndStrokeState::colour, String::toHexString ((int) fill.colour.getARGB()), undoManager);
  69862. }
  69863. else if (fill.isGradient())
  69864. {
  69865. v.setProperty (FillAndStrokeState::type, "gradient", undoManager);
  69866. v.setProperty (FillAndStrokeState::gradientPoint1, gradientPoint1.toString(), undoManager);
  69867. v.setProperty (FillAndStrokeState::gradientPoint2, gradientPoint2.toString(), undoManager);
  69868. v.setProperty (FillAndStrokeState::gradientPoint3, gradientPoint3.toString(), undoManager);
  69869. const ColourGradient& cg = *fill.gradient;
  69870. v.setProperty (FillAndStrokeState::radial, cg.isRadial, undoManager);
  69871. String s;
  69872. for (int i = 0; i < cg.getNumColours(); ++i)
  69873. s << ' ' << cg.getColourPosition (i)
  69874. << ' ' << String::toHexString ((int) cg.getColour(i).getARGB());
  69875. v.setProperty (FillAndStrokeState::colours, s.trimStart(), undoManager);
  69876. }
  69877. else if (fill.isTiledImage())
  69878. {
  69879. v.setProperty (FillAndStrokeState::type, "image", undoManager);
  69880. if (imageProvider != 0)
  69881. v.setProperty (FillAndStrokeState::imageId, imageProvider->getIdentifierForImage (fill.image), undoManager);
  69882. if (fill.getOpacity() < 1.0f)
  69883. v.setProperty (FillAndStrokeState::imageOpacity, fill.getOpacity(), undoManager);
  69884. else
  69885. v.removeProperty (FillAndStrokeState::imageOpacity, undoManager);
  69886. }
  69887. else
  69888. {
  69889. jassertfalse;
  69890. }
  69891. }
  69892. bool DrawableShape::RelativeFillType::readFrom (const ValueTree& v, ComponentBuilder::ImageProvider* imageProvider)
  69893. {
  69894. const String newType (v [FillAndStrokeState::type].toString());
  69895. if (newType == "solid")
  69896. {
  69897. const String colourString (v [FillAndStrokeState::colour].toString());
  69898. fill.setColour (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69899. : (uint32) colourString.getHexValue32()));
  69900. return true;
  69901. }
  69902. else if (newType == "gradient")
  69903. {
  69904. ColourGradient g;
  69905. g.isRadial = v [FillAndStrokeState::radial];
  69906. StringArray colourSteps;
  69907. colourSteps.addTokens (v [FillAndStrokeState::colours].toString(), false);
  69908. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69909. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69910. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69911. fill.setGradient (g);
  69912. gradientPoint1 = RelativePoint (v [FillAndStrokeState::gradientPoint1]);
  69913. gradientPoint2 = RelativePoint (v [FillAndStrokeState::gradientPoint2]);
  69914. gradientPoint3 = RelativePoint (v [FillAndStrokeState::gradientPoint3]);
  69915. return true;
  69916. }
  69917. else if (newType == "image")
  69918. {
  69919. Image im;
  69920. if (imageProvider != 0)
  69921. im = imageProvider->getImageForIdentifier (v [FillAndStrokeState::imageId]);
  69922. fill.setTiledImage (im, AffineTransform::identity);
  69923. fill.setOpacity ((float) v.getProperty (FillAndStrokeState::imageOpacity, 1.0f));
  69924. return true;
  69925. }
  69926. jassertfalse;
  69927. return false;
  69928. }
  69929. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69930. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69931. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69932. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69933. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69934. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69935. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69936. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69937. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69938. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69939. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69940. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69941. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69942. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69943. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69944. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69945. : Drawable::ValueTreeWrapperBase (state_)
  69946. {
  69947. }
  69948. const DrawableShape::RelativeFillType DrawableShape::FillAndStrokeState::getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider* imageProvider) const
  69949. {
  69950. DrawableShape::RelativeFillType f;
  69951. f.readFrom (state.getChildWithName (fillOrStrokeType), imageProvider);
  69952. return f;
  69953. }
  69954. ValueTree DrawableShape::FillAndStrokeState::getFillState (const Identifier& fillOrStrokeType)
  69955. {
  69956. ValueTree v (state.getChildWithName (fillOrStrokeType));
  69957. if (v.isValid())
  69958. return v;
  69959. setFill (fillOrStrokeType, FillType (Colours::black), 0, 0);
  69960. return getFillState (fillOrStrokeType);
  69961. }
  69962. void DrawableShape::FillAndStrokeState::setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  69963. ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager)
  69964. {
  69965. ValueTree v (state.getOrCreateChildWithName (fillOrStrokeType, undoManager));
  69966. newFill.writeTo (v, imageProvider, undoManager);
  69967. }
  69968. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69969. {
  69970. const String jointStyleString (state [jointStyle].toString());
  69971. const String capStyleString (state [capStyle].toString());
  69972. return PathStrokeType (state [strokeWidth],
  69973. jointStyleString == "curved" ? PathStrokeType::curved
  69974. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69975. : PathStrokeType::mitered),
  69976. capStyleString == "square" ? PathStrokeType::square
  69977. : (capStyleString == "round" ? PathStrokeType::rounded
  69978. : PathStrokeType::butt));
  69979. }
  69980. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69981. {
  69982. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69983. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69984. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69985. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69986. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69987. }
  69988. END_JUCE_NAMESPACE
  69989. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69990. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69991. BEGIN_JUCE_NAMESPACE
  69992. DrawableComposite::DrawableComposite()
  69993. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  69994. updateBoundsReentrant (false)
  69995. {
  69996. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69997. RelativeCoordinate (100.0),
  69998. RelativeCoordinate (0.0),
  69999. RelativeCoordinate (100.0)));
  70000. }
  70001. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  70002. : bounds (other.bounds),
  70003. markersX (other.markersX),
  70004. markersY (other.markersY),
  70005. updateBoundsReentrant (false)
  70006. {
  70007. for (int i = 0; i < other.getNumChildComponents(); ++i)
  70008. {
  70009. const Drawable* const d = dynamic_cast <const Drawable*> (other.getChildComponent(i));
  70010. if (d != 0)
  70011. addAndMakeVisible (d->createCopy());
  70012. }
  70013. }
  70014. DrawableComposite::~DrawableComposite()
  70015. {
  70016. deleteAllChildren();
  70017. }
  70018. Drawable* DrawableComposite::createCopy() const
  70019. {
  70020. return new DrawableComposite (*this);
  70021. }
  70022. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  70023. {
  70024. Rectangle<float> r;
  70025. for (int i = getNumChildComponents(); --i >= 0;)
  70026. {
  70027. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70028. if (d != 0)
  70029. r = r.getUnion (d->isTransformed() ? d->getDrawableBounds().transformed (d->getTransform())
  70030. : d->getDrawableBounds());
  70031. }
  70032. return r;
  70033. }
  70034. MarkerList* DrawableComposite::getMarkers (bool xAxis)
  70035. {
  70036. return xAxis ? &markersX : &markersY;
  70037. }
  70038. const RelativeRectangle DrawableComposite::getContentArea() const
  70039. {
  70040. jassert (markersX.getNumMarkers() >= 2 && markersX.getMarker (0)->name == contentLeftMarkerName && markersX.getMarker (1)->name == contentRightMarkerName);
  70041. jassert (markersY.getNumMarkers() >= 2 && markersY.getMarker (0)->name == contentTopMarkerName && markersY.getMarker (1)->name == contentBottomMarkerName);
  70042. return RelativeRectangle (markersX.getMarker(0)->position, markersX.getMarker(1)->position,
  70043. markersY.getMarker(0)->position, markersY.getMarker(1)->position);
  70044. }
  70045. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  70046. {
  70047. markersX.setMarker (contentLeftMarkerName, newArea.left);
  70048. markersX.setMarker (contentRightMarkerName, newArea.right);
  70049. markersY.setMarker (contentTopMarkerName, newArea.top);
  70050. markersY.setMarker (contentBottomMarkerName, newArea.bottom);
  70051. }
  70052. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBounds)
  70053. {
  70054. if (bounds != newBounds)
  70055. {
  70056. bounds = newBounds;
  70057. if (bounds.isDynamic())
  70058. {
  70059. Drawable::Positioner<DrawableComposite>* const p = new Drawable::Positioner<DrawableComposite> (*this);
  70060. setPositioner (p);
  70061. p->apply();
  70062. }
  70063. else
  70064. {
  70065. setPositioner (0);
  70066. recalculateCoordinates (0);
  70067. }
  70068. }
  70069. }
  70070. void DrawableComposite::resetBoundingBoxToContentArea()
  70071. {
  70072. const RelativeRectangle content (getContentArea());
  70073. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70074. RelativePoint (content.right, content.top),
  70075. RelativePoint (content.left, content.bottom)));
  70076. }
  70077. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  70078. {
  70079. const Rectangle<float> activeArea (getDrawableBounds());
  70080. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  70081. RelativeCoordinate (activeArea.getRight()),
  70082. RelativeCoordinate (activeArea.getY()),
  70083. RelativeCoordinate (activeArea.getBottom())));
  70084. resetBoundingBoxToContentArea();
  70085. }
  70086. bool DrawableComposite::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70087. {
  70088. bool ok = positioner.addPoint (bounds.topLeft);
  70089. ok = positioner.addPoint (bounds.topRight) && ok;
  70090. return positioner.addPoint (bounds.bottomLeft) && ok;
  70091. }
  70092. void DrawableComposite::recalculateCoordinates (Expression::EvaluationContext* context)
  70093. {
  70094. Point<float> resolved[3];
  70095. bounds.resolveThreePoints (resolved, context);
  70096. const Rectangle<float> content (getContentArea().resolve (context));
  70097. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  70098. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  70099. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  70100. if (t.isSingularity())
  70101. t = AffineTransform::identity;
  70102. setTransform (t);
  70103. }
  70104. void DrawableComposite::parentHierarchyChanged()
  70105. {
  70106. DrawableComposite* parent = getParent();
  70107. if (parent != 0)
  70108. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  70109. }
  70110. void DrawableComposite::childBoundsChanged (Component*)
  70111. {
  70112. updateBoundsToFitChildren();
  70113. }
  70114. void DrawableComposite::childrenChanged()
  70115. {
  70116. updateBoundsToFitChildren();
  70117. }
  70118. void DrawableComposite::updateBoundsToFitChildren()
  70119. {
  70120. if (! updateBoundsReentrant)
  70121. {
  70122. const ScopedValueSetter<bool> setter (updateBoundsReentrant, true, false);
  70123. Rectangle<int> childArea;
  70124. for (int i = getNumChildComponents(); --i >= 0;)
  70125. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  70126. const Point<int> delta (childArea.getPosition());
  70127. childArea += getPosition();
  70128. if (childArea != getBounds())
  70129. {
  70130. if (! delta.isOrigin())
  70131. {
  70132. originRelativeToComponent -= delta;
  70133. for (int i = getNumChildComponents(); --i >= 0;)
  70134. {
  70135. Component* const c = getChildComponent(i);
  70136. if (c != 0)
  70137. c->setBounds (c->getBounds() - delta);
  70138. }
  70139. }
  70140. setBounds (childArea);
  70141. }
  70142. }
  70143. }
  70144. const char* const DrawableComposite::contentLeftMarkerName = "left";
  70145. const char* const DrawableComposite::contentRightMarkerName = "right";
  70146. const char* const DrawableComposite::contentTopMarkerName = "top";
  70147. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  70148. const Identifier DrawableComposite::valueTreeType ("Group");
  70149. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70150. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70151. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70152. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70153. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70154. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70155. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70156. : ValueTreeWrapperBase (state_)
  70157. {
  70158. jassert (state.hasType (valueTreeType));
  70159. }
  70160. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70161. {
  70162. return state.getChildWithName (childGroupTag);
  70163. }
  70164. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70165. {
  70166. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70167. }
  70168. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70169. {
  70170. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70171. state.getProperty (topRight, "100, 0"),
  70172. state.getProperty (bottomLeft, "0, 100"));
  70173. }
  70174. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70175. {
  70176. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70177. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70178. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70179. }
  70180. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70181. {
  70182. const RelativeRectangle content (getContentArea());
  70183. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70184. RelativePoint (content.right, content.top),
  70185. RelativePoint (content.left, content.bottom)), undoManager);
  70186. }
  70187. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70188. {
  70189. MarkerList::ValueTreeWrapper markersX (getMarkerList (true));
  70190. MarkerList::ValueTreeWrapper markersY (getMarkerList (false));
  70191. return RelativeRectangle (markersX.getMarker (markersX.getMarkerState (0)).position,
  70192. markersX.getMarker (markersX.getMarkerState (1)).position,
  70193. markersY.getMarker (markersY.getMarkerState (0)).position,
  70194. markersY.getMarker (markersY.getMarkerState (1)).position);
  70195. }
  70196. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70197. {
  70198. MarkerList::ValueTreeWrapper markersX (getMarkerListCreating (true, 0));
  70199. MarkerList::ValueTreeWrapper markersY (getMarkerListCreating (false, 0));
  70200. markersX.setMarker (MarkerList::Marker (contentLeftMarkerName, newArea.left), undoManager);
  70201. markersX.setMarker (MarkerList::Marker (contentRightMarkerName, newArea.right), undoManager);
  70202. markersY.setMarker (MarkerList::Marker (contentTopMarkerName, newArea.top), undoManager);
  70203. markersY.setMarker (MarkerList::Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70204. }
  70205. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70206. {
  70207. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70208. }
  70209. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70210. {
  70211. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70212. }
  70213. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70214. {
  70215. const ValueTreeWrapper wrapper (tree);
  70216. setComponentID (wrapper.getID());
  70217. wrapper.getMarkerList (true).applyTo (markersX);
  70218. wrapper.getMarkerList (false).applyTo (markersY);
  70219. setBoundingBox (wrapper.getBoundingBox());
  70220. builder.updateChildComponents (*this, wrapper.getChildList());
  70221. }
  70222. const ValueTree DrawableComposite::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70223. {
  70224. ValueTree tree (valueTreeType);
  70225. ValueTreeWrapper v (tree);
  70226. v.setID (getComponentID());
  70227. v.setBoundingBox (bounds, 0);
  70228. ValueTree childList (v.getChildListCreating (0));
  70229. for (int i = getNumChildComponents(); --i >= 0;)
  70230. {
  70231. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70232. jassert (d != 0); // You can't save a mix of Drawables and normal components!
  70233. childList.addChild (d->createValueTree (imageProvider), -1, 0);
  70234. }
  70235. v.getMarkerListCreating (true, 0).readFrom (markersX, 0);
  70236. v.getMarkerListCreating (false, 0).readFrom (markersY, 0);
  70237. return tree;
  70238. }
  70239. END_JUCE_NAMESPACE
  70240. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70241. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70242. BEGIN_JUCE_NAMESPACE
  70243. DrawableImage::DrawableImage()
  70244. : image (0),
  70245. opacity (1.0f),
  70246. overlayColour (0x00000000)
  70247. {
  70248. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70249. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70250. }
  70251. DrawableImage::DrawableImage (const DrawableImage& other)
  70252. : image (other.image),
  70253. opacity (other.opacity),
  70254. overlayColour (other.overlayColour),
  70255. bounds (other.bounds)
  70256. {
  70257. }
  70258. DrawableImage::~DrawableImage()
  70259. {
  70260. }
  70261. void DrawableImage::setImage (const Image& imageToUse)
  70262. {
  70263. image = imageToUse;
  70264. setBounds (imageToUse.getBounds());
  70265. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70266. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70267. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70268. recalculateCoordinates (0);
  70269. repaint();
  70270. }
  70271. void DrawableImage::setOpacity (const float newOpacity)
  70272. {
  70273. opacity = newOpacity;
  70274. }
  70275. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70276. {
  70277. overlayColour = newOverlayColour;
  70278. }
  70279. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70280. {
  70281. if (bounds != newBounds)
  70282. {
  70283. bounds = newBounds;
  70284. if (bounds.isDynamic())
  70285. {
  70286. Drawable::Positioner<DrawableImage>* const p = new Drawable::Positioner<DrawableImage> (*this);
  70287. setPositioner (p);
  70288. p->apply();
  70289. }
  70290. else
  70291. {
  70292. setPositioner (0);
  70293. recalculateCoordinates (0);
  70294. }
  70295. }
  70296. }
  70297. bool DrawableImage::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70298. {
  70299. bool ok = positioner.addPoint (bounds.topLeft);
  70300. ok = positioner.addPoint (bounds.topRight) && ok;
  70301. return positioner.addPoint (bounds.bottomLeft) && ok;
  70302. }
  70303. void DrawableImage::recalculateCoordinates (Expression::EvaluationContext* context)
  70304. {
  70305. if (image.isValid())
  70306. {
  70307. Point<float> resolved[3];
  70308. bounds.resolveThreePoints (resolved, context);
  70309. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70310. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70311. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70312. tr.getX(), tr.getY(),
  70313. bl.getX(), bl.getY()));
  70314. if (t.isSingularity())
  70315. t = AffineTransform::identity;
  70316. setTransform (t);
  70317. }
  70318. }
  70319. void DrawableImage::paint (Graphics& g)
  70320. {
  70321. if (image.isValid())
  70322. {
  70323. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70324. {
  70325. g.setOpacity (opacity);
  70326. g.drawImageAt (image, 0, 0, false);
  70327. }
  70328. if (! overlayColour.isTransparent())
  70329. {
  70330. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70331. g.drawImageAt (image, 0, 0, true);
  70332. }
  70333. }
  70334. }
  70335. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70336. {
  70337. return image.getBounds().toFloat();
  70338. }
  70339. bool DrawableImage::hitTest (int x, int y) const
  70340. {
  70341. return (! image.isNull())
  70342. && image.getPixelAt (x, y).getAlpha() >= 127;
  70343. }
  70344. Drawable* DrawableImage::createCopy() const
  70345. {
  70346. return new DrawableImage (*this);
  70347. }
  70348. const Identifier DrawableImage::valueTreeType ("Image");
  70349. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70350. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70351. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70352. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70353. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70354. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70355. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70356. : ValueTreeWrapperBase (state_)
  70357. {
  70358. jassert (state.hasType (valueTreeType));
  70359. }
  70360. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70361. {
  70362. return state [image];
  70363. }
  70364. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70365. {
  70366. return state.getPropertyAsValue (image, undoManager);
  70367. }
  70368. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70369. {
  70370. state.setProperty (image, newIdentifier, undoManager);
  70371. }
  70372. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70373. {
  70374. return (float) state.getProperty (opacity, 1.0);
  70375. }
  70376. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70377. {
  70378. if (! state.hasProperty (opacity))
  70379. state.setProperty (opacity, 1.0, undoManager);
  70380. return state.getPropertyAsValue (opacity, undoManager);
  70381. }
  70382. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70383. {
  70384. state.setProperty (opacity, newOpacity, undoManager);
  70385. }
  70386. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70387. {
  70388. return Colour (state [overlay].toString().getHexValue32());
  70389. }
  70390. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70391. {
  70392. if (newColour.isTransparent())
  70393. state.removeProperty (overlay, undoManager);
  70394. else
  70395. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70396. }
  70397. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70398. {
  70399. return state.getPropertyAsValue (overlay, undoManager);
  70400. }
  70401. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70402. {
  70403. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70404. state.getProperty (topRight, "100, 0"),
  70405. state.getProperty (bottomLeft, "0, 100"));
  70406. }
  70407. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70408. {
  70409. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70410. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70411. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70412. }
  70413. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70414. {
  70415. const ValueTreeWrapper controller (tree);
  70416. setComponentID (controller.getID());
  70417. const float newOpacity = controller.getOpacity();
  70418. const Colour newOverlayColour (controller.getOverlayColour());
  70419. Image newImage;
  70420. const var imageIdentifier (controller.getImageIdentifier());
  70421. jassert (builder.getImageProvider() != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70422. if (builder.getImageProvider() != 0)
  70423. newImage = builder.getImageProvider()->getImageForIdentifier (imageIdentifier);
  70424. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70425. if (bounds != newBounds || newOpacity != opacity
  70426. || overlayColour != newOverlayColour || image != newImage)
  70427. {
  70428. repaint();
  70429. opacity = newOpacity;
  70430. overlayColour = newOverlayColour;
  70431. if (image != newImage)
  70432. setImage (newImage);
  70433. setBoundingBox (newBounds);
  70434. }
  70435. }
  70436. const ValueTree DrawableImage::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70437. {
  70438. ValueTree tree (valueTreeType);
  70439. ValueTreeWrapper v (tree);
  70440. v.setID (getComponentID());
  70441. v.setOpacity (opacity, 0);
  70442. v.setOverlayColour (overlayColour, 0);
  70443. v.setBoundingBox (bounds, 0);
  70444. if (image.isValid())
  70445. {
  70446. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70447. if (imageProvider != 0)
  70448. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70449. }
  70450. return tree;
  70451. }
  70452. END_JUCE_NAMESPACE
  70453. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70454. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70455. BEGIN_JUCE_NAMESPACE
  70456. DrawablePath::DrawablePath()
  70457. {
  70458. }
  70459. DrawablePath::DrawablePath (const DrawablePath& other)
  70460. : DrawableShape (other)
  70461. {
  70462. if (other.relativePath != 0)
  70463. setPath (*other.relativePath);
  70464. else
  70465. setPath (other.path);
  70466. }
  70467. DrawablePath::~DrawablePath()
  70468. {
  70469. }
  70470. Drawable* DrawablePath::createCopy() const
  70471. {
  70472. return new DrawablePath (*this);
  70473. }
  70474. void DrawablePath::setPath (const Path& newPath)
  70475. {
  70476. path = newPath;
  70477. pathChanged();
  70478. }
  70479. const Path& DrawablePath::getPath() const
  70480. {
  70481. return path;
  70482. }
  70483. const Path& DrawablePath::getStrokePath() const
  70484. {
  70485. return strokePath;
  70486. }
  70487. void DrawablePath::applyRelativePath (const RelativePointPath& newRelativePath, Expression::EvaluationContext* context)
  70488. {
  70489. Path newPath;
  70490. newRelativePath.createPath (newPath, context);
  70491. if (path != newPath)
  70492. {
  70493. path.swapWithPath (newPath);
  70494. pathChanged();
  70495. }
  70496. }
  70497. class DrawablePath::RelativePositioner : public RelativeCoordinatePositionerBase
  70498. {
  70499. public:
  70500. RelativePositioner (DrawablePath& component_)
  70501. : RelativeCoordinatePositionerBase (component_),
  70502. owner (component_)
  70503. {
  70504. }
  70505. bool registerCoordinates()
  70506. {
  70507. bool ok = true;
  70508. jassert (owner.relativePath != 0);
  70509. const RelativePointPath& path = *owner.relativePath;
  70510. for (int i = 0; i < path.elements.size(); ++i)
  70511. {
  70512. RelativePointPath::ElementBase* const e = path.elements.getUnchecked(i);
  70513. int numPoints;
  70514. RelativePoint* const points = e->getControlPoints (numPoints);
  70515. for (int j = numPoints; --j >= 0;)
  70516. ok = addPoint (points[j]) && ok;
  70517. }
  70518. return ok;
  70519. }
  70520. void applyToComponentBounds()
  70521. {
  70522. jassert (owner.relativePath != 0);
  70523. owner.applyRelativePath (*owner.relativePath, this);
  70524. }
  70525. private:
  70526. DrawablePath& owner;
  70527. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70528. };
  70529. void DrawablePath::setPath (const RelativePointPath& newRelativePath)
  70530. {
  70531. if (newRelativePath.containsAnyDynamicPoints())
  70532. {
  70533. if (relativePath == 0 || newRelativePath != *relativePath)
  70534. {
  70535. relativePath = new RelativePointPath (newRelativePath);
  70536. RelativePositioner* const p = new RelativePositioner (*this);
  70537. setPositioner (p);
  70538. p->apply();
  70539. }
  70540. }
  70541. else
  70542. {
  70543. relativePath = 0;
  70544. applyRelativePath (newRelativePath, 0);
  70545. }
  70546. }
  70547. const Identifier DrawablePath::valueTreeType ("Path");
  70548. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70549. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70550. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70551. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70552. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70553. : FillAndStrokeState (state_)
  70554. {
  70555. jassert (state.hasType (valueTreeType));
  70556. }
  70557. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70558. {
  70559. return state.getOrCreateChildWithName (path, 0);
  70560. }
  70561. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70562. {
  70563. return state [nonZeroWinding];
  70564. }
  70565. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70566. {
  70567. state.setProperty (nonZeroWinding, b, undoManager);
  70568. }
  70569. void DrawablePath::ValueTreeWrapper::readFrom (const RelativePointPath& relativePath, UndoManager* undoManager)
  70570. {
  70571. setUsesNonZeroWinding (relativePath.usesNonZeroWinding, undoManager);
  70572. ValueTree pathTree (getPathState());
  70573. pathTree.removeAllChildren (undoManager);
  70574. for (int i = 0; i < relativePath.elements.size(); ++i)
  70575. pathTree.addChild (relativePath.elements.getUnchecked(i)->createTree(), -1, undoManager);
  70576. }
  70577. void DrawablePath::ValueTreeWrapper::writeTo (RelativePointPath& relativePath) const
  70578. {
  70579. relativePath.usesNonZeroWinding = usesNonZeroWinding();
  70580. RelativePoint points[3];
  70581. const ValueTree pathTree (state.getChildWithName (path));
  70582. const int num = pathTree.getNumChildren();
  70583. for (int i = 0; i < num; ++i)
  70584. {
  70585. const Element e (pathTree.getChild(i));
  70586. const int numCps = e.getNumControlPoints();
  70587. for (int j = 0; j < numCps; ++j)
  70588. points[j] = e.getControlPoint (j);
  70589. const Identifier type (e.getType());
  70590. RelativePointPath::ElementBase* newElement = 0;
  70591. if (type == Element::startSubPathElement) newElement = new RelativePointPath::StartSubPath (points[0]);
  70592. else if (type == Element::closeSubPathElement) newElement = new RelativePointPath::CloseSubPath();
  70593. else if (type == Element::lineToElement) newElement = new RelativePointPath::LineTo (points[0]);
  70594. else if (type == Element::quadraticToElement) newElement = new RelativePointPath::QuadraticTo (points[0], points[1]);
  70595. else if (type == Element::cubicToElement) newElement = new RelativePointPath::CubicTo (points[0], points[1], points[2]);
  70596. else jassertfalse;
  70597. relativePath.addElement (newElement);
  70598. }
  70599. }
  70600. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70601. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70602. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70603. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70604. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70605. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70606. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70607. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70608. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70609. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70610. : state (state_)
  70611. {
  70612. }
  70613. DrawablePath::ValueTreeWrapper::Element::~Element()
  70614. {
  70615. }
  70616. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70617. {
  70618. return ValueTreeWrapper (state.getParent().getParent());
  70619. }
  70620. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70621. {
  70622. return Element (state.getSibling (-1));
  70623. }
  70624. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70625. {
  70626. const Identifier i (state.getType());
  70627. if (i == startSubPathElement || i == lineToElement) return 1;
  70628. if (i == quadraticToElement) return 2;
  70629. if (i == cubicToElement) return 3;
  70630. return 0;
  70631. }
  70632. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70633. {
  70634. jassert (index >= 0 && index < getNumControlPoints());
  70635. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70636. }
  70637. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70638. {
  70639. jassert (index >= 0 && index < getNumControlPoints());
  70640. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70641. }
  70642. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70643. {
  70644. jassert (index >= 0 && index < getNumControlPoints());
  70645. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70646. }
  70647. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70648. {
  70649. const Identifier i (state.getType());
  70650. if (i == startSubPathElement)
  70651. return getControlPoint (0);
  70652. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70653. return getPreviousElement().getEndPoint();
  70654. }
  70655. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70656. {
  70657. const Identifier i (state.getType());
  70658. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70659. if (i == quadraticToElement) return getControlPoint (1);
  70660. if (i == cubicToElement) return getControlPoint (2);
  70661. jassert (i == closeSubPathElement);
  70662. return RelativePoint();
  70663. }
  70664. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* context) const
  70665. {
  70666. const Identifier i (state.getType());
  70667. if (i == lineToElement || i == closeSubPathElement)
  70668. return getEndPoint().resolve (context).getDistanceFrom (getStartPoint().resolve (context));
  70669. if (i == cubicToElement)
  70670. {
  70671. Path p;
  70672. p.startNewSubPath (getStartPoint().resolve (context));
  70673. p.cubicTo (getControlPoint (0).resolve (context), getControlPoint (1).resolve (context), getControlPoint (2).resolve (context));
  70674. return p.getLength();
  70675. }
  70676. if (i == quadraticToElement)
  70677. {
  70678. Path p;
  70679. p.startNewSubPath (getStartPoint().resolve (context));
  70680. p.quadraticTo (getControlPoint (0).resolve (context), getControlPoint (1).resolve (context));
  70681. return p.getLength();
  70682. }
  70683. jassert (i == startSubPathElement);
  70684. return 0;
  70685. }
  70686. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70687. {
  70688. return state [mode].toString();
  70689. }
  70690. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70691. {
  70692. if (state.hasType (cubicToElement))
  70693. state.setProperty (mode, newMode, undoManager);
  70694. }
  70695. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70696. {
  70697. const Identifier i (state.getType());
  70698. if (i == quadraticToElement || i == cubicToElement)
  70699. {
  70700. ValueTree newState (lineToElement);
  70701. Element e (newState);
  70702. e.setControlPoint (0, getEndPoint(), undoManager);
  70703. state = newState;
  70704. }
  70705. }
  70706. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* context, UndoManager* undoManager)
  70707. {
  70708. const Identifier i (state.getType());
  70709. if (i == lineToElement || i == quadraticToElement)
  70710. {
  70711. ValueTree newState (cubicToElement);
  70712. Element e (newState);
  70713. const RelativePoint start (getStartPoint());
  70714. const RelativePoint end (getEndPoint());
  70715. const Point<float> startResolved (start.resolve (context));
  70716. const Point<float> endResolved (end.resolve (context));
  70717. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70718. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70719. e.setControlPoint (2, end, undoManager);
  70720. state = newState;
  70721. }
  70722. }
  70723. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70724. {
  70725. const Identifier i (state.getType());
  70726. if (i != startSubPathElement)
  70727. {
  70728. ValueTree newState (startSubPathElement);
  70729. Element e (newState);
  70730. e.setControlPoint (0, getEndPoint(), undoManager);
  70731. state = newState;
  70732. }
  70733. }
  70734. namespace DrawablePathHelpers
  70735. {
  70736. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70737. {
  70738. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70739. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70740. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70741. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70742. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70743. return newCp1 + (newCp2 - newCp1) * proportion;
  70744. }
  70745. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70746. {
  70747. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70748. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70749. return mid1 + (mid2 - mid1) * proportion;
  70750. }
  70751. }
  70752. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* context) const
  70753. {
  70754. using namespace DrawablePathHelpers;
  70755. const Identifier type (state.getType());
  70756. float bestProp = 0;
  70757. if (type == cubicToElement)
  70758. {
  70759. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70760. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context), rp4.resolve (context) };
  70761. float bestDistance = std::numeric_limits<float>::max();
  70762. for (int i = 110; --i >= 0;)
  70763. {
  70764. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70765. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70766. const float distance = centre.getDistanceFrom (targetPoint);
  70767. if (distance < bestDistance)
  70768. {
  70769. bestProp = prop;
  70770. bestDistance = distance;
  70771. }
  70772. }
  70773. }
  70774. else if (type == quadraticToElement)
  70775. {
  70776. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70777. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context) };
  70778. float bestDistance = std::numeric_limits<float>::max();
  70779. for (int i = 110; --i >= 0;)
  70780. {
  70781. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70782. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70783. const float distance = centre.getDistanceFrom (targetPoint);
  70784. if (distance < bestDistance)
  70785. {
  70786. bestProp = prop;
  70787. bestDistance = distance;
  70788. }
  70789. }
  70790. }
  70791. else if (type == lineToElement)
  70792. {
  70793. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70794. const Line<float> line (rp1.resolve (context), rp2.resolve (context));
  70795. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70796. }
  70797. return bestProp;
  70798. }
  70799. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* context, UndoManager* undoManager)
  70800. {
  70801. ValueTree newTree;
  70802. const Identifier type (state.getType());
  70803. if (type == cubicToElement)
  70804. {
  70805. float bestProp = findProportionAlongLine (targetPoint, context);
  70806. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70807. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context), rp4.resolve (context) };
  70808. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70809. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70810. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70811. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70812. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70813. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70814. setControlPoint (0, mid1, undoManager);
  70815. setControlPoint (1, newCp1, undoManager);
  70816. setControlPoint (2, newCentre, undoManager);
  70817. setModeOfEndPoint (roundedMode, undoManager);
  70818. Element newElement (newTree = ValueTree (cubicToElement));
  70819. newElement.setControlPoint (0, newCp2, 0);
  70820. newElement.setControlPoint (1, mid3, 0);
  70821. newElement.setControlPoint (2, rp4, 0);
  70822. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70823. }
  70824. else if (type == quadraticToElement)
  70825. {
  70826. float bestProp = findProportionAlongLine (targetPoint, context);
  70827. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70828. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context) };
  70829. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70830. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70831. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70832. setControlPoint (0, mid1, undoManager);
  70833. setControlPoint (1, newCentre, undoManager);
  70834. setModeOfEndPoint (roundedMode, undoManager);
  70835. Element newElement (newTree = ValueTree (quadraticToElement));
  70836. newElement.setControlPoint (0, mid2, 0);
  70837. newElement.setControlPoint (1, rp3, 0);
  70838. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70839. }
  70840. else if (type == lineToElement)
  70841. {
  70842. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70843. const Line<float> line (rp1.resolve (context), rp2.resolve (context));
  70844. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70845. setControlPoint (0, newPoint, undoManager);
  70846. Element newElement (newTree = ValueTree (lineToElement));
  70847. newElement.setControlPoint (0, rp2, 0);
  70848. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70849. }
  70850. else if (type == closeSubPathElement)
  70851. {
  70852. }
  70853. return newTree;
  70854. }
  70855. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70856. {
  70857. state.getParent().removeChild (state, undoManager);
  70858. }
  70859. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70860. {
  70861. ValueTreeWrapper v (tree);
  70862. setComponentID (v.getID());
  70863. refreshFillTypes (v, builder.getImageProvider());
  70864. setStrokeType (v.getStrokeType());
  70865. RelativePointPath newRelativePath;
  70866. v.writeTo (newRelativePath);
  70867. setPath (newRelativePath);
  70868. }
  70869. const ValueTree DrawablePath::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70870. {
  70871. ValueTree tree (valueTreeType);
  70872. ValueTreeWrapper v (tree);
  70873. v.setID (getComponentID());
  70874. writeTo (v, imageProvider, 0);
  70875. if (relativePath != 0)
  70876. v.readFrom (*relativePath, 0);
  70877. else
  70878. v.readFrom (RelativePointPath (path), 0);
  70879. return tree;
  70880. }
  70881. END_JUCE_NAMESPACE
  70882. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70883. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70884. BEGIN_JUCE_NAMESPACE
  70885. DrawableRectangle::DrawableRectangle()
  70886. {
  70887. }
  70888. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70889. : DrawableShape (other),
  70890. bounds (other.bounds),
  70891. cornerSize (other.cornerSize)
  70892. {
  70893. }
  70894. DrawableRectangle::~DrawableRectangle()
  70895. {
  70896. }
  70897. Drawable* DrawableRectangle::createCopy() const
  70898. {
  70899. return new DrawableRectangle (*this);
  70900. }
  70901. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70902. {
  70903. if (bounds != newBounds)
  70904. {
  70905. bounds = newBounds;
  70906. rebuildPath();
  70907. }
  70908. }
  70909. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70910. {
  70911. if (cornerSize != newSize)
  70912. {
  70913. cornerSize = newSize;
  70914. rebuildPath();
  70915. }
  70916. }
  70917. void DrawableRectangle::rebuildPath()
  70918. {
  70919. if (bounds.isDynamic() || cornerSize.isDynamic())
  70920. {
  70921. Drawable::Positioner<DrawableRectangle>* const p = new Drawable::Positioner<DrawableRectangle> (*this);
  70922. setPositioner (p);
  70923. p->apply();
  70924. }
  70925. else
  70926. {
  70927. setPositioner (0);
  70928. recalculateCoordinates (0);
  70929. }
  70930. }
  70931. bool DrawableRectangle::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70932. {
  70933. bool ok = positioner.addPoint (bounds.topLeft);
  70934. ok = positioner.addPoint (bounds.topRight) && ok;
  70935. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70936. return positioner.addPoint (cornerSize) && ok;
  70937. }
  70938. void DrawableRectangle::recalculateCoordinates (Expression::EvaluationContext* context)
  70939. {
  70940. Point<float> points[3];
  70941. bounds.resolveThreePoints (points, context);
  70942. const float cornerSizeX = (float) cornerSize.x.resolve (context);
  70943. const float cornerSizeY = (float) cornerSize.y.resolve (context);
  70944. const float w = Line<float> (points[0], points[1]).getLength();
  70945. const float h = Line<float> (points[0], points[2]).getLength();
  70946. Path newPath;
  70947. if (cornerSizeX > 0 && cornerSizeY > 0)
  70948. newPath.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70949. else
  70950. newPath.addRectangle (0, 0, w, h);
  70951. newPath.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70952. w, 0, points[1].getX(), points[1].getY(),
  70953. 0, h, points[2].getX(), points[2].getY()));
  70954. if (path != newPath)
  70955. {
  70956. path.swapWithPath (newPath);
  70957. pathChanged();
  70958. }
  70959. }
  70960. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70961. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70962. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70963. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70964. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70965. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70966. : FillAndStrokeState (state_)
  70967. {
  70968. jassert (state.hasType (valueTreeType));
  70969. }
  70970. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70971. {
  70972. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70973. state.getProperty (topRight, "100, 0"),
  70974. state.getProperty (bottomLeft, "0, 100"));
  70975. }
  70976. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70977. {
  70978. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70979. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70980. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70981. }
  70982. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70983. {
  70984. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70985. }
  70986. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70987. {
  70988. return RelativePoint (state [cornerSize]);
  70989. }
  70990. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70991. {
  70992. return state.getPropertyAsValue (cornerSize, undoManager);
  70993. }
  70994. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70995. {
  70996. ValueTreeWrapper v (tree);
  70997. setComponentID (v.getID());
  70998. refreshFillTypes (v, builder.getImageProvider());
  70999. setStrokeType (v.getStrokeType());
  71000. setRectangle (v.getRectangle());
  71001. setCornerSize (v.getCornerSize());
  71002. }
  71003. const ValueTree DrawableRectangle::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  71004. {
  71005. ValueTree tree (valueTreeType);
  71006. ValueTreeWrapper v (tree);
  71007. v.setID (getComponentID());
  71008. writeTo (v, imageProvider, 0);
  71009. v.setRectangle (bounds, 0);
  71010. v.setCornerSize (cornerSize, 0);
  71011. return tree;
  71012. }
  71013. END_JUCE_NAMESPACE
  71014. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  71015. /*** Start of inlined file: juce_DrawableText.cpp ***/
  71016. BEGIN_JUCE_NAMESPACE
  71017. DrawableText::DrawableText()
  71018. : colour (Colours::black),
  71019. justification (Justification::centredLeft)
  71020. {
  71021. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  71022. RelativePoint (50.0f, 0.0f),
  71023. RelativePoint (0.0f, 20.0f)));
  71024. setFont (Font (15.0f), true);
  71025. }
  71026. DrawableText::DrawableText (const DrawableText& other)
  71027. : bounds (other.bounds),
  71028. fontSizeControlPoint (other.fontSizeControlPoint),
  71029. font (other.font),
  71030. text (other.text),
  71031. colour (other.colour),
  71032. justification (other.justification)
  71033. {
  71034. }
  71035. DrawableText::~DrawableText()
  71036. {
  71037. }
  71038. void DrawableText::setText (const String& newText)
  71039. {
  71040. if (text != newText)
  71041. {
  71042. text = newText;
  71043. refreshBounds();
  71044. }
  71045. }
  71046. void DrawableText::setColour (const Colour& newColour)
  71047. {
  71048. if (colour != newColour)
  71049. {
  71050. colour = newColour;
  71051. repaint();
  71052. }
  71053. }
  71054. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  71055. {
  71056. if (font != newFont)
  71057. {
  71058. font = newFont;
  71059. if (applySizeAndScale)
  71060. {
  71061. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (resolvedPoints,
  71062. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  71063. }
  71064. refreshBounds();
  71065. }
  71066. }
  71067. void DrawableText::setJustification (const Justification& newJustification)
  71068. {
  71069. justification = newJustification;
  71070. repaint();
  71071. }
  71072. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  71073. {
  71074. if (bounds != newBounds)
  71075. {
  71076. bounds = newBounds;
  71077. refreshBounds();
  71078. }
  71079. }
  71080. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  71081. {
  71082. if (fontSizeControlPoint != newPoint)
  71083. {
  71084. fontSizeControlPoint = newPoint;
  71085. refreshBounds();
  71086. }
  71087. }
  71088. void DrawableText::refreshBounds()
  71089. {
  71090. if (bounds.isDynamic() || fontSizeControlPoint.isDynamic())
  71091. {
  71092. Drawable::Positioner<DrawableText>* const p = new Drawable::Positioner<DrawableText> (*this);
  71093. setPositioner (p);
  71094. p->apply();
  71095. }
  71096. else
  71097. {
  71098. setPositioner (0);
  71099. recalculateCoordinates (0);
  71100. }
  71101. }
  71102. bool DrawableText::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  71103. {
  71104. bool ok = positioner.addPoint (bounds.topLeft);
  71105. ok = positioner.addPoint (bounds.topRight) && ok;
  71106. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  71107. return positioner.addPoint (fontSizeControlPoint) && ok;
  71108. }
  71109. void DrawableText::recalculateCoordinates (Expression::EvaluationContext* context)
  71110. {
  71111. bounds.resolveThreePoints (resolvedPoints, context);
  71112. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71113. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71114. const Point<float> fontCoords (RelativeParallelogram::getInternalCoordForPoint (resolvedPoints, fontSizeControlPoint.resolve (context)));
  71115. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  71116. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  71117. scaledFont = font;
  71118. scaledFont.setHeight (fontHeight);
  71119. scaledFont.setHorizontalScale (fontWidth / fontHeight);
  71120. setBoundsToEnclose (getDrawableBounds());
  71121. repaint();
  71122. }
  71123. const AffineTransform DrawableText::getArrangementAndTransform (GlyphArrangement& glyphs) const
  71124. {
  71125. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71126. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71127. glyphs.addFittedText (scaledFont, text, 0, 0, w, h, justification, 0x100000);
  71128. return AffineTransform::fromTargetPoints (0, 0, resolvedPoints[0].getX(), resolvedPoints[0].getY(),
  71129. w, 0, resolvedPoints[1].getX(), resolvedPoints[1].getY(),
  71130. 0, h, resolvedPoints[2].getX(), resolvedPoints[2].getY());
  71131. }
  71132. void DrawableText::paint (Graphics& g)
  71133. {
  71134. transformContextToCorrectOrigin (g);
  71135. g.setColour (colour);
  71136. GlyphArrangement ga;
  71137. const AffineTransform transform (getArrangementAndTransform (ga));
  71138. ga.draw (g, transform);
  71139. }
  71140. const Rectangle<float> DrawableText::getDrawableBounds() const
  71141. {
  71142. return RelativeParallelogram::getBoundingBox (resolvedPoints);
  71143. }
  71144. Drawable* DrawableText::createCopy() const
  71145. {
  71146. return new DrawableText (*this);
  71147. }
  71148. const Identifier DrawableText::valueTreeType ("Text");
  71149. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71150. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71151. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71152. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71153. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71154. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71155. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71156. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71157. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71158. : ValueTreeWrapperBase (state_)
  71159. {
  71160. jassert (state.hasType (valueTreeType));
  71161. }
  71162. const String DrawableText::ValueTreeWrapper::getText() const
  71163. {
  71164. return state [text].toString();
  71165. }
  71166. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71167. {
  71168. state.setProperty (text, newText, undoManager);
  71169. }
  71170. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71171. {
  71172. return state.getPropertyAsValue (text, undoManager);
  71173. }
  71174. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71175. {
  71176. return Colour::fromString (state [colour].toString());
  71177. }
  71178. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71179. {
  71180. state.setProperty (colour, newColour.toString(), undoManager);
  71181. }
  71182. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71183. {
  71184. return Justification ((int) state [justification]);
  71185. }
  71186. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71187. {
  71188. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71189. }
  71190. const Font DrawableText::ValueTreeWrapper::getFont() const
  71191. {
  71192. return Font::fromString (state [font]);
  71193. }
  71194. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71195. {
  71196. state.setProperty (font, newFont.toString(), undoManager);
  71197. }
  71198. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71199. {
  71200. return state.getPropertyAsValue (font, undoManager);
  71201. }
  71202. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71203. {
  71204. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71205. }
  71206. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71207. {
  71208. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71209. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71210. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71211. }
  71212. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71213. {
  71214. return state [fontSizeAnchor].toString();
  71215. }
  71216. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71217. {
  71218. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71219. }
  71220. void DrawableText::refreshFromValueTree (const ValueTree& tree, ComponentBuilder&)
  71221. {
  71222. ValueTreeWrapper v (tree);
  71223. setComponentID (v.getID());
  71224. const RelativeParallelogram newBounds (v.getBoundingBox());
  71225. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71226. const Colour newColour (v.getColour());
  71227. const Justification newJustification (v.getJustification());
  71228. const String newText (v.getText());
  71229. const Font newFont (v.getFont());
  71230. if (text != newText || font != newFont || justification != newJustification
  71231. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71232. {
  71233. setBoundingBox (newBounds);
  71234. setFontSizeControlPoint (newFontPoint);
  71235. setColour (newColour);
  71236. setFont (newFont, false);
  71237. setJustification (newJustification);
  71238. setText (newText);
  71239. }
  71240. }
  71241. const ValueTree DrawableText::createValueTree (ComponentBuilder::ImageProvider*) const
  71242. {
  71243. ValueTree tree (valueTreeType);
  71244. ValueTreeWrapper v (tree);
  71245. v.setID (getComponentID());
  71246. v.setText (text, 0);
  71247. v.setFont (font, 0);
  71248. v.setJustification (justification, 0);
  71249. v.setColour (colour, 0);
  71250. v.setBoundingBox (bounds, 0);
  71251. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71252. return tree;
  71253. }
  71254. END_JUCE_NAMESPACE
  71255. /*** End of inlined file: juce_DrawableText.cpp ***/
  71256. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71257. BEGIN_JUCE_NAMESPACE
  71258. class SVGState
  71259. {
  71260. public:
  71261. SVGState (const XmlElement* const topLevel)
  71262. : topLevelXml (topLevel),
  71263. elementX (0), elementY (0),
  71264. width (512), height (512),
  71265. viewBoxW (0), viewBoxH (0)
  71266. {
  71267. }
  71268. ~SVGState()
  71269. {
  71270. }
  71271. Drawable* parseSVGElement (const XmlElement& xml)
  71272. {
  71273. if (! xml.hasTagName ("svg"))
  71274. return 0;
  71275. DrawableComposite* const drawable = new DrawableComposite();
  71276. drawable->setName (xml.getStringAttribute ("id"));
  71277. SVGState newState (*this);
  71278. if (xml.hasAttribute ("transform"))
  71279. newState.addTransform (xml);
  71280. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71281. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71282. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71283. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71284. if (xml.hasAttribute ("viewBox"))
  71285. {
  71286. const String viewParams (xml.getStringAttribute ("viewBox"));
  71287. int i = 0;
  71288. float vx, vy, vw, vh;
  71289. if (parseCoords (viewParams, vx, vy, i, true)
  71290. && parseCoords (viewParams, vw, vh, i, true)
  71291. && vw > 0
  71292. && vh > 0)
  71293. {
  71294. newState.viewBoxW = vw;
  71295. newState.viewBoxH = vh;
  71296. int placementFlags = 0;
  71297. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71298. if (aspect.containsIgnoreCase ("none"))
  71299. {
  71300. placementFlags = RectanglePlacement::stretchToFit;
  71301. }
  71302. else
  71303. {
  71304. if (aspect.containsIgnoreCase ("slice"))
  71305. placementFlags |= RectanglePlacement::fillDestination;
  71306. if (aspect.containsIgnoreCase ("xMin"))
  71307. placementFlags |= RectanglePlacement::xLeft;
  71308. else if (aspect.containsIgnoreCase ("xMax"))
  71309. placementFlags |= RectanglePlacement::xRight;
  71310. else
  71311. placementFlags |= RectanglePlacement::xMid;
  71312. if (aspect.containsIgnoreCase ("yMin"))
  71313. placementFlags |= RectanglePlacement::yTop;
  71314. else if (aspect.containsIgnoreCase ("yMax"))
  71315. placementFlags |= RectanglePlacement::yBottom;
  71316. else
  71317. placementFlags |= RectanglePlacement::yMid;
  71318. }
  71319. const RectanglePlacement placement (placementFlags);
  71320. newState.transform
  71321. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71322. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71323. .followedBy (newState.transform);
  71324. }
  71325. }
  71326. else
  71327. {
  71328. if (viewBoxW == 0)
  71329. newState.viewBoxW = newState.width;
  71330. if (viewBoxH == 0)
  71331. newState.viewBoxH = newState.height;
  71332. }
  71333. newState.parseSubElements (xml, drawable);
  71334. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71335. return drawable;
  71336. }
  71337. private:
  71338. const XmlElement* const topLevelXml;
  71339. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71340. AffineTransform transform;
  71341. String cssStyleText;
  71342. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71343. {
  71344. forEachXmlChildElement (xml, e)
  71345. {
  71346. Drawable* d = 0;
  71347. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71348. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71349. else if (e->hasTagName ("path")) d = parsePath (*e);
  71350. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71351. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71352. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71353. else if (e->hasTagName ("line")) d = parseLine (*e);
  71354. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71355. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71356. else if (e->hasTagName ("text")) d = parseText (*e);
  71357. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71358. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71359. parentDrawable->addAndMakeVisible (d);
  71360. }
  71361. }
  71362. DrawableComposite* parseSwitch (const XmlElement& xml)
  71363. {
  71364. const XmlElement* const group = xml.getChildByName ("g");
  71365. if (group != 0)
  71366. return parseGroupElement (*group);
  71367. return 0;
  71368. }
  71369. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71370. {
  71371. DrawableComposite* const drawable = new DrawableComposite();
  71372. drawable->setName (xml.getStringAttribute ("id"));
  71373. if (xml.hasAttribute ("transform"))
  71374. {
  71375. SVGState newState (*this);
  71376. newState.addTransform (xml);
  71377. newState.parseSubElements (xml, drawable);
  71378. }
  71379. else
  71380. {
  71381. parseSubElements (xml, drawable);
  71382. }
  71383. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71384. return drawable;
  71385. }
  71386. Drawable* parsePath (const XmlElement& xml) const
  71387. {
  71388. const String d (xml.getStringAttribute ("d").trimStart());
  71389. Path path;
  71390. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71391. path.setUsingNonZeroWinding (false);
  71392. int index = 0;
  71393. float lastX = 0, lastY = 0;
  71394. float lastX2 = 0, lastY2 = 0;
  71395. juce_wchar lastCommandChar = 0;
  71396. bool isRelative = true;
  71397. bool carryOn = true;
  71398. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71399. while (d[index] != 0)
  71400. {
  71401. float x, y, x2, y2, x3, y3;
  71402. if (validCommandChars.containsChar (d[index]))
  71403. {
  71404. lastCommandChar = d [index++];
  71405. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71406. }
  71407. switch (lastCommandChar)
  71408. {
  71409. case 'M':
  71410. case 'm':
  71411. case 'L':
  71412. case 'l':
  71413. if (parseCoords (d, x, y, index, false))
  71414. {
  71415. if (isRelative)
  71416. {
  71417. x += lastX;
  71418. y += lastY;
  71419. }
  71420. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71421. {
  71422. path.startNewSubPath (x, y);
  71423. lastCommandChar = 'l';
  71424. }
  71425. else
  71426. path.lineTo (x, y);
  71427. lastX2 = lastX;
  71428. lastY2 = lastY;
  71429. lastX = x;
  71430. lastY = y;
  71431. }
  71432. else
  71433. {
  71434. ++index;
  71435. }
  71436. break;
  71437. case 'H':
  71438. case 'h':
  71439. if (parseCoord (d, x, index, false, true))
  71440. {
  71441. if (isRelative)
  71442. x += lastX;
  71443. path.lineTo (x, lastY);
  71444. lastX2 = lastX;
  71445. lastX = x;
  71446. }
  71447. else
  71448. {
  71449. ++index;
  71450. }
  71451. break;
  71452. case 'V':
  71453. case 'v':
  71454. if (parseCoord (d, y, index, false, false))
  71455. {
  71456. if (isRelative)
  71457. y += lastY;
  71458. path.lineTo (lastX, y);
  71459. lastY2 = lastY;
  71460. lastY = y;
  71461. }
  71462. else
  71463. {
  71464. ++index;
  71465. }
  71466. break;
  71467. case 'C':
  71468. case 'c':
  71469. if (parseCoords (d, x, y, index, false)
  71470. && parseCoords (d, x2, y2, index, false)
  71471. && parseCoords (d, x3, y3, index, false))
  71472. {
  71473. if (isRelative)
  71474. {
  71475. x += lastX;
  71476. y += lastY;
  71477. x2 += lastX;
  71478. y2 += lastY;
  71479. x3 += lastX;
  71480. y3 += lastY;
  71481. }
  71482. path.cubicTo (x, y, x2, y2, x3, y3);
  71483. lastX2 = x2;
  71484. lastY2 = y2;
  71485. lastX = x3;
  71486. lastY = y3;
  71487. }
  71488. else
  71489. {
  71490. ++index;
  71491. }
  71492. break;
  71493. case 'S':
  71494. case 's':
  71495. if (parseCoords (d, x, y, index, false)
  71496. && parseCoords (d, x3, y3, index, false))
  71497. {
  71498. if (isRelative)
  71499. {
  71500. x += lastX;
  71501. y += lastY;
  71502. x3 += lastX;
  71503. y3 += lastY;
  71504. }
  71505. x2 = lastX + (lastX - lastX2);
  71506. y2 = lastY + (lastY - lastY2);
  71507. path.cubicTo (x2, y2, x, y, x3, y3);
  71508. lastX2 = x;
  71509. lastY2 = y;
  71510. lastX = x3;
  71511. lastY = y3;
  71512. }
  71513. else
  71514. {
  71515. ++index;
  71516. }
  71517. break;
  71518. case 'Q':
  71519. case 'q':
  71520. if (parseCoords (d, x, y, index, false)
  71521. && parseCoords (d, x2, y2, index, false))
  71522. {
  71523. if (isRelative)
  71524. {
  71525. x += lastX;
  71526. y += lastY;
  71527. x2 += lastX;
  71528. y2 += lastY;
  71529. }
  71530. path.quadraticTo (x, y, x2, y2);
  71531. lastX2 = x;
  71532. lastY2 = y;
  71533. lastX = x2;
  71534. lastY = y2;
  71535. }
  71536. else
  71537. {
  71538. ++index;
  71539. }
  71540. break;
  71541. case 'T':
  71542. case 't':
  71543. if (parseCoords (d, x, y, index, false))
  71544. {
  71545. if (isRelative)
  71546. {
  71547. x += lastX;
  71548. y += lastY;
  71549. }
  71550. x2 = lastX + (lastX - lastX2);
  71551. y2 = lastY + (lastY - lastY2);
  71552. path.quadraticTo (x2, y2, x, y);
  71553. lastX2 = x2;
  71554. lastY2 = y2;
  71555. lastX = x;
  71556. lastY = y;
  71557. }
  71558. else
  71559. {
  71560. ++index;
  71561. }
  71562. break;
  71563. case 'A':
  71564. case 'a':
  71565. if (parseCoords (d, x, y, index, false))
  71566. {
  71567. String num;
  71568. if (parseNextNumber (d, num, index, false))
  71569. {
  71570. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71571. if (parseNextNumber (d, num, index, false))
  71572. {
  71573. const bool largeArc = num.getIntValue() != 0;
  71574. if (parseNextNumber (d, num, index, false))
  71575. {
  71576. const bool sweep = num.getIntValue() != 0;
  71577. if (parseCoords (d, x2, y2, index, false))
  71578. {
  71579. if (isRelative)
  71580. {
  71581. x2 += lastX;
  71582. y2 += lastY;
  71583. }
  71584. if (lastX != x2 || lastY != y2)
  71585. {
  71586. double centreX, centreY, startAngle, deltaAngle;
  71587. double rx = x, ry = y;
  71588. endpointToCentreParameters (lastX, lastY, x2, y2,
  71589. angle, largeArc, sweep,
  71590. rx, ry, centreX, centreY,
  71591. startAngle, deltaAngle);
  71592. path.addCentredArc ((float) centreX, (float) centreY,
  71593. (float) rx, (float) ry,
  71594. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71595. false);
  71596. path.lineTo (x2, y2);
  71597. }
  71598. lastX2 = lastX;
  71599. lastY2 = lastY;
  71600. lastX = x2;
  71601. lastY = y2;
  71602. }
  71603. }
  71604. }
  71605. }
  71606. }
  71607. else
  71608. {
  71609. ++index;
  71610. }
  71611. break;
  71612. case 'Z':
  71613. case 'z':
  71614. path.closeSubPath();
  71615. while (CharacterFunctions::isWhitespace (d [index]))
  71616. ++index;
  71617. break;
  71618. default:
  71619. carryOn = false;
  71620. break;
  71621. }
  71622. if (! carryOn)
  71623. break;
  71624. }
  71625. return parseShape (xml, path);
  71626. }
  71627. Drawable* parseRect (const XmlElement& xml) const
  71628. {
  71629. Path rect;
  71630. const bool hasRX = xml.hasAttribute ("rx");
  71631. const bool hasRY = xml.hasAttribute ("ry");
  71632. if (hasRX || hasRY)
  71633. {
  71634. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71635. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71636. if (! hasRX)
  71637. rx = ry;
  71638. else if (! hasRY)
  71639. ry = rx;
  71640. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71641. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71642. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71643. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71644. rx, ry);
  71645. }
  71646. else
  71647. {
  71648. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71649. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71650. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71651. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71652. }
  71653. return parseShape (xml, rect);
  71654. }
  71655. Drawable* parseCircle (const XmlElement& xml) const
  71656. {
  71657. Path circle;
  71658. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71659. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71660. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71661. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71662. return parseShape (xml, circle);
  71663. }
  71664. Drawable* parseEllipse (const XmlElement& xml) const
  71665. {
  71666. Path ellipse;
  71667. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71668. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71669. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71670. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71671. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71672. return parseShape (xml, ellipse);
  71673. }
  71674. Drawable* parseLine (const XmlElement& xml) const
  71675. {
  71676. Path line;
  71677. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71678. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71679. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71680. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71681. line.startNewSubPath (x1, y1);
  71682. line.lineTo (x2, y2);
  71683. return parseShape (xml, line);
  71684. }
  71685. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71686. {
  71687. const String points (xml.getStringAttribute ("points"));
  71688. Path path;
  71689. int index = 0;
  71690. float x, y;
  71691. if (parseCoords (points, x, y, index, true))
  71692. {
  71693. float firstX = x;
  71694. float firstY = y;
  71695. float lastX = 0, lastY = 0;
  71696. path.startNewSubPath (x, y);
  71697. while (parseCoords (points, x, y, index, true))
  71698. {
  71699. lastX = x;
  71700. lastY = y;
  71701. path.lineTo (x, y);
  71702. }
  71703. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71704. path.closeSubPath();
  71705. }
  71706. return parseShape (xml, path);
  71707. }
  71708. Drawable* parseShape (const XmlElement& xml, Path& path,
  71709. const bool shouldParseTransform = true) const
  71710. {
  71711. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71712. {
  71713. SVGState newState (*this);
  71714. newState.addTransform (xml);
  71715. return newState.parseShape (xml, path, false);
  71716. }
  71717. DrawablePath* dp = new DrawablePath();
  71718. dp->setName (xml.getStringAttribute ("id"));
  71719. dp->setFill (Colours::transparentBlack);
  71720. path.applyTransform (transform);
  71721. dp->setPath (path);
  71722. Path::Iterator iter (path);
  71723. bool containsClosedSubPath = false;
  71724. while (iter.next())
  71725. {
  71726. if (iter.elementType == Path::Iterator::closePath)
  71727. {
  71728. containsClosedSubPath = true;
  71729. break;
  71730. }
  71731. }
  71732. dp->setFill (getPathFillType (path,
  71733. getStyleAttribute (&xml, "fill"),
  71734. getStyleAttribute (&xml, "fill-opacity"),
  71735. getStyleAttribute (&xml, "opacity"),
  71736. containsClosedSubPath ? Colours::black
  71737. : Colours::transparentBlack));
  71738. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71739. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71740. {
  71741. dp->setStrokeFill (getPathFillType (path, strokeType,
  71742. getStyleAttribute (&xml, "stroke-opacity"),
  71743. getStyleAttribute (&xml, "opacity"),
  71744. Colours::transparentBlack));
  71745. dp->setStrokeType (getStrokeFor (&xml));
  71746. }
  71747. return dp;
  71748. }
  71749. const XmlElement* findLinkedElement (const XmlElement* e) const
  71750. {
  71751. const String id (e->getStringAttribute ("xlink:href"));
  71752. if (! id.startsWithChar ('#'))
  71753. return 0;
  71754. return findElementForId (topLevelXml, id.substring (1));
  71755. }
  71756. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71757. {
  71758. if (fillXml == 0)
  71759. return;
  71760. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71761. {
  71762. int index = 0;
  71763. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71764. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71765. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71766. double offset = e->getDoubleAttribute ("offset");
  71767. if (e->getStringAttribute ("offset").containsChar ('%'))
  71768. offset *= 0.01;
  71769. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71770. }
  71771. }
  71772. const FillType getPathFillType (const Path& path,
  71773. const String& fill,
  71774. const String& fillOpacity,
  71775. const String& overallOpacity,
  71776. const Colour& defaultColour) const
  71777. {
  71778. float opacity = 1.0f;
  71779. if (overallOpacity.isNotEmpty())
  71780. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71781. if (fillOpacity.isNotEmpty())
  71782. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71783. if (fill.startsWithIgnoreCase ("url"))
  71784. {
  71785. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71786. .upToLastOccurrenceOf (")", false, false).trim());
  71787. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71788. if (fillXml != 0
  71789. && (fillXml->hasTagName ("linearGradient")
  71790. || fillXml->hasTagName ("radialGradient")))
  71791. {
  71792. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71793. ColourGradient gradient;
  71794. addGradientStopsIn (gradient, inheritedFrom);
  71795. addGradientStopsIn (gradient, fillXml);
  71796. if (gradient.getNumColours() > 0)
  71797. {
  71798. gradient.addColour (0.0, gradient.getColour (0));
  71799. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71800. }
  71801. else
  71802. {
  71803. gradient.addColour (0.0, Colours::black);
  71804. gradient.addColour (1.0, Colours::black);
  71805. }
  71806. if (overallOpacity.isNotEmpty())
  71807. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71808. jassert (gradient.getNumColours() > 0);
  71809. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71810. float gradientWidth = viewBoxW;
  71811. float gradientHeight = viewBoxH;
  71812. float dx = 0.0f;
  71813. float dy = 0.0f;
  71814. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71815. if (! userSpace)
  71816. {
  71817. const Rectangle<float> bounds (path.getBounds());
  71818. dx = bounds.getX();
  71819. dy = bounds.getY();
  71820. gradientWidth = bounds.getWidth();
  71821. gradientHeight = bounds.getHeight();
  71822. }
  71823. if (gradient.isRadial)
  71824. {
  71825. if (userSpace)
  71826. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71827. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71828. else
  71829. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71830. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71831. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71832. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71833. //xxx (the fx, fy focal point isn't handled properly here..)
  71834. }
  71835. else
  71836. {
  71837. if (userSpace)
  71838. {
  71839. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71840. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71841. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71842. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71843. }
  71844. else
  71845. {
  71846. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71847. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71848. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71849. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71850. }
  71851. if (gradient.point1 == gradient.point2)
  71852. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71853. }
  71854. FillType type (gradient);
  71855. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71856. .followedBy (transform);
  71857. return type;
  71858. }
  71859. }
  71860. if (fill.equalsIgnoreCase ("none"))
  71861. return Colours::transparentBlack;
  71862. int i = 0;
  71863. const Colour colour (parseColour (fill, i, defaultColour));
  71864. return colour.withMultipliedAlpha (opacity);
  71865. }
  71866. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71867. {
  71868. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71869. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71870. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71871. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71872. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71873. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71874. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71875. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71876. if (join.equalsIgnoreCase ("round"))
  71877. joinStyle = PathStrokeType::curved;
  71878. else if (join.equalsIgnoreCase ("bevel"))
  71879. joinStyle = PathStrokeType::beveled;
  71880. if (cap.equalsIgnoreCase ("round"))
  71881. capStyle = PathStrokeType::rounded;
  71882. else if (cap.equalsIgnoreCase ("square"))
  71883. capStyle = PathStrokeType::square;
  71884. float ox = 0.0f, oy = 0.0f;
  71885. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71886. transform.transformPoints (ox, oy, x, y);
  71887. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  71888. joinStyle, capStyle);
  71889. }
  71890. Drawable* parseText (const XmlElement& xml)
  71891. {
  71892. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71893. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71894. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71895. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71896. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71897. //xxx not done text yet!
  71898. forEachXmlChildElement (xml, e)
  71899. {
  71900. if (e->isTextElement())
  71901. {
  71902. const String text (e->getText());
  71903. Path path;
  71904. Drawable* s = parseShape (*e, path);
  71905. delete s; // xxx not finished!
  71906. }
  71907. else if (e->hasTagName ("tspan"))
  71908. {
  71909. Drawable* s = parseText (*e);
  71910. delete s; // xxx not finished!
  71911. }
  71912. }
  71913. return 0;
  71914. }
  71915. void addTransform (const XmlElement& xml)
  71916. {
  71917. transform = parseTransform (xml.getStringAttribute ("transform"))
  71918. .followedBy (transform);
  71919. }
  71920. bool parseCoord (const String& s, float& value, int& index,
  71921. const bool allowUnits, const bool isX) const
  71922. {
  71923. String number;
  71924. if (! parseNextNumber (s, number, index, allowUnits))
  71925. {
  71926. value = 0;
  71927. return false;
  71928. }
  71929. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71930. return true;
  71931. }
  71932. bool parseCoords (const String& s, float& x, float& y,
  71933. int& index, const bool allowUnits) const
  71934. {
  71935. return parseCoord (s, x, index, allowUnits, true)
  71936. && parseCoord (s, y, index, allowUnits, false);
  71937. }
  71938. float getCoordLength (const String& s, const float sizeForProportions) const
  71939. {
  71940. float n = s.getFloatValue();
  71941. const int len = s.length();
  71942. if (len > 2)
  71943. {
  71944. const float dpi = 96.0f;
  71945. const juce_wchar n1 = s [len - 2];
  71946. const juce_wchar n2 = s [len - 1];
  71947. if (n1 == 'i' && n2 == 'n')
  71948. n *= dpi;
  71949. else if (n1 == 'm' && n2 == 'm')
  71950. n *= dpi / 25.4f;
  71951. else if (n1 == 'c' && n2 == 'm')
  71952. n *= dpi / 2.54f;
  71953. else if (n1 == 'p' && n2 == 'c')
  71954. n *= 15.0f;
  71955. else if (n2 == '%')
  71956. n *= 0.01f * sizeForProportions;
  71957. }
  71958. return n;
  71959. }
  71960. void getCoordList (Array <float>& coords, const String& list,
  71961. const bool allowUnits, const bool isX) const
  71962. {
  71963. int index = 0;
  71964. float value;
  71965. while (parseCoord (list, value, index, allowUnits, isX))
  71966. coords.add (value);
  71967. }
  71968. void parseCSSStyle (const XmlElement& xml)
  71969. {
  71970. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71971. }
  71972. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71973. const String& defaultValue = String::empty) const
  71974. {
  71975. if (xml->hasAttribute (attributeName))
  71976. return xml->getStringAttribute (attributeName, defaultValue);
  71977. const String styleAtt (xml->getStringAttribute ("style"));
  71978. if (styleAtt.isNotEmpty())
  71979. {
  71980. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71981. if (value.isNotEmpty())
  71982. return value;
  71983. }
  71984. else if (xml->hasAttribute ("class"))
  71985. {
  71986. const String className ("." + xml->getStringAttribute ("class"));
  71987. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71988. if (index < 0)
  71989. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71990. if (index >= 0)
  71991. {
  71992. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71993. if (openBracket > index)
  71994. {
  71995. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71996. if (closeBracket > openBracket)
  71997. {
  71998. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71999. if (value.isNotEmpty())
  72000. return value;
  72001. }
  72002. }
  72003. }
  72004. }
  72005. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72006. if (xml != 0)
  72007. return getStyleAttribute (xml, attributeName, defaultValue);
  72008. return defaultValue;
  72009. }
  72010. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  72011. {
  72012. if (xml->hasAttribute (attributeName))
  72013. return xml->getStringAttribute (attributeName);
  72014. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72015. if (xml != 0)
  72016. return getInheritedAttribute (xml, attributeName);
  72017. return String::empty;
  72018. }
  72019. static bool isIdentifierChar (const juce_wchar c)
  72020. {
  72021. return CharacterFunctions::isLetter (c) || c == '-';
  72022. }
  72023. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  72024. {
  72025. int i = 0;
  72026. for (;;)
  72027. {
  72028. i = list.indexOf (i, attributeName);
  72029. if (i < 0)
  72030. break;
  72031. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  72032. && ! isIdentifierChar (list [i + attributeName.length()]))
  72033. {
  72034. i = list.indexOfChar (i, ':');
  72035. if (i < 0)
  72036. break;
  72037. int end = list.indexOfChar (i, ';');
  72038. if (end < 0)
  72039. end = 0x7ffff;
  72040. return list.substring (i + 1, end).trim();
  72041. }
  72042. ++i;
  72043. }
  72044. return defaultValue;
  72045. }
  72046. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  72047. {
  72048. const juce_wchar* const s = source;
  72049. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72050. ++index;
  72051. int start = index;
  72052. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  72053. ++index;
  72054. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  72055. ++index;
  72056. if ((s[index] == 'e' || s[index] == 'E')
  72057. && (CharacterFunctions::isDigit (s[index + 1])
  72058. || s[index + 1] == '-'
  72059. || s[index + 1] == '+'))
  72060. {
  72061. index += 2;
  72062. while (CharacterFunctions::isDigit (s[index]))
  72063. ++index;
  72064. }
  72065. if (allowUnits)
  72066. {
  72067. while (CharacterFunctions::isLetter (s[index]))
  72068. ++index;
  72069. }
  72070. if (index == start)
  72071. return false;
  72072. value = String (s + start, index - start);
  72073. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72074. ++index;
  72075. return true;
  72076. }
  72077. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  72078. {
  72079. if (s [index] == '#')
  72080. {
  72081. uint32 hex [6];
  72082. zeromem (hex, sizeof (hex));
  72083. int numChars = 0;
  72084. for (int i = 6; --i >= 0;)
  72085. {
  72086. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  72087. if (hexValue >= 0)
  72088. hex [numChars++] = hexValue;
  72089. else
  72090. break;
  72091. }
  72092. if (numChars <= 3)
  72093. return Colour ((uint8) (hex [0] * 0x11),
  72094. (uint8) (hex [1] * 0x11),
  72095. (uint8) (hex [2] * 0x11));
  72096. else
  72097. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  72098. (uint8) ((hex [2] << 4) + hex [3]),
  72099. (uint8) ((hex [4] << 4) + hex [5]));
  72100. }
  72101. else if (s [index] == 'r'
  72102. && s [index + 1] == 'g'
  72103. && s [index + 2] == 'b')
  72104. {
  72105. const int openBracket = s.indexOfChar (index, '(');
  72106. const int closeBracket = s.indexOfChar (openBracket, ')');
  72107. if (openBracket >= 3 && closeBracket > openBracket)
  72108. {
  72109. index = closeBracket;
  72110. StringArray tokens;
  72111. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72112. tokens.trim();
  72113. tokens.removeEmptyStrings();
  72114. if (tokens[0].containsChar ('%'))
  72115. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72116. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72117. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72118. else
  72119. return Colour ((uint8) tokens[0].getIntValue(),
  72120. (uint8) tokens[1].getIntValue(),
  72121. (uint8) tokens[2].getIntValue());
  72122. }
  72123. }
  72124. return Colours::findColourForName (s, defaultColour);
  72125. }
  72126. static const AffineTransform parseTransform (String t)
  72127. {
  72128. AffineTransform result;
  72129. while (t.isNotEmpty())
  72130. {
  72131. StringArray tokens;
  72132. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72133. .upToFirstOccurrenceOf (")", false, false),
  72134. ", ", String::empty);
  72135. tokens.removeEmptyStrings (true);
  72136. float numbers [6];
  72137. for (int i = 0; i < 6; ++i)
  72138. numbers[i] = tokens[i].getFloatValue();
  72139. AffineTransform trans;
  72140. if (t.startsWithIgnoreCase ("matrix"))
  72141. {
  72142. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72143. numbers[1], numbers[3], numbers[5]);
  72144. }
  72145. else if (t.startsWithIgnoreCase ("translate"))
  72146. {
  72147. jassert (tokens.size() == 2);
  72148. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72149. }
  72150. else if (t.startsWithIgnoreCase ("scale"))
  72151. {
  72152. if (tokens.size() == 1)
  72153. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72154. else
  72155. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72156. }
  72157. else if (t.startsWithIgnoreCase ("rotate"))
  72158. {
  72159. if (tokens.size() != 3)
  72160. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72161. else
  72162. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72163. numbers[1], numbers[2]);
  72164. }
  72165. else if (t.startsWithIgnoreCase ("skewX"))
  72166. {
  72167. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72168. 0.0f, 1.0f, 0.0f);
  72169. }
  72170. else if (t.startsWithIgnoreCase ("skewY"))
  72171. {
  72172. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72173. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72174. }
  72175. result = trans.followedBy (result);
  72176. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72177. }
  72178. return result;
  72179. }
  72180. static void endpointToCentreParameters (const double x1, const double y1,
  72181. const double x2, const double y2,
  72182. const double angle,
  72183. const bool largeArc, const bool sweep,
  72184. double& rx, double& ry,
  72185. double& centreX, double& centreY,
  72186. double& startAngle, double& deltaAngle)
  72187. {
  72188. const double midX = (x1 - x2) * 0.5;
  72189. const double midY = (y1 - y2) * 0.5;
  72190. const double cosAngle = cos (angle);
  72191. const double sinAngle = sin (angle);
  72192. const double xp = cosAngle * midX + sinAngle * midY;
  72193. const double yp = cosAngle * midY - sinAngle * midX;
  72194. const double xp2 = xp * xp;
  72195. const double yp2 = yp * yp;
  72196. double rx2 = rx * rx;
  72197. double ry2 = ry * ry;
  72198. const double s = (xp2 / rx2) + (yp2 / ry2);
  72199. double c;
  72200. if (s <= 1.0)
  72201. {
  72202. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72203. / (( rx2 * yp2) + (ry2 * xp2))));
  72204. if (largeArc == sweep)
  72205. c = -c;
  72206. }
  72207. else
  72208. {
  72209. const double s2 = std::sqrt (s);
  72210. rx *= s2;
  72211. ry *= s2;
  72212. rx2 = rx * rx;
  72213. ry2 = ry * ry;
  72214. c = 0;
  72215. }
  72216. const double cpx = ((rx * yp) / ry) * c;
  72217. const double cpy = ((-ry * xp) / rx) * c;
  72218. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72219. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72220. const double ux = (xp - cpx) / rx;
  72221. const double uy = (yp - cpy) / ry;
  72222. const double vx = (-xp - cpx) / rx;
  72223. const double vy = (-yp - cpy) / ry;
  72224. const double length = juce_hypot (ux, uy);
  72225. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72226. if (uy < 0)
  72227. startAngle = -startAngle;
  72228. startAngle += double_Pi * 0.5;
  72229. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72230. / (length * juce_hypot (vx, vy))));
  72231. if ((ux * vy) - (uy * vx) < 0)
  72232. deltaAngle = -deltaAngle;
  72233. if (sweep)
  72234. {
  72235. if (deltaAngle < 0)
  72236. deltaAngle += double_Pi * 2.0;
  72237. }
  72238. else
  72239. {
  72240. if (deltaAngle > 0)
  72241. deltaAngle -= double_Pi * 2.0;
  72242. }
  72243. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72244. }
  72245. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72246. {
  72247. forEachXmlChildElement (*parent, e)
  72248. {
  72249. if (e->compareAttribute ("id", id))
  72250. return e;
  72251. const XmlElement* const found = findElementForId (e, id);
  72252. if (found != 0)
  72253. return found;
  72254. }
  72255. return 0;
  72256. }
  72257. SVGState& operator= (const SVGState&);
  72258. };
  72259. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72260. {
  72261. SVGState state (&svgDocument);
  72262. return state.parseSVGElement (svgDocument);
  72263. }
  72264. END_JUCE_NAMESPACE
  72265. /*** End of inlined file: juce_SVGParser.cpp ***/
  72266. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72267. BEGIN_JUCE_NAMESPACE
  72268. #if JUCE_MSVC && JUCE_DEBUG
  72269. #pragma optimize ("t", on)
  72270. #endif
  72271. DropShadowEffect::DropShadowEffect()
  72272. : offsetX (0),
  72273. offsetY (0),
  72274. radius (4),
  72275. opacity (0.6f)
  72276. {
  72277. }
  72278. DropShadowEffect::~DropShadowEffect()
  72279. {
  72280. }
  72281. void DropShadowEffect::setShadowProperties (const float newRadius,
  72282. const float newOpacity,
  72283. const int newShadowOffsetX,
  72284. const int newShadowOffsetY)
  72285. {
  72286. radius = jmax (1.1f, newRadius);
  72287. offsetX = newShadowOffsetX;
  72288. offsetY = newShadowOffsetY;
  72289. opacity = newOpacity;
  72290. }
  72291. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72292. {
  72293. const int w = image.getWidth();
  72294. const int h = image.getHeight();
  72295. Image shadowImage (Image::SingleChannel, w, h, false);
  72296. const Image::BitmapData srcData (image, false);
  72297. const Image::BitmapData destData (shadowImage, true);
  72298. const int filter = roundToInt (63.0f / radius);
  72299. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72300. for (int x = w; --x >= 0;)
  72301. {
  72302. int shadowAlpha = 0;
  72303. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72304. uint8* shadowPix = destData.data + x;
  72305. for (int y = h; --y >= 0;)
  72306. {
  72307. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72308. *shadowPix = (uint8) shadowAlpha;
  72309. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72310. shadowPix += destData.lineStride;
  72311. }
  72312. }
  72313. for (int y = h; --y >= 0;)
  72314. {
  72315. int shadowAlpha = 0;
  72316. uint8* shadowPix = destData.getLinePointer (y);
  72317. for (int x = w; --x >= 0;)
  72318. {
  72319. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72320. *shadowPix++ = (uint8) shadowAlpha;
  72321. }
  72322. }
  72323. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72324. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72325. g.setOpacity (alpha);
  72326. g.drawImageAt (image, 0, 0);
  72327. }
  72328. #if JUCE_MSVC && JUCE_DEBUG
  72329. #pragma optimize ("", on) // resets optimisations to the project defaults
  72330. #endif
  72331. END_JUCE_NAMESPACE
  72332. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72333. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72334. BEGIN_JUCE_NAMESPACE
  72335. GlowEffect::GlowEffect()
  72336. : radius (2.0f),
  72337. colour (Colours::white)
  72338. {
  72339. }
  72340. GlowEffect::~GlowEffect()
  72341. {
  72342. }
  72343. void GlowEffect::setGlowProperties (const float newRadius,
  72344. const Colour& newColour)
  72345. {
  72346. radius = newRadius;
  72347. colour = newColour;
  72348. }
  72349. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72350. {
  72351. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72352. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72353. blurKernel.createGaussianBlur (radius);
  72354. blurKernel.rescaleAllValues (radius);
  72355. blurKernel.applyToImage (temp, image, image.getBounds());
  72356. g.setColour (colour.withMultipliedAlpha (alpha));
  72357. g.drawImageAt (temp, 0, 0, true);
  72358. g.setOpacity (alpha);
  72359. g.drawImageAt (image, 0, 0, false);
  72360. }
  72361. END_JUCE_NAMESPACE
  72362. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72363. /*** Start of inlined file: juce_Font.cpp ***/
  72364. BEGIN_JUCE_NAMESPACE
  72365. namespace FontValues
  72366. {
  72367. float limitFontHeight (const float height) throw()
  72368. {
  72369. return jlimit (0.1f, 10000.0f, height);
  72370. }
  72371. const float defaultFontHeight = 14.0f;
  72372. String fallbackFont;
  72373. }
  72374. class TypefaceCache : public DeletedAtShutdown
  72375. {
  72376. public:
  72377. TypefaceCache()
  72378. : counter (0)
  72379. {
  72380. setSize (10);
  72381. }
  72382. ~TypefaceCache()
  72383. {
  72384. clearSingletonInstance();
  72385. }
  72386. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72387. void setSize (const int numToCache)
  72388. {
  72389. faces.clear();
  72390. faces.insertMultiple (-1, CachedFace(), numToCache);
  72391. }
  72392. const Typeface::Ptr findTypefaceFor (const Font& font)
  72393. {
  72394. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72395. const String faceName (font.getTypefaceName());
  72396. int i;
  72397. for (i = faces.size(); --i >= 0;)
  72398. {
  72399. CachedFace& face = faces.getReference(i);
  72400. if (face.flags == flags
  72401. && face.typefaceName == faceName
  72402. && face.typeface->isSuitableForFont (font))
  72403. {
  72404. face.lastUsageCount = ++counter;
  72405. return face.typeface;
  72406. }
  72407. }
  72408. int replaceIndex = 0;
  72409. int bestLastUsageCount = std::numeric_limits<int>::max();
  72410. for (i = faces.size(); --i >= 0;)
  72411. {
  72412. const int lu = faces.getReference(i).lastUsageCount;
  72413. if (bestLastUsageCount > lu)
  72414. {
  72415. bestLastUsageCount = lu;
  72416. replaceIndex = i;
  72417. }
  72418. }
  72419. CachedFace& face = faces.getReference (replaceIndex);
  72420. face.typefaceName = faceName;
  72421. face.flags = flags;
  72422. face.lastUsageCount = ++counter;
  72423. face.typeface = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72424. jassert (face.typeface != 0); // the look and feel must return a typeface!
  72425. if (defaultFace == 0 && font == Font())
  72426. defaultFace = face.typeface;
  72427. return face.typeface;
  72428. }
  72429. const Typeface::Ptr getDefaultTypeface() const throw()
  72430. {
  72431. return defaultFace;
  72432. }
  72433. private:
  72434. struct CachedFace
  72435. {
  72436. CachedFace() throw()
  72437. : lastUsageCount (0), flags (-1)
  72438. {
  72439. }
  72440. // Although it seems a bit wacky to store the name here, it's because it may be a
  72441. // placeholder rather than a real one, e.g. "<Sans-Serif>" vs the actual typeface name.
  72442. // Since the typeface itself doesn't know that it may have this alias, the name under
  72443. // which it was fetched needs to be stored separately.
  72444. String typefaceName;
  72445. int lastUsageCount, flags;
  72446. Typeface::Ptr typeface;
  72447. };
  72448. Array <CachedFace> faces;
  72449. Typeface::Ptr defaultFace;
  72450. int counter;
  72451. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72452. };
  72453. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72454. void Typeface::setTypefaceCacheSize (int numFontsToCache)
  72455. {
  72456. TypefaceCache::getInstance()->setSize (numFontsToCache);
  72457. }
  72458. Font::SharedFontInternal::SharedFontInternal (const float height_, const int styleFlags_) throw()
  72459. : typefaceName (Font::getDefaultSansSerifFontName()),
  72460. height (height_),
  72461. horizontalScale (1.0f),
  72462. kerning (0),
  72463. ascent (0),
  72464. styleFlags (styleFlags_),
  72465. typeface (TypefaceCache::getInstance()->getDefaultTypeface())
  72466. {
  72467. }
  72468. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const int styleFlags_) throw()
  72469. : typefaceName (typefaceName_),
  72470. height (height_),
  72471. horizontalScale (1.0f),
  72472. kerning (0),
  72473. ascent (0),
  72474. styleFlags (styleFlags_),
  72475. typeface (0)
  72476. {
  72477. }
  72478. Font::SharedFontInternal::SharedFontInternal (const Typeface::Ptr& typeface_) throw()
  72479. : typefaceName (typeface_->getName()),
  72480. height (FontValues::defaultFontHeight),
  72481. horizontalScale (1.0f),
  72482. kerning (0),
  72483. ascent (0),
  72484. styleFlags (Font::plain),
  72485. typeface (typeface_)
  72486. {
  72487. }
  72488. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72489. : typefaceName (other.typefaceName),
  72490. height (other.height),
  72491. horizontalScale (other.horizontalScale),
  72492. kerning (other.kerning),
  72493. ascent (other.ascent),
  72494. styleFlags (other.styleFlags),
  72495. typeface (other.typeface)
  72496. {
  72497. }
  72498. bool Font::SharedFontInternal::operator== (const SharedFontInternal& other) const throw()
  72499. {
  72500. return height == other.height
  72501. && styleFlags == other.styleFlags
  72502. && horizontalScale == other.horizontalScale
  72503. && kerning == other.kerning
  72504. && typefaceName == other.typefaceName;
  72505. }
  72506. Font::Font()
  72507. : font (new SharedFontInternal (FontValues::defaultFontHeight, Font::plain))
  72508. {
  72509. }
  72510. Font::Font (const float fontHeight, const int styleFlags_)
  72511. : font (new SharedFontInternal (FontValues::limitFontHeight (fontHeight), styleFlags_))
  72512. {
  72513. }
  72514. Font::Font (const String& typefaceName_, const float fontHeight, const int styleFlags_)
  72515. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight), styleFlags_))
  72516. {
  72517. }
  72518. Font::Font (const Typeface::Ptr& typeface)
  72519. : font (new SharedFontInternal (typeface))
  72520. {
  72521. }
  72522. Font::Font (const Font& other) throw()
  72523. : font (other.font)
  72524. {
  72525. }
  72526. Font& Font::operator= (const Font& other) throw()
  72527. {
  72528. font = other.font;
  72529. return *this;
  72530. }
  72531. Font::~Font() throw()
  72532. {
  72533. }
  72534. bool Font::operator== (const Font& other) const throw()
  72535. {
  72536. return font == other.font
  72537. || *font == *other.font;
  72538. }
  72539. bool Font::operator!= (const Font& other) const throw()
  72540. {
  72541. return ! operator== (other);
  72542. }
  72543. void Font::dupeInternalIfShared()
  72544. {
  72545. if (font->getReferenceCount() > 1)
  72546. font = new SharedFontInternal (*font);
  72547. }
  72548. const String Font::getDefaultSansSerifFontName()
  72549. {
  72550. static const String name ("<Sans-Serif>");
  72551. return name;
  72552. }
  72553. const String Font::getDefaultSerifFontName()
  72554. {
  72555. static const String name ("<Serif>");
  72556. return name;
  72557. }
  72558. const String Font::getDefaultMonospacedFontName()
  72559. {
  72560. static const String name ("<Monospaced>");
  72561. return name;
  72562. }
  72563. void Font::setTypefaceName (const String& faceName)
  72564. {
  72565. if (faceName != font->typefaceName)
  72566. {
  72567. dupeInternalIfShared();
  72568. font->typefaceName = faceName;
  72569. font->typeface = 0;
  72570. font->ascent = 0;
  72571. }
  72572. }
  72573. const String Font::getFallbackFontName()
  72574. {
  72575. return FontValues::fallbackFont;
  72576. }
  72577. void Font::setFallbackFontName (const String& name)
  72578. {
  72579. FontValues::fallbackFont = name;
  72580. }
  72581. void Font::setHeight (float newHeight)
  72582. {
  72583. newHeight = FontValues::limitFontHeight (newHeight);
  72584. if (font->height != newHeight)
  72585. {
  72586. dupeInternalIfShared();
  72587. font->height = newHeight;
  72588. }
  72589. }
  72590. void Font::setHeightWithoutChangingWidth (float newHeight)
  72591. {
  72592. newHeight = FontValues::limitFontHeight (newHeight);
  72593. if (font->height != newHeight)
  72594. {
  72595. dupeInternalIfShared();
  72596. font->horizontalScale *= (font->height / newHeight);
  72597. font->height = newHeight;
  72598. }
  72599. }
  72600. void Font::setStyleFlags (const int newFlags)
  72601. {
  72602. if (font->styleFlags != newFlags)
  72603. {
  72604. dupeInternalIfShared();
  72605. font->styleFlags = newFlags;
  72606. font->typeface = 0;
  72607. font->ascent = 0;
  72608. }
  72609. }
  72610. void Font::setSizeAndStyle (float newHeight,
  72611. const int newStyleFlags,
  72612. const float newHorizontalScale,
  72613. const float newKerningAmount)
  72614. {
  72615. newHeight = FontValues::limitFontHeight (newHeight);
  72616. if (font->height != newHeight
  72617. || font->horizontalScale != newHorizontalScale
  72618. || font->kerning != newKerningAmount)
  72619. {
  72620. dupeInternalIfShared();
  72621. font->height = newHeight;
  72622. font->horizontalScale = newHorizontalScale;
  72623. font->kerning = newKerningAmount;
  72624. }
  72625. setStyleFlags (newStyleFlags);
  72626. }
  72627. void Font::setHorizontalScale (const float scaleFactor)
  72628. {
  72629. dupeInternalIfShared();
  72630. font->horizontalScale = scaleFactor;
  72631. }
  72632. void Font::setExtraKerningFactor (const float extraKerning)
  72633. {
  72634. dupeInternalIfShared();
  72635. font->kerning = extraKerning;
  72636. }
  72637. void Font::setBold (const bool shouldBeBold)
  72638. {
  72639. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72640. : (font->styleFlags & ~bold));
  72641. }
  72642. const Font Font::boldened() const
  72643. {
  72644. Font f (*this);
  72645. f.setBold (true);
  72646. return f;
  72647. }
  72648. bool Font::isBold() const throw()
  72649. {
  72650. return (font->styleFlags & bold) != 0;
  72651. }
  72652. void Font::setItalic (const bool shouldBeItalic)
  72653. {
  72654. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72655. : (font->styleFlags & ~italic));
  72656. }
  72657. const Font Font::italicised() const
  72658. {
  72659. Font f (*this);
  72660. f.setItalic (true);
  72661. return f;
  72662. }
  72663. bool Font::isItalic() const throw()
  72664. {
  72665. return (font->styleFlags & italic) != 0;
  72666. }
  72667. void Font::setUnderline (const bool shouldBeUnderlined)
  72668. {
  72669. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72670. : (font->styleFlags & ~underlined));
  72671. }
  72672. bool Font::isUnderlined() const throw()
  72673. {
  72674. return (font->styleFlags & underlined) != 0;
  72675. }
  72676. float Font::getAscent() const
  72677. {
  72678. if (font->ascent == 0)
  72679. font->ascent = getTypeface()->getAscent();
  72680. return font->height * font->ascent;
  72681. }
  72682. float Font::getDescent() const
  72683. {
  72684. return font->height - getAscent();
  72685. }
  72686. int Font::getStringWidth (const String& text) const
  72687. {
  72688. return roundToInt (getStringWidthFloat (text));
  72689. }
  72690. float Font::getStringWidthFloat (const String& text) const
  72691. {
  72692. float w = getTypeface()->getStringWidth (text);
  72693. if (font->kerning != 0)
  72694. w += font->kerning * text.length();
  72695. return w * font->height * font->horizontalScale;
  72696. }
  72697. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72698. {
  72699. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72700. const float scale = font->height * font->horizontalScale;
  72701. const int num = xOffsets.size();
  72702. if (num > 0)
  72703. {
  72704. float* const x = &(xOffsets.getReference(0));
  72705. if (font->kerning != 0)
  72706. {
  72707. for (int i = 0; i < num; ++i)
  72708. x[i] = (x[i] + i * font->kerning) * scale;
  72709. }
  72710. else
  72711. {
  72712. for (int i = 0; i < num; ++i)
  72713. x[i] *= scale;
  72714. }
  72715. }
  72716. }
  72717. void Font::findFonts (Array<Font>& destArray)
  72718. {
  72719. const StringArray names (findAllTypefaceNames());
  72720. for (int i = 0; i < names.size(); ++i)
  72721. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72722. }
  72723. const String Font::toString() const
  72724. {
  72725. String s (getTypefaceName());
  72726. if (s == getDefaultSansSerifFontName())
  72727. s = String::empty;
  72728. else
  72729. s += "; ";
  72730. s += String (getHeight(), 1);
  72731. if (isBold())
  72732. s += " bold";
  72733. if (isItalic())
  72734. s += " italic";
  72735. return s;
  72736. }
  72737. const Font Font::fromString (const String& fontDescription)
  72738. {
  72739. String name;
  72740. const int separator = fontDescription.indexOfChar (';');
  72741. if (separator > 0)
  72742. name = fontDescription.substring (0, separator).trim();
  72743. if (name.isEmpty())
  72744. name = getDefaultSansSerifFontName();
  72745. String sizeAndStyle (fontDescription.substring (separator + 1));
  72746. float height = sizeAndStyle.getFloatValue();
  72747. if (height <= 0)
  72748. height = 10.0f;
  72749. int flags = Font::plain;
  72750. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72751. flags |= Font::bold;
  72752. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72753. flags |= Font::italic;
  72754. return Font (name, height, flags);
  72755. }
  72756. Typeface* Font::getTypeface() const
  72757. {
  72758. if (font->typeface == 0)
  72759. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72760. return font->typeface;
  72761. }
  72762. END_JUCE_NAMESPACE
  72763. /*** End of inlined file: juce_Font.cpp ***/
  72764. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72765. BEGIN_JUCE_NAMESPACE
  72766. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72767. const juce_wchar character_, const int glyph_)
  72768. : x (x_),
  72769. y (y_),
  72770. w (w_),
  72771. font (font_),
  72772. character (character_),
  72773. glyph (glyph_)
  72774. {
  72775. }
  72776. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72777. : x (other.x),
  72778. y (other.y),
  72779. w (other.w),
  72780. font (other.font),
  72781. character (other.character),
  72782. glyph (other.glyph)
  72783. {
  72784. }
  72785. void PositionedGlyph::draw (const Graphics& g) const
  72786. {
  72787. if (! isWhitespace())
  72788. {
  72789. g.getInternalContext()->setFont (font);
  72790. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72791. }
  72792. }
  72793. void PositionedGlyph::draw (const Graphics& g,
  72794. const AffineTransform& transform) const
  72795. {
  72796. if (! isWhitespace())
  72797. {
  72798. g.getInternalContext()->setFont (font);
  72799. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72800. .followedBy (transform));
  72801. }
  72802. }
  72803. void PositionedGlyph::createPath (Path& path) const
  72804. {
  72805. if (! isWhitespace())
  72806. {
  72807. Typeface* const t = font.getTypeface();
  72808. if (t != 0)
  72809. {
  72810. Path p;
  72811. t->getOutlineForGlyph (glyph, p);
  72812. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72813. .translated (x, y));
  72814. }
  72815. }
  72816. }
  72817. bool PositionedGlyph::hitTest (float px, float py) const
  72818. {
  72819. if (getBounds().contains (px, py) && ! isWhitespace())
  72820. {
  72821. Typeface* const t = font.getTypeface();
  72822. if (t != 0)
  72823. {
  72824. Path p;
  72825. t->getOutlineForGlyph (glyph, p);
  72826. AffineTransform::translation (-x, -y)
  72827. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72828. .transformPoint (px, py);
  72829. return p.contains (px, py);
  72830. }
  72831. }
  72832. return false;
  72833. }
  72834. void PositionedGlyph::moveBy (const float deltaX,
  72835. const float deltaY)
  72836. {
  72837. x += deltaX;
  72838. y += deltaY;
  72839. }
  72840. GlyphArrangement::GlyphArrangement()
  72841. {
  72842. glyphs.ensureStorageAllocated (128);
  72843. }
  72844. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72845. {
  72846. addGlyphArrangement (other);
  72847. }
  72848. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72849. {
  72850. if (this != &other)
  72851. {
  72852. clear();
  72853. addGlyphArrangement (other);
  72854. }
  72855. return *this;
  72856. }
  72857. GlyphArrangement::~GlyphArrangement()
  72858. {
  72859. }
  72860. void GlyphArrangement::clear()
  72861. {
  72862. glyphs.clear();
  72863. }
  72864. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72865. {
  72866. jassert (isPositiveAndBelow (index, glyphs.size()));
  72867. return *glyphs [index];
  72868. }
  72869. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72870. {
  72871. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72872. glyphs.addCopiesOf (other.glyphs);
  72873. }
  72874. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72875. {
  72876. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72877. }
  72878. void GlyphArrangement::addLineOfText (const Font& font,
  72879. const String& text,
  72880. const float xOffset,
  72881. const float yOffset)
  72882. {
  72883. addCurtailedLineOfText (font, text,
  72884. xOffset, yOffset,
  72885. 1.0e10f, false);
  72886. }
  72887. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72888. const String& text,
  72889. float xOffset,
  72890. const float yOffset,
  72891. const float maxWidthPixels,
  72892. const bool useEllipsis)
  72893. {
  72894. if (text.isNotEmpty())
  72895. {
  72896. Array <int> newGlyphs;
  72897. Array <float> xOffsets;
  72898. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72899. const int textLen = newGlyphs.size();
  72900. const juce_wchar* const unicodeText = text;
  72901. for (int i = 0; i < textLen; ++i)
  72902. {
  72903. const float thisX = xOffsets.getUnchecked (i);
  72904. const float nextX = xOffsets.getUnchecked (i + 1);
  72905. if (nextX > maxWidthPixels + 1.0f)
  72906. {
  72907. // curtail the string if it's too wide..
  72908. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72909. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72910. break;
  72911. }
  72912. else
  72913. {
  72914. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72915. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72916. }
  72917. }
  72918. }
  72919. }
  72920. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72921. const int startIndex, int endIndex)
  72922. {
  72923. int numDeleted = 0;
  72924. if (glyphs.size() > 0)
  72925. {
  72926. Array<int> dotGlyphs;
  72927. Array<float> dotXs;
  72928. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72929. const float dx = dotXs[1];
  72930. float xOffset = 0.0f, yOffset = 0.0f;
  72931. while (endIndex > startIndex)
  72932. {
  72933. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72934. xOffset = pg->x;
  72935. yOffset = pg->y;
  72936. glyphs.remove (endIndex);
  72937. ++numDeleted;
  72938. if (xOffset + dx * 3 <= maxXPos)
  72939. break;
  72940. }
  72941. for (int i = 3; --i >= 0;)
  72942. {
  72943. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72944. font, '.', dotGlyphs.getFirst()));
  72945. --numDeleted;
  72946. xOffset += dx;
  72947. if (xOffset > maxXPos)
  72948. break;
  72949. }
  72950. }
  72951. return numDeleted;
  72952. }
  72953. void GlyphArrangement::addJustifiedText (const Font& font,
  72954. const String& text,
  72955. float x, float y,
  72956. const float maxLineWidth,
  72957. const Justification& horizontalLayout)
  72958. {
  72959. int lineStartIndex = glyphs.size();
  72960. addLineOfText (font, text, x, y);
  72961. const float originalY = y;
  72962. while (lineStartIndex < glyphs.size())
  72963. {
  72964. int i = lineStartIndex;
  72965. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72966. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72967. ++i;
  72968. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72969. int lastWordBreakIndex = -1;
  72970. while (i < glyphs.size())
  72971. {
  72972. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72973. const juce_wchar c = pg->getCharacter();
  72974. if (c == '\r' || c == '\n')
  72975. {
  72976. ++i;
  72977. if (c == '\r' && i < glyphs.size()
  72978. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72979. ++i;
  72980. break;
  72981. }
  72982. else if (pg->isWhitespace())
  72983. {
  72984. lastWordBreakIndex = i + 1;
  72985. }
  72986. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72987. {
  72988. if (lastWordBreakIndex >= 0)
  72989. i = lastWordBreakIndex;
  72990. break;
  72991. }
  72992. ++i;
  72993. }
  72994. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72995. float currentLineEndX = currentLineStartX;
  72996. for (int j = i; --j >= lineStartIndex;)
  72997. {
  72998. if (! glyphs.getUnchecked (j)->isWhitespace())
  72999. {
  73000. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  73001. break;
  73002. }
  73003. }
  73004. float deltaX = 0.0f;
  73005. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  73006. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  73007. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  73008. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  73009. else if (horizontalLayout.testFlags (Justification::right))
  73010. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  73011. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  73012. x + deltaX - currentLineStartX, y - originalY);
  73013. lineStartIndex = i;
  73014. y += font.getHeight();
  73015. }
  73016. }
  73017. void GlyphArrangement::addFittedText (const Font& f,
  73018. const String& text,
  73019. const float x, const float y,
  73020. const float width, const float height,
  73021. const Justification& layout,
  73022. int maximumLines,
  73023. const float minimumHorizontalScale)
  73024. {
  73025. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  73026. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  73027. if (text.containsAnyOf ("\r\n"))
  73028. {
  73029. GlyphArrangement ga;
  73030. ga.addJustifiedText (f, text, x, y, width, layout);
  73031. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  73032. float dy = y - bb.getY();
  73033. if (layout.testFlags (Justification::verticallyCentred))
  73034. dy += (height - bb.getHeight()) * 0.5f;
  73035. else if (layout.testFlags (Justification::bottom))
  73036. dy += height - bb.getHeight();
  73037. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  73038. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  73039. for (int i = 0; i < ga.glyphs.size(); ++i)
  73040. glyphs.add (ga.glyphs.getUnchecked (i));
  73041. ga.glyphs.clear (false);
  73042. return;
  73043. }
  73044. int startIndex = glyphs.size();
  73045. addLineOfText (f, text.trim(), x, y);
  73046. if (glyphs.size() > startIndex)
  73047. {
  73048. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73049. - glyphs.getUnchecked (startIndex)->getLeft();
  73050. if (lineWidth <= 0)
  73051. return;
  73052. if (lineWidth * minimumHorizontalScale < width)
  73053. {
  73054. if (lineWidth > width)
  73055. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  73056. width / lineWidth);
  73057. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  73058. x, y, width, height, layout);
  73059. }
  73060. else if (maximumLines <= 1)
  73061. {
  73062. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  73063. x, y, width, height, f, layout, minimumHorizontalScale);
  73064. }
  73065. else
  73066. {
  73067. Font font (f);
  73068. String txt (text.trim());
  73069. const int length = txt.length();
  73070. const int originalStartIndex = startIndex;
  73071. int numLines = 1;
  73072. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  73073. maximumLines = 1;
  73074. maximumLines = jmin (maximumLines, length);
  73075. while (numLines < maximumLines)
  73076. {
  73077. ++numLines;
  73078. const float newFontHeight = height / (float) numLines;
  73079. if (newFontHeight < font.getHeight())
  73080. {
  73081. font.setHeight (jmax (8.0f, newFontHeight));
  73082. removeRangeOfGlyphs (startIndex, -1);
  73083. addLineOfText (font, txt, x, y);
  73084. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73085. - glyphs.getUnchecked (startIndex)->getLeft();
  73086. }
  73087. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  73088. break;
  73089. }
  73090. if (numLines < 1)
  73091. numLines = 1;
  73092. float lineY = y;
  73093. float widthPerLine = lineWidth / numLines;
  73094. int lastLineStartIndex = 0;
  73095. for (int line = 0; line < numLines; ++line)
  73096. {
  73097. int i = startIndex;
  73098. lastLineStartIndex = i;
  73099. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  73100. if (line == numLines - 1)
  73101. {
  73102. widthPerLine = width;
  73103. i = glyphs.size();
  73104. }
  73105. else
  73106. {
  73107. while (i < glyphs.size())
  73108. {
  73109. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  73110. if (lineWidth > widthPerLine)
  73111. {
  73112. // got to a point where the line's too long, so skip forward to find a
  73113. // good place to break it..
  73114. const int searchStartIndex = i;
  73115. while (i < glyphs.size())
  73116. {
  73117. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73118. {
  73119. if (glyphs.getUnchecked (i)->isWhitespace()
  73120. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73121. {
  73122. ++i;
  73123. break;
  73124. }
  73125. }
  73126. else
  73127. {
  73128. // can't find a suitable break, so try looking backwards..
  73129. i = searchStartIndex;
  73130. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73131. {
  73132. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73133. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73134. {
  73135. i -= back - 1;
  73136. break;
  73137. }
  73138. }
  73139. break;
  73140. }
  73141. ++i;
  73142. }
  73143. break;
  73144. }
  73145. ++i;
  73146. }
  73147. int wsStart = i;
  73148. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73149. --wsStart;
  73150. int wsEnd = i;
  73151. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73152. ++wsEnd;
  73153. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73154. i = jmax (wsStart, startIndex + 1);
  73155. }
  73156. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73157. x, lineY, width, font.getHeight(), font,
  73158. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73159. minimumHorizontalScale);
  73160. startIndex = i;
  73161. lineY += font.getHeight();
  73162. if (startIndex >= glyphs.size())
  73163. break;
  73164. }
  73165. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73166. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73167. }
  73168. }
  73169. }
  73170. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73171. const float dx, const float dy)
  73172. {
  73173. jassert (startIndex >= 0);
  73174. if (dx != 0.0f || dy != 0.0f)
  73175. {
  73176. if (num < 0 || startIndex + num > glyphs.size())
  73177. num = glyphs.size() - startIndex;
  73178. while (--num >= 0)
  73179. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73180. }
  73181. }
  73182. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73183. const Justification& justification, float minimumHorizontalScale)
  73184. {
  73185. int numDeleted = 0;
  73186. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73187. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73188. if (lineWidth > w)
  73189. {
  73190. if (minimumHorizontalScale < 1.0f)
  73191. {
  73192. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73193. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73194. }
  73195. if (lineWidth > w)
  73196. {
  73197. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73198. numGlyphs -= numDeleted;
  73199. }
  73200. }
  73201. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73202. return numDeleted;
  73203. }
  73204. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73205. const float horizontalScaleFactor)
  73206. {
  73207. jassert (startIndex >= 0);
  73208. if (num < 0 || startIndex + num > glyphs.size())
  73209. num = glyphs.size() - startIndex;
  73210. if (num > 0)
  73211. {
  73212. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73213. while (--num >= 0)
  73214. {
  73215. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73216. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73217. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73218. pg->w *= horizontalScaleFactor;
  73219. }
  73220. }
  73221. }
  73222. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73223. {
  73224. jassert (startIndex >= 0);
  73225. if (num < 0 || startIndex + num > glyphs.size())
  73226. num = glyphs.size() - startIndex;
  73227. Rectangle<float> result;
  73228. while (--num >= 0)
  73229. {
  73230. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73231. if (includeWhitespace || ! pg->isWhitespace())
  73232. result = result.getUnion (pg->getBounds());
  73233. }
  73234. return result;
  73235. }
  73236. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73237. const float x, const float y, const float width, const float height,
  73238. const Justification& justification)
  73239. {
  73240. jassert (num >= 0 && startIndex >= 0);
  73241. if (glyphs.size() > 0 && num > 0)
  73242. {
  73243. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73244. | Justification::horizontallyCentred)));
  73245. float deltaX = 0.0f;
  73246. if (justification.testFlags (Justification::horizontallyJustified))
  73247. deltaX = x - bb.getX();
  73248. else if (justification.testFlags (Justification::horizontallyCentred))
  73249. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73250. else if (justification.testFlags (Justification::right))
  73251. deltaX = (x + width) - bb.getRight();
  73252. else
  73253. deltaX = x - bb.getX();
  73254. float deltaY = 0.0f;
  73255. if (justification.testFlags (Justification::top))
  73256. deltaY = y - bb.getY();
  73257. else if (justification.testFlags (Justification::bottom))
  73258. deltaY = (y + height) - bb.getBottom();
  73259. else
  73260. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73261. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73262. if (justification.testFlags (Justification::horizontallyJustified))
  73263. {
  73264. int lineStart = 0;
  73265. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73266. int i;
  73267. for (i = 0; i < num; ++i)
  73268. {
  73269. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73270. if (glyphY != baseY)
  73271. {
  73272. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73273. lineStart = i;
  73274. baseY = glyphY;
  73275. }
  73276. }
  73277. if (i > lineStart)
  73278. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73279. }
  73280. }
  73281. }
  73282. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73283. {
  73284. if (start + num < glyphs.size()
  73285. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73286. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73287. {
  73288. int numSpaces = 0;
  73289. int spacesAtEnd = 0;
  73290. for (int i = 0; i < num; ++i)
  73291. {
  73292. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73293. {
  73294. ++spacesAtEnd;
  73295. ++numSpaces;
  73296. }
  73297. else
  73298. {
  73299. spacesAtEnd = 0;
  73300. }
  73301. }
  73302. numSpaces -= spacesAtEnd;
  73303. if (numSpaces > 0)
  73304. {
  73305. const float startX = glyphs.getUnchecked (start)->getLeft();
  73306. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73307. const float extraPaddingBetweenWords
  73308. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73309. float deltaX = 0.0f;
  73310. for (int i = 0; i < num; ++i)
  73311. {
  73312. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73313. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73314. deltaX += extraPaddingBetweenWords;
  73315. }
  73316. }
  73317. }
  73318. }
  73319. void GlyphArrangement::draw (const Graphics& g) const
  73320. {
  73321. for (int i = 0; i < glyphs.size(); ++i)
  73322. {
  73323. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73324. if (pg->font.isUnderlined())
  73325. {
  73326. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73327. float nextX = pg->x + pg->w;
  73328. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73329. nextX = glyphs.getUnchecked (i + 1)->x;
  73330. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73331. nextX - pg->x, lineThickness);
  73332. }
  73333. pg->draw (g);
  73334. }
  73335. }
  73336. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73337. {
  73338. for (int i = 0; i < glyphs.size(); ++i)
  73339. {
  73340. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73341. if (pg->font.isUnderlined())
  73342. {
  73343. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73344. float nextX = pg->x + pg->w;
  73345. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73346. nextX = glyphs.getUnchecked (i + 1)->x;
  73347. Path p;
  73348. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73349. nextX, pg->y + lineThickness * 2.0f),
  73350. lineThickness);
  73351. g.fillPath (p, transform);
  73352. }
  73353. pg->draw (g, transform);
  73354. }
  73355. }
  73356. void GlyphArrangement::createPath (Path& path) const
  73357. {
  73358. for (int i = 0; i < glyphs.size(); ++i)
  73359. glyphs.getUnchecked (i)->createPath (path);
  73360. }
  73361. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73362. {
  73363. for (int i = 0; i < glyphs.size(); ++i)
  73364. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73365. return i;
  73366. return -1;
  73367. }
  73368. END_JUCE_NAMESPACE
  73369. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73370. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73371. BEGIN_JUCE_NAMESPACE
  73372. class TextLayout::Token
  73373. {
  73374. public:
  73375. Token (const String& t,
  73376. const Font& f,
  73377. const bool isWhitespace_)
  73378. : text (t),
  73379. font (f),
  73380. x(0),
  73381. y(0),
  73382. isWhitespace (isWhitespace_)
  73383. {
  73384. w = font.getStringWidth (t);
  73385. h = roundToInt (f.getHeight());
  73386. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73387. }
  73388. Token (const Token& other)
  73389. : text (other.text),
  73390. font (other.font),
  73391. x (other.x),
  73392. y (other.y),
  73393. w (other.w),
  73394. h (other.h),
  73395. line (other.line),
  73396. lineHeight (other.lineHeight),
  73397. isWhitespace (other.isWhitespace),
  73398. isNewLine (other.isNewLine)
  73399. {
  73400. }
  73401. void draw (Graphics& g,
  73402. const int xOffset,
  73403. const int yOffset)
  73404. {
  73405. if (! isWhitespace)
  73406. {
  73407. g.setFont (font);
  73408. g.drawSingleLineText (text.trimEnd(),
  73409. xOffset + x,
  73410. yOffset + y + (lineHeight - h)
  73411. + roundToInt (font.getAscent()));
  73412. }
  73413. }
  73414. String text;
  73415. Font font;
  73416. int x, y, w, h;
  73417. int line, lineHeight;
  73418. bool isWhitespace, isNewLine;
  73419. private:
  73420. JUCE_LEAK_DETECTOR (Token);
  73421. };
  73422. TextLayout::TextLayout()
  73423. : totalLines (0)
  73424. {
  73425. tokens.ensureStorageAllocated (64);
  73426. }
  73427. TextLayout::TextLayout (const String& text, const Font& font)
  73428. : totalLines (0)
  73429. {
  73430. tokens.ensureStorageAllocated (64);
  73431. appendText (text, font);
  73432. }
  73433. TextLayout::TextLayout (const TextLayout& other)
  73434. : totalLines (0)
  73435. {
  73436. *this = other;
  73437. }
  73438. TextLayout& TextLayout::operator= (const TextLayout& other)
  73439. {
  73440. if (this != &other)
  73441. {
  73442. clear();
  73443. totalLines = other.totalLines;
  73444. tokens.addCopiesOf (other.tokens);
  73445. }
  73446. return *this;
  73447. }
  73448. TextLayout::~TextLayout()
  73449. {
  73450. clear();
  73451. }
  73452. void TextLayout::clear()
  73453. {
  73454. tokens.clear();
  73455. totalLines = 0;
  73456. }
  73457. bool TextLayout::isEmpty() const
  73458. {
  73459. return tokens.size() == 0;
  73460. }
  73461. void TextLayout::appendText (const String& text, const Font& font)
  73462. {
  73463. const juce_wchar* t = text;
  73464. String currentString;
  73465. int lastCharType = 0;
  73466. for (;;)
  73467. {
  73468. const juce_wchar c = *t++;
  73469. if (c == 0)
  73470. break;
  73471. int charType;
  73472. if (c == '\r' || c == '\n')
  73473. {
  73474. charType = 0;
  73475. }
  73476. else if (CharacterFunctions::isWhitespace (c))
  73477. {
  73478. charType = 2;
  73479. }
  73480. else
  73481. {
  73482. charType = 1;
  73483. }
  73484. if (charType == 0 || charType != lastCharType)
  73485. {
  73486. if (currentString.isNotEmpty())
  73487. {
  73488. tokens.add (new Token (currentString, font,
  73489. lastCharType == 2 || lastCharType == 0));
  73490. }
  73491. currentString = String::charToString (c);
  73492. if (c == '\r' && *t == '\n')
  73493. currentString += *t++;
  73494. }
  73495. else
  73496. {
  73497. currentString += c;
  73498. }
  73499. lastCharType = charType;
  73500. }
  73501. if (currentString.isNotEmpty())
  73502. tokens.add (new Token (currentString, font, lastCharType == 2));
  73503. }
  73504. void TextLayout::setText (const String& text, const Font& font)
  73505. {
  73506. clear();
  73507. appendText (text, font);
  73508. }
  73509. void TextLayout::layout (int maxWidth,
  73510. const Justification& justification,
  73511. const bool attemptToBalanceLineLengths)
  73512. {
  73513. if (attemptToBalanceLineLengths)
  73514. {
  73515. const int originalW = maxWidth;
  73516. int bestWidth = maxWidth;
  73517. float bestLineProportion = 0.0f;
  73518. while (maxWidth > originalW / 2)
  73519. {
  73520. layout (maxWidth, justification, false);
  73521. if (getNumLines() <= 1)
  73522. return;
  73523. const int lastLineW = getLineWidth (getNumLines() - 1);
  73524. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73525. const float prop = lastLineW / (float) lastButOneLineW;
  73526. if (prop > 0.9f)
  73527. return;
  73528. if (prop > bestLineProportion)
  73529. {
  73530. bestLineProportion = prop;
  73531. bestWidth = maxWidth;
  73532. }
  73533. maxWidth -= 10;
  73534. }
  73535. layout (bestWidth, justification, false);
  73536. }
  73537. else
  73538. {
  73539. int x = 0;
  73540. int y = 0;
  73541. int h = 0;
  73542. totalLines = 0;
  73543. int i;
  73544. for (i = 0; i < tokens.size(); ++i)
  73545. {
  73546. Token* const t = tokens.getUnchecked(i);
  73547. t->x = x;
  73548. t->y = y;
  73549. t->line = totalLines;
  73550. x += t->w;
  73551. h = jmax (h, t->h);
  73552. const Token* nextTok = tokens [i + 1];
  73553. if (nextTok == 0)
  73554. break;
  73555. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73556. {
  73557. // finished a line, so go back and update the heights of the things on it
  73558. for (int j = i; j >= 0; --j)
  73559. {
  73560. Token* const tok = tokens.getUnchecked(j);
  73561. if (tok->line == totalLines)
  73562. tok->lineHeight = h;
  73563. else
  73564. break;
  73565. }
  73566. x = 0;
  73567. y += h;
  73568. h = 0;
  73569. ++totalLines;
  73570. }
  73571. }
  73572. // finished a line, so go back and update the heights of the things on it
  73573. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73574. {
  73575. Token* const t = tokens.getUnchecked(j);
  73576. if (t->line == totalLines)
  73577. t->lineHeight = h;
  73578. else
  73579. break;
  73580. }
  73581. ++totalLines;
  73582. if (! justification.testFlags (Justification::left))
  73583. {
  73584. int totalW = getWidth();
  73585. for (i = totalLines; --i >= 0;)
  73586. {
  73587. const int lineW = getLineWidth (i);
  73588. int dx = 0;
  73589. if (justification.testFlags (Justification::horizontallyCentred))
  73590. dx = (totalW - lineW) / 2;
  73591. else if (justification.testFlags (Justification::right))
  73592. dx = totalW - lineW;
  73593. for (int j = tokens.size(); --j >= 0;)
  73594. {
  73595. Token* const t = tokens.getUnchecked(j);
  73596. if (t->line == i)
  73597. t->x += dx;
  73598. }
  73599. }
  73600. }
  73601. }
  73602. }
  73603. int TextLayout::getLineWidth (const int lineNumber) const
  73604. {
  73605. int maxW = 0;
  73606. for (int i = tokens.size(); --i >= 0;)
  73607. {
  73608. const Token* const t = tokens.getUnchecked(i);
  73609. if (t->line == lineNumber && ! t->isWhitespace)
  73610. maxW = jmax (maxW, t->x + t->w);
  73611. }
  73612. return maxW;
  73613. }
  73614. int TextLayout::getWidth() const
  73615. {
  73616. int maxW = 0;
  73617. for (int i = tokens.size(); --i >= 0;)
  73618. {
  73619. const Token* const t = tokens.getUnchecked(i);
  73620. if (! t->isWhitespace)
  73621. maxW = jmax (maxW, t->x + t->w);
  73622. }
  73623. return maxW;
  73624. }
  73625. int TextLayout::getHeight() const
  73626. {
  73627. int maxH = 0;
  73628. for (int i = tokens.size(); --i >= 0;)
  73629. {
  73630. const Token* const t = tokens.getUnchecked(i);
  73631. if (! t->isWhitespace)
  73632. maxH = jmax (maxH, t->y + t->h);
  73633. }
  73634. return maxH;
  73635. }
  73636. void TextLayout::draw (Graphics& g,
  73637. const int xOffset,
  73638. const int yOffset) const
  73639. {
  73640. for (int i = tokens.size(); --i >= 0;)
  73641. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73642. }
  73643. void TextLayout::drawWithin (Graphics& g,
  73644. int x, int y, int w, int h,
  73645. const Justification& justification) const
  73646. {
  73647. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73648. x, y, w, h);
  73649. draw (g, x, y);
  73650. }
  73651. END_JUCE_NAMESPACE
  73652. /*** End of inlined file: juce_TextLayout.cpp ***/
  73653. /*** Start of inlined file: juce_Typeface.cpp ***/
  73654. BEGIN_JUCE_NAMESPACE
  73655. Typeface::Typeface (const String& name_) throw()
  73656. : name (name_), isFallbackFont (false)
  73657. {
  73658. }
  73659. Typeface::~Typeface()
  73660. {
  73661. }
  73662. const Typeface::Ptr Typeface::getFallbackTypeface()
  73663. {
  73664. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73665. Typeface* t = fallbackFont.getTypeface();
  73666. t->isFallbackFont = true;
  73667. return t;
  73668. }
  73669. class CustomTypeface::GlyphInfo
  73670. {
  73671. public:
  73672. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73673. : character (character_), path (path_), width (width_)
  73674. {
  73675. }
  73676. struct KerningPair
  73677. {
  73678. juce_wchar character2;
  73679. float kerningAmount;
  73680. };
  73681. void addKerningPair (const juce_wchar subsequentCharacter,
  73682. const float extraKerningAmount) throw()
  73683. {
  73684. KerningPair kp;
  73685. kp.character2 = subsequentCharacter;
  73686. kp.kerningAmount = extraKerningAmount;
  73687. kerningPairs.add (kp);
  73688. }
  73689. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73690. {
  73691. if (subsequentCharacter != 0)
  73692. {
  73693. for (int i = kerningPairs.size(); --i >= 0;)
  73694. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73695. return width + kerningPairs.getReference(i).kerningAmount;
  73696. }
  73697. return width;
  73698. }
  73699. const juce_wchar character;
  73700. const Path path;
  73701. float width;
  73702. Array <KerningPair> kerningPairs;
  73703. private:
  73704. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  73705. };
  73706. CustomTypeface::CustomTypeface()
  73707. : Typeface (String::empty)
  73708. {
  73709. clear();
  73710. }
  73711. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73712. : Typeface (String::empty)
  73713. {
  73714. clear();
  73715. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73716. BufferedInputStream in (gzin, 32768);
  73717. name = in.readString();
  73718. isBold = in.readBool();
  73719. isItalic = in.readBool();
  73720. ascent = in.readFloat();
  73721. defaultCharacter = (juce_wchar) in.readShort();
  73722. int i, numChars = in.readInt();
  73723. for (i = 0; i < numChars; ++i)
  73724. {
  73725. const juce_wchar c = (juce_wchar) in.readShort();
  73726. const float width = in.readFloat();
  73727. Path p;
  73728. p.loadPathFromStream (in);
  73729. addGlyph (c, p, width);
  73730. }
  73731. const int numKerningPairs = in.readInt();
  73732. for (i = 0; i < numKerningPairs; ++i)
  73733. {
  73734. const juce_wchar char1 = (juce_wchar) in.readShort();
  73735. const juce_wchar char2 = (juce_wchar) in.readShort();
  73736. addKerningPair (char1, char2, in.readFloat());
  73737. }
  73738. }
  73739. CustomTypeface::~CustomTypeface()
  73740. {
  73741. }
  73742. void CustomTypeface::clear()
  73743. {
  73744. defaultCharacter = 0;
  73745. ascent = 1.0f;
  73746. isBold = isItalic = false;
  73747. zeromem (lookupTable, sizeof (lookupTable));
  73748. glyphs.clear();
  73749. }
  73750. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73751. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73752. {
  73753. name = name_;
  73754. defaultCharacter = defaultCharacter_;
  73755. ascent = ascent_;
  73756. isBold = isBold_;
  73757. isItalic = isItalic_;
  73758. }
  73759. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73760. {
  73761. // Check that you're not trying to add the same character twice..
  73762. jassert (findGlyph (character, false) == 0);
  73763. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  73764. lookupTable [character] = (short) glyphs.size();
  73765. glyphs.add (new GlyphInfo (character, path, width));
  73766. }
  73767. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73768. {
  73769. if (extraAmount != 0)
  73770. {
  73771. GlyphInfo* const g = findGlyph (char1, true);
  73772. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73773. if (g != 0)
  73774. g->addKerningPair (char2, extraAmount);
  73775. }
  73776. }
  73777. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73778. {
  73779. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  73780. return glyphs [(int) lookupTable [(int) character]];
  73781. for (int i = 0; i < glyphs.size(); ++i)
  73782. {
  73783. GlyphInfo* const g = glyphs.getUnchecked(i);
  73784. if (g->character == character)
  73785. return g;
  73786. }
  73787. if (loadIfNeeded && loadGlyphIfPossible (character))
  73788. return findGlyph (character, false);
  73789. return 0;
  73790. }
  73791. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73792. {
  73793. GlyphInfo* glyph = findGlyph (character, true);
  73794. if (glyph == 0)
  73795. {
  73796. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73797. glyph = findGlyph (L' ', true);
  73798. if (glyph == 0)
  73799. {
  73800. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73801. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73802. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73803. {
  73804. Path path;
  73805. fallbackTypeface->getOutlineForGlyph (character, path);
  73806. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73807. }
  73808. if (glyph == 0)
  73809. glyph = findGlyph (defaultCharacter, true);
  73810. }
  73811. }
  73812. return glyph;
  73813. }
  73814. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73815. {
  73816. return false;
  73817. }
  73818. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73819. {
  73820. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73821. for (int i = 0; i < numCharacters; ++i)
  73822. {
  73823. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73824. Array <int> glyphIndexes;
  73825. Array <float> offsets;
  73826. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73827. const int glyphIndex = glyphIndexes.getFirst();
  73828. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73829. {
  73830. const float glyphWidth = offsets[1];
  73831. Path p;
  73832. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73833. addGlyph (c, p, glyphWidth);
  73834. for (int j = glyphs.size() - 1; --j >= 0;)
  73835. {
  73836. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73837. glyphIndexes.clearQuick();
  73838. offsets.clearQuick();
  73839. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73840. if (offsets.size() > 1)
  73841. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73842. }
  73843. }
  73844. }
  73845. }
  73846. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73847. {
  73848. GZIPCompressorOutputStream out (&outputStream);
  73849. out.writeString (name);
  73850. out.writeBool (isBold);
  73851. out.writeBool (isItalic);
  73852. out.writeFloat (ascent);
  73853. out.writeShort ((short) (unsigned short) defaultCharacter);
  73854. out.writeInt (glyphs.size());
  73855. int i, numKerningPairs = 0;
  73856. for (i = 0; i < glyphs.size(); ++i)
  73857. {
  73858. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73859. out.writeShort ((short) (unsigned short) g->character);
  73860. out.writeFloat (g->width);
  73861. g->path.writePathToStream (out);
  73862. numKerningPairs += g->kerningPairs.size();
  73863. }
  73864. out.writeInt (numKerningPairs);
  73865. for (i = 0; i < glyphs.size(); ++i)
  73866. {
  73867. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73868. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73869. {
  73870. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73871. out.writeShort ((short) (unsigned short) g->character);
  73872. out.writeShort ((short) (unsigned short) p.character2);
  73873. out.writeFloat (p.kerningAmount);
  73874. }
  73875. }
  73876. return true;
  73877. }
  73878. float CustomTypeface::getAscent() const
  73879. {
  73880. return ascent;
  73881. }
  73882. float CustomTypeface::getDescent() const
  73883. {
  73884. return 1.0f - ascent;
  73885. }
  73886. float CustomTypeface::getStringWidth (const String& text)
  73887. {
  73888. float x = 0;
  73889. const juce_wchar* t = text;
  73890. while (*t != 0)
  73891. {
  73892. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73893. if (glyph == 0 && ! isFallbackFont)
  73894. {
  73895. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73896. if (fallbackTypeface != 0)
  73897. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73898. }
  73899. if (glyph != 0)
  73900. x += glyph->getHorizontalSpacing (*t);
  73901. }
  73902. return x;
  73903. }
  73904. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73905. {
  73906. xOffsets.add (0);
  73907. float x = 0;
  73908. const juce_wchar* t = text;
  73909. while (*t != 0)
  73910. {
  73911. const juce_wchar c = *t++;
  73912. const GlyphInfo* const glyph = findGlyph (c, true);
  73913. if (glyph == 0 && ! isFallbackFont)
  73914. {
  73915. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73916. if (fallbackTypeface != 0)
  73917. {
  73918. Array <int> subGlyphs;
  73919. Array <float> subOffsets;
  73920. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73921. if (subGlyphs.size() > 0)
  73922. {
  73923. resultGlyphs.add (subGlyphs.getFirst());
  73924. x += subOffsets[1];
  73925. xOffsets.add (x);
  73926. }
  73927. }
  73928. }
  73929. if (glyph != 0)
  73930. {
  73931. x += glyph->getHorizontalSpacing (*t);
  73932. resultGlyphs.add ((int) glyph->character);
  73933. xOffsets.add (x);
  73934. }
  73935. }
  73936. }
  73937. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73938. {
  73939. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73940. if (glyph == 0 && ! isFallbackFont)
  73941. {
  73942. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73943. if (fallbackTypeface != 0)
  73944. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73945. }
  73946. if (glyph != 0)
  73947. {
  73948. path = glyph->path;
  73949. return true;
  73950. }
  73951. return false;
  73952. }
  73953. END_JUCE_NAMESPACE
  73954. /*** End of inlined file: juce_Typeface.cpp ***/
  73955. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73956. BEGIN_JUCE_NAMESPACE
  73957. AffineTransform::AffineTransform() throw()
  73958. : mat00 (1.0f), mat01 (0), mat02 (0),
  73959. mat10 (0), mat11 (1.0f), mat12 (0)
  73960. {
  73961. }
  73962. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73963. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  73964. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  73965. {
  73966. }
  73967. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  73968. const float mat10_, const float mat11_, const float mat12_) throw()
  73969. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  73970. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  73971. {
  73972. }
  73973. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73974. {
  73975. mat00 = other.mat00;
  73976. mat01 = other.mat01;
  73977. mat02 = other.mat02;
  73978. mat10 = other.mat10;
  73979. mat11 = other.mat11;
  73980. mat12 = other.mat12;
  73981. return *this;
  73982. }
  73983. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73984. {
  73985. return mat00 == other.mat00
  73986. && mat01 == other.mat01
  73987. && mat02 == other.mat02
  73988. && mat10 == other.mat10
  73989. && mat11 == other.mat11
  73990. && mat12 == other.mat12;
  73991. }
  73992. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73993. {
  73994. return ! operator== (other);
  73995. }
  73996. bool AffineTransform::isIdentity() const throw()
  73997. {
  73998. return (mat01 == 0)
  73999. && (mat02 == 0)
  74000. && (mat10 == 0)
  74001. && (mat12 == 0)
  74002. && (mat00 == 1.0f)
  74003. && (mat11 == 1.0f);
  74004. }
  74005. const AffineTransform AffineTransform::identity;
  74006. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  74007. {
  74008. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  74009. other.mat00 * mat01 + other.mat01 * mat11,
  74010. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  74011. other.mat10 * mat00 + other.mat11 * mat10,
  74012. other.mat10 * mat01 + other.mat11 * mat11,
  74013. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  74014. }
  74015. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  74016. {
  74017. return AffineTransform (mat00, mat01, mat02 + dx,
  74018. mat10, mat11, mat12 + dy);
  74019. }
  74020. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  74021. {
  74022. return AffineTransform (1.0f, 0, dx,
  74023. 0, 1.0f, dy);
  74024. }
  74025. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  74026. {
  74027. const float cosRad = std::cos (rad);
  74028. const float sinRad = std::sin (rad);
  74029. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  74030. cosRad * mat01 + -sinRad * mat11,
  74031. cosRad * mat02 + -sinRad * mat12,
  74032. sinRad * mat00 + cosRad * mat10,
  74033. sinRad * mat01 + cosRad * mat11,
  74034. sinRad * mat02 + cosRad * mat12);
  74035. }
  74036. const AffineTransform AffineTransform::rotation (const float rad) throw()
  74037. {
  74038. const float cosRad = std::cos (rad);
  74039. const float sinRad = std::sin (rad);
  74040. return AffineTransform (cosRad, -sinRad, 0,
  74041. sinRad, cosRad, 0);
  74042. }
  74043. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  74044. {
  74045. const float cosRad = std::cos (rad);
  74046. const float sinRad = std::sin (rad);
  74047. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  74048. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  74049. }
  74050. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  74051. {
  74052. return followedBy (rotation (angle, pivotX, pivotY));
  74053. }
  74054. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  74055. {
  74056. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  74057. factorY * mat10, factorY * mat11, factorY * mat12);
  74058. }
  74059. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  74060. {
  74061. return AffineTransform (factorX, 0, 0,
  74062. 0, factorY, 0);
  74063. }
  74064. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  74065. const float pivotX, const float pivotY) const throw()
  74066. {
  74067. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  74068. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  74069. }
  74070. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  74071. const float pivotX, const float pivotY) throw()
  74072. {
  74073. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  74074. 0, factorY, pivotY * (1.0f - factorY));
  74075. }
  74076. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  74077. {
  74078. return AffineTransform (1.0f, shearX, 0,
  74079. shearY, 1.0f, 0);
  74080. }
  74081. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  74082. {
  74083. return AffineTransform (mat00 + shearX * mat10,
  74084. mat01 + shearX * mat11,
  74085. mat02 + shearX * mat12,
  74086. shearY * mat00 + mat10,
  74087. shearY * mat01 + mat11,
  74088. shearY * mat02 + mat12);
  74089. }
  74090. const AffineTransform AffineTransform::inverted() const throw()
  74091. {
  74092. double determinant = (mat00 * mat11 - mat10 * mat01);
  74093. if (determinant != 0.0)
  74094. {
  74095. determinant = 1.0 / determinant;
  74096. const float dst00 = (float) (mat11 * determinant);
  74097. const float dst10 = (float) (-mat10 * determinant);
  74098. const float dst01 = (float) (-mat01 * determinant);
  74099. const float dst11 = (float) (mat00 * determinant);
  74100. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  74101. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  74102. }
  74103. else
  74104. {
  74105. // singularity..
  74106. return *this;
  74107. }
  74108. }
  74109. bool AffineTransform::isSingularity() const throw()
  74110. {
  74111. return (mat00 * mat11 - mat10 * mat01) == 0;
  74112. }
  74113. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  74114. const float x10, const float y10,
  74115. const float x01, const float y01) throw()
  74116. {
  74117. return AffineTransform (x10 - x00, x01 - x00, x00,
  74118. y10 - y00, y01 - y00, y00);
  74119. }
  74120. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74121. const float sx2, const float sy2, const float tx2, const float ty2,
  74122. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74123. {
  74124. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74125. .inverted()
  74126. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74127. }
  74128. bool AffineTransform::isOnlyTranslation() const throw()
  74129. {
  74130. return (mat01 == 0)
  74131. && (mat10 == 0)
  74132. && (mat00 == 1.0f)
  74133. && (mat11 == 1.0f);
  74134. }
  74135. float AffineTransform::getScaleFactor() const throw()
  74136. {
  74137. return juce_hypot (mat00 + mat01, mat10 + mat11);
  74138. }
  74139. END_JUCE_NAMESPACE
  74140. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74141. /*** Start of inlined file: juce_Path.cpp ***/
  74142. BEGIN_JUCE_NAMESPACE
  74143. // tests that some co-ords aren't NaNs
  74144. #define CHECK_COORDS_ARE_VALID(x, y) \
  74145. jassert (x == x && y == y);
  74146. namespace PathHelpers
  74147. {
  74148. const float ellipseAngularIncrement = 0.05f;
  74149. const String nextToken (const juce_wchar*& t)
  74150. {
  74151. while (CharacterFunctions::isWhitespace (*t))
  74152. ++t;
  74153. const juce_wchar* const start = t;
  74154. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74155. ++t;
  74156. return String (start, (int) (t - start));
  74157. }
  74158. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  74159. {
  74160. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  74161. }
  74162. }
  74163. const float Path::lineMarker = 100001.0f;
  74164. const float Path::moveMarker = 100002.0f;
  74165. const float Path::quadMarker = 100003.0f;
  74166. const float Path::cubicMarker = 100004.0f;
  74167. const float Path::closeSubPathMarker = 100005.0f;
  74168. Path::Path()
  74169. : numElements (0),
  74170. pathXMin (0),
  74171. pathXMax (0),
  74172. pathYMin (0),
  74173. pathYMax (0),
  74174. useNonZeroWinding (true)
  74175. {
  74176. }
  74177. Path::~Path()
  74178. {
  74179. }
  74180. Path::Path (const Path& other)
  74181. : numElements (other.numElements),
  74182. pathXMin (other.pathXMin),
  74183. pathXMax (other.pathXMax),
  74184. pathYMin (other.pathYMin),
  74185. pathYMax (other.pathYMax),
  74186. useNonZeroWinding (other.useNonZeroWinding)
  74187. {
  74188. if (numElements > 0)
  74189. {
  74190. data.setAllocatedSize ((int) numElements);
  74191. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74192. }
  74193. }
  74194. Path& Path::operator= (const Path& other)
  74195. {
  74196. if (this != &other)
  74197. {
  74198. data.ensureAllocatedSize ((int) other.numElements);
  74199. numElements = other.numElements;
  74200. pathXMin = other.pathXMin;
  74201. pathXMax = other.pathXMax;
  74202. pathYMin = other.pathYMin;
  74203. pathYMax = other.pathYMax;
  74204. useNonZeroWinding = other.useNonZeroWinding;
  74205. if (numElements > 0)
  74206. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74207. }
  74208. return *this;
  74209. }
  74210. bool Path::operator== (const Path& other) const throw()
  74211. {
  74212. return ! operator!= (other);
  74213. }
  74214. bool Path::operator!= (const Path& other) const throw()
  74215. {
  74216. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74217. return true;
  74218. for (size_t i = 0; i < numElements; ++i)
  74219. if (data.elements[i] != other.data.elements[i])
  74220. return true;
  74221. return false;
  74222. }
  74223. void Path::clear() throw()
  74224. {
  74225. numElements = 0;
  74226. pathXMin = 0;
  74227. pathYMin = 0;
  74228. pathYMax = 0;
  74229. pathXMax = 0;
  74230. }
  74231. void Path::swapWithPath (Path& other) throw()
  74232. {
  74233. data.swapWith (other.data);
  74234. swapVariables <size_t> (numElements, other.numElements);
  74235. swapVariables <float> (pathXMin, other.pathXMin);
  74236. swapVariables <float> (pathXMax, other.pathXMax);
  74237. swapVariables <float> (pathYMin, other.pathYMin);
  74238. swapVariables <float> (pathYMax, other.pathYMax);
  74239. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74240. }
  74241. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74242. {
  74243. useNonZeroWinding = isNonZero;
  74244. }
  74245. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74246. const bool preserveProportions) throw()
  74247. {
  74248. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74249. }
  74250. bool Path::isEmpty() const throw()
  74251. {
  74252. size_t i = 0;
  74253. while (i < numElements)
  74254. {
  74255. const float type = data.elements [i++];
  74256. if (type == moveMarker)
  74257. {
  74258. i += 2;
  74259. }
  74260. else if (type == lineMarker
  74261. || type == quadMarker
  74262. || type == cubicMarker)
  74263. {
  74264. return false;
  74265. }
  74266. }
  74267. return true;
  74268. }
  74269. const Rectangle<float> Path::getBounds() const throw()
  74270. {
  74271. return Rectangle<float> (pathXMin, pathYMin,
  74272. pathXMax - pathXMin,
  74273. pathYMax - pathYMin);
  74274. }
  74275. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74276. {
  74277. return getBounds().transformed (transform);
  74278. }
  74279. void Path::startNewSubPath (const float x, const float y)
  74280. {
  74281. CHECK_COORDS_ARE_VALID (x, y);
  74282. if (numElements == 0)
  74283. {
  74284. pathXMin = pathXMax = x;
  74285. pathYMin = pathYMax = y;
  74286. }
  74287. else
  74288. {
  74289. pathXMin = jmin (pathXMin, x);
  74290. pathXMax = jmax (pathXMax, x);
  74291. pathYMin = jmin (pathYMin, y);
  74292. pathYMax = jmax (pathYMax, y);
  74293. }
  74294. data.ensureAllocatedSize ((int) numElements + 3);
  74295. data.elements [numElements++] = moveMarker;
  74296. data.elements [numElements++] = x;
  74297. data.elements [numElements++] = y;
  74298. }
  74299. void Path::startNewSubPath (const Point<float>& start)
  74300. {
  74301. startNewSubPath (start.getX(), start.getY());
  74302. }
  74303. void Path::lineTo (const float x, const float y)
  74304. {
  74305. CHECK_COORDS_ARE_VALID (x, y);
  74306. if (numElements == 0)
  74307. startNewSubPath (0, 0);
  74308. data.ensureAllocatedSize ((int) numElements + 3);
  74309. data.elements [numElements++] = lineMarker;
  74310. data.elements [numElements++] = x;
  74311. data.elements [numElements++] = y;
  74312. pathXMin = jmin (pathXMin, x);
  74313. pathXMax = jmax (pathXMax, x);
  74314. pathYMin = jmin (pathYMin, y);
  74315. pathYMax = jmax (pathYMax, y);
  74316. }
  74317. void Path::lineTo (const Point<float>& end)
  74318. {
  74319. lineTo (end.getX(), end.getY());
  74320. }
  74321. void Path::quadraticTo (const float x1, const float y1,
  74322. const float x2, const float y2)
  74323. {
  74324. CHECK_COORDS_ARE_VALID (x1, y1);
  74325. CHECK_COORDS_ARE_VALID (x2, y2);
  74326. if (numElements == 0)
  74327. startNewSubPath (0, 0);
  74328. data.ensureAllocatedSize ((int) numElements + 5);
  74329. data.elements [numElements++] = quadMarker;
  74330. data.elements [numElements++] = x1;
  74331. data.elements [numElements++] = y1;
  74332. data.elements [numElements++] = x2;
  74333. data.elements [numElements++] = y2;
  74334. pathXMin = jmin (pathXMin, x1, x2);
  74335. pathXMax = jmax (pathXMax, x1, x2);
  74336. pathYMin = jmin (pathYMin, y1, y2);
  74337. pathYMax = jmax (pathYMax, y1, y2);
  74338. }
  74339. void Path::quadraticTo (const Point<float>& controlPoint,
  74340. const Point<float>& endPoint)
  74341. {
  74342. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74343. endPoint.getX(), endPoint.getY());
  74344. }
  74345. void Path::cubicTo (const float x1, const float y1,
  74346. const float x2, const float y2,
  74347. const float x3, const float y3)
  74348. {
  74349. CHECK_COORDS_ARE_VALID (x1, y1);
  74350. CHECK_COORDS_ARE_VALID (x2, y2);
  74351. CHECK_COORDS_ARE_VALID (x3, y3);
  74352. if (numElements == 0)
  74353. startNewSubPath (0, 0);
  74354. data.ensureAllocatedSize ((int) numElements + 7);
  74355. data.elements [numElements++] = cubicMarker;
  74356. data.elements [numElements++] = x1;
  74357. data.elements [numElements++] = y1;
  74358. data.elements [numElements++] = x2;
  74359. data.elements [numElements++] = y2;
  74360. data.elements [numElements++] = x3;
  74361. data.elements [numElements++] = y3;
  74362. pathXMin = jmin (pathXMin, x1, x2, x3);
  74363. pathXMax = jmax (pathXMax, x1, x2, x3);
  74364. pathYMin = jmin (pathYMin, y1, y2, y3);
  74365. pathYMax = jmax (pathYMax, y1, y2, y3);
  74366. }
  74367. void Path::cubicTo (const Point<float>& controlPoint1,
  74368. const Point<float>& controlPoint2,
  74369. const Point<float>& endPoint)
  74370. {
  74371. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74372. controlPoint2.getX(), controlPoint2.getY(),
  74373. endPoint.getX(), endPoint.getY());
  74374. }
  74375. void Path::closeSubPath()
  74376. {
  74377. if (numElements > 0
  74378. && data.elements [numElements - 1] != closeSubPathMarker)
  74379. {
  74380. data.ensureAllocatedSize ((int) numElements + 1);
  74381. data.elements [numElements++] = closeSubPathMarker;
  74382. }
  74383. }
  74384. const Point<float> Path::getCurrentPosition() const
  74385. {
  74386. size_t i = numElements - 1;
  74387. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74388. {
  74389. while (i >= 0)
  74390. {
  74391. if (data.elements[i] == moveMarker)
  74392. {
  74393. i += 2;
  74394. break;
  74395. }
  74396. --i;
  74397. }
  74398. }
  74399. if (i > 0)
  74400. return Point<float> (data.elements [i - 1], data.elements [i]);
  74401. return Point<float>();
  74402. }
  74403. void Path::addRectangle (const float x, const float y,
  74404. const float w, const float h)
  74405. {
  74406. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74407. if (w < 0)
  74408. swapVariables (x1, x2);
  74409. if (h < 0)
  74410. swapVariables (y1, y2);
  74411. data.ensureAllocatedSize ((int) numElements + 13);
  74412. if (numElements == 0)
  74413. {
  74414. pathXMin = x1;
  74415. pathXMax = x2;
  74416. pathYMin = y1;
  74417. pathYMax = y2;
  74418. }
  74419. else
  74420. {
  74421. pathXMin = jmin (pathXMin, x1);
  74422. pathXMax = jmax (pathXMax, x2);
  74423. pathYMin = jmin (pathYMin, y1);
  74424. pathYMax = jmax (pathYMax, y2);
  74425. }
  74426. data.elements [numElements++] = moveMarker;
  74427. data.elements [numElements++] = x1;
  74428. data.elements [numElements++] = y2;
  74429. data.elements [numElements++] = lineMarker;
  74430. data.elements [numElements++] = x1;
  74431. data.elements [numElements++] = y1;
  74432. data.elements [numElements++] = lineMarker;
  74433. data.elements [numElements++] = x2;
  74434. data.elements [numElements++] = y1;
  74435. data.elements [numElements++] = lineMarker;
  74436. data.elements [numElements++] = x2;
  74437. data.elements [numElements++] = y2;
  74438. data.elements [numElements++] = closeSubPathMarker;
  74439. }
  74440. void Path::addRoundedRectangle (const float x, const float y,
  74441. const float w, const float h,
  74442. float csx,
  74443. float csy)
  74444. {
  74445. csx = jmin (csx, w * 0.5f);
  74446. csy = jmin (csy, h * 0.5f);
  74447. const float cs45x = csx * 0.45f;
  74448. const float cs45y = csy * 0.45f;
  74449. const float x2 = x + w;
  74450. const float y2 = y + h;
  74451. startNewSubPath (x + csx, y);
  74452. lineTo (x2 - csx, y);
  74453. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74454. lineTo (x2, y2 - csy);
  74455. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74456. lineTo (x + csx, y2);
  74457. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74458. lineTo (x, y + csy);
  74459. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74460. closeSubPath();
  74461. }
  74462. void Path::addRoundedRectangle (const float x, const float y,
  74463. const float w, const float h,
  74464. float cs)
  74465. {
  74466. addRoundedRectangle (x, y, w, h, cs, cs);
  74467. }
  74468. void Path::addTriangle (const float x1, const float y1,
  74469. const float x2, const float y2,
  74470. const float x3, const float y3)
  74471. {
  74472. startNewSubPath (x1, y1);
  74473. lineTo (x2, y2);
  74474. lineTo (x3, y3);
  74475. closeSubPath();
  74476. }
  74477. void Path::addQuadrilateral (const float x1, const float y1,
  74478. const float x2, const float y2,
  74479. const float x3, const float y3,
  74480. const float x4, const float y4)
  74481. {
  74482. startNewSubPath (x1, y1);
  74483. lineTo (x2, y2);
  74484. lineTo (x3, y3);
  74485. lineTo (x4, y4);
  74486. closeSubPath();
  74487. }
  74488. void Path::addEllipse (const float x, const float y,
  74489. const float w, const float h)
  74490. {
  74491. const float hw = w * 0.5f;
  74492. const float hw55 = hw * 0.55f;
  74493. const float hh = h * 0.5f;
  74494. const float hh55 = hh * 0.55f;
  74495. const float cx = x + hw;
  74496. const float cy = y + hh;
  74497. startNewSubPath (cx, cy - hh);
  74498. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74499. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74500. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74501. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74502. closeSubPath();
  74503. }
  74504. void Path::addArc (const float x, const float y,
  74505. const float w, const float h,
  74506. const float fromRadians,
  74507. const float toRadians,
  74508. const bool startAsNewSubPath)
  74509. {
  74510. const float radiusX = w / 2.0f;
  74511. const float radiusY = h / 2.0f;
  74512. addCentredArc (x + radiusX,
  74513. y + radiusY,
  74514. radiusX, radiusY,
  74515. 0.0f,
  74516. fromRadians, toRadians,
  74517. startAsNewSubPath);
  74518. }
  74519. void Path::addCentredArc (const float centreX, const float centreY,
  74520. const float radiusX, const float radiusY,
  74521. const float rotationOfEllipse,
  74522. const float fromRadians,
  74523. const float toRadians,
  74524. const bool startAsNewSubPath)
  74525. {
  74526. if (radiusX > 0.0f && radiusY > 0.0f)
  74527. {
  74528. const Point<float> centre (centreX, centreY);
  74529. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74530. float angle = fromRadians;
  74531. if (startAsNewSubPath)
  74532. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74533. if (fromRadians < toRadians)
  74534. {
  74535. if (startAsNewSubPath)
  74536. angle += PathHelpers::ellipseAngularIncrement;
  74537. while (angle < toRadians)
  74538. {
  74539. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74540. angle += PathHelpers::ellipseAngularIncrement;
  74541. }
  74542. }
  74543. else
  74544. {
  74545. if (startAsNewSubPath)
  74546. angle -= PathHelpers::ellipseAngularIncrement;
  74547. while (angle > toRadians)
  74548. {
  74549. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74550. angle -= PathHelpers::ellipseAngularIncrement;
  74551. }
  74552. }
  74553. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74554. }
  74555. }
  74556. void Path::addPieSegment (const float x, const float y,
  74557. const float width, const float height,
  74558. const float fromRadians,
  74559. const float toRadians,
  74560. const float innerCircleProportionalSize)
  74561. {
  74562. float radiusX = width * 0.5f;
  74563. float radiusY = height * 0.5f;
  74564. const Point<float> centre (x + radiusX, y + radiusY);
  74565. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74566. addArc (x, y, width, height, fromRadians, toRadians);
  74567. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74568. {
  74569. closeSubPath();
  74570. if (innerCircleProportionalSize > 0)
  74571. {
  74572. radiusX *= innerCircleProportionalSize;
  74573. radiusY *= innerCircleProportionalSize;
  74574. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74575. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74576. }
  74577. }
  74578. else
  74579. {
  74580. if (innerCircleProportionalSize > 0)
  74581. {
  74582. radiusX *= innerCircleProportionalSize;
  74583. radiusY *= innerCircleProportionalSize;
  74584. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74585. }
  74586. else
  74587. {
  74588. lineTo (centre);
  74589. }
  74590. }
  74591. closeSubPath();
  74592. }
  74593. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74594. {
  74595. const Line<float> reversed (line.reversed());
  74596. lineThickness *= 0.5f;
  74597. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74598. lineTo (line.getPointAlongLine (0, -lineThickness));
  74599. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74600. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74601. closeSubPath();
  74602. }
  74603. void Path::addArrow (const Line<float>& line, float lineThickness,
  74604. float arrowheadWidth, float arrowheadLength)
  74605. {
  74606. const Line<float> reversed (line.reversed());
  74607. lineThickness *= 0.5f;
  74608. arrowheadWidth *= 0.5f;
  74609. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74610. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74611. lineTo (line.getPointAlongLine (0, -lineThickness));
  74612. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74613. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74614. lineTo (line.getEnd());
  74615. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74616. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74617. closeSubPath();
  74618. }
  74619. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74620. const float radius, const float startAngle)
  74621. {
  74622. jassert (numberOfSides > 1); // this would be silly.
  74623. if (numberOfSides > 1)
  74624. {
  74625. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74626. for (int i = 0; i < numberOfSides; ++i)
  74627. {
  74628. const float angle = startAngle + i * angleBetweenPoints;
  74629. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74630. if (i == 0)
  74631. startNewSubPath (p);
  74632. else
  74633. lineTo (p);
  74634. }
  74635. closeSubPath();
  74636. }
  74637. }
  74638. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74639. const float innerRadius, const float outerRadius, const float startAngle)
  74640. {
  74641. jassert (numberOfPoints > 1); // this would be silly.
  74642. if (numberOfPoints > 1)
  74643. {
  74644. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74645. for (int i = 0; i < numberOfPoints; ++i)
  74646. {
  74647. const float angle = startAngle + i * angleBetweenPoints;
  74648. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74649. if (i == 0)
  74650. startNewSubPath (p);
  74651. else
  74652. lineTo (p);
  74653. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74654. }
  74655. closeSubPath();
  74656. }
  74657. }
  74658. void Path::addBubble (float x, float y,
  74659. float w, float h,
  74660. float cs,
  74661. float tipX,
  74662. float tipY,
  74663. int whichSide,
  74664. float arrowPos,
  74665. float arrowWidth)
  74666. {
  74667. if (w > 1.0f && h > 1.0f)
  74668. {
  74669. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74670. const float cs2 = 2.0f * cs;
  74671. startNewSubPath (x + cs, y);
  74672. if (whichSide == 0)
  74673. {
  74674. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74675. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74676. lineTo (arrowX1, y);
  74677. lineTo (tipX, tipY);
  74678. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74679. }
  74680. lineTo (x + w - cs, y);
  74681. if (cs > 0.0f)
  74682. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74683. if (whichSide == 3)
  74684. {
  74685. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74686. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74687. lineTo (x + w, arrowY1);
  74688. lineTo (tipX, tipY);
  74689. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74690. }
  74691. lineTo (x + w, y + h - cs);
  74692. if (cs > 0.0f)
  74693. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74694. if (whichSide == 2)
  74695. {
  74696. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74697. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74698. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74699. lineTo (tipX, tipY);
  74700. lineTo (arrowX1, y + h);
  74701. }
  74702. lineTo (x + cs, y + h);
  74703. if (cs > 0.0f)
  74704. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74705. if (whichSide == 1)
  74706. {
  74707. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74708. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74709. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74710. lineTo (tipX, tipY);
  74711. lineTo (x, arrowY1);
  74712. }
  74713. lineTo (x, y + cs);
  74714. if (cs > 0.0f)
  74715. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74716. closeSubPath();
  74717. }
  74718. }
  74719. void Path::addPath (const Path& other)
  74720. {
  74721. size_t i = 0;
  74722. while (i < other.numElements)
  74723. {
  74724. const float type = other.data.elements [i++];
  74725. if (type == moveMarker)
  74726. {
  74727. startNewSubPath (other.data.elements [i],
  74728. other.data.elements [i + 1]);
  74729. i += 2;
  74730. }
  74731. else if (type == lineMarker)
  74732. {
  74733. lineTo (other.data.elements [i],
  74734. other.data.elements [i + 1]);
  74735. i += 2;
  74736. }
  74737. else if (type == quadMarker)
  74738. {
  74739. quadraticTo (other.data.elements [i],
  74740. other.data.elements [i + 1],
  74741. other.data.elements [i + 2],
  74742. other.data.elements [i + 3]);
  74743. i += 4;
  74744. }
  74745. else if (type == cubicMarker)
  74746. {
  74747. cubicTo (other.data.elements [i],
  74748. other.data.elements [i + 1],
  74749. other.data.elements [i + 2],
  74750. other.data.elements [i + 3],
  74751. other.data.elements [i + 4],
  74752. other.data.elements [i + 5]);
  74753. i += 6;
  74754. }
  74755. else if (type == closeSubPathMarker)
  74756. {
  74757. closeSubPath();
  74758. }
  74759. else
  74760. {
  74761. // something's gone wrong with the element list!
  74762. jassertfalse;
  74763. }
  74764. }
  74765. }
  74766. void Path::addPath (const Path& other,
  74767. const AffineTransform& transformToApply)
  74768. {
  74769. size_t i = 0;
  74770. while (i < other.numElements)
  74771. {
  74772. const float type = other.data.elements [i++];
  74773. if (type == closeSubPathMarker)
  74774. {
  74775. closeSubPath();
  74776. }
  74777. else
  74778. {
  74779. float x = other.data.elements [i++];
  74780. float y = other.data.elements [i++];
  74781. transformToApply.transformPoint (x, y);
  74782. if (type == moveMarker)
  74783. {
  74784. startNewSubPath (x, y);
  74785. }
  74786. else if (type == lineMarker)
  74787. {
  74788. lineTo (x, y);
  74789. }
  74790. else if (type == quadMarker)
  74791. {
  74792. float x2 = other.data.elements [i++];
  74793. float y2 = other.data.elements [i++];
  74794. transformToApply.transformPoint (x2, y2);
  74795. quadraticTo (x, y, x2, y2);
  74796. }
  74797. else if (type == cubicMarker)
  74798. {
  74799. float x2 = other.data.elements [i++];
  74800. float y2 = other.data.elements [i++];
  74801. float x3 = other.data.elements [i++];
  74802. float y3 = other.data.elements [i++];
  74803. transformToApply.transformPoints (x2, y2, x3, y3);
  74804. cubicTo (x, y, x2, y2, x3, y3);
  74805. }
  74806. else
  74807. {
  74808. // something's gone wrong with the element list!
  74809. jassertfalse;
  74810. }
  74811. }
  74812. }
  74813. }
  74814. void Path::applyTransform (const AffineTransform& transform) throw()
  74815. {
  74816. size_t i = 0;
  74817. pathYMin = pathXMin = 0;
  74818. pathYMax = pathXMax = 0;
  74819. bool setMaxMin = false;
  74820. while (i < numElements)
  74821. {
  74822. const float type = data.elements [i++];
  74823. if (type == moveMarker)
  74824. {
  74825. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74826. if (setMaxMin)
  74827. {
  74828. pathXMin = jmin (pathXMin, data.elements [i]);
  74829. pathXMax = jmax (pathXMax, data.elements [i]);
  74830. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74831. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74832. }
  74833. else
  74834. {
  74835. pathXMin = pathXMax = data.elements [i];
  74836. pathYMin = pathYMax = data.elements [i + 1];
  74837. setMaxMin = true;
  74838. }
  74839. i += 2;
  74840. }
  74841. else if (type == lineMarker)
  74842. {
  74843. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74844. pathXMin = jmin (pathXMin, data.elements [i]);
  74845. pathXMax = jmax (pathXMax, data.elements [i]);
  74846. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74847. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74848. i += 2;
  74849. }
  74850. else if (type == quadMarker)
  74851. {
  74852. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74853. data.elements [i + 2], data.elements [i + 3]);
  74854. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74855. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74856. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74857. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74858. i += 4;
  74859. }
  74860. else if (type == cubicMarker)
  74861. {
  74862. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74863. data.elements [i + 2], data.elements [i + 3],
  74864. data.elements [i + 4], data.elements [i + 5]);
  74865. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74866. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74867. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74868. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74869. i += 6;
  74870. }
  74871. }
  74872. }
  74873. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74874. const float w, const float h,
  74875. const bool preserveProportions,
  74876. const Justification& justification) const
  74877. {
  74878. Rectangle<float> bounds (getBounds());
  74879. if (preserveProportions)
  74880. {
  74881. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74882. return AffineTransform::identity;
  74883. float newW, newH;
  74884. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74885. if (srcRatio > h / w)
  74886. {
  74887. newW = h / srcRatio;
  74888. newH = h;
  74889. }
  74890. else
  74891. {
  74892. newW = w;
  74893. newH = w * srcRatio;
  74894. }
  74895. float newXCentre = x;
  74896. float newYCentre = y;
  74897. if (justification.testFlags (Justification::left))
  74898. newXCentre += newW * 0.5f;
  74899. else if (justification.testFlags (Justification::right))
  74900. newXCentre += w - newW * 0.5f;
  74901. else
  74902. newXCentre += w * 0.5f;
  74903. if (justification.testFlags (Justification::top))
  74904. newYCentre += newH * 0.5f;
  74905. else if (justification.testFlags (Justification::bottom))
  74906. newYCentre += h - newH * 0.5f;
  74907. else
  74908. newYCentre += h * 0.5f;
  74909. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74910. bounds.getHeight() * -0.5f - bounds.getY())
  74911. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74912. .translated (newXCentre, newYCentre);
  74913. }
  74914. else
  74915. {
  74916. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74917. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74918. .translated (x, y);
  74919. }
  74920. }
  74921. bool Path::contains (const float x, const float y, const float tolerance) const
  74922. {
  74923. if (x <= pathXMin || x >= pathXMax
  74924. || y <= pathYMin || y >= pathYMax)
  74925. return false;
  74926. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74927. int positiveCrossings = 0;
  74928. int negativeCrossings = 0;
  74929. while (i.next())
  74930. {
  74931. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74932. {
  74933. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74934. if (intersectX <= x)
  74935. {
  74936. if (i.y1 < i.y2)
  74937. ++positiveCrossings;
  74938. else
  74939. ++negativeCrossings;
  74940. }
  74941. }
  74942. }
  74943. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74944. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74945. }
  74946. bool Path::contains (const Point<float>& point, const float tolerance) const
  74947. {
  74948. return contains (point.getX(), point.getY(), tolerance);
  74949. }
  74950. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  74951. {
  74952. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74953. Point<float> intersection;
  74954. while (i.next())
  74955. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74956. return true;
  74957. return false;
  74958. }
  74959. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74960. {
  74961. Line<float> result (line);
  74962. const bool startInside = contains (line.getStart());
  74963. const bool endInside = contains (line.getEnd());
  74964. if (startInside == endInside)
  74965. {
  74966. if (keepSectionOutsidePath == startInside)
  74967. result = Line<float>();
  74968. }
  74969. else
  74970. {
  74971. PathFlatteningIterator i (*this, AffineTransform::identity);
  74972. Point<float> intersection;
  74973. while (i.next())
  74974. {
  74975. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74976. {
  74977. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74978. result.setStart (intersection);
  74979. else
  74980. result.setEnd (intersection);
  74981. }
  74982. }
  74983. }
  74984. return result;
  74985. }
  74986. float Path::getLength (const AffineTransform& transform) const
  74987. {
  74988. float length = 0;
  74989. PathFlatteningIterator i (*this, transform);
  74990. while (i.next())
  74991. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74992. return length;
  74993. }
  74994. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74995. {
  74996. PathFlatteningIterator i (*this, transform);
  74997. while (i.next())
  74998. {
  74999. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75000. const float lineLength = line.getLength();
  75001. if (distanceFromStart <= lineLength)
  75002. return line.getPointAlongLine (distanceFromStart);
  75003. distanceFromStart -= lineLength;
  75004. }
  75005. return Point<float> (i.x2, i.y2);
  75006. }
  75007. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  75008. const AffineTransform& transform) const
  75009. {
  75010. PathFlatteningIterator i (*this, transform);
  75011. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  75012. float length = 0;
  75013. Point<float> pointOnLine;
  75014. while (i.next())
  75015. {
  75016. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75017. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  75018. if (distance < bestDistance)
  75019. {
  75020. bestDistance = distance;
  75021. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  75022. pointOnPath = pointOnLine;
  75023. }
  75024. length += line.getLength();
  75025. }
  75026. return bestPosition;
  75027. }
  75028. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  75029. {
  75030. if (cornerRadius <= 0.01f)
  75031. return *this;
  75032. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  75033. size_t n = 0;
  75034. bool lastWasLine = false, firstWasLine = false;
  75035. Path p;
  75036. while (n < numElements)
  75037. {
  75038. const float type = data.elements [n++];
  75039. if (type == moveMarker)
  75040. {
  75041. indexOfPathStart = p.numElements;
  75042. indexOfPathStartThis = n - 1;
  75043. const float x = data.elements [n++];
  75044. const float y = data.elements [n++];
  75045. p.startNewSubPath (x, y);
  75046. lastWasLine = false;
  75047. firstWasLine = (data.elements [n] == lineMarker);
  75048. }
  75049. else if (type == lineMarker || type == closeSubPathMarker)
  75050. {
  75051. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  75052. if (type == lineMarker)
  75053. {
  75054. endX = data.elements [n++];
  75055. endY = data.elements [n++];
  75056. if (n > 8)
  75057. {
  75058. startX = data.elements [n - 8];
  75059. startY = data.elements [n - 7];
  75060. joinX = data.elements [n - 5];
  75061. joinY = data.elements [n - 4];
  75062. }
  75063. }
  75064. else
  75065. {
  75066. endX = data.elements [indexOfPathStartThis + 1];
  75067. endY = data.elements [indexOfPathStartThis + 2];
  75068. if (n > 6)
  75069. {
  75070. startX = data.elements [n - 6];
  75071. startY = data.elements [n - 5];
  75072. joinX = data.elements [n - 3];
  75073. joinY = data.elements [n - 2];
  75074. }
  75075. }
  75076. if (lastWasLine)
  75077. {
  75078. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75079. if (len1 > 0)
  75080. {
  75081. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75082. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75083. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75084. }
  75085. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75086. if (len2 > 0)
  75087. {
  75088. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75089. p.quadraticTo (joinX, joinY,
  75090. (float) (joinX + (endX - joinX) * propNeeded),
  75091. (float) (joinY + (endY - joinY) * propNeeded));
  75092. }
  75093. p.lineTo (endX, endY);
  75094. }
  75095. else if (type == lineMarker)
  75096. {
  75097. p.lineTo (endX, endY);
  75098. lastWasLine = true;
  75099. }
  75100. if (type == closeSubPathMarker)
  75101. {
  75102. if (firstWasLine)
  75103. {
  75104. startX = data.elements [n - 3];
  75105. startY = data.elements [n - 2];
  75106. joinX = endX;
  75107. joinY = endY;
  75108. endX = data.elements [indexOfPathStartThis + 4];
  75109. endY = data.elements [indexOfPathStartThis + 5];
  75110. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75111. if (len1 > 0)
  75112. {
  75113. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75114. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75115. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75116. }
  75117. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75118. if (len2 > 0)
  75119. {
  75120. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75121. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75122. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75123. p.quadraticTo (joinX, joinY, endX, endY);
  75124. p.data.elements [indexOfPathStart + 1] = endX;
  75125. p.data.elements [indexOfPathStart + 2] = endY;
  75126. }
  75127. }
  75128. p.closeSubPath();
  75129. }
  75130. }
  75131. else if (type == quadMarker)
  75132. {
  75133. lastWasLine = false;
  75134. const float x1 = data.elements [n++];
  75135. const float y1 = data.elements [n++];
  75136. const float x2 = data.elements [n++];
  75137. const float y2 = data.elements [n++];
  75138. p.quadraticTo (x1, y1, x2, y2);
  75139. }
  75140. else if (type == cubicMarker)
  75141. {
  75142. lastWasLine = false;
  75143. const float x1 = data.elements [n++];
  75144. const float y1 = data.elements [n++];
  75145. const float x2 = data.elements [n++];
  75146. const float y2 = data.elements [n++];
  75147. const float x3 = data.elements [n++];
  75148. const float y3 = data.elements [n++];
  75149. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75150. }
  75151. }
  75152. return p;
  75153. }
  75154. void Path::loadPathFromStream (InputStream& source)
  75155. {
  75156. while (! source.isExhausted())
  75157. {
  75158. switch (source.readByte())
  75159. {
  75160. case 'm':
  75161. {
  75162. const float x = source.readFloat();
  75163. const float y = source.readFloat();
  75164. startNewSubPath (x, y);
  75165. break;
  75166. }
  75167. case 'l':
  75168. {
  75169. const float x = source.readFloat();
  75170. const float y = source.readFloat();
  75171. lineTo (x, y);
  75172. break;
  75173. }
  75174. case 'q':
  75175. {
  75176. const float x1 = source.readFloat();
  75177. const float y1 = source.readFloat();
  75178. const float x2 = source.readFloat();
  75179. const float y2 = source.readFloat();
  75180. quadraticTo (x1, y1, x2, y2);
  75181. break;
  75182. }
  75183. case 'b':
  75184. {
  75185. const float x1 = source.readFloat();
  75186. const float y1 = source.readFloat();
  75187. const float x2 = source.readFloat();
  75188. const float y2 = source.readFloat();
  75189. const float x3 = source.readFloat();
  75190. const float y3 = source.readFloat();
  75191. cubicTo (x1, y1, x2, y2, x3, y3);
  75192. break;
  75193. }
  75194. case 'c':
  75195. closeSubPath();
  75196. break;
  75197. case 'n':
  75198. useNonZeroWinding = true;
  75199. break;
  75200. case 'z':
  75201. useNonZeroWinding = false;
  75202. break;
  75203. case 'e':
  75204. return; // end of path marker
  75205. default:
  75206. jassertfalse; // illegal char in the stream
  75207. break;
  75208. }
  75209. }
  75210. }
  75211. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75212. {
  75213. MemoryInputStream in (pathData, numberOfBytes, false);
  75214. loadPathFromStream (in);
  75215. }
  75216. void Path::writePathToStream (OutputStream& dest) const
  75217. {
  75218. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75219. size_t i = 0;
  75220. while (i < numElements)
  75221. {
  75222. const float type = data.elements [i++];
  75223. if (type == moveMarker)
  75224. {
  75225. dest.writeByte ('m');
  75226. dest.writeFloat (data.elements [i++]);
  75227. dest.writeFloat (data.elements [i++]);
  75228. }
  75229. else if (type == lineMarker)
  75230. {
  75231. dest.writeByte ('l');
  75232. dest.writeFloat (data.elements [i++]);
  75233. dest.writeFloat (data.elements [i++]);
  75234. }
  75235. else if (type == quadMarker)
  75236. {
  75237. dest.writeByte ('q');
  75238. dest.writeFloat (data.elements [i++]);
  75239. dest.writeFloat (data.elements [i++]);
  75240. dest.writeFloat (data.elements [i++]);
  75241. dest.writeFloat (data.elements [i++]);
  75242. }
  75243. else if (type == cubicMarker)
  75244. {
  75245. dest.writeByte ('b');
  75246. dest.writeFloat (data.elements [i++]);
  75247. dest.writeFloat (data.elements [i++]);
  75248. dest.writeFloat (data.elements [i++]);
  75249. dest.writeFloat (data.elements [i++]);
  75250. dest.writeFloat (data.elements [i++]);
  75251. dest.writeFloat (data.elements [i++]);
  75252. }
  75253. else if (type == closeSubPathMarker)
  75254. {
  75255. dest.writeByte ('c');
  75256. }
  75257. }
  75258. dest.writeByte ('e'); // marks the end-of-path
  75259. }
  75260. const String Path::toString() const
  75261. {
  75262. MemoryOutputStream s (2048);
  75263. if (! useNonZeroWinding)
  75264. s << 'a';
  75265. size_t i = 0;
  75266. float lastMarker = 0.0f;
  75267. while (i < numElements)
  75268. {
  75269. const float marker = data.elements [i++];
  75270. char markerChar = 0;
  75271. int numCoords = 0;
  75272. if (marker == moveMarker)
  75273. {
  75274. markerChar = 'm';
  75275. numCoords = 2;
  75276. }
  75277. else if (marker == lineMarker)
  75278. {
  75279. markerChar = 'l';
  75280. numCoords = 2;
  75281. }
  75282. else if (marker == quadMarker)
  75283. {
  75284. markerChar = 'q';
  75285. numCoords = 4;
  75286. }
  75287. else if (marker == cubicMarker)
  75288. {
  75289. markerChar = 'c';
  75290. numCoords = 6;
  75291. }
  75292. else
  75293. {
  75294. jassert (marker == closeSubPathMarker);
  75295. markerChar = 'z';
  75296. }
  75297. if (marker != lastMarker)
  75298. {
  75299. if (s.getDataSize() != 0)
  75300. s << ' ';
  75301. s << markerChar;
  75302. lastMarker = marker;
  75303. }
  75304. while (--numCoords >= 0 && i < numElements)
  75305. {
  75306. String coord (data.elements [i++], 3);
  75307. while (coord.endsWithChar ('0') && coord != "0")
  75308. coord = coord.dropLastCharacters (1);
  75309. if (coord.endsWithChar ('.'))
  75310. coord = coord.dropLastCharacters (1);
  75311. if (s.getDataSize() != 0)
  75312. s << ' ';
  75313. s << coord;
  75314. }
  75315. }
  75316. return s.toUTF8();
  75317. }
  75318. void Path::restoreFromString (const String& stringVersion)
  75319. {
  75320. clear();
  75321. setUsingNonZeroWinding (true);
  75322. const juce_wchar* t = stringVersion;
  75323. juce_wchar marker = 'm';
  75324. int numValues = 2;
  75325. float values [6];
  75326. for (;;)
  75327. {
  75328. const String token (PathHelpers::nextToken (t));
  75329. const juce_wchar firstChar = token[0];
  75330. int startNum = 0;
  75331. if (firstChar == 0)
  75332. break;
  75333. if (firstChar == 'm' || firstChar == 'l')
  75334. {
  75335. marker = firstChar;
  75336. numValues = 2;
  75337. }
  75338. else if (firstChar == 'q')
  75339. {
  75340. marker = firstChar;
  75341. numValues = 4;
  75342. }
  75343. else if (firstChar == 'c')
  75344. {
  75345. marker = firstChar;
  75346. numValues = 6;
  75347. }
  75348. else if (firstChar == 'z')
  75349. {
  75350. marker = firstChar;
  75351. numValues = 0;
  75352. }
  75353. else if (firstChar == 'a')
  75354. {
  75355. setUsingNonZeroWinding (false);
  75356. continue;
  75357. }
  75358. else
  75359. {
  75360. ++startNum;
  75361. values [0] = token.getFloatValue();
  75362. }
  75363. for (int i = startNum; i < numValues; ++i)
  75364. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75365. switch (marker)
  75366. {
  75367. case 'm': startNewSubPath (values[0], values[1]); break;
  75368. case 'l': lineTo (values[0], values[1]); break;
  75369. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75370. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75371. case 'z': closeSubPath(); break;
  75372. default: jassertfalse; break; // illegal string format?
  75373. }
  75374. }
  75375. }
  75376. Path::Iterator::Iterator (const Path& path_)
  75377. : path (path_),
  75378. index (0)
  75379. {
  75380. }
  75381. Path::Iterator::~Iterator()
  75382. {
  75383. }
  75384. bool Path::Iterator::next()
  75385. {
  75386. const float* const elements = path.data.elements;
  75387. if (index < path.numElements)
  75388. {
  75389. const float type = elements [index++];
  75390. if (type == moveMarker)
  75391. {
  75392. elementType = startNewSubPath;
  75393. x1 = elements [index++];
  75394. y1 = elements [index++];
  75395. }
  75396. else if (type == lineMarker)
  75397. {
  75398. elementType = lineTo;
  75399. x1 = elements [index++];
  75400. y1 = elements [index++];
  75401. }
  75402. else if (type == quadMarker)
  75403. {
  75404. elementType = quadraticTo;
  75405. x1 = elements [index++];
  75406. y1 = elements [index++];
  75407. x2 = elements [index++];
  75408. y2 = elements [index++];
  75409. }
  75410. else if (type == cubicMarker)
  75411. {
  75412. elementType = cubicTo;
  75413. x1 = elements [index++];
  75414. y1 = elements [index++];
  75415. x2 = elements [index++];
  75416. y2 = elements [index++];
  75417. x3 = elements [index++];
  75418. y3 = elements [index++];
  75419. }
  75420. else if (type == closeSubPathMarker)
  75421. {
  75422. elementType = closePath;
  75423. }
  75424. return true;
  75425. }
  75426. return false;
  75427. }
  75428. END_JUCE_NAMESPACE
  75429. /*** End of inlined file: juce_Path.cpp ***/
  75430. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75431. BEGIN_JUCE_NAMESPACE
  75432. #if JUCE_MSVC && JUCE_DEBUG
  75433. #pragma optimize ("t", on)
  75434. #endif
  75435. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75436. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75437. const AffineTransform& transform_,
  75438. const float tolerance)
  75439. : x2 (0),
  75440. y2 (0),
  75441. closesSubPath (false),
  75442. subPathIndex (-1),
  75443. path (path_),
  75444. transform (transform_),
  75445. points (path_.data.elements),
  75446. toleranceSquared (tolerance * tolerance),
  75447. subPathCloseX (0),
  75448. subPathCloseY (0),
  75449. isIdentityTransform (transform_.isIdentity()),
  75450. stackBase (32),
  75451. index (0),
  75452. stackSize (32)
  75453. {
  75454. stackPos = stackBase;
  75455. }
  75456. PathFlatteningIterator::~PathFlatteningIterator()
  75457. {
  75458. }
  75459. bool PathFlatteningIterator::next()
  75460. {
  75461. x1 = x2;
  75462. y1 = y2;
  75463. float x3 = 0;
  75464. float y3 = 0;
  75465. float x4 = 0;
  75466. float y4 = 0;
  75467. float type;
  75468. for (;;)
  75469. {
  75470. if (stackPos == stackBase)
  75471. {
  75472. if (index >= path.numElements)
  75473. {
  75474. return false;
  75475. }
  75476. else
  75477. {
  75478. type = points [index++];
  75479. if (type != Path::closeSubPathMarker)
  75480. {
  75481. x2 = points [index++];
  75482. y2 = points [index++];
  75483. if (type == Path::quadMarker)
  75484. {
  75485. x3 = points [index++];
  75486. y3 = points [index++];
  75487. if (! isIdentityTransform)
  75488. transform.transformPoints (x2, y2, x3, y3);
  75489. }
  75490. else if (type == Path::cubicMarker)
  75491. {
  75492. x3 = points [index++];
  75493. y3 = points [index++];
  75494. x4 = points [index++];
  75495. y4 = points [index++];
  75496. if (! isIdentityTransform)
  75497. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75498. }
  75499. else
  75500. {
  75501. if (! isIdentityTransform)
  75502. transform.transformPoint (x2, y2);
  75503. }
  75504. }
  75505. }
  75506. }
  75507. else
  75508. {
  75509. type = *--stackPos;
  75510. if (type != Path::closeSubPathMarker)
  75511. {
  75512. x2 = *--stackPos;
  75513. y2 = *--stackPos;
  75514. if (type == Path::quadMarker)
  75515. {
  75516. x3 = *--stackPos;
  75517. y3 = *--stackPos;
  75518. }
  75519. else if (type == Path::cubicMarker)
  75520. {
  75521. x3 = *--stackPos;
  75522. y3 = *--stackPos;
  75523. x4 = *--stackPos;
  75524. y4 = *--stackPos;
  75525. }
  75526. }
  75527. }
  75528. if (type == Path::lineMarker)
  75529. {
  75530. ++subPathIndex;
  75531. closesSubPath = (stackPos == stackBase)
  75532. && (index < path.numElements)
  75533. && (points [index] == Path::closeSubPathMarker)
  75534. && x2 == subPathCloseX
  75535. && y2 == subPathCloseY;
  75536. return true;
  75537. }
  75538. else if (type == Path::quadMarker)
  75539. {
  75540. const size_t offset = (size_t) (stackPos - stackBase);
  75541. if (offset >= stackSize - 10)
  75542. {
  75543. stackSize <<= 1;
  75544. stackBase.realloc (stackSize);
  75545. stackPos = stackBase + offset;
  75546. }
  75547. const float m1x = (x1 + x2) * 0.5f;
  75548. const float m1y = (y1 + y2) * 0.5f;
  75549. const float m2x = (x2 + x3) * 0.5f;
  75550. const float m2y = (y2 + y3) * 0.5f;
  75551. const float m3x = (m1x + m2x) * 0.5f;
  75552. const float m3y = (m1y + m2y) * 0.5f;
  75553. const float errorX = m3x - x2;
  75554. const float errorY = m3y - y2;
  75555. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75556. {
  75557. *stackPos++ = y3;
  75558. *stackPos++ = x3;
  75559. *stackPos++ = m2y;
  75560. *stackPos++ = m2x;
  75561. *stackPos++ = Path::quadMarker;
  75562. *stackPos++ = m3y;
  75563. *stackPos++ = m3x;
  75564. *stackPos++ = m1y;
  75565. *stackPos++ = m1x;
  75566. *stackPos++ = Path::quadMarker;
  75567. }
  75568. else
  75569. {
  75570. *stackPos++ = y3;
  75571. *stackPos++ = x3;
  75572. *stackPos++ = Path::lineMarker;
  75573. *stackPos++ = m3y;
  75574. *stackPos++ = m3x;
  75575. *stackPos++ = Path::lineMarker;
  75576. }
  75577. jassert (stackPos < stackBase + stackSize);
  75578. }
  75579. else if (type == Path::cubicMarker)
  75580. {
  75581. const size_t offset = (size_t) (stackPos - stackBase);
  75582. if (offset >= stackSize - 16)
  75583. {
  75584. stackSize <<= 1;
  75585. stackBase.realloc (stackSize);
  75586. stackPos = stackBase + offset;
  75587. }
  75588. const float m1x = (x1 + x2) * 0.5f;
  75589. const float m1y = (y1 + y2) * 0.5f;
  75590. const float m2x = (x3 + x2) * 0.5f;
  75591. const float m2y = (y3 + y2) * 0.5f;
  75592. const float m3x = (x3 + x4) * 0.5f;
  75593. const float m3y = (y3 + y4) * 0.5f;
  75594. const float m4x = (m1x + m2x) * 0.5f;
  75595. const float m4y = (m1y + m2y) * 0.5f;
  75596. const float m5x = (m3x + m2x) * 0.5f;
  75597. const float m5y = (m3y + m2y) * 0.5f;
  75598. const float error1X = m4x - x2;
  75599. const float error1Y = m4y - y2;
  75600. const float error2X = m5x - x3;
  75601. const float error2Y = m5y - y3;
  75602. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  75603. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  75604. {
  75605. *stackPos++ = y4;
  75606. *stackPos++ = x4;
  75607. *stackPos++ = m3y;
  75608. *stackPos++ = m3x;
  75609. *stackPos++ = m5y;
  75610. *stackPos++ = m5x;
  75611. *stackPos++ = Path::cubicMarker;
  75612. *stackPos++ = (m4y + m5y) * 0.5f;
  75613. *stackPos++ = (m4x + m5x) * 0.5f;
  75614. *stackPos++ = m4y;
  75615. *stackPos++ = m4x;
  75616. *stackPos++ = m1y;
  75617. *stackPos++ = m1x;
  75618. *stackPos++ = Path::cubicMarker;
  75619. }
  75620. else
  75621. {
  75622. *stackPos++ = y4;
  75623. *stackPos++ = x4;
  75624. *stackPos++ = Path::lineMarker;
  75625. *stackPos++ = m5y;
  75626. *stackPos++ = m5x;
  75627. *stackPos++ = Path::lineMarker;
  75628. *stackPos++ = m4y;
  75629. *stackPos++ = m4x;
  75630. *stackPos++ = Path::lineMarker;
  75631. }
  75632. }
  75633. else if (type == Path::closeSubPathMarker)
  75634. {
  75635. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75636. {
  75637. x1 = x2;
  75638. y1 = y2;
  75639. x2 = subPathCloseX;
  75640. y2 = subPathCloseY;
  75641. closesSubPath = true;
  75642. return true;
  75643. }
  75644. }
  75645. else
  75646. {
  75647. jassert (type == Path::moveMarker);
  75648. subPathIndex = -1;
  75649. subPathCloseX = x1 = x2;
  75650. subPathCloseY = y1 = y2;
  75651. }
  75652. }
  75653. }
  75654. #if JUCE_MSVC && JUCE_DEBUG
  75655. #pragma optimize ("", on) // resets optimisations to the project defaults
  75656. #endif
  75657. END_JUCE_NAMESPACE
  75658. /*** End of inlined file: juce_PathIterator.cpp ***/
  75659. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75660. BEGIN_JUCE_NAMESPACE
  75661. PathStrokeType::PathStrokeType (const float strokeThickness,
  75662. const JointStyle jointStyle_,
  75663. const EndCapStyle endStyle_) throw()
  75664. : thickness (strokeThickness),
  75665. jointStyle (jointStyle_),
  75666. endStyle (endStyle_)
  75667. {
  75668. }
  75669. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75670. : thickness (other.thickness),
  75671. jointStyle (other.jointStyle),
  75672. endStyle (other.endStyle)
  75673. {
  75674. }
  75675. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75676. {
  75677. thickness = other.thickness;
  75678. jointStyle = other.jointStyle;
  75679. endStyle = other.endStyle;
  75680. return *this;
  75681. }
  75682. PathStrokeType::~PathStrokeType() throw()
  75683. {
  75684. }
  75685. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75686. {
  75687. return thickness == other.thickness
  75688. && jointStyle == other.jointStyle
  75689. && endStyle == other.endStyle;
  75690. }
  75691. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75692. {
  75693. return ! operator== (other);
  75694. }
  75695. namespace PathStrokeHelpers
  75696. {
  75697. bool lineIntersection (const float x1, const float y1,
  75698. const float x2, const float y2,
  75699. const float x3, const float y3,
  75700. const float x4, const float y4,
  75701. float& intersectionX,
  75702. float& intersectionY,
  75703. float& distanceBeyondLine1EndSquared) throw()
  75704. {
  75705. if (x2 != x3 || y2 != y3)
  75706. {
  75707. const float dx1 = x2 - x1;
  75708. const float dy1 = y2 - y1;
  75709. const float dx2 = x4 - x3;
  75710. const float dy2 = y4 - y3;
  75711. const float divisor = dx1 * dy2 - dx2 * dy1;
  75712. if (divisor == 0)
  75713. {
  75714. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75715. {
  75716. if (dy1 == 0 && dy2 != 0)
  75717. {
  75718. const float along = (y1 - y3) / dy2;
  75719. intersectionX = x3 + along * dx2;
  75720. intersectionY = y1;
  75721. distanceBeyondLine1EndSquared = intersectionX - x2;
  75722. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75723. if ((x2 > x1) == (intersectionX < x2))
  75724. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75725. return along >= 0 && along <= 1.0f;
  75726. }
  75727. else if (dy2 == 0 && dy1 != 0)
  75728. {
  75729. const float along = (y3 - y1) / dy1;
  75730. intersectionX = x1 + along * dx1;
  75731. intersectionY = y3;
  75732. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75733. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75734. if (along < 1.0f)
  75735. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75736. return along >= 0 && along <= 1.0f;
  75737. }
  75738. else if (dx1 == 0 && dx2 != 0)
  75739. {
  75740. const float along = (x1 - x3) / dx2;
  75741. intersectionX = x1;
  75742. intersectionY = y3 + along * dy2;
  75743. distanceBeyondLine1EndSquared = intersectionY - y2;
  75744. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75745. if ((y2 > y1) == (intersectionY < y2))
  75746. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75747. return along >= 0 && along <= 1.0f;
  75748. }
  75749. else if (dx2 == 0 && dx1 != 0)
  75750. {
  75751. const float along = (x3 - x1) / dx1;
  75752. intersectionX = x3;
  75753. intersectionY = y1 + along * dy1;
  75754. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75755. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75756. if (along < 1.0f)
  75757. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75758. return along >= 0 && along <= 1.0f;
  75759. }
  75760. }
  75761. intersectionX = 0.5f * (x2 + x3);
  75762. intersectionY = 0.5f * (y2 + y3);
  75763. distanceBeyondLine1EndSquared = 0.0f;
  75764. return false;
  75765. }
  75766. else
  75767. {
  75768. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75769. intersectionX = x1 + along1 * dx1;
  75770. intersectionY = y1 + along1 * dy1;
  75771. if (along1 >= 0 && along1 <= 1.0f)
  75772. {
  75773. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75774. if (along2 >= 0 && along2 <= divisor)
  75775. {
  75776. distanceBeyondLine1EndSquared = 0.0f;
  75777. return true;
  75778. }
  75779. }
  75780. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75781. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75782. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75783. if (along1 < 1.0f)
  75784. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75785. return false;
  75786. }
  75787. }
  75788. intersectionX = x2;
  75789. intersectionY = y2;
  75790. distanceBeyondLine1EndSquared = 0.0f;
  75791. return true;
  75792. }
  75793. void addEdgeAndJoint (Path& destPath,
  75794. const PathStrokeType::JointStyle style,
  75795. const float maxMiterExtensionSquared, const float width,
  75796. const float x1, const float y1,
  75797. const float x2, const float y2,
  75798. const float x3, const float y3,
  75799. const float x4, const float y4,
  75800. const float midX, const float midY)
  75801. {
  75802. if (style == PathStrokeType::beveled
  75803. || (x3 == x4 && y3 == y4)
  75804. || (x1 == x2 && y1 == y2))
  75805. {
  75806. destPath.lineTo (x2, y2);
  75807. destPath.lineTo (x3, y3);
  75808. }
  75809. else
  75810. {
  75811. float jx, jy, distanceBeyondLine1EndSquared;
  75812. // if they intersect, use this point..
  75813. if (lineIntersection (x1, y1, x2, y2,
  75814. x3, y3, x4, y4,
  75815. jx, jy, distanceBeyondLine1EndSquared))
  75816. {
  75817. destPath.lineTo (jx, jy);
  75818. }
  75819. else
  75820. {
  75821. if (style == PathStrokeType::mitered)
  75822. {
  75823. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75824. && distanceBeyondLine1EndSquared > 0.0f)
  75825. {
  75826. destPath.lineTo (jx, jy);
  75827. }
  75828. else
  75829. {
  75830. // the end sticks out too far, so just use a blunt joint
  75831. destPath.lineTo (x2, y2);
  75832. destPath.lineTo (x3, y3);
  75833. }
  75834. }
  75835. else
  75836. {
  75837. // curved joints
  75838. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75839. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75840. const float angleIncrement = 0.1f;
  75841. destPath.lineTo (x2, y2);
  75842. if (std::abs (angle1 - angle2) > angleIncrement)
  75843. {
  75844. if (angle2 > angle1 + float_Pi
  75845. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75846. {
  75847. if (angle2 > angle1)
  75848. angle2 -= float_Pi * 2.0f;
  75849. jassert (angle1 <= angle2 + float_Pi);
  75850. angle1 -= angleIncrement;
  75851. while (angle1 > angle2)
  75852. {
  75853. destPath.lineTo (midX + width * std::sin (angle1),
  75854. midY + width * std::cos (angle1));
  75855. angle1 -= angleIncrement;
  75856. }
  75857. }
  75858. else
  75859. {
  75860. if (angle1 > angle2)
  75861. angle1 -= float_Pi * 2.0f;
  75862. jassert (angle1 >= angle2 - float_Pi);
  75863. angle1 += angleIncrement;
  75864. while (angle1 < angle2)
  75865. {
  75866. destPath.lineTo (midX + width * std::sin (angle1),
  75867. midY + width * std::cos (angle1));
  75868. angle1 += angleIncrement;
  75869. }
  75870. }
  75871. }
  75872. destPath.lineTo (x3, y3);
  75873. }
  75874. }
  75875. }
  75876. }
  75877. void addLineEnd (Path& destPath,
  75878. const PathStrokeType::EndCapStyle style,
  75879. const float x1, const float y1,
  75880. const float x2, const float y2,
  75881. const float width)
  75882. {
  75883. if (style == PathStrokeType::butt)
  75884. {
  75885. destPath.lineTo (x2, y2);
  75886. }
  75887. else
  75888. {
  75889. float offx1, offy1, offx2, offy2;
  75890. float dx = x2 - x1;
  75891. float dy = y2 - y1;
  75892. const float len = juce_hypot (dx, dy);
  75893. if (len == 0)
  75894. {
  75895. offx1 = offx2 = x1;
  75896. offy1 = offy2 = y1;
  75897. }
  75898. else
  75899. {
  75900. const float offset = width / len;
  75901. dx *= offset;
  75902. dy *= offset;
  75903. offx1 = x1 + dy;
  75904. offy1 = y1 - dx;
  75905. offx2 = x2 + dy;
  75906. offy2 = y2 - dx;
  75907. }
  75908. if (style == PathStrokeType::square)
  75909. {
  75910. // sqaure ends
  75911. destPath.lineTo (offx1, offy1);
  75912. destPath.lineTo (offx2, offy2);
  75913. destPath.lineTo (x2, y2);
  75914. }
  75915. else
  75916. {
  75917. // rounded ends
  75918. const float midx = (offx1 + offx2) * 0.5f;
  75919. const float midy = (offy1 + offy2) * 0.5f;
  75920. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75921. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75922. midx, midy);
  75923. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75924. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75925. x2, y2);
  75926. }
  75927. }
  75928. }
  75929. struct Arrowhead
  75930. {
  75931. float startWidth, startLength;
  75932. float endWidth, endLength;
  75933. };
  75934. void addArrowhead (Path& destPath,
  75935. const float x1, const float y1,
  75936. const float x2, const float y2,
  75937. const float tipX, const float tipY,
  75938. const float width,
  75939. const float arrowheadWidth)
  75940. {
  75941. Line<float> line (x1, y1, x2, y2);
  75942. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75943. destPath.lineTo (tipX, tipY);
  75944. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75945. destPath.lineTo (x2, y2);
  75946. }
  75947. struct LineSection
  75948. {
  75949. float x1, y1, x2, y2; // original line
  75950. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75951. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75952. };
  75953. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75954. {
  75955. while (amountAtEnd > 0 && subPath.size() > 0)
  75956. {
  75957. LineSection& l = subPath.getReference (subPath.size() - 1);
  75958. float dx = l.rx2 - l.rx1;
  75959. float dy = l.ry2 - l.ry1;
  75960. const float len = juce_hypot (dx, dy);
  75961. if (len <= amountAtEnd && subPath.size() > 1)
  75962. {
  75963. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75964. prev.x2 = l.x2;
  75965. prev.y2 = l.y2;
  75966. subPath.removeLast();
  75967. amountAtEnd -= len;
  75968. }
  75969. else
  75970. {
  75971. const float prop = jmin (0.9999f, amountAtEnd / len);
  75972. dx *= prop;
  75973. dy *= prop;
  75974. l.rx1 += dx;
  75975. l.ry1 += dy;
  75976. l.lx2 += dx;
  75977. l.ly2 += dy;
  75978. break;
  75979. }
  75980. }
  75981. while (amountAtStart > 0 && subPath.size() > 0)
  75982. {
  75983. LineSection& l = subPath.getReference (0);
  75984. float dx = l.rx2 - l.rx1;
  75985. float dy = l.ry2 - l.ry1;
  75986. const float len = juce_hypot (dx, dy);
  75987. if (len <= amountAtStart && subPath.size() > 1)
  75988. {
  75989. LineSection& next = subPath.getReference (1);
  75990. next.x1 = l.x1;
  75991. next.y1 = l.y1;
  75992. subPath.remove (0);
  75993. amountAtStart -= len;
  75994. }
  75995. else
  75996. {
  75997. const float prop = jmin (0.9999f, amountAtStart / len);
  75998. dx *= prop;
  75999. dy *= prop;
  76000. l.rx2 -= dx;
  76001. l.ry2 -= dy;
  76002. l.lx1 -= dx;
  76003. l.ly1 -= dy;
  76004. break;
  76005. }
  76006. }
  76007. }
  76008. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  76009. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  76010. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  76011. const Arrowhead* const arrowhead)
  76012. {
  76013. jassert (subPath.size() > 0);
  76014. if (arrowhead != 0)
  76015. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  76016. const LineSection& firstLine = subPath.getReference (0);
  76017. float lastX1 = firstLine.lx1;
  76018. float lastY1 = firstLine.ly1;
  76019. float lastX2 = firstLine.lx2;
  76020. float lastY2 = firstLine.ly2;
  76021. if (isClosed)
  76022. {
  76023. destPath.startNewSubPath (lastX1, lastY1);
  76024. }
  76025. else
  76026. {
  76027. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  76028. if (arrowhead != 0)
  76029. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  76030. width, arrowhead->startWidth);
  76031. else
  76032. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  76033. }
  76034. int i;
  76035. for (i = 1; i < subPath.size(); ++i)
  76036. {
  76037. const LineSection& l = subPath.getReference (i);
  76038. addEdgeAndJoint (destPath, jointStyle,
  76039. maxMiterExtensionSquared, width,
  76040. lastX1, lastY1, lastX2, lastY2,
  76041. l.lx1, l.ly1, l.lx2, l.ly2,
  76042. l.x1, l.y1);
  76043. lastX1 = l.lx1;
  76044. lastY1 = l.ly1;
  76045. lastX2 = l.lx2;
  76046. lastY2 = l.ly2;
  76047. }
  76048. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  76049. if (isClosed)
  76050. {
  76051. const LineSection& l = subPath.getReference (0);
  76052. addEdgeAndJoint (destPath, jointStyle,
  76053. maxMiterExtensionSquared, width,
  76054. lastX1, lastY1, lastX2, lastY2,
  76055. l.lx1, l.ly1, l.lx2, l.ly2,
  76056. l.x1, l.y1);
  76057. destPath.closeSubPath();
  76058. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  76059. }
  76060. else
  76061. {
  76062. destPath.lineTo (lastX2, lastY2);
  76063. if (arrowhead != 0)
  76064. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  76065. width, arrowhead->endWidth);
  76066. else
  76067. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  76068. }
  76069. lastX1 = lastLine.rx1;
  76070. lastY1 = lastLine.ry1;
  76071. lastX2 = lastLine.rx2;
  76072. lastY2 = lastLine.ry2;
  76073. for (i = subPath.size() - 1; --i >= 0;)
  76074. {
  76075. const LineSection& l = subPath.getReference (i);
  76076. addEdgeAndJoint (destPath, jointStyle,
  76077. maxMiterExtensionSquared, width,
  76078. lastX1, lastY1, lastX2, lastY2,
  76079. l.rx1, l.ry1, l.rx2, l.ry2,
  76080. l.x2, l.y2);
  76081. lastX1 = l.rx1;
  76082. lastY1 = l.ry1;
  76083. lastX2 = l.rx2;
  76084. lastY2 = l.ry2;
  76085. }
  76086. if (isClosed)
  76087. {
  76088. addEdgeAndJoint (destPath, jointStyle,
  76089. maxMiterExtensionSquared, width,
  76090. lastX1, lastY1, lastX2, lastY2,
  76091. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76092. lastLine.x2, lastLine.y2);
  76093. }
  76094. else
  76095. {
  76096. // do the last line
  76097. destPath.lineTo (lastX2, lastY2);
  76098. }
  76099. destPath.closeSubPath();
  76100. }
  76101. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76102. const PathStrokeType::EndCapStyle endStyle,
  76103. Path& destPath, const Path& source,
  76104. const AffineTransform& transform,
  76105. const float extraAccuracy, const Arrowhead* const arrowhead)
  76106. {
  76107. jassert (extraAccuracy > 0);
  76108. if (thickness <= 0)
  76109. {
  76110. destPath.clear();
  76111. return;
  76112. }
  76113. const Path* sourcePath = &source;
  76114. Path temp;
  76115. if (sourcePath == &destPath)
  76116. {
  76117. destPath.swapWithPath (temp);
  76118. sourcePath = &temp;
  76119. }
  76120. else
  76121. {
  76122. destPath.clear();
  76123. }
  76124. destPath.setUsingNonZeroWinding (true);
  76125. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76126. const float width = 0.5f * thickness;
  76127. // Iterate the path, creating a list of the
  76128. // left/right-hand lines along either side of it...
  76129. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76130. Array <LineSection> subPath;
  76131. subPath.ensureStorageAllocated (512);
  76132. LineSection l;
  76133. l.x1 = 0;
  76134. l.y1 = 0;
  76135. const float minSegmentLength = 0.0001f;
  76136. while (it.next())
  76137. {
  76138. if (it.subPathIndex == 0)
  76139. {
  76140. if (subPath.size() > 0)
  76141. {
  76142. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76143. subPath.clearQuick();
  76144. }
  76145. l.x1 = it.x1;
  76146. l.y1 = it.y1;
  76147. }
  76148. l.x2 = it.x2;
  76149. l.y2 = it.y2;
  76150. float dx = l.x2 - l.x1;
  76151. float dy = l.y2 - l.y1;
  76152. const float hypotSquared = dx*dx + dy*dy;
  76153. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76154. {
  76155. const float len = std::sqrt (hypotSquared);
  76156. if (len == 0)
  76157. {
  76158. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76159. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76160. }
  76161. else
  76162. {
  76163. const float offset = width / len;
  76164. dx *= offset;
  76165. dy *= offset;
  76166. l.rx2 = l.x1 - dy;
  76167. l.ry2 = l.y1 + dx;
  76168. l.lx1 = l.x1 + dy;
  76169. l.ly1 = l.y1 - dx;
  76170. l.lx2 = l.x2 + dy;
  76171. l.ly2 = l.y2 - dx;
  76172. l.rx1 = l.x2 - dy;
  76173. l.ry1 = l.y2 + dx;
  76174. }
  76175. subPath.add (l);
  76176. if (it.closesSubPath)
  76177. {
  76178. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76179. subPath.clearQuick();
  76180. }
  76181. else
  76182. {
  76183. l.x1 = it.x2;
  76184. l.y1 = it.y2;
  76185. }
  76186. }
  76187. }
  76188. if (subPath.size() > 0)
  76189. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76190. }
  76191. }
  76192. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76193. const AffineTransform& transform, const float extraAccuracy) const
  76194. {
  76195. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76196. transform, extraAccuracy, 0);
  76197. }
  76198. void PathStrokeType::createDashedStroke (Path& destPath,
  76199. const Path& sourcePath,
  76200. const float* dashLengths,
  76201. int numDashLengths,
  76202. const AffineTransform& transform,
  76203. const float extraAccuracy) const
  76204. {
  76205. jassert (extraAccuracy > 0);
  76206. if (thickness <= 0)
  76207. return;
  76208. // this should really be an even number..
  76209. jassert ((numDashLengths & 1) == 0);
  76210. Path newDestPath;
  76211. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76212. bool first = true;
  76213. int dashNum = 0;
  76214. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76215. float dx = 0.0f, dy = 0.0f;
  76216. for (;;)
  76217. {
  76218. const bool isSolid = ((dashNum & 1) == 0);
  76219. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76220. jassert (dashLen > 0); // must be a positive increment!
  76221. if (dashLen <= 0)
  76222. break;
  76223. pos += dashLen;
  76224. while (pos > lineEndPos)
  76225. {
  76226. if (! it.next())
  76227. {
  76228. if (isSolid && ! first)
  76229. newDestPath.lineTo (it.x2, it.y2);
  76230. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76231. return;
  76232. }
  76233. if (isSolid && ! first)
  76234. newDestPath.lineTo (it.x1, it.y1);
  76235. else
  76236. newDestPath.startNewSubPath (it.x1, it.y1);
  76237. dx = it.x2 - it.x1;
  76238. dy = it.y2 - it.y1;
  76239. lineLen = juce_hypot (dx, dy);
  76240. lineEndPos += lineLen;
  76241. first = it.closesSubPath;
  76242. }
  76243. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76244. if (isSolid)
  76245. newDestPath.lineTo (it.x1 + dx * alpha,
  76246. it.y1 + dy * alpha);
  76247. else
  76248. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76249. it.y1 + dy * alpha);
  76250. }
  76251. }
  76252. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76253. const Path& sourcePath,
  76254. const float arrowheadStartWidth, const float arrowheadStartLength,
  76255. const float arrowheadEndWidth, const float arrowheadEndLength,
  76256. const AffineTransform& transform,
  76257. const float extraAccuracy) const
  76258. {
  76259. PathStrokeHelpers::Arrowhead head;
  76260. head.startWidth = arrowheadStartWidth;
  76261. head.startLength = arrowheadStartLength;
  76262. head.endWidth = arrowheadEndWidth;
  76263. head.endLength = arrowheadEndLength;
  76264. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76265. destPath, sourcePath, transform, extraAccuracy, &head);
  76266. }
  76267. END_JUCE_NAMESPACE
  76268. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76269. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76270. BEGIN_JUCE_NAMESPACE
  76271. RectangleList::RectangleList() throw()
  76272. {
  76273. }
  76274. RectangleList::RectangleList (const Rectangle<int>& rect)
  76275. {
  76276. if (! rect.isEmpty())
  76277. rects.add (rect);
  76278. }
  76279. RectangleList::RectangleList (const RectangleList& other)
  76280. : rects (other.rects)
  76281. {
  76282. }
  76283. RectangleList& RectangleList::operator= (const RectangleList& other)
  76284. {
  76285. rects = other.rects;
  76286. return *this;
  76287. }
  76288. RectangleList::~RectangleList()
  76289. {
  76290. }
  76291. void RectangleList::clear()
  76292. {
  76293. rects.clearQuick();
  76294. }
  76295. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76296. {
  76297. if (isPositiveAndBelow (index, rects.size()))
  76298. return rects.getReference (index);
  76299. return Rectangle<int>();
  76300. }
  76301. bool RectangleList::isEmpty() const throw()
  76302. {
  76303. return rects.size() == 0;
  76304. }
  76305. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76306. : current (0),
  76307. owner (list),
  76308. index (list.rects.size())
  76309. {
  76310. }
  76311. RectangleList::Iterator::~Iterator()
  76312. {
  76313. }
  76314. bool RectangleList::Iterator::next() throw()
  76315. {
  76316. if (--index >= 0)
  76317. {
  76318. current = & (owner.rects.getReference (index));
  76319. return true;
  76320. }
  76321. return false;
  76322. }
  76323. void RectangleList::add (const Rectangle<int>& rect)
  76324. {
  76325. if (! rect.isEmpty())
  76326. {
  76327. if (rects.size() == 0)
  76328. {
  76329. rects.add (rect);
  76330. }
  76331. else
  76332. {
  76333. bool anyOverlaps = false;
  76334. int i;
  76335. for (i = rects.size(); --i >= 0;)
  76336. {
  76337. Rectangle<int>& ourRect = rects.getReference (i);
  76338. if (rect.intersects (ourRect))
  76339. {
  76340. if (rect.contains (ourRect))
  76341. rects.remove (i);
  76342. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76343. anyOverlaps = true;
  76344. }
  76345. }
  76346. if (anyOverlaps && rects.size() > 0)
  76347. {
  76348. RectangleList r (rect);
  76349. for (i = rects.size(); --i >= 0;)
  76350. {
  76351. const Rectangle<int>& ourRect = rects.getReference (i);
  76352. if (rect.intersects (ourRect))
  76353. {
  76354. r.subtract (ourRect);
  76355. if (r.rects.size() == 0)
  76356. return;
  76357. }
  76358. }
  76359. for (i = r.getNumRectangles(); --i >= 0;)
  76360. rects.add (r.rects.getReference (i));
  76361. }
  76362. else
  76363. {
  76364. rects.add (rect);
  76365. }
  76366. }
  76367. }
  76368. }
  76369. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76370. {
  76371. if (! rect.isEmpty())
  76372. rects.add (rect);
  76373. }
  76374. void RectangleList::add (const int x, const int y, const int w, const int h)
  76375. {
  76376. if (rects.size() == 0)
  76377. {
  76378. if (w > 0 && h > 0)
  76379. rects.add (Rectangle<int> (x, y, w, h));
  76380. }
  76381. else
  76382. {
  76383. add (Rectangle<int> (x, y, w, h));
  76384. }
  76385. }
  76386. void RectangleList::add (const RectangleList& other)
  76387. {
  76388. for (int i = 0; i < other.rects.size(); ++i)
  76389. add (other.rects.getReference (i));
  76390. }
  76391. void RectangleList::subtract (const Rectangle<int>& rect)
  76392. {
  76393. const int originalNumRects = rects.size();
  76394. if (originalNumRects > 0)
  76395. {
  76396. const int x1 = rect.x;
  76397. const int y1 = rect.y;
  76398. const int x2 = x1 + rect.w;
  76399. const int y2 = y1 + rect.h;
  76400. for (int i = getNumRectangles(); --i >= 0;)
  76401. {
  76402. Rectangle<int>& r = rects.getReference (i);
  76403. const int rx1 = r.x;
  76404. const int ry1 = r.y;
  76405. const int rx2 = rx1 + r.w;
  76406. const int ry2 = ry1 + r.h;
  76407. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76408. {
  76409. if (x1 > rx1 && x1 < rx2)
  76410. {
  76411. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76412. {
  76413. r.w = x1 - rx1;
  76414. }
  76415. else
  76416. {
  76417. r.x = x1;
  76418. r.w = rx2 - x1;
  76419. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76420. i += 2;
  76421. }
  76422. }
  76423. else if (x2 > rx1 && x2 < rx2)
  76424. {
  76425. r.x = x2;
  76426. r.w = rx2 - x2;
  76427. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76428. {
  76429. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76430. i += 2;
  76431. }
  76432. }
  76433. else if (y1 > ry1 && y1 < ry2)
  76434. {
  76435. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76436. {
  76437. r.h = y1 - ry1;
  76438. }
  76439. else
  76440. {
  76441. r.y = y1;
  76442. r.h = ry2 - y1;
  76443. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76444. i += 2;
  76445. }
  76446. }
  76447. else if (y2 > ry1 && y2 < ry2)
  76448. {
  76449. r.y = y2;
  76450. r.h = ry2 - y2;
  76451. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76452. {
  76453. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76454. i += 2;
  76455. }
  76456. }
  76457. else
  76458. {
  76459. rects.remove (i);
  76460. }
  76461. }
  76462. }
  76463. }
  76464. }
  76465. bool RectangleList::subtract (const RectangleList& otherList)
  76466. {
  76467. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76468. subtract (otherList.rects.getReference (i));
  76469. return rects.size() > 0;
  76470. }
  76471. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76472. {
  76473. bool notEmpty = false;
  76474. if (rect.isEmpty())
  76475. {
  76476. clear();
  76477. }
  76478. else
  76479. {
  76480. for (int i = rects.size(); --i >= 0;)
  76481. {
  76482. Rectangle<int>& r = rects.getReference (i);
  76483. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76484. rects.remove (i);
  76485. else
  76486. notEmpty = true;
  76487. }
  76488. }
  76489. return notEmpty;
  76490. }
  76491. bool RectangleList::clipTo (const RectangleList& other)
  76492. {
  76493. if (rects.size() == 0)
  76494. return false;
  76495. RectangleList result;
  76496. for (int j = 0; j < rects.size(); ++j)
  76497. {
  76498. const Rectangle<int>& rect = rects.getReference (j);
  76499. for (int i = other.rects.size(); --i >= 0;)
  76500. {
  76501. Rectangle<int> r (other.rects.getReference (i));
  76502. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76503. result.rects.add (r);
  76504. }
  76505. }
  76506. swapWith (result);
  76507. return ! isEmpty();
  76508. }
  76509. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76510. {
  76511. destRegion.clear();
  76512. if (! rect.isEmpty())
  76513. {
  76514. for (int i = rects.size(); --i >= 0;)
  76515. {
  76516. Rectangle<int> r (rects.getReference (i));
  76517. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76518. destRegion.rects.add (r);
  76519. }
  76520. }
  76521. return destRegion.rects.size() > 0;
  76522. }
  76523. void RectangleList::swapWith (RectangleList& otherList) throw()
  76524. {
  76525. rects.swapWithArray (otherList.rects);
  76526. }
  76527. void RectangleList::consolidate()
  76528. {
  76529. int i;
  76530. for (i = 0; i < getNumRectangles() - 1; ++i)
  76531. {
  76532. Rectangle<int>& r = rects.getReference (i);
  76533. const int rx1 = r.x;
  76534. const int ry1 = r.y;
  76535. const int rx2 = rx1 + r.w;
  76536. const int ry2 = ry1 + r.h;
  76537. for (int j = rects.size(); --j > i;)
  76538. {
  76539. Rectangle<int>& r2 = rects.getReference (j);
  76540. const int jrx1 = r2.x;
  76541. const int jry1 = r2.y;
  76542. const int jrx2 = jrx1 + r2.w;
  76543. const int jry2 = jry1 + r2.h;
  76544. // if the vertical edges of any blocks are touching and their horizontals don't
  76545. // line up, split them horizontally..
  76546. if (jrx1 == rx2 || jrx2 == rx1)
  76547. {
  76548. if (jry1 > ry1 && jry1 < ry2)
  76549. {
  76550. r.h = jry1 - ry1;
  76551. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76552. i = -1;
  76553. break;
  76554. }
  76555. if (jry2 > ry1 && jry2 < ry2)
  76556. {
  76557. r.h = jry2 - ry1;
  76558. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76559. i = -1;
  76560. break;
  76561. }
  76562. else if (ry1 > jry1 && ry1 < jry2)
  76563. {
  76564. r2.h = ry1 - jry1;
  76565. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76566. i = -1;
  76567. break;
  76568. }
  76569. else if (ry2 > jry1 && ry2 < jry2)
  76570. {
  76571. r2.h = ry2 - jry1;
  76572. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76573. i = -1;
  76574. break;
  76575. }
  76576. }
  76577. }
  76578. }
  76579. for (i = 0; i < rects.size() - 1; ++i)
  76580. {
  76581. Rectangle<int>& r = rects.getReference (i);
  76582. for (int j = rects.size(); --j > i;)
  76583. {
  76584. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76585. {
  76586. rects.remove (j);
  76587. i = -1;
  76588. break;
  76589. }
  76590. }
  76591. }
  76592. }
  76593. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76594. {
  76595. for (int i = getNumRectangles(); --i >= 0;)
  76596. if (rects.getReference (i).contains (x, y))
  76597. return true;
  76598. return false;
  76599. }
  76600. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76601. {
  76602. if (rects.size() > 1)
  76603. {
  76604. RectangleList r (rectangleToCheck);
  76605. for (int i = rects.size(); --i >= 0;)
  76606. {
  76607. r.subtract (rects.getReference (i));
  76608. if (r.rects.size() == 0)
  76609. return true;
  76610. }
  76611. }
  76612. else if (rects.size() > 0)
  76613. {
  76614. return rects.getReference (0).contains (rectangleToCheck);
  76615. }
  76616. return false;
  76617. }
  76618. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76619. {
  76620. for (int i = rects.size(); --i >= 0;)
  76621. if (rects.getReference (i).intersects (rectangleToCheck))
  76622. return true;
  76623. return false;
  76624. }
  76625. bool RectangleList::intersects (const RectangleList& other) const throw()
  76626. {
  76627. for (int i = rects.size(); --i >= 0;)
  76628. if (other.intersectsRectangle (rects.getReference (i)))
  76629. return true;
  76630. return false;
  76631. }
  76632. const Rectangle<int> RectangleList::getBounds() const throw()
  76633. {
  76634. if (rects.size() <= 1)
  76635. {
  76636. if (rects.size() == 0)
  76637. return Rectangle<int>();
  76638. else
  76639. return rects.getReference (0);
  76640. }
  76641. else
  76642. {
  76643. const Rectangle<int>& r = rects.getReference (0);
  76644. int minX = r.x;
  76645. int minY = r.y;
  76646. int maxX = minX + r.w;
  76647. int maxY = minY + r.h;
  76648. for (int i = rects.size(); --i > 0;)
  76649. {
  76650. const Rectangle<int>& r2 = rects.getReference (i);
  76651. minX = jmin (minX, r2.x);
  76652. minY = jmin (minY, r2.y);
  76653. maxX = jmax (maxX, r2.getRight());
  76654. maxY = jmax (maxY, r2.getBottom());
  76655. }
  76656. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76657. }
  76658. }
  76659. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76660. {
  76661. for (int i = rects.size(); --i >= 0;)
  76662. {
  76663. Rectangle<int>& r = rects.getReference (i);
  76664. r.x += dx;
  76665. r.y += dy;
  76666. }
  76667. }
  76668. const Path RectangleList::toPath() const
  76669. {
  76670. Path p;
  76671. for (int i = rects.size(); --i >= 0;)
  76672. {
  76673. const Rectangle<int>& r = rects.getReference (i);
  76674. p.addRectangle ((float) r.x,
  76675. (float) r.y,
  76676. (float) r.w,
  76677. (float) r.h);
  76678. }
  76679. return p;
  76680. }
  76681. END_JUCE_NAMESPACE
  76682. /*** End of inlined file: juce_RectangleList.cpp ***/
  76683. /*** Start of inlined file: juce_Image.cpp ***/
  76684. BEGIN_JUCE_NAMESPACE
  76685. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76686. : format (format_), width (width_), height (height_)
  76687. {
  76688. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76689. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76690. }
  76691. Image::SharedImage::~SharedImage()
  76692. {
  76693. }
  76694. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76695. {
  76696. return imageData + lineStride * y + pixelStride * x;
  76697. }
  76698. class SoftwareSharedImage : public Image::SharedImage
  76699. {
  76700. public:
  76701. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76702. : Image::SharedImage (format_, width_, height_)
  76703. {
  76704. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76705. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76706. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76707. imageData = imageDataAllocated;
  76708. }
  76709. Image::ImageType getType() const
  76710. {
  76711. return Image::SoftwareImage;
  76712. }
  76713. LowLevelGraphicsContext* createLowLevelContext()
  76714. {
  76715. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76716. }
  76717. Image::SharedImage* clone()
  76718. {
  76719. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76720. memcpy (s->imageData, imageData, lineStride * height);
  76721. return s;
  76722. }
  76723. private:
  76724. HeapBlock<uint8> imageDataAllocated;
  76725. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  76726. };
  76727. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76728. {
  76729. return new SoftwareSharedImage (format, width, height, clearImage);
  76730. }
  76731. class SubsectionSharedImage : public Image::SharedImage
  76732. {
  76733. public:
  76734. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76735. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76736. image (image_), area (area_)
  76737. {
  76738. pixelStride = image_->getPixelStride();
  76739. lineStride = image_->getLineStride();
  76740. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76741. }
  76742. Image::ImageType getType() const
  76743. {
  76744. return Image::SoftwareImage;
  76745. }
  76746. LowLevelGraphicsContext* createLowLevelContext()
  76747. {
  76748. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76749. g->clipToRectangle (area);
  76750. g->setOrigin (area.getX(), area.getY());
  76751. return g;
  76752. }
  76753. Image::SharedImage* clone()
  76754. {
  76755. return new SubsectionSharedImage (image->clone(), area);
  76756. }
  76757. private:
  76758. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76759. const Rectangle<int> area;
  76760. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  76761. };
  76762. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76763. {
  76764. if (area.contains (getBounds()))
  76765. return *this;
  76766. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76767. if (validArea.isEmpty())
  76768. return Image::null;
  76769. return Image (new SubsectionSharedImage (image, validArea));
  76770. }
  76771. Image::Image()
  76772. {
  76773. }
  76774. Image::Image (SharedImage* const instance)
  76775. : image (instance)
  76776. {
  76777. }
  76778. Image::Image (const PixelFormat format,
  76779. const int width, const int height,
  76780. const bool clearImage, const ImageType type)
  76781. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76782. : new SoftwareSharedImage (format, width, height, clearImage))
  76783. {
  76784. }
  76785. Image::Image (const Image& other)
  76786. : image (other.image)
  76787. {
  76788. }
  76789. Image& Image::operator= (const Image& other)
  76790. {
  76791. image = other.image;
  76792. return *this;
  76793. }
  76794. Image::~Image()
  76795. {
  76796. }
  76797. const Image Image::null;
  76798. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76799. {
  76800. return image == 0 ? 0 : image->createLowLevelContext();
  76801. }
  76802. void Image::duplicateIfShared()
  76803. {
  76804. if (image != 0 && image->getReferenceCount() > 1)
  76805. image = image->clone();
  76806. }
  76807. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76808. {
  76809. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76810. return *this;
  76811. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76812. Graphics g (newImage);
  76813. g.setImageResamplingQuality (quality);
  76814. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76815. return newImage;
  76816. }
  76817. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76818. {
  76819. if (image == 0 || newFormat == image->format)
  76820. return *this;
  76821. const int w = image->width, h = image->height;
  76822. Image newImage (newFormat, w, h, false, image->getType());
  76823. if (newFormat == SingleChannel)
  76824. {
  76825. if (! hasAlphaChannel())
  76826. {
  76827. newImage.clear (getBounds(), Colours::black);
  76828. }
  76829. else
  76830. {
  76831. const BitmapData destData (newImage, 0, 0, w, h, true);
  76832. const BitmapData srcData (*this, 0, 0, w, h);
  76833. for (int y = 0; y < h; ++y)
  76834. {
  76835. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76836. uint8* dst = destData.getLinePointer (y);
  76837. for (int x = w; --x >= 0;)
  76838. {
  76839. *dst++ = src->getAlpha();
  76840. ++src;
  76841. }
  76842. }
  76843. }
  76844. }
  76845. else
  76846. {
  76847. if (hasAlphaChannel())
  76848. newImage.clear (getBounds());
  76849. Graphics g (newImage);
  76850. g.drawImageAt (*this, 0, 0);
  76851. }
  76852. return newImage;
  76853. }
  76854. NamedValueSet* Image::getProperties() const
  76855. {
  76856. return image == 0 ? 0 : &(image->userData);
  76857. }
  76858. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76859. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76860. pixelFormat (image.getFormat()),
  76861. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76862. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76863. width (w),
  76864. height (h)
  76865. {
  76866. jassert (data != 0);
  76867. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76868. }
  76869. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76870. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76871. pixelFormat (image.getFormat()),
  76872. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76873. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76874. width (w),
  76875. height (h)
  76876. {
  76877. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76878. }
  76879. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76880. : data (image.image == 0 ? 0 : image.image->imageData),
  76881. pixelFormat (image.getFormat()),
  76882. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76883. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76884. width (image.getWidth()),
  76885. height (image.getHeight())
  76886. {
  76887. }
  76888. Image::BitmapData::~BitmapData()
  76889. {
  76890. }
  76891. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76892. {
  76893. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  76894. const uint8* const pixel = getPixelPointer (x, y);
  76895. switch (pixelFormat)
  76896. {
  76897. case Image::ARGB:
  76898. {
  76899. PixelARGB p (*(const PixelARGB*) pixel);
  76900. p.unpremultiply();
  76901. return Colour (p.getARGB());
  76902. }
  76903. case Image::RGB:
  76904. return Colour (((const PixelRGB*) pixel)->getARGB());
  76905. case Image::SingleChannel:
  76906. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76907. default:
  76908. jassertfalse;
  76909. break;
  76910. }
  76911. return Colour();
  76912. }
  76913. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76914. {
  76915. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  76916. uint8* const pixel = getPixelPointer (x, y);
  76917. const PixelARGB col (colour.getPixelARGB());
  76918. switch (pixelFormat)
  76919. {
  76920. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76921. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76922. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76923. default: jassertfalse; break;
  76924. }
  76925. }
  76926. void Image::setPixelData (int x, int y, int w, int h,
  76927. const uint8* const sourcePixelData, const int sourceLineStride)
  76928. {
  76929. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76930. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76931. {
  76932. const BitmapData dest (*this, x, y, w, h, true);
  76933. for (int i = 0; i < h; ++i)
  76934. {
  76935. memcpy (dest.getLinePointer(i),
  76936. sourcePixelData + sourceLineStride * i,
  76937. w * dest.pixelStride);
  76938. }
  76939. }
  76940. }
  76941. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76942. {
  76943. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76944. if (! clipped.isEmpty())
  76945. {
  76946. const PixelARGB col (colourToClearTo.getPixelARGB());
  76947. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76948. uint8* dest = destData.data;
  76949. int dh = clipped.getHeight();
  76950. while (--dh >= 0)
  76951. {
  76952. uint8* line = dest;
  76953. dest += destData.lineStride;
  76954. if (isARGB())
  76955. {
  76956. for (int x = clipped.getWidth(); --x >= 0;)
  76957. {
  76958. ((PixelARGB*) line)->set (col);
  76959. line += destData.pixelStride;
  76960. }
  76961. }
  76962. else if (isRGB())
  76963. {
  76964. for (int x = clipped.getWidth(); --x >= 0;)
  76965. {
  76966. ((PixelRGB*) line)->set (col);
  76967. line += destData.pixelStride;
  76968. }
  76969. }
  76970. else
  76971. {
  76972. for (int x = clipped.getWidth(); --x >= 0;)
  76973. {
  76974. *line = col.getAlpha();
  76975. line += destData.pixelStride;
  76976. }
  76977. }
  76978. }
  76979. }
  76980. }
  76981. const Colour Image::getPixelAt (const int x, const int y) const
  76982. {
  76983. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  76984. {
  76985. const BitmapData srcData (*this, x, y, 1, 1);
  76986. return srcData.getPixelColour (0, 0);
  76987. }
  76988. return Colour();
  76989. }
  76990. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76991. {
  76992. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  76993. {
  76994. const BitmapData destData (*this, x, y, 1, 1, true);
  76995. destData.setPixelColour (0, 0, colour);
  76996. }
  76997. }
  76998. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76999. {
  77000. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  77001. && hasAlphaChannel())
  77002. {
  77003. const BitmapData destData (*this, x, y, 1, 1, true);
  77004. if (isARGB())
  77005. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77006. else
  77007. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77008. }
  77009. }
  77010. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77011. {
  77012. if (hasAlphaChannel())
  77013. {
  77014. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77015. if (isARGB())
  77016. {
  77017. for (int y = 0; y < destData.height; ++y)
  77018. {
  77019. uint8* p = destData.getLinePointer (y);
  77020. for (int x = 0; x < destData.width; ++x)
  77021. {
  77022. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77023. p += destData.pixelStride;
  77024. }
  77025. }
  77026. }
  77027. else
  77028. {
  77029. for (int y = 0; y < destData.height; ++y)
  77030. {
  77031. uint8* p = destData.getLinePointer (y);
  77032. for (int x = 0; x < destData.width; ++x)
  77033. {
  77034. *p = (uint8) (*p * amountToMultiplyBy);
  77035. p += destData.pixelStride;
  77036. }
  77037. }
  77038. }
  77039. }
  77040. else
  77041. {
  77042. jassertfalse; // can't do this without an alpha-channel!
  77043. }
  77044. }
  77045. void Image::desaturate()
  77046. {
  77047. if (isARGB() || isRGB())
  77048. {
  77049. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77050. if (isARGB())
  77051. {
  77052. for (int y = 0; y < destData.height; ++y)
  77053. {
  77054. uint8* p = destData.getLinePointer (y);
  77055. for (int x = 0; x < destData.width; ++x)
  77056. {
  77057. ((PixelARGB*) p)->desaturate();
  77058. p += destData.pixelStride;
  77059. }
  77060. }
  77061. }
  77062. else
  77063. {
  77064. for (int y = 0; y < destData.height; ++y)
  77065. {
  77066. uint8* p = destData.getLinePointer (y);
  77067. for (int x = 0; x < destData.width; ++x)
  77068. {
  77069. ((PixelRGB*) p)->desaturate();
  77070. p += destData.pixelStride;
  77071. }
  77072. }
  77073. }
  77074. }
  77075. }
  77076. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77077. {
  77078. if (hasAlphaChannel())
  77079. {
  77080. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77081. SparseSet<int> pixelsOnRow;
  77082. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77083. for (int y = 0; y < srcData.height; ++y)
  77084. {
  77085. pixelsOnRow.clear();
  77086. const uint8* lineData = srcData.getLinePointer (y);
  77087. if (isARGB())
  77088. {
  77089. for (int x = 0; x < srcData.width; ++x)
  77090. {
  77091. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77092. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77093. lineData += srcData.pixelStride;
  77094. }
  77095. }
  77096. else
  77097. {
  77098. for (int x = 0; x < srcData.width; ++x)
  77099. {
  77100. if (*lineData >= threshold)
  77101. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77102. lineData += srcData.pixelStride;
  77103. }
  77104. }
  77105. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77106. {
  77107. const Range<int> range (pixelsOnRow.getRange (i));
  77108. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77109. }
  77110. result.consolidate();
  77111. }
  77112. }
  77113. else
  77114. {
  77115. result.add (0, 0, getWidth(), getHeight());
  77116. }
  77117. }
  77118. void Image::moveImageSection (int dx, int dy,
  77119. int sx, int sy,
  77120. int w, int h)
  77121. {
  77122. if (dx < 0)
  77123. {
  77124. w += dx;
  77125. sx -= dx;
  77126. dx = 0;
  77127. }
  77128. if (dy < 0)
  77129. {
  77130. h += dy;
  77131. sy -= dy;
  77132. dy = 0;
  77133. }
  77134. if (sx < 0)
  77135. {
  77136. w += sx;
  77137. dx -= sx;
  77138. sx = 0;
  77139. }
  77140. if (sy < 0)
  77141. {
  77142. h += sy;
  77143. dy -= sy;
  77144. sy = 0;
  77145. }
  77146. const int minX = jmin (dx, sx);
  77147. const int minY = jmin (dy, sy);
  77148. w = jmin (w, getWidth() - jmax (sx, dx));
  77149. h = jmin (h, getHeight() - jmax (sy, dy));
  77150. if (w > 0 && h > 0)
  77151. {
  77152. const int maxX = jmax (dx, sx) + w;
  77153. const int maxY = jmax (dy, sy) + h;
  77154. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77155. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77156. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77157. const int lineSize = destData.pixelStride * w;
  77158. if (dy > sy)
  77159. {
  77160. while (--h >= 0)
  77161. {
  77162. const int offset = h * destData.lineStride;
  77163. memmove (dst + offset, src + offset, lineSize);
  77164. }
  77165. }
  77166. else if (dst != src)
  77167. {
  77168. while (--h >= 0)
  77169. {
  77170. memmove (dst, src, lineSize);
  77171. dst += destData.lineStride;
  77172. src += destData.lineStride;
  77173. }
  77174. }
  77175. }
  77176. }
  77177. END_JUCE_NAMESPACE
  77178. /*** End of inlined file: juce_Image.cpp ***/
  77179. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77180. BEGIN_JUCE_NAMESPACE
  77181. class ImageCache::Pimpl : public Timer,
  77182. public DeletedAtShutdown
  77183. {
  77184. public:
  77185. Pimpl()
  77186. : cacheTimeout (5000)
  77187. {
  77188. }
  77189. ~Pimpl()
  77190. {
  77191. clearSingletonInstance();
  77192. }
  77193. const Image getFromHashCode (const int64 hashCode)
  77194. {
  77195. const ScopedLock sl (lock);
  77196. for (int i = images.size(); --i >= 0;)
  77197. {
  77198. Item* const item = images.getUnchecked(i);
  77199. if (item->hashCode == hashCode)
  77200. return item->image;
  77201. }
  77202. return Image::null;
  77203. }
  77204. void addImageToCache (const Image& image, const int64 hashCode)
  77205. {
  77206. if (image.isValid())
  77207. {
  77208. if (! isTimerRunning())
  77209. startTimer (2000);
  77210. Item* const item = new Item();
  77211. item->hashCode = hashCode;
  77212. item->image = image;
  77213. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77214. const ScopedLock sl (lock);
  77215. images.add (item);
  77216. }
  77217. }
  77218. void timerCallback()
  77219. {
  77220. const uint32 now = Time::getApproximateMillisecondCounter();
  77221. const ScopedLock sl (lock);
  77222. for (int i = images.size(); --i >= 0;)
  77223. {
  77224. Item* const item = images.getUnchecked(i);
  77225. if (item->image.getReferenceCount() <= 1)
  77226. {
  77227. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77228. images.remove (i);
  77229. }
  77230. else
  77231. {
  77232. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77233. }
  77234. }
  77235. if (images.size() == 0)
  77236. stopTimer();
  77237. }
  77238. struct Item
  77239. {
  77240. Image image;
  77241. int64 hashCode;
  77242. uint32 lastUseTime;
  77243. };
  77244. int cacheTimeout;
  77245. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77246. private:
  77247. OwnedArray<Item> images;
  77248. CriticalSection lock;
  77249. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77250. };
  77251. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77252. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77253. {
  77254. if (Pimpl::getInstanceWithoutCreating() != 0)
  77255. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77256. return Image::null;
  77257. }
  77258. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77259. {
  77260. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77261. }
  77262. const Image ImageCache::getFromFile (const File& file)
  77263. {
  77264. const int64 hashCode = file.hashCode64();
  77265. Image image (getFromHashCode (hashCode));
  77266. if (image.isNull())
  77267. {
  77268. image = ImageFileFormat::loadFrom (file);
  77269. addImageToCache (image, hashCode);
  77270. }
  77271. return image;
  77272. }
  77273. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77274. {
  77275. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77276. Image image (getFromHashCode (hashCode));
  77277. if (image.isNull())
  77278. {
  77279. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77280. addImageToCache (image, hashCode);
  77281. }
  77282. return image;
  77283. }
  77284. void ImageCache::setCacheTimeout (const int millisecs)
  77285. {
  77286. Pimpl::getInstance()->cacheTimeout = millisecs;
  77287. }
  77288. END_JUCE_NAMESPACE
  77289. /*** End of inlined file: juce_ImageCache.cpp ***/
  77290. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77291. BEGIN_JUCE_NAMESPACE
  77292. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77293. : values (size_ * size_),
  77294. size (size_)
  77295. {
  77296. clear();
  77297. }
  77298. ImageConvolutionKernel::~ImageConvolutionKernel()
  77299. {
  77300. }
  77301. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77302. {
  77303. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77304. return values [x + y * size];
  77305. jassertfalse;
  77306. return 0;
  77307. }
  77308. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77309. {
  77310. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77311. {
  77312. values [x + y * size] = value;
  77313. }
  77314. else
  77315. {
  77316. jassertfalse;
  77317. }
  77318. }
  77319. void ImageConvolutionKernel::clear()
  77320. {
  77321. for (int i = size * size; --i >= 0;)
  77322. values[i] = 0;
  77323. }
  77324. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77325. {
  77326. double currentTotal = 0.0;
  77327. for (int i = size * size; --i >= 0;)
  77328. currentTotal += values[i];
  77329. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77330. }
  77331. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77332. {
  77333. for (int i = size * size; --i >= 0;)
  77334. values[i] *= multiplier;
  77335. }
  77336. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77337. {
  77338. const double radiusFactor = -1.0 / (radius * radius * 2);
  77339. const int centre = size >> 1;
  77340. for (int y = size; --y >= 0;)
  77341. {
  77342. for (int x = size; --x >= 0;)
  77343. {
  77344. const int cx = x - centre;
  77345. const int cy = y - centre;
  77346. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77347. }
  77348. }
  77349. setOverallSum (1.0f);
  77350. }
  77351. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77352. const Image& sourceImage,
  77353. const Rectangle<int>& destinationArea) const
  77354. {
  77355. if (sourceImage == destImage)
  77356. {
  77357. destImage.duplicateIfShared();
  77358. }
  77359. else
  77360. {
  77361. if (sourceImage.getWidth() != destImage.getWidth()
  77362. || sourceImage.getHeight() != destImage.getHeight()
  77363. || sourceImage.getFormat() != destImage.getFormat())
  77364. {
  77365. jassertfalse;
  77366. return;
  77367. }
  77368. }
  77369. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77370. if (area.isEmpty())
  77371. return;
  77372. const int right = area.getRight();
  77373. const int bottom = area.getBottom();
  77374. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77375. uint8* line = destData.data;
  77376. const Image::BitmapData srcData (sourceImage, false);
  77377. if (destData.pixelStride == 4)
  77378. {
  77379. for (int y = area.getY(); y < bottom; ++y)
  77380. {
  77381. uint8* dest = line;
  77382. line += destData.lineStride;
  77383. for (int x = area.getX(); x < right; ++x)
  77384. {
  77385. float c1 = 0;
  77386. float c2 = 0;
  77387. float c3 = 0;
  77388. float c4 = 0;
  77389. for (int yy = 0; yy < size; ++yy)
  77390. {
  77391. const int sy = y + yy - (size >> 1);
  77392. if (sy >= srcData.height)
  77393. break;
  77394. if (sy >= 0)
  77395. {
  77396. int sx = x - (size >> 1);
  77397. const uint8* src = srcData.getPixelPointer (sx, sy);
  77398. for (int xx = 0; xx < size; ++xx)
  77399. {
  77400. if (sx >= srcData.width)
  77401. break;
  77402. if (sx >= 0)
  77403. {
  77404. const float kernelMult = values [xx + yy * size];
  77405. c1 += kernelMult * *src++;
  77406. c2 += kernelMult * *src++;
  77407. c3 += kernelMult * *src++;
  77408. c4 += kernelMult * *src++;
  77409. }
  77410. else
  77411. {
  77412. src += 4;
  77413. }
  77414. ++sx;
  77415. }
  77416. }
  77417. }
  77418. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77419. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77420. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77421. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77422. }
  77423. }
  77424. }
  77425. else if (destData.pixelStride == 3)
  77426. {
  77427. for (int y = area.getY(); y < bottom; ++y)
  77428. {
  77429. uint8* dest = line;
  77430. line += destData.lineStride;
  77431. for (int x = area.getX(); x < right; ++x)
  77432. {
  77433. float c1 = 0;
  77434. float c2 = 0;
  77435. float c3 = 0;
  77436. for (int yy = 0; yy < size; ++yy)
  77437. {
  77438. const int sy = y + yy - (size >> 1);
  77439. if (sy >= srcData.height)
  77440. break;
  77441. if (sy >= 0)
  77442. {
  77443. int sx = x - (size >> 1);
  77444. const uint8* src = srcData.getPixelPointer (sx, sy);
  77445. for (int xx = 0; xx < size; ++xx)
  77446. {
  77447. if (sx >= srcData.width)
  77448. break;
  77449. if (sx >= 0)
  77450. {
  77451. const float kernelMult = values [xx + yy * size];
  77452. c1 += kernelMult * *src++;
  77453. c2 += kernelMult * *src++;
  77454. c3 += kernelMult * *src++;
  77455. }
  77456. else
  77457. {
  77458. src += 3;
  77459. }
  77460. ++sx;
  77461. }
  77462. }
  77463. }
  77464. *dest++ = (uint8) roundToInt (c1);
  77465. *dest++ = (uint8) roundToInt (c2);
  77466. *dest++ = (uint8) roundToInt (c3);
  77467. }
  77468. }
  77469. }
  77470. }
  77471. END_JUCE_NAMESPACE
  77472. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77473. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77474. BEGIN_JUCE_NAMESPACE
  77475. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77476. {
  77477. static PNGImageFormat png;
  77478. static JPEGImageFormat jpg;
  77479. static GIFImageFormat gif;
  77480. ImageFileFormat* formats[4];
  77481. int numFormats = 0;
  77482. formats [numFormats++] = &png;
  77483. formats [numFormats++] = &jpg;
  77484. formats [numFormats++] = &gif;
  77485. const int64 streamPos = input.getPosition();
  77486. for (int i = 0; i < numFormats; ++i)
  77487. {
  77488. const bool found = formats[i]->canUnderstand (input);
  77489. input.setPosition (streamPos);
  77490. if (found)
  77491. return formats[i];
  77492. }
  77493. return 0;
  77494. }
  77495. const Image ImageFileFormat::loadFrom (InputStream& input)
  77496. {
  77497. ImageFileFormat* const format = findImageFormatForStream (input);
  77498. if (format != 0)
  77499. return format->decodeImage (input);
  77500. return Image::null;
  77501. }
  77502. const Image ImageFileFormat::loadFrom (const File& file)
  77503. {
  77504. InputStream* const in = file.createInputStream();
  77505. if (in != 0)
  77506. {
  77507. BufferedInputStream b (in, 8192, true);
  77508. return loadFrom (b);
  77509. }
  77510. return Image::null;
  77511. }
  77512. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77513. {
  77514. if (rawData != 0 && numBytes > 4)
  77515. {
  77516. MemoryInputStream stream (rawData, numBytes, false);
  77517. return loadFrom (stream);
  77518. }
  77519. return Image::null;
  77520. }
  77521. END_JUCE_NAMESPACE
  77522. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77523. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77524. BEGIN_JUCE_NAMESPACE
  77525. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77526. const Image juce_loadWithCoreImage (InputStream& input);
  77527. #else
  77528. class GIFLoader
  77529. {
  77530. public:
  77531. GIFLoader (InputStream& in)
  77532. : input (in),
  77533. dataBlockIsZero (false),
  77534. fresh (false),
  77535. finished (false)
  77536. {
  77537. currentBit = lastBit = lastByteIndex = 0;
  77538. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77539. firstcode = oldcode = 0;
  77540. clearCode = end_code = 0;
  77541. int imageWidth, imageHeight;
  77542. int transparent = -1;
  77543. if (! getSizeFromHeader (imageWidth, imageHeight))
  77544. return;
  77545. if ((imageWidth <= 0) || (imageHeight <= 0))
  77546. return;
  77547. unsigned char buf [16];
  77548. if (in.read (buf, 3) != 3)
  77549. return;
  77550. int numColours = 2 << (buf[0] & 7);
  77551. if ((buf[0] & 0x80) != 0)
  77552. readPalette (numColours);
  77553. for (;;)
  77554. {
  77555. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77556. break;
  77557. if (buf[0] == '!')
  77558. {
  77559. if (input.read (buf, 1) != 1)
  77560. break;
  77561. if (processExtension (buf[0], transparent) < 0)
  77562. break;
  77563. continue;
  77564. }
  77565. if (buf[0] != ',')
  77566. continue;
  77567. if (input.read (buf, 9) != 9)
  77568. break;
  77569. imageWidth = makeWord (buf[4], buf[5]);
  77570. imageHeight = makeWord (buf[6], buf[7]);
  77571. numColours = 2 << (buf[8] & 7);
  77572. if ((buf[8] & 0x80) != 0)
  77573. if (! readPalette (numColours))
  77574. break;
  77575. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77576. imageWidth, imageHeight, (transparent >= 0));
  77577. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77578. readImage ((buf[8] & 0x40) != 0, transparent);
  77579. break;
  77580. }
  77581. }
  77582. ~GIFLoader() {}
  77583. Image image;
  77584. private:
  77585. InputStream& input;
  77586. uint8 buffer [300];
  77587. uint8 palette [256][4];
  77588. bool dataBlockIsZero, fresh, finished;
  77589. int currentBit, lastBit, lastByteIndex;
  77590. int codeSize, setCodeSize;
  77591. int maxCode, maxCodeSize;
  77592. int firstcode, oldcode;
  77593. int clearCode, end_code;
  77594. enum { maxGifCode = 1 << 12 };
  77595. int table [2] [maxGifCode];
  77596. int stack [2 * maxGifCode];
  77597. int *sp;
  77598. bool getSizeFromHeader (int& w, int& h)
  77599. {
  77600. char b[8];
  77601. if (input.read (b, 6) == 6)
  77602. {
  77603. if ((strncmp ("GIF87a", b, 6) == 0)
  77604. || (strncmp ("GIF89a", b, 6) == 0))
  77605. {
  77606. if (input.read (b, 4) == 4)
  77607. {
  77608. w = makeWord (b[0], b[1]);
  77609. h = makeWord (b[2], b[3]);
  77610. return true;
  77611. }
  77612. }
  77613. }
  77614. return false;
  77615. }
  77616. bool readPalette (const int numCols)
  77617. {
  77618. unsigned char rgb[4];
  77619. for (int i = 0; i < numCols; ++i)
  77620. {
  77621. input.read (rgb, 3);
  77622. palette [i][0] = rgb[0];
  77623. palette [i][1] = rgb[1];
  77624. palette [i][2] = rgb[2];
  77625. palette [i][3] = 0xff;
  77626. }
  77627. return true;
  77628. }
  77629. int readDataBlock (unsigned char* dest)
  77630. {
  77631. unsigned char n;
  77632. if (input.read (&n, 1) == 1)
  77633. {
  77634. dataBlockIsZero = (n == 0);
  77635. if (dataBlockIsZero || (input.read (dest, n) == n))
  77636. return n;
  77637. }
  77638. return -1;
  77639. }
  77640. int processExtension (const int type, int& transparent)
  77641. {
  77642. unsigned char b [300];
  77643. int n = 0;
  77644. if (type == 0xf9)
  77645. {
  77646. n = readDataBlock (b);
  77647. if (n < 0)
  77648. return 1;
  77649. if ((b[0] & 0x1) != 0)
  77650. transparent = b[3];
  77651. }
  77652. do
  77653. {
  77654. n = readDataBlock (b);
  77655. }
  77656. while (n > 0);
  77657. return n;
  77658. }
  77659. int readLZWByte (const bool initialise, const int inputCodeSize)
  77660. {
  77661. int code, incode, i;
  77662. if (initialise)
  77663. {
  77664. setCodeSize = inputCodeSize;
  77665. codeSize = setCodeSize + 1;
  77666. clearCode = 1 << setCodeSize;
  77667. end_code = clearCode + 1;
  77668. maxCodeSize = 2 * clearCode;
  77669. maxCode = clearCode + 2;
  77670. getCode (0, true);
  77671. fresh = true;
  77672. for (i = 0; i < clearCode; ++i)
  77673. {
  77674. table[0][i] = 0;
  77675. table[1][i] = i;
  77676. }
  77677. for (; i < maxGifCode; ++i)
  77678. {
  77679. table[0][i] = 0;
  77680. table[1][i] = 0;
  77681. }
  77682. sp = stack;
  77683. return 0;
  77684. }
  77685. else if (fresh)
  77686. {
  77687. fresh = false;
  77688. do
  77689. {
  77690. firstcode = oldcode
  77691. = getCode (codeSize, false);
  77692. }
  77693. while (firstcode == clearCode);
  77694. return firstcode;
  77695. }
  77696. if (sp > stack)
  77697. return *--sp;
  77698. while ((code = getCode (codeSize, false)) >= 0)
  77699. {
  77700. if (code == clearCode)
  77701. {
  77702. for (i = 0; i < clearCode; ++i)
  77703. {
  77704. table[0][i] = 0;
  77705. table[1][i] = i;
  77706. }
  77707. for (; i < maxGifCode; ++i)
  77708. {
  77709. table[0][i] = 0;
  77710. table[1][i] = 0;
  77711. }
  77712. codeSize = setCodeSize + 1;
  77713. maxCodeSize = 2 * clearCode;
  77714. maxCode = clearCode + 2;
  77715. sp = stack;
  77716. firstcode = oldcode = getCode (codeSize, false);
  77717. return firstcode;
  77718. }
  77719. else if (code == end_code)
  77720. {
  77721. if (dataBlockIsZero)
  77722. return -2;
  77723. unsigned char buf [260];
  77724. int n;
  77725. while ((n = readDataBlock (buf)) > 0)
  77726. {}
  77727. if (n != 0)
  77728. return -2;
  77729. }
  77730. incode = code;
  77731. if (code >= maxCode)
  77732. {
  77733. *sp++ = firstcode;
  77734. code = oldcode;
  77735. }
  77736. while (code >= clearCode)
  77737. {
  77738. *sp++ = table[1][code];
  77739. if (code == table[0][code])
  77740. return -2;
  77741. code = table[0][code];
  77742. }
  77743. *sp++ = firstcode = table[1][code];
  77744. if ((code = maxCode) < maxGifCode)
  77745. {
  77746. table[0][code] = oldcode;
  77747. table[1][code] = firstcode;
  77748. ++maxCode;
  77749. if ((maxCode >= maxCodeSize)
  77750. && (maxCodeSize < maxGifCode))
  77751. {
  77752. maxCodeSize <<= 1;
  77753. ++codeSize;
  77754. }
  77755. }
  77756. oldcode = incode;
  77757. if (sp > stack)
  77758. return *--sp;
  77759. }
  77760. return code;
  77761. }
  77762. int getCode (const int codeSize_, const bool initialise)
  77763. {
  77764. if (initialise)
  77765. {
  77766. currentBit = 0;
  77767. lastBit = 0;
  77768. finished = false;
  77769. return 0;
  77770. }
  77771. if ((currentBit + codeSize_) >= lastBit)
  77772. {
  77773. if (finished)
  77774. return -1;
  77775. buffer[0] = buffer [lastByteIndex - 2];
  77776. buffer[1] = buffer [lastByteIndex - 1];
  77777. const int n = readDataBlock (&buffer[2]);
  77778. if (n == 0)
  77779. finished = true;
  77780. lastByteIndex = 2 + n;
  77781. currentBit = (currentBit - lastBit) + 16;
  77782. lastBit = (2 + n) * 8 ;
  77783. }
  77784. int result = 0;
  77785. int i = currentBit;
  77786. for (int j = 0; j < codeSize_; ++j)
  77787. {
  77788. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77789. ++i;
  77790. }
  77791. currentBit += codeSize_;
  77792. return result;
  77793. }
  77794. bool readImage (const int interlace, const int transparent)
  77795. {
  77796. unsigned char c;
  77797. if (input.read (&c, 1) != 1
  77798. || readLZWByte (true, c) < 0)
  77799. return false;
  77800. if (transparent >= 0)
  77801. {
  77802. palette [transparent][0] = 0;
  77803. palette [transparent][1] = 0;
  77804. palette [transparent][2] = 0;
  77805. palette [transparent][3] = 0;
  77806. }
  77807. int index;
  77808. int xpos = 0, ypos = 0, pass = 0;
  77809. const Image::BitmapData destData (image, true);
  77810. uint8* p = destData.data;
  77811. const bool hasAlpha = image.hasAlphaChannel();
  77812. while ((index = readLZWByte (false, c)) >= 0)
  77813. {
  77814. const uint8* const paletteEntry = palette [index];
  77815. if (hasAlpha)
  77816. {
  77817. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77818. paletteEntry[0],
  77819. paletteEntry[1],
  77820. paletteEntry[2]);
  77821. ((PixelARGB*) p)->premultiply();
  77822. }
  77823. else
  77824. {
  77825. ((PixelRGB*) p)->setARGB (0,
  77826. paletteEntry[0],
  77827. paletteEntry[1],
  77828. paletteEntry[2]);
  77829. }
  77830. p += destData.pixelStride;
  77831. ++xpos;
  77832. if (xpos == destData.width)
  77833. {
  77834. xpos = 0;
  77835. if (interlace)
  77836. {
  77837. switch (pass)
  77838. {
  77839. case 0:
  77840. case 1: ypos += 8; break;
  77841. case 2: ypos += 4; break;
  77842. case 3: ypos += 2; break;
  77843. }
  77844. while (ypos >= destData.height)
  77845. {
  77846. ++pass;
  77847. switch (pass)
  77848. {
  77849. case 1: ypos = 4; break;
  77850. case 2: ypos = 2; break;
  77851. case 3: ypos = 1; break;
  77852. default: return true;
  77853. }
  77854. }
  77855. }
  77856. else
  77857. {
  77858. ++ypos;
  77859. }
  77860. p = destData.getPixelPointer (xpos, ypos);
  77861. }
  77862. if (ypos >= destData.height)
  77863. break;
  77864. }
  77865. return true;
  77866. }
  77867. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77868. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  77869. };
  77870. #endif
  77871. GIFImageFormat::GIFImageFormat() {}
  77872. GIFImageFormat::~GIFImageFormat() {}
  77873. const String GIFImageFormat::getFormatName() { return "GIF"; }
  77874. bool GIFImageFormat::canUnderstand (InputStream& in)
  77875. {
  77876. char header [4];
  77877. return (in.read (header, sizeof (header)) == sizeof (header))
  77878. && header[0] == 'G'
  77879. && header[1] == 'I'
  77880. && header[2] == 'F';
  77881. }
  77882. const Image GIFImageFormat::decodeImage (InputStream& in)
  77883. {
  77884. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77885. return juce_loadWithCoreImage (in);
  77886. #else
  77887. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77888. return loader->image;
  77889. #endif
  77890. }
  77891. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77892. {
  77893. jassertfalse; // writing isn't implemented for GIFs!
  77894. return false;
  77895. }
  77896. END_JUCE_NAMESPACE
  77897. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77898. #endif
  77899. //==============================================================================
  77900. // some files include lots of library code, so leave them to the end to avoid cluttering
  77901. // up the build for the clean files.
  77902. #if JUCE_BUILD_CORE
  77903. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77904. namespace zlibNamespace
  77905. {
  77906. #if JUCE_INCLUDE_ZLIB_CODE
  77907. #undef OS_CODE
  77908. #undef fdopen
  77909. /*** Start of inlined file: zlib.h ***/
  77910. #ifndef ZLIB_H
  77911. #define ZLIB_H
  77912. /*** Start of inlined file: zconf.h ***/
  77913. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77914. #ifndef ZCONF_H
  77915. #define ZCONF_H
  77916. // *** Just a few hacks here to make it compile nicely with Juce..
  77917. #define Z_PREFIX 1
  77918. #undef __MACTYPES__
  77919. #ifdef _MSC_VER
  77920. #pragma warning (disable : 4131 4127 4244 4267)
  77921. #endif
  77922. /*
  77923. * If you *really* need a unique prefix for all types and library functions,
  77924. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77925. */
  77926. #ifdef Z_PREFIX
  77927. # define deflateInit_ z_deflateInit_
  77928. # define deflate z_deflate
  77929. # define deflateEnd z_deflateEnd
  77930. # define inflateInit_ z_inflateInit_
  77931. # define inflate z_inflate
  77932. # define inflateEnd z_inflateEnd
  77933. # define inflatePrime z_inflatePrime
  77934. # define inflateGetHeader z_inflateGetHeader
  77935. # define adler32_combine z_adler32_combine
  77936. # define crc32_combine z_crc32_combine
  77937. # define deflateInit2_ z_deflateInit2_
  77938. # define deflateSetDictionary z_deflateSetDictionary
  77939. # define deflateCopy z_deflateCopy
  77940. # define deflateReset z_deflateReset
  77941. # define deflateParams z_deflateParams
  77942. # define deflateBound z_deflateBound
  77943. # define deflatePrime z_deflatePrime
  77944. # define inflateInit2_ z_inflateInit2_
  77945. # define inflateSetDictionary z_inflateSetDictionary
  77946. # define inflateSync z_inflateSync
  77947. # define inflateSyncPoint z_inflateSyncPoint
  77948. # define inflateCopy z_inflateCopy
  77949. # define inflateReset z_inflateReset
  77950. # define inflateBack z_inflateBack
  77951. # define inflateBackEnd z_inflateBackEnd
  77952. # define compress z_compress
  77953. # define compress2 z_compress2
  77954. # define compressBound z_compressBound
  77955. # define uncompress z_uncompress
  77956. # define adler32 z_adler32
  77957. # define crc32 z_crc32
  77958. # define get_crc_table z_get_crc_table
  77959. # define zError z_zError
  77960. # define alloc_func z_alloc_func
  77961. # define free_func z_free_func
  77962. # define in_func z_in_func
  77963. # define out_func z_out_func
  77964. # define Byte z_Byte
  77965. # define uInt z_uInt
  77966. # define uLong z_uLong
  77967. # define Bytef z_Bytef
  77968. # define charf z_charf
  77969. # define intf z_intf
  77970. # define uIntf z_uIntf
  77971. # define uLongf z_uLongf
  77972. # define voidpf z_voidpf
  77973. # define voidp z_voidp
  77974. #endif
  77975. #if defined(__MSDOS__) && !defined(MSDOS)
  77976. # define MSDOS
  77977. #endif
  77978. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77979. # define OS2
  77980. #endif
  77981. #if defined(_WINDOWS) && !defined(WINDOWS)
  77982. # define WINDOWS
  77983. #endif
  77984. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77985. # ifndef WIN32
  77986. # define WIN32
  77987. # endif
  77988. #endif
  77989. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77990. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77991. # ifndef SYS16BIT
  77992. # define SYS16BIT
  77993. # endif
  77994. # endif
  77995. #endif
  77996. /*
  77997. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77998. * than 64k bytes at a time (needed on systems with 16-bit int).
  77999. */
  78000. #ifdef SYS16BIT
  78001. # define MAXSEG_64K
  78002. #endif
  78003. #ifdef MSDOS
  78004. # define UNALIGNED_OK
  78005. #endif
  78006. #ifdef __STDC_VERSION__
  78007. # ifndef STDC
  78008. # define STDC
  78009. # endif
  78010. # if __STDC_VERSION__ >= 199901L
  78011. # ifndef STDC99
  78012. # define STDC99
  78013. # endif
  78014. # endif
  78015. #endif
  78016. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78017. # define STDC
  78018. #endif
  78019. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78020. # define STDC
  78021. #endif
  78022. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78023. # define STDC
  78024. #endif
  78025. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78026. # define STDC
  78027. #endif
  78028. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78029. # define STDC
  78030. #endif
  78031. #ifndef STDC
  78032. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78033. # define const /* note: need a more gentle solution here */
  78034. # endif
  78035. #endif
  78036. /* Some Mac compilers merge all .h files incorrectly: */
  78037. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78038. # define NO_DUMMY_DECL
  78039. #endif
  78040. /* Maximum value for memLevel in deflateInit2 */
  78041. #ifndef MAX_MEM_LEVEL
  78042. # ifdef MAXSEG_64K
  78043. # define MAX_MEM_LEVEL 8
  78044. # else
  78045. # define MAX_MEM_LEVEL 9
  78046. # endif
  78047. #endif
  78048. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78049. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78050. * created by gzip. (Files created by minigzip can still be extracted by
  78051. * gzip.)
  78052. */
  78053. #ifndef MAX_WBITS
  78054. # define MAX_WBITS 15 /* 32K LZ77 window */
  78055. #endif
  78056. /* The memory requirements for deflate are (in bytes):
  78057. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78058. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78059. plus a few kilobytes for small objects. For example, if you want to reduce
  78060. the default memory requirements from 256K to 128K, compile with
  78061. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78062. Of course this will generally degrade compression (there's no free lunch).
  78063. The memory requirements for inflate are (in bytes) 1 << windowBits
  78064. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78065. for small objects.
  78066. */
  78067. /* Type declarations */
  78068. #ifndef OF /* function prototypes */
  78069. # ifdef STDC
  78070. # define OF(args) args
  78071. # else
  78072. # define OF(args) ()
  78073. # endif
  78074. #endif
  78075. /* The following definitions for FAR are needed only for MSDOS mixed
  78076. * model programming (small or medium model with some far allocations).
  78077. * This was tested only with MSC; for other MSDOS compilers you may have
  78078. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78079. * just define FAR to be empty.
  78080. */
  78081. #ifdef SYS16BIT
  78082. # if defined(M_I86SM) || defined(M_I86MM)
  78083. /* MSC small or medium model */
  78084. # define SMALL_MEDIUM
  78085. # ifdef _MSC_VER
  78086. # define FAR _far
  78087. # else
  78088. # define FAR far
  78089. # endif
  78090. # endif
  78091. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78092. /* Turbo C small or medium model */
  78093. # define SMALL_MEDIUM
  78094. # ifdef __BORLANDC__
  78095. # define FAR _far
  78096. # else
  78097. # define FAR far
  78098. # endif
  78099. # endif
  78100. #endif
  78101. #if defined(WINDOWS) || defined(WIN32)
  78102. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78103. * This is not mandatory, but it offers a little performance increase.
  78104. */
  78105. # ifdef ZLIB_DLL
  78106. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78107. # ifdef ZLIB_INTERNAL
  78108. # define ZEXTERN extern __declspec(dllexport)
  78109. # else
  78110. # define ZEXTERN extern __declspec(dllimport)
  78111. # endif
  78112. # endif
  78113. # endif /* ZLIB_DLL */
  78114. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78115. * define ZLIB_WINAPI.
  78116. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78117. */
  78118. # ifdef ZLIB_WINAPI
  78119. # ifdef FAR
  78120. # undef FAR
  78121. # endif
  78122. # include <windows.h>
  78123. /* No need for _export, use ZLIB.DEF instead. */
  78124. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78125. # define ZEXPORT WINAPI
  78126. # ifdef WIN32
  78127. # define ZEXPORTVA WINAPIV
  78128. # else
  78129. # define ZEXPORTVA FAR CDECL
  78130. # endif
  78131. # endif
  78132. #endif
  78133. #if defined (__BEOS__)
  78134. # ifdef ZLIB_DLL
  78135. # ifdef ZLIB_INTERNAL
  78136. # define ZEXPORT __declspec(dllexport)
  78137. # define ZEXPORTVA __declspec(dllexport)
  78138. # else
  78139. # define ZEXPORT __declspec(dllimport)
  78140. # define ZEXPORTVA __declspec(dllimport)
  78141. # endif
  78142. # endif
  78143. #endif
  78144. #ifndef ZEXTERN
  78145. # define ZEXTERN extern
  78146. #endif
  78147. #ifndef ZEXPORT
  78148. # define ZEXPORT
  78149. #endif
  78150. #ifndef ZEXPORTVA
  78151. # define ZEXPORTVA
  78152. #endif
  78153. #ifndef FAR
  78154. # define FAR
  78155. #endif
  78156. #if !defined(__MACTYPES__)
  78157. typedef unsigned char Byte; /* 8 bits */
  78158. #endif
  78159. typedef unsigned int uInt; /* 16 bits or more */
  78160. typedef unsigned long uLong; /* 32 bits or more */
  78161. #ifdef SMALL_MEDIUM
  78162. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78163. # define Bytef Byte FAR
  78164. #else
  78165. typedef Byte FAR Bytef;
  78166. #endif
  78167. typedef char FAR charf;
  78168. typedef int FAR intf;
  78169. typedef uInt FAR uIntf;
  78170. typedef uLong FAR uLongf;
  78171. #ifdef STDC
  78172. typedef void const *voidpc;
  78173. typedef void FAR *voidpf;
  78174. typedef void *voidp;
  78175. #else
  78176. typedef Byte const *voidpc;
  78177. typedef Byte FAR *voidpf;
  78178. typedef Byte *voidp;
  78179. #endif
  78180. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78181. # include <sys/types.h> /* for off_t */
  78182. # include <unistd.h> /* for SEEK_* and off_t */
  78183. # ifdef VMS
  78184. # include <unixio.h> /* for off_t */
  78185. # endif
  78186. # define z_off_t off_t
  78187. #endif
  78188. #ifndef SEEK_SET
  78189. # define SEEK_SET 0 /* Seek from beginning of file. */
  78190. # define SEEK_CUR 1 /* Seek from current position. */
  78191. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78192. #endif
  78193. #ifndef z_off_t
  78194. # define z_off_t long
  78195. #endif
  78196. #if defined(__OS400__)
  78197. # define NO_vsnprintf
  78198. #endif
  78199. #if defined(__MVS__)
  78200. # define NO_vsnprintf
  78201. # ifdef FAR
  78202. # undef FAR
  78203. # endif
  78204. #endif
  78205. /* MVS linker does not support external names larger than 8 bytes */
  78206. #if defined(__MVS__)
  78207. # pragma map(deflateInit_,"DEIN")
  78208. # pragma map(deflateInit2_,"DEIN2")
  78209. # pragma map(deflateEnd,"DEEND")
  78210. # pragma map(deflateBound,"DEBND")
  78211. # pragma map(inflateInit_,"ININ")
  78212. # pragma map(inflateInit2_,"ININ2")
  78213. # pragma map(inflateEnd,"INEND")
  78214. # pragma map(inflateSync,"INSY")
  78215. # pragma map(inflateSetDictionary,"INSEDI")
  78216. # pragma map(compressBound,"CMBND")
  78217. # pragma map(inflate_table,"INTABL")
  78218. # pragma map(inflate_fast,"INFA")
  78219. # pragma map(inflate_copyright,"INCOPY")
  78220. #endif
  78221. #endif /* ZCONF_H */
  78222. /*** End of inlined file: zconf.h ***/
  78223. #ifdef __cplusplus
  78224. //extern "C" {
  78225. #endif
  78226. #define ZLIB_VERSION "1.2.3"
  78227. #define ZLIB_VERNUM 0x1230
  78228. /*
  78229. The 'zlib' compression library provides in-memory compression and
  78230. decompression functions, including integrity checks of the uncompressed
  78231. data. This version of the library supports only one compression method
  78232. (deflation) but other algorithms will be added later and will have the same
  78233. stream interface.
  78234. Compression can be done in a single step if the buffers are large
  78235. enough (for example if an input file is mmap'ed), or can be done by
  78236. repeated calls of the compression function. In the latter case, the
  78237. application must provide more input and/or consume the output
  78238. (providing more output space) before each call.
  78239. The compressed data format used by default by the in-memory functions is
  78240. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78241. around a deflate stream, which is itself documented in RFC 1951.
  78242. The library also supports reading and writing files in gzip (.gz) format
  78243. with an interface similar to that of stdio using the functions that start
  78244. with "gz". The gzip format is different from the zlib format. gzip is a
  78245. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78246. This library can optionally read and write gzip streams in memory as well.
  78247. The zlib format was designed to be compact and fast for use in memory
  78248. and on communications channels. The gzip format was designed for single-
  78249. file compression on file systems, has a larger header than zlib to maintain
  78250. directory information, and uses a different, slower check method than zlib.
  78251. The library does not install any signal handler. The decoder checks
  78252. the consistency of the compressed data, so the library should never
  78253. crash even in case of corrupted input.
  78254. */
  78255. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78256. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78257. struct internal_state;
  78258. typedef struct z_stream_s {
  78259. Bytef *next_in; /* next input byte */
  78260. uInt avail_in; /* number of bytes available at next_in */
  78261. uLong total_in; /* total nb of input bytes read so far */
  78262. Bytef *next_out; /* next output byte should be put there */
  78263. uInt avail_out; /* remaining free space at next_out */
  78264. uLong total_out; /* total nb of bytes output so far */
  78265. char *msg; /* last error message, NULL if no error */
  78266. struct internal_state FAR *state; /* not visible by applications */
  78267. alloc_func zalloc; /* used to allocate the internal state */
  78268. free_func zfree; /* used to free the internal state */
  78269. voidpf opaque; /* private data object passed to zalloc and zfree */
  78270. int data_type; /* best guess about the data type: binary or text */
  78271. uLong adler; /* adler32 value of the uncompressed data */
  78272. uLong reserved; /* reserved for future use */
  78273. } z_stream;
  78274. typedef z_stream FAR *z_streamp;
  78275. /*
  78276. gzip header information passed to and from zlib routines. See RFC 1952
  78277. for more details on the meanings of these fields.
  78278. */
  78279. typedef struct gz_header_s {
  78280. int text; /* true if compressed data believed to be text */
  78281. uLong time; /* modification time */
  78282. int xflags; /* extra flags (not used when writing a gzip file) */
  78283. int os; /* operating system */
  78284. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78285. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78286. uInt extra_max; /* space at extra (only when reading header) */
  78287. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78288. uInt name_max; /* space at name (only when reading header) */
  78289. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78290. uInt comm_max; /* space at comment (only when reading header) */
  78291. int hcrc; /* true if there was or will be a header crc */
  78292. int done; /* true when done reading gzip header (not used
  78293. when writing a gzip file) */
  78294. } gz_header;
  78295. typedef gz_header FAR *gz_headerp;
  78296. /*
  78297. The application must update next_in and avail_in when avail_in has
  78298. dropped to zero. It must update next_out and avail_out when avail_out
  78299. has dropped to zero. The application must initialize zalloc, zfree and
  78300. opaque before calling the init function. All other fields are set by the
  78301. compression library and must not be updated by the application.
  78302. The opaque value provided by the application will be passed as the first
  78303. parameter for calls of zalloc and zfree. This can be useful for custom
  78304. memory management. The compression library attaches no meaning to the
  78305. opaque value.
  78306. zalloc must return Z_NULL if there is not enough memory for the object.
  78307. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78308. thread safe.
  78309. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78310. exactly 65536 bytes, but will not be required to allocate more than this
  78311. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78312. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78313. have their offset normalized to zero. The default allocation function
  78314. provided by this library ensures this (see zutil.c). To reduce memory
  78315. requirements and avoid any allocation of 64K objects, at the expense of
  78316. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78317. The fields total_in and total_out can be used for statistics or
  78318. progress reports. After compression, total_in holds the total size of
  78319. the uncompressed data and may be saved for use in the decompressor
  78320. (particularly if the decompressor wants to decompress everything in
  78321. a single step).
  78322. */
  78323. /* constants */
  78324. #define Z_NO_FLUSH 0
  78325. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78326. #define Z_SYNC_FLUSH 2
  78327. #define Z_FULL_FLUSH 3
  78328. #define Z_FINISH 4
  78329. #define Z_BLOCK 5
  78330. /* Allowed flush values; see deflate() and inflate() below for details */
  78331. #define Z_OK 0
  78332. #define Z_STREAM_END 1
  78333. #define Z_NEED_DICT 2
  78334. #define Z_ERRNO (-1)
  78335. #define Z_STREAM_ERROR (-2)
  78336. #define Z_DATA_ERROR (-3)
  78337. #define Z_MEM_ERROR (-4)
  78338. #define Z_BUF_ERROR (-5)
  78339. #define Z_VERSION_ERROR (-6)
  78340. /* Return codes for the compression/decompression functions. Negative
  78341. * values are errors, positive values are used for special but normal events.
  78342. */
  78343. #define Z_NO_COMPRESSION 0
  78344. #define Z_BEST_SPEED 1
  78345. #define Z_BEST_COMPRESSION 9
  78346. #define Z_DEFAULT_COMPRESSION (-1)
  78347. /* compression levels */
  78348. #define Z_FILTERED 1
  78349. #define Z_HUFFMAN_ONLY 2
  78350. #define Z_RLE 3
  78351. #define Z_FIXED 4
  78352. #define Z_DEFAULT_STRATEGY 0
  78353. /* compression strategy; see deflateInit2() below for details */
  78354. #define Z_BINARY 0
  78355. #define Z_TEXT 1
  78356. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78357. #define Z_UNKNOWN 2
  78358. /* Possible values of the data_type field (though see inflate()) */
  78359. #define Z_DEFLATED 8
  78360. /* The deflate compression method (the only one supported in this version) */
  78361. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78362. #define zlib_version zlibVersion()
  78363. /* for compatibility with versions < 1.0.2 */
  78364. /* basic functions */
  78365. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78366. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78367. If the first character differs, the library code actually used is
  78368. not compatible with the zlib.h header file used by the application.
  78369. This check is automatically made by deflateInit and inflateInit.
  78370. */
  78371. /*
  78372. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78373. Initializes the internal stream state for compression. The fields
  78374. zalloc, zfree and opaque must be initialized before by the caller.
  78375. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78376. use default allocation functions.
  78377. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78378. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78379. all (the input data is simply copied a block at a time).
  78380. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78381. compression (currently equivalent to level 6).
  78382. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78383. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78384. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78385. with the version assumed by the caller (ZLIB_VERSION).
  78386. msg is set to null if there is no error message. deflateInit does not
  78387. perform any compression: this will be done by deflate().
  78388. */
  78389. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78390. /*
  78391. deflate compresses as much data as possible, and stops when the input
  78392. buffer becomes empty or the output buffer becomes full. It may introduce some
  78393. output latency (reading input without producing any output) except when
  78394. forced to flush.
  78395. The detailed semantics are as follows. deflate performs one or both of the
  78396. following actions:
  78397. - Compress more input starting at next_in and update next_in and avail_in
  78398. accordingly. If not all input can be processed (because there is not
  78399. enough room in the output buffer), next_in and avail_in are updated and
  78400. processing will resume at this point for the next call of deflate().
  78401. - Provide more output starting at next_out and update next_out and avail_out
  78402. accordingly. This action is forced if the parameter flush is non zero.
  78403. Forcing flush frequently degrades the compression ratio, so this parameter
  78404. should be set only when necessary (in interactive applications).
  78405. Some output may be provided even if flush is not set.
  78406. Before the call of deflate(), the application should ensure that at least
  78407. one of the actions is possible, by providing more input and/or consuming
  78408. more output, and updating avail_in or avail_out accordingly; avail_out
  78409. should never be zero before the call. The application can consume the
  78410. compressed output when it wants, for example when the output buffer is full
  78411. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78412. and with zero avail_out, it must be called again after making room in the
  78413. output buffer because there might be more output pending.
  78414. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78415. decide how much data to accumualte before producing output, in order to
  78416. maximize compression.
  78417. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78418. flushed to the output buffer and the output is aligned on a byte boundary, so
  78419. that the decompressor can get all input data available so far. (In particular
  78420. avail_in is zero after the call if enough output space has been provided
  78421. before the call.) Flushing may degrade compression for some compression
  78422. algorithms and so it should be used only when necessary.
  78423. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78424. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78425. restart from this point if previous compressed data has been damaged or if
  78426. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78427. compression.
  78428. If deflate returns with avail_out == 0, this function must be called again
  78429. with the same value of the flush parameter and more output space (updated
  78430. avail_out), until the flush is complete (deflate returns with non-zero
  78431. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78432. avail_out is greater than six to avoid repeated flush markers due to
  78433. avail_out == 0 on return.
  78434. If the parameter flush is set to Z_FINISH, pending input is processed,
  78435. pending output is flushed and deflate returns with Z_STREAM_END if there
  78436. was enough output space; if deflate returns with Z_OK, this function must be
  78437. called again with Z_FINISH and more output space (updated avail_out) but no
  78438. more input data, until it returns with Z_STREAM_END or an error. After
  78439. deflate has returned Z_STREAM_END, the only possible operations on the
  78440. stream are deflateReset or deflateEnd.
  78441. Z_FINISH can be used immediately after deflateInit if all the compression
  78442. is to be done in a single step. In this case, avail_out must be at least
  78443. the value returned by deflateBound (see below). If deflate does not return
  78444. Z_STREAM_END, then it must be called again as described above.
  78445. deflate() sets strm->adler to the adler32 checksum of all input read
  78446. so far (that is, total_in bytes).
  78447. deflate() may update strm->data_type if it can make a good guess about
  78448. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78449. binary. This field is only for information purposes and does not affect
  78450. the compression algorithm in any manner.
  78451. deflate() returns Z_OK if some progress has been made (more input
  78452. processed or more output produced), Z_STREAM_END if all input has been
  78453. consumed and all output has been produced (only when flush is set to
  78454. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78455. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78456. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78457. fatal, and deflate() can be called again with more input and more output
  78458. space to continue compressing.
  78459. */
  78460. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78461. /*
  78462. All dynamically allocated data structures for this stream are freed.
  78463. This function discards any unprocessed input and does not flush any
  78464. pending output.
  78465. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78466. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78467. prematurely (some input or output was discarded). In the error case,
  78468. msg may be set but then points to a static string (which must not be
  78469. deallocated).
  78470. */
  78471. /*
  78472. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78473. Initializes the internal stream state for decompression. The fields
  78474. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78475. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78476. value depends on the compression method), inflateInit determines the
  78477. compression method from the zlib header and allocates all data structures
  78478. accordingly; otherwise the allocation will be deferred to the first call of
  78479. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78480. use default allocation functions.
  78481. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78482. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78483. version assumed by the caller. msg is set to null if there is no error
  78484. message. inflateInit does not perform any decompression apart from reading
  78485. the zlib header if present: this will be done by inflate(). (So next_in and
  78486. avail_in may be modified, but next_out and avail_out are unchanged.)
  78487. */
  78488. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78489. /*
  78490. inflate decompresses as much data as possible, and stops when the input
  78491. buffer becomes empty or the output buffer becomes full. It may introduce
  78492. some output latency (reading input without producing any output) except when
  78493. forced to flush.
  78494. The detailed semantics are as follows. inflate performs one or both of the
  78495. following actions:
  78496. - Decompress more input starting at next_in and update next_in and avail_in
  78497. accordingly. If not all input can be processed (because there is not
  78498. enough room in the output buffer), next_in is updated and processing
  78499. will resume at this point for the next call of inflate().
  78500. - Provide more output starting at next_out and update next_out and avail_out
  78501. accordingly. inflate() provides as much output as possible, until there
  78502. is no more input data or no more space in the output buffer (see below
  78503. about the flush parameter).
  78504. Before the call of inflate(), the application should ensure that at least
  78505. one of the actions is possible, by providing more input and/or consuming
  78506. more output, and updating the next_* and avail_* values accordingly.
  78507. The application can consume the uncompressed output when it wants, for
  78508. example when the output buffer is full (avail_out == 0), or after each
  78509. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78510. must be called again after making room in the output buffer because there
  78511. might be more output pending.
  78512. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78513. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78514. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78515. if and when it gets to the next deflate block boundary. When decoding the
  78516. zlib or gzip format, this will cause inflate() to return immediately after
  78517. the header and before the first block. When doing a raw inflate, inflate()
  78518. will go ahead and process the first block, and will return when it gets to
  78519. the end of that block, or when it runs out of data.
  78520. The Z_BLOCK option assists in appending to or combining deflate streams.
  78521. Also to assist in this, on return inflate() will set strm->data_type to the
  78522. number of unused bits in the last byte taken from strm->next_in, plus 64
  78523. if inflate() is currently decoding the last block in the deflate stream,
  78524. plus 128 if inflate() returned immediately after decoding an end-of-block
  78525. code or decoding the complete header up to just before the first byte of the
  78526. deflate stream. The end-of-block will not be indicated until all of the
  78527. uncompressed data from that block has been written to strm->next_out. The
  78528. number of unused bits may in general be greater than seven, except when
  78529. bit 7 of data_type is set, in which case the number of unused bits will be
  78530. less than eight.
  78531. inflate() should normally be called until it returns Z_STREAM_END or an
  78532. error. However if all decompression is to be performed in a single step
  78533. (a single call of inflate), the parameter flush should be set to
  78534. Z_FINISH. In this case all pending input is processed and all pending
  78535. output is flushed; avail_out must be large enough to hold all the
  78536. uncompressed data. (The size of the uncompressed data may have been saved
  78537. by the compressor for this purpose.) The next operation on this stream must
  78538. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78539. is never required, but can be used to inform inflate that a faster approach
  78540. may be used for the single inflate() call.
  78541. In this implementation, inflate() always flushes as much output as
  78542. possible to the output buffer, and always uses the faster approach on the
  78543. first call. So the only effect of the flush parameter in this implementation
  78544. is on the return value of inflate(), as noted below, or when it returns early
  78545. because Z_BLOCK is used.
  78546. If a preset dictionary is needed after this call (see inflateSetDictionary
  78547. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78548. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78549. strm->adler to the adler32 checksum of all output produced so far (that is,
  78550. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78551. below. At the end of the stream, inflate() checks that its computed adler32
  78552. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78553. only if the checksum is correct.
  78554. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78555. deflate data. The header type is detected automatically. Any information
  78556. contained in the gzip header is not retained, so applications that need that
  78557. information should instead use raw inflate, see inflateInit2() below, or
  78558. inflateBack() and perform their own processing of the gzip header and
  78559. trailer.
  78560. inflate() returns Z_OK if some progress has been made (more input processed
  78561. or more output produced), Z_STREAM_END if the end of the compressed data has
  78562. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78563. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78564. corrupted (input stream not conforming to the zlib format or incorrect check
  78565. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78566. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78567. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78568. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78569. inflate() can be called again with more input and more output space to
  78570. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78571. call inflateSync() to look for a good compression block if a partial recovery
  78572. of the data is desired.
  78573. */
  78574. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78575. /*
  78576. All dynamically allocated data structures for this stream are freed.
  78577. This function discards any unprocessed input and does not flush any
  78578. pending output.
  78579. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78580. was inconsistent. In the error case, msg may be set but then points to a
  78581. static string (which must not be deallocated).
  78582. */
  78583. /* Advanced functions */
  78584. /*
  78585. The following functions are needed only in some special applications.
  78586. */
  78587. /*
  78588. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78589. int level,
  78590. int method,
  78591. int windowBits,
  78592. int memLevel,
  78593. int strategy));
  78594. This is another version of deflateInit with more compression options. The
  78595. fields next_in, zalloc, zfree and opaque must be initialized before by
  78596. the caller.
  78597. The method parameter is the compression method. It must be Z_DEFLATED in
  78598. this version of the library.
  78599. The windowBits parameter is the base two logarithm of the window size
  78600. (the size of the history buffer). It should be in the range 8..15 for this
  78601. version of the library. Larger values of this parameter result in better
  78602. compression at the expense of memory usage. The default value is 15 if
  78603. deflateInit is used instead.
  78604. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78605. determines the window size. deflate() will then generate raw deflate data
  78606. with no zlib header or trailer, and will not compute an adler32 check value.
  78607. windowBits can also be greater than 15 for optional gzip encoding. Add
  78608. 16 to windowBits to write a simple gzip header and trailer around the
  78609. compressed data instead of a zlib wrapper. The gzip header will have no
  78610. file name, no extra data, no comment, no modification time (set to zero),
  78611. no header crc, and the operating system will be set to 255 (unknown). If a
  78612. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78613. The memLevel parameter specifies how much memory should be allocated
  78614. for the internal compression state. memLevel=1 uses minimum memory but
  78615. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78616. for optimal speed. The default value is 8. See zconf.h for total memory
  78617. usage as a function of windowBits and memLevel.
  78618. The strategy parameter is used to tune the compression algorithm. Use the
  78619. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78620. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78621. string match), or Z_RLE to limit match distances to one (run-length
  78622. encoding). Filtered data consists mostly of small values with a somewhat
  78623. random distribution. In this case, the compression algorithm is tuned to
  78624. compress them better. The effect of Z_FILTERED is to force more Huffman
  78625. coding and less string matching; it is somewhat intermediate between
  78626. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78627. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78628. parameter only affects the compression ratio but not the correctness of the
  78629. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78630. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78631. applications.
  78632. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78633. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78634. method). msg is set to null if there is no error message. deflateInit2 does
  78635. not perform any compression: this will be done by deflate().
  78636. */
  78637. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78638. const Bytef *dictionary,
  78639. uInt dictLength));
  78640. /*
  78641. Initializes the compression dictionary from the given byte sequence
  78642. without producing any compressed output. This function must be called
  78643. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78644. call of deflate. The compressor and decompressor must use exactly the same
  78645. dictionary (see inflateSetDictionary).
  78646. The dictionary should consist of strings (byte sequences) that are likely
  78647. to be encountered later in the data to be compressed, with the most commonly
  78648. used strings preferably put towards the end of the dictionary. Using a
  78649. dictionary is most useful when the data to be compressed is short and can be
  78650. predicted with good accuracy; the data can then be compressed better than
  78651. with the default empty dictionary.
  78652. Depending on the size of the compression data structures selected by
  78653. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78654. discarded, for example if the dictionary is larger than the window size in
  78655. deflate or deflate2. Thus the strings most likely to be useful should be
  78656. put at the end of the dictionary, not at the front. In addition, the
  78657. current implementation of deflate will use at most the window size minus
  78658. 262 bytes of the provided dictionary.
  78659. Upon return of this function, strm->adler is set to the adler32 value
  78660. of the dictionary; the decompressor may later use this value to determine
  78661. which dictionary has been used by the compressor. (The adler32 value
  78662. applies to the whole dictionary even if only a subset of the dictionary is
  78663. actually used by the compressor.) If a raw deflate was requested, then the
  78664. adler32 value is not computed and strm->adler is not set.
  78665. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78666. parameter is invalid (such as NULL dictionary) or the stream state is
  78667. inconsistent (for example if deflate has already been called for this stream
  78668. or if the compression method is bsort). deflateSetDictionary does not
  78669. perform any compression: this will be done by deflate().
  78670. */
  78671. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78672. z_streamp source));
  78673. /*
  78674. Sets the destination stream as a complete copy of the source stream.
  78675. This function can be useful when several compression strategies will be
  78676. tried, for example when there are several ways of pre-processing the input
  78677. data with a filter. The streams that will be discarded should then be freed
  78678. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78679. compression state which can be quite large, so this strategy is slow and
  78680. can consume lots of memory.
  78681. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78682. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78683. (such as zalloc being NULL). msg is left unchanged in both source and
  78684. destination.
  78685. */
  78686. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78687. /*
  78688. This function is equivalent to deflateEnd followed by deflateInit,
  78689. but does not free and reallocate all the internal compression state.
  78690. The stream will keep the same compression level and any other attributes
  78691. that may have been set by deflateInit2.
  78692. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78693. stream state was inconsistent (such as zalloc or state being NULL).
  78694. */
  78695. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78696. int level,
  78697. int strategy));
  78698. /*
  78699. Dynamically update the compression level and compression strategy. The
  78700. interpretation of level and strategy is as in deflateInit2. This can be
  78701. used to switch between compression and straight copy of the input data, or
  78702. to switch to a different kind of input data requiring a different
  78703. strategy. If the compression level is changed, the input available so far
  78704. is compressed with the old level (and may be flushed); the new level will
  78705. take effect only at the next call of deflate().
  78706. Before the call of deflateParams, the stream state must be set as for
  78707. a call of deflate(), since the currently available input may have to
  78708. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78709. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78710. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78711. if strm->avail_out was zero.
  78712. */
  78713. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78714. int good_length,
  78715. int max_lazy,
  78716. int nice_length,
  78717. int max_chain));
  78718. /*
  78719. Fine tune deflate's internal compression parameters. This should only be
  78720. used by someone who understands the algorithm used by zlib's deflate for
  78721. searching for the best matching string, and even then only by the most
  78722. fanatic optimizer trying to squeeze out the last compressed bit for their
  78723. specific input data. Read the deflate.c source code for the meaning of the
  78724. max_lazy, good_length, nice_length, and max_chain parameters.
  78725. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78726. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78727. */
  78728. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78729. uLong sourceLen));
  78730. /*
  78731. deflateBound() returns an upper bound on the compressed size after
  78732. deflation of sourceLen bytes. It must be called after deflateInit()
  78733. or deflateInit2(). This would be used to allocate an output buffer
  78734. for deflation in a single pass, and so would be called before deflate().
  78735. */
  78736. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78737. int bits,
  78738. int value));
  78739. /*
  78740. deflatePrime() inserts bits in the deflate output stream. The intent
  78741. is that this function is used to start off the deflate output with the
  78742. bits leftover from a previous deflate stream when appending to it. As such,
  78743. this function can only be used for raw deflate, and must be used before the
  78744. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78745. less than or equal to 16, and that many of the least significant bits of
  78746. value will be inserted in the output.
  78747. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78748. stream state was inconsistent.
  78749. */
  78750. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78751. gz_headerp head));
  78752. /*
  78753. deflateSetHeader() provides gzip header information for when a gzip
  78754. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78755. after deflateInit2() or deflateReset() and before the first call of
  78756. deflate(). The text, time, os, extra field, name, and comment information
  78757. in the provided gz_header structure are written to the gzip header (xflag is
  78758. ignored -- the extra flags are set according to the compression level). The
  78759. caller must assure that, if not Z_NULL, name and comment are terminated with
  78760. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78761. available there. If hcrc is true, a gzip header crc is included. Note that
  78762. the current versions of the command-line version of gzip (up through version
  78763. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78764. gzip file" and give up.
  78765. If deflateSetHeader is not used, the default gzip header has text false,
  78766. the time set to zero, and os set to 255, with no extra, name, or comment
  78767. fields. The gzip header is returned to the default state by deflateReset().
  78768. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78769. stream state was inconsistent.
  78770. */
  78771. /*
  78772. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78773. int windowBits));
  78774. This is another version of inflateInit with an extra parameter. The
  78775. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78776. before by the caller.
  78777. The windowBits parameter is the base two logarithm of the maximum window
  78778. size (the size of the history buffer). It should be in the range 8..15 for
  78779. this version of the library. The default value is 15 if inflateInit is used
  78780. instead. windowBits must be greater than or equal to the windowBits value
  78781. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78782. deflateInit2() was not used. If a compressed stream with a larger window
  78783. size is given as input, inflate() will return with the error code
  78784. Z_DATA_ERROR instead of trying to allocate a larger window.
  78785. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78786. determines the window size. inflate() will then process raw deflate data,
  78787. not looking for a zlib or gzip header, not generating a check value, and not
  78788. looking for any check values for comparison at the end of the stream. This
  78789. is for use with other formats that use the deflate compressed data format
  78790. such as zip. Those formats provide their own check values. If a custom
  78791. format is developed using the raw deflate format for compressed data, it is
  78792. recommended that a check value such as an adler32 or a crc32 be applied to
  78793. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78794. most applications, the zlib format should be used as is. Note that comments
  78795. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78796. windowBits can also be greater than 15 for optional gzip decoding. Add
  78797. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78798. detection, or add 16 to decode only the gzip format (the zlib format will
  78799. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78800. a crc32 instead of an adler32.
  78801. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78802. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78803. is set to null if there is no error message. inflateInit2 does not perform
  78804. any decompression apart from reading the zlib header if present: this will
  78805. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78806. and avail_out are unchanged.)
  78807. */
  78808. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78809. const Bytef *dictionary,
  78810. uInt dictLength));
  78811. /*
  78812. Initializes the decompression dictionary from the given uncompressed byte
  78813. sequence. This function must be called immediately after a call of inflate,
  78814. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78815. can be determined from the adler32 value returned by that call of inflate.
  78816. The compressor and decompressor must use exactly the same dictionary (see
  78817. deflateSetDictionary). For raw inflate, this function can be called
  78818. immediately after inflateInit2() or inflateReset() and before any call of
  78819. inflate() to set the dictionary. The application must insure that the
  78820. dictionary that was used for compression is provided.
  78821. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78822. parameter is invalid (such as NULL dictionary) or the stream state is
  78823. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78824. expected one (incorrect adler32 value). inflateSetDictionary does not
  78825. perform any decompression: this will be done by subsequent calls of
  78826. inflate().
  78827. */
  78828. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78829. /*
  78830. Skips invalid compressed data until a full flush point (see above the
  78831. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78832. available input is skipped. No output is provided.
  78833. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78834. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78835. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78836. case, the application may save the current current value of total_in which
  78837. indicates where valid compressed data was found. In the error case, the
  78838. application may repeatedly call inflateSync, providing more input each time,
  78839. until success or end of the input data.
  78840. */
  78841. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78842. z_streamp source));
  78843. /*
  78844. Sets the destination stream as a complete copy of the source stream.
  78845. This function can be useful when randomly accessing a large stream. The
  78846. first pass through the stream can periodically record the inflate state,
  78847. allowing restarting inflate at those points when randomly accessing the
  78848. stream.
  78849. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78850. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78851. (such as zalloc being NULL). msg is left unchanged in both source and
  78852. destination.
  78853. */
  78854. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78855. /*
  78856. This function is equivalent to inflateEnd followed by inflateInit,
  78857. but does not free and reallocate all the internal decompression state.
  78858. The stream will keep attributes that may have been set by inflateInit2.
  78859. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78860. stream state was inconsistent (such as zalloc or state being NULL).
  78861. */
  78862. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78863. int bits,
  78864. int value));
  78865. /*
  78866. This function inserts bits in the inflate input stream. The intent is
  78867. that this function is used to start inflating at a bit position in the
  78868. middle of a byte. The provided bits will be used before any bytes are used
  78869. from next_in. This function should only be used with raw inflate, and
  78870. should be used before the first inflate() call after inflateInit2() or
  78871. inflateReset(). bits must be less than or equal to 16, and that many of the
  78872. least significant bits of value will be inserted in the input.
  78873. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78874. stream state was inconsistent.
  78875. */
  78876. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78877. gz_headerp head));
  78878. /*
  78879. inflateGetHeader() requests that gzip header information be stored in the
  78880. provided gz_header structure. inflateGetHeader() may be called after
  78881. inflateInit2() or inflateReset(), and before the first call of inflate().
  78882. As inflate() processes the gzip stream, head->done is zero until the header
  78883. is completed, at which time head->done is set to one. If a zlib stream is
  78884. being decoded, then head->done is set to -1 to indicate that there will be
  78885. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78886. force inflate() to return immediately after header processing is complete
  78887. and before any actual data is decompressed.
  78888. The text, time, xflags, and os fields are filled in with the gzip header
  78889. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78890. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78891. contains the maximum number of bytes to write to extra. Once done is true,
  78892. extra_len contains the actual extra field length, and extra contains the
  78893. extra field, or that field truncated if extra_max is less than extra_len.
  78894. If name is not Z_NULL, then up to name_max characters are written there,
  78895. terminated with a zero unless the length is greater than name_max. If
  78896. comment is not Z_NULL, then up to comm_max characters are written there,
  78897. terminated with a zero unless the length is greater than comm_max. When
  78898. any of extra, name, or comment are not Z_NULL and the respective field is
  78899. not present in the header, then that field is set to Z_NULL to signal its
  78900. absence. This allows the use of deflateSetHeader() with the returned
  78901. structure to duplicate the header. However if those fields are set to
  78902. allocated memory, then the application will need to save those pointers
  78903. elsewhere so that they can be eventually freed.
  78904. If inflateGetHeader is not used, then the header information is simply
  78905. discarded. The header is always checked for validity, including the header
  78906. CRC if present. inflateReset() will reset the process to discard the header
  78907. information. The application would need to call inflateGetHeader() again to
  78908. retrieve the header from the next gzip stream.
  78909. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78910. stream state was inconsistent.
  78911. */
  78912. /*
  78913. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78914. unsigned char FAR *window));
  78915. Initialize the internal stream state for decompression using inflateBack()
  78916. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78917. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78918. derived memory allocation routines are used. windowBits is the base two
  78919. logarithm of the window size, in the range 8..15. window is a caller
  78920. supplied buffer of that size. Except for special applications where it is
  78921. assured that deflate was used with small window sizes, windowBits must be 15
  78922. and a 32K byte window must be supplied to be able to decompress general
  78923. deflate streams.
  78924. See inflateBack() for the usage of these routines.
  78925. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78926. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78927. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78928. match the version of the header file.
  78929. */
  78930. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78931. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78932. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78933. in_func in, void FAR *in_desc,
  78934. out_func out, void FAR *out_desc));
  78935. /*
  78936. inflateBack() does a raw inflate with a single call using a call-back
  78937. interface for input and output. This is more efficient than inflate() for
  78938. file i/o applications in that it avoids copying between the output and the
  78939. sliding window by simply making the window itself the output buffer. This
  78940. function trusts the application to not change the output buffer passed by
  78941. the output function, at least until inflateBack() returns.
  78942. inflateBackInit() must be called first to allocate the internal state
  78943. and to initialize the state with the user-provided window buffer.
  78944. inflateBack() may then be used multiple times to inflate a complete, raw
  78945. deflate stream with each call. inflateBackEnd() is then called to free
  78946. the allocated state.
  78947. A raw deflate stream is one with no zlib or gzip header or trailer.
  78948. This routine would normally be used in a utility that reads zip or gzip
  78949. files and writes out uncompressed files. The utility would decode the
  78950. header and process the trailer on its own, hence this routine expects
  78951. only the raw deflate stream to decompress. This is different from the
  78952. normal behavior of inflate(), which expects either a zlib or gzip header and
  78953. trailer around the deflate stream.
  78954. inflateBack() uses two subroutines supplied by the caller that are then
  78955. called by inflateBack() for input and output. inflateBack() calls those
  78956. routines until it reads a complete deflate stream and writes out all of the
  78957. uncompressed data, or until it encounters an error. The function's
  78958. parameters and return types are defined above in the in_func and out_func
  78959. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78960. number of bytes of provided input, and a pointer to that input in buf. If
  78961. there is no input available, in() must return zero--buf is ignored in that
  78962. case--and inflateBack() will return a buffer error. inflateBack() will call
  78963. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78964. should return zero on success, or non-zero on failure. If out() returns
  78965. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78966. are permitted to change the contents of the window provided to
  78967. inflateBackInit(), which is also the buffer that out() uses to write from.
  78968. The length written by out() will be at most the window size. Any non-zero
  78969. amount of input may be provided by in().
  78970. For convenience, inflateBack() can be provided input on the first call by
  78971. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78972. in() will be called. Therefore strm->next_in must be initialized before
  78973. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78974. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78975. must also be initialized, and then if strm->avail_in is not zero, input will
  78976. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78977. The in_desc and out_desc parameters of inflateBack() is passed as the
  78978. first parameter of in() and out() respectively when they are called. These
  78979. descriptors can be optionally used to pass any information that the caller-
  78980. supplied in() and out() functions need to do their job.
  78981. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78982. pass back any unused input that was provided by the last in() call. The
  78983. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78984. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78985. error in the deflate stream (in which case strm->msg is set to indicate the
  78986. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78987. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78988. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78989. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78990. out() returning non-zero. (in() will always be called before out(), so
  78991. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78992. that inflateBack() cannot return Z_OK.
  78993. */
  78994. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78995. /*
  78996. All memory allocated by inflateBackInit() is freed.
  78997. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78998. state was inconsistent.
  78999. */
  79000. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79001. /* Return flags indicating compile-time options.
  79002. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79003. 1.0: size of uInt
  79004. 3.2: size of uLong
  79005. 5.4: size of voidpf (pointer)
  79006. 7.6: size of z_off_t
  79007. Compiler, assembler, and debug options:
  79008. 8: DEBUG
  79009. 9: ASMV or ASMINF -- use ASM code
  79010. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79011. 11: 0 (reserved)
  79012. One-time table building (smaller code, but not thread-safe if true):
  79013. 12: BUILDFIXED -- build static block decoding tables when needed
  79014. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79015. 14,15: 0 (reserved)
  79016. Library content (indicates missing functionality):
  79017. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79018. deflate code when not needed)
  79019. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79020. and decode gzip streams (to avoid linking crc code)
  79021. 18-19: 0 (reserved)
  79022. Operation variations (changes in library functionality):
  79023. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79024. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79025. 22,23: 0 (reserved)
  79026. The sprintf variant used by gzprintf (zero is best):
  79027. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79028. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79029. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79030. Remainder:
  79031. 27-31: 0 (reserved)
  79032. */
  79033. /* utility functions */
  79034. /*
  79035. The following utility functions are implemented on top of the
  79036. basic stream-oriented functions. To simplify the interface, some
  79037. default options are assumed (compression level and memory usage,
  79038. standard memory allocation functions). The source code of these
  79039. utility functions can easily be modified if you need special options.
  79040. */
  79041. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79042. const Bytef *source, uLong sourceLen));
  79043. /*
  79044. Compresses the source buffer into the destination buffer. sourceLen is
  79045. the byte length of the source buffer. Upon entry, destLen is the total
  79046. size of the destination buffer, which must be at least the value returned
  79047. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79048. compressed buffer.
  79049. This function can be used to compress a whole file at once if the
  79050. input file is mmap'ed.
  79051. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79052. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79053. buffer.
  79054. */
  79055. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79056. const Bytef *source, uLong sourceLen,
  79057. int level));
  79058. /*
  79059. Compresses the source buffer into the destination buffer. The level
  79060. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79061. length of the source buffer. Upon entry, destLen is the total size of the
  79062. destination buffer, which must be at least the value returned by
  79063. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79064. compressed buffer.
  79065. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79066. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79067. Z_STREAM_ERROR if the level parameter is invalid.
  79068. */
  79069. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79070. /*
  79071. compressBound() returns an upper bound on the compressed size after
  79072. compress() or compress2() on sourceLen bytes. It would be used before
  79073. a compress() or compress2() call to allocate the destination buffer.
  79074. */
  79075. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79076. const Bytef *source, uLong sourceLen));
  79077. /*
  79078. Decompresses the source buffer into the destination buffer. sourceLen is
  79079. the byte length of the source buffer. Upon entry, destLen is the total
  79080. size of the destination buffer, which must be large enough to hold the
  79081. entire uncompressed data. (The size of the uncompressed data must have
  79082. been saved previously by the compressor and transmitted to the decompressor
  79083. by some mechanism outside the scope of this compression library.)
  79084. Upon exit, destLen is the actual size of the compressed buffer.
  79085. This function can be used to decompress a whole file at once if the
  79086. input file is mmap'ed.
  79087. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79088. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79089. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79090. */
  79091. typedef voidp gzFile;
  79092. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79093. /*
  79094. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79095. is as in fopen ("rb" or "wb") but can also include a compression level
  79096. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79097. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79098. as in "wb1R". (See the description of deflateInit2 for more information
  79099. about the strategy parameter.)
  79100. gzopen can be used to read a file which is not in gzip format; in this
  79101. case gzread will directly read from the file without decompression.
  79102. gzopen returns NULL if the file could not be opened or if there was
  79103. insufficient memory to allocate the (de)compression state; errno
  79104. can be checked to distinguish the two cases (if errno is zero, the
  79105. zlib error is Z_MEM_ERROR). */
  79106. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79107. /*
  79108. gzdopen() associates a gzFile with the file descriptor fd. File
  79109. descriptors are obtained from calls like open, dup, creat, pipe or
  79110. fileno (in the file has been previously opened with fopen).
  79111. The mode parameter is as in gzopen.
  79112. The next call of gzclose on the returned gzFile will also close the
  79113. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79114. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79115. gzdopen returns NULL if there was insufficient memory to allocate
  79116. the (de)compression state.
  79117. */
  79118. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79119. /*
  79120. Dynamically update the compression level or strategy. See the description
  79121. of deflateInit2 for the meaning of these parameters.
  79122. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79123. opened for writing.
  79124. */
  79125. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79126. /*
  79127. Reads the given number of uncompressed bytes from the compressed file.
  79128. If the input file was not in gzip format, gzread copies the given number
  79129. of bytes into the buffer.
  79130. gzread returns the number of uncompressed bytes actually read (0 for
  79131. end of file, -1 for error). */
  79132. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79133. voidpc buf, unsigned len));
  79134. /*
  79135. Writes the given number of uncompressed bytes into the compressed file.
  79136. gzwrite returns the number of uncompressed bytes actually written
  79137. (0 in case of error).
  79138. */
  79139. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79140. /*
  79141. Converts, formats, and writes the args to the compressed file under
  79142. control of the format string, as in fprintf. gzprintf returns the number of
  79143. uncompressed bytes actually written (0 in case of error). The number of
  79144. uncompressed bytes written is limited to 4095. The caller should assure that
  79145. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79146. return an error (0) with nothing written. In this case, there may also be a
  79147. buffer overflow with unpredictable consequences, which is possible only if
  79148. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79149. because the secure snprintf() or vsnprintf() functions were not available.
  79150. */
  79151. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79152. /*
  79153. Writes the given null-terminated string to the compressed file, excluding
  79154. the terminating null character.
  79155. gzputs returns the number of characters written, or -1 in case of error.
  79156. */
  79157. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79158. /*
  79159. Reads bytes from the compressed file until len-1 characters are read, or
  79160. a newline character is read and transferred to buf, or an end-of-file
  79161. condition is encountered. The string is then terminated with a null
  79162. character.
  79163. gzgets returns buf, or Z_NULL in case of error.
  79164. */
  79165. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79166. /*
  79167. Writes c, converted to an unsigned char, into the compressed file.
  79168. gzputc returns the value that was written, or -1 in case of error.
  79169. */
  79170. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79171. /*
  79172. Reads one byte from the compressed file. gzgetc returns this byte
  79173. or -1 in case of end of file or error.
  79174. */
  79175. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79176. /*
  79177. Push one character back onto the stream to be read again later.
  79178. Only one character of push-back is allowed. gzungetc() returns the
  79179. character pushed, or -1 on failure. gzungetc() will fail if a
  79180. character has been pushed but not read yet, or if c is -1. The pushed
  79181. character will be discarded if the stream is repositioned with gzseek()
  79182. or gzrewind().
  79183. */
  79184. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79185. /*
  79186. Flushes all pending output into the compressed file. The parameter
  79187. flush is as in the deflate() function. The return value is the zlib
  79188. error number (see function gzerror below). gzflush returns Z_OK if
  79189. the flush parameter is Z_FINISH and all output could be flushed.
  79190. gzflush should be called only when strictly necessary because it can
  79191. degrade compression.
  79192. */
  79193. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79194. z_off_t offset, int whence));
  79195. /*
  79196. Sets the starting position for the next gzread or gzwrite on the
  79197. given compressed file. The offset represents a number of bytes in the
  79198. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79199. the value SEEK_END is not supported.
  79200. If the file is opened for reading, this function is emulated but can be
  79201. extremely slow. If the file is opened for writing, only forward seeks are
  79202. supported; gzseek then compresses a sequence of zeroes up to the new
  79203. starting position.
  79204. gzseek returns the resulting offset location as measured in bytes from
  79205. the beginning of the uncompressed stream, or -1 in case of error, in
  79206. particular if the file is opened for writing and the new starting position
  79207. would be before the current position.
  79208. */
  79209. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79210. /*
  79211. Rewinds the given file. This function is supported only for reading.
  79212. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79213. */
  79214. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79215. /*
  79216. Returns the starting position for the next gzread or gzwrite on the
  79217. given compressed file. This position represents a number of bytes in the
  79218. uncompressed data stream.
  79219. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79220. */
  79221. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79222. /*
  79223. Returns 1 when EOF has previously been detected reading the given
  79224. input stream, otherwise zero.
  79225. */
  79226. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79227. /*
  79228. Returns 1 if file is being read directly without decompression, otherwise
  79229. zero.
  79230. */
  79231. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79232. /*
  79233. Flushes all pending output if necessary, closes the compressed file
  79234. and deallocates all the (de)compression state. The return value is the zlib
  79235. error number (see function gzerror below).
  79236. */
  79237. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79238. /*
  79239. Returns the error message for the last error which occurred on the
  79240. given compressed file. errnum is set to zlib error number. If an
  79241. error occurred in the file system and not in the compression library,
  79242. errnum is set to Z_ERRNO and the application may consult errno
  79243. to get the exact error code.
  79244. */
  79245. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79246. /*
  79247. Clears the error and end-of-file flags for file. This is analogous to the
  79248. clearerr() function in stdio. This is useful for continuing to read a gzip
  79249. file that is being written concurrently.
  79250. */
  79251. /* checksum functions */
  79252. /*
  79253. These functions are not related to compression but are exported
  79254. anyway because they might be useful in applications using the
  79255. compression library.
  79256. */
  79257. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79258. /*
  79259. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79260. return the updated checksum. If buf is NULL, this function returns
  79261. the required initial value for the checksum.
  79262. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79263. much faster. Usage example:
  79264. uLong adler = adler32(0L, Z_NULL, 0);
  79265. while (read_buffer(buffer, length) != EOF) {
  79266. adler = adler32(adler, buffer, length);
  79267. }
  79268. if (adler != original_adler) error();
  79269. */
  79270. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79271. z_off_t len2));
  79272. /*
  79273. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79274. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79275. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79276. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79277. */
  79278. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79279. /*
  79280. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79281. updated CRC-32. If buf is NULL, this function returns the required initial
  79282. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79283. performed within this function so it shouldn't be done by the application.
  79284. Usage example:
  79285. uLong crc = crc32(0L, Z_NULL, 0);
  79286. while (read_buffer(buffer, length) != EOF) {
  79287. crc = crc32(crc, buffer, length);
  79288. }
  79289. if (crc != original_crc) error();
  79290. */
  79291. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79292. /*
  79293. Combine two CRC-32 check values into one. For two sequences of bytes,
  79294. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79295. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79296. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79297. len2.
  79298. */
  79299. /* various hacks, don't look :) */
  79300. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79301. * and the compiler's view of z_stream:
  79302. */
  79303. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79304. const char *version, int stream_size));
  79305. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79306. const char *version, int stream_size));
  79307. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79308. int windowBits, int memLevel,
  79309. int strategy, const char *version,
  79310. int stream_size));
  79311. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79312. const char *version, int stream_size));
  79313. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79314. unsigned char FAR *window,
  79315. const char *version,
  79316. int stream_size));
  79317. #define deflateInit(strm, level) \
  79318. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79319. #define inflateInit(strm) \
  79320. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79321. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79322. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79323. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79324. #define inflateInit2(strm, windowBits) \
  79325. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79326. #define inflateBackInit(strm, windowBits, window) \
  79327. inflateBackInit_((strm), (windowBits), (window), \
  79328. ZLIB_VERSION, sizeof(z_stream))
  79329. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79330. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79331. #endif
  79332. ZEXTERN const char * ZEXPORT zError OF((int));
  79333. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79334. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79335. #ifdef __cplusplus
  79336. //}
  79337. #endif
  79338. #endif /* ZLIB_H */
  79339. /*** End of inlined file: zlib.h ***/
  79340. #undef OS_CODE
  79341. #else
  79342. #include <zlib.h>
  79343. #endif
  79344. }
  79345. BEGIN_JUCE_NAMESPACE
  79346. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79347. {
  79348. public:
  79349. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79350. : data (0),
  79351. dataSize (0),
  79352. compLevel (compressionLevel),
  79353. strategy (0),
  79354. setParams (true),
  79355. streamIsValid (false),
  79356. finished (false),
  79357. shouldFinish (false)
  79358. {
  79359. using namespace zlibNamespace;
  79360. zerostruct (stream);
  79361. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79362. windowBits != 0 ? windowBits : MAX_WBITS,
  79363. 8, strategy) == Z_OK);
  79364. }
  79365. ~GZIPCompressorHelper()
  79366. {
  79367. using namespace zlibNamespace;
  79368. if (streamIsValid)
  79369. deflateEnd (&stream);
  79370. }
  79371. bool needsInput() const throw()
  79372. {
  79373. return dataSize <= 0;
  79374. }
  79375. void setInput (const uint8* const newData, const int size) throw()
  79376. {
  79377. data = newData;
  79378. dataSize = size;
  79379. }
  79380. int doNextBlock (uint8* const dest, const int destSize) throw()
  79381. {
  79382. using namespace zlibNamespace;
  79383. if (streamIsValid)
  79384. {
  79385. stream.next_in = const_cast <uint8*> (data);
  79386. stream.next_out = dest;
  79387. stream.avail_in = dataSize;
  79388. stream.avail_out = destSize;
  79389. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79390. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79391. setParams = false;
  79392. switch (result)
  79393. {
  79394. case Z_STREAM_END:
  79395. finished = true;
  79396. // Deliberate fall-through..
  79397. case Z_OK:
  79398. data += dataSize - stream.avail_in;
  79399. dataSize = stream.avail_in;
  79400. return destSize - stream.avail_out;
  79401. default:
  79402. break;
  79403. }
  79404. }
  79405. return 0;
  79406. }
  79407. enum { gzipCompBufferSize = 32768 };
  79408. private:
  79409. zlibNamespace::z_stream stream;
  79410. const uint8* data;
  79411. int dataSize, compLevel, strategy;
  79412. bool setParams, streamIsValid;
  79413. public:
  79414. bool finished, shouldFinish;
  79415. };
  79416. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79417. int compressionLevel,
  79418. const bool deleteDestStream,
  79419. const int windowBits)
  79420. : destStream (destStream_),
  79421. streamToDelete (deleteDestStream ? destStream_ : 0),
  79422. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79423. {
  79424. if (compressionLevel < 1 || compressionLevel > 9)
  79425. compressionLevel = -1;
  79426. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79427. }
  79428. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79429. {
  79430. flush();
  79431. }
  79432. void GZIPCompressorOutputStream::flush()
  79433. {
  79434. if (! helper->finished)
  79435. {
  79436. helper->shouldFinish = true;
  79437. while (! helper->finished)
  79438. doNextBlock();
  79439. }
  79440. destStream->flush();
  79441. }
  79442. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79443. {
  79444. if (! helper->finished)
  79445. {
  79446. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79447. while (! helper->needsInput())
  79448. {
  79449. if (! doNextBlock())
  79450. return false;
  79451. }
  79452. }
  79453. return true;
  79454. }
  79455. bool GZIPCompressorOutputStream::doNextBlock()
  79456. {
  79457. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79458. return len <= 0 || destStream->write (buffer, len);
  79459. }
  79460. int64 GZIPCompressorOutputStream::getPosition()
  79461. {
  79462. return destStream->getPosition();
  79463. }
  79464. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79465. {
  79466. jassertfalse; // can't do it!
  79467. return false;
  79468. }
  79469. END_JUCE_NAMESPACE
  79470. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79471. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79472. #if JUCE_MSVC
  79473. #pragma warning (push)
  79474. #pragma warning (disable: 4309 4305)
  79475. #endif
  79476. namespace zlibNamespace
  79477. {
  79478. #if JUCE_INCLUDE_ZLIB_CODE
  79479. #undef OS_CODE
  79480. #undef fdopen
  79481. #define ZLIB_INTERNAL
  79482. #define NO_DUMMY_DECL
  79483. /*** Start of inlined file: adler32.c ***/
  79484. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79485. #define ZLIB_INTERNAL
  79486. #define BASE 65521UL /* largest prime smaller than 65536 */
  79487. #define NMAX 5552
  79488. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79489. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79490. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79491. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79492. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79493. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79494. /* use NO_DIVIDE if your processor does not do division in hardware */
  79495. #ifdef NO_DIVIDE
  79496. # define MOD(a) \
  79497. do { \
  79498. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79499. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79500. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79501. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79502. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79503. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79504. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79505. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79506. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79507. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79508. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79509. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79510. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79511. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79512. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79513. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79514. if (a >= BASE) a -= BASE; \
  79515. } while (0)
  79516. # define MOD4(a) \
  79517. do { \
  79518. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79519. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79520. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79521. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79522. if (a >= BASE) a -= BASE; \
  79523. } while (0)
  79524. #else
  79525. # define MOD(a) a %= BASE
  79526. # define MOD4(a) a %= BASE
  79527. #endif
  79528. /* ========================================================================= */
  79529. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79530. {
  79531. unsigned long sum2;
  79532. unsigned n;
  79533. /* split Adler-32 into component sums */
  79534. sum2 = (adler >> 16) & 0xffff;
  79535. adler &= 0xffff;
  79536. /* in case user likes doing a byte at a time, keep it fast */
  79537. if (len == 1) {
  79538. adler += buf[0];
  79539. if (adler >= BASE)
  79540. adler -= BASE;
  79541. sum2 += adler;
  79542. if (sum2 >= BASE)
  79543. sum2 -= BASE;
  79544. return adler | (sum2 << 16);
  79545. }
  79546. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79547. if (buf == Z_NULL)
  79548. return 1L;
  79549. /* in case short lengths are provided, keep it somewhat fast */
  79550. if (len < 16) {
  79551. while (len--) {
  79552. adler += *buf++;
  79553. sum2 += adler;
  79554. }
  79555. if (adler >= BASE)
  79556. adler -= BASE;
  79557. MOD4(sum2); /* only added so many BASE's */
  79558. return adler | (sum2 << 16);
  79559. }
  79560. /* do length NMAX blocks -- requires just one modulo operation */
  79561. while (len >= NMAX) {
  79562. len -= NMAX;
  79563. n = NMAX / 16; /* NMAX is divisible by 16 */
  79564. do {
  79565. DO16(buf); /* 16 sums unrolled */
  79566. buf += 16;
  79567. } while (--n);
  79568. MOD(adler);
  79569. MOD(sum2);
  79570. }
  79571. /* do remaining bytes (less than NMAX, still just one modulo) */
  79572. if (len) { /* avoid modulos if none remaining */
  79573. while (len >= 16) {
  79574. len -= 16;
  79575. DO16(buf);
  79576. buf += 16;
  79577. }
  79578. while (len--) {
  79579. adler += *buf++;
  79580. sum2 += adler;
  79581. }
  79582. MOD(adler);
  79583. MOD(sum2);
  79584. }
  79585. /* return recombined sums */
  79586. return adler | (sum2 << 16);
  79587. }
  79588. /* ========================================================================= */
  79589. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79590. {
  79591. unsigned long sum1;
  79592. unsigned long sum2;
  79593. unsigned rem;
  79594. /* the derivation of this formula is left as an exercise for the reader */
  79595. rem = (unsigned)(len2 % BASE);
  79596. sum1 = adler1 & 0xffff;
  79597. sum2 = rem * sum1;
  79598. MOD(sum2);
  79599. sum1 += (adler2 & 0xffff) + BASE - 1;
  79600. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79601. if (sum1 > BASE) sum1 -= BASE;
  79602. if (sum1 > BASE) sum1 -= BASE;
  79603. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79604. if (sum2 > BASE) sum2 -= BASE;
  79605. return sum1 | (sum2 << 16);
  79606. }
  79607. /*** End of inlined file: adler32.c ***/
  79608. /*** Start of inlined file: compress.c ***/
  79609. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79610. #define ZLIB_INTERNAL
  79611. /* ===========================================================================
  79612. Compresses the source buffer into the destination buffer. The level
  79613. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79614. length of the source buffer. Upon entry, destLen is the total size of the
  79615. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79616. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79617. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79618. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79619. Z_STREAM_ERROR if the level parameter is invalid.
  79620. */
  79621. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79622. uLong sourceLen, int level)
  79623. {
  79624. z_stream stream;
  79625. int err;
  79626. stream.next_in = (Bytef*)source;
  79627. stream.avail_in = (uInt)sourceLen;
  79628. #ifdef MAXSEG_64K
  79629. /* Check for source > 64K on 16-bit machine: */
  79630. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79631. #endif
  79632. stream.next_out = dest;
  79633. stream.avail_out = (uInt)*destLen;
  79634. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79635. stream.zalloc = (alloc_func)0;
  79636. stream.zfree = (free_func)0;
  79637. stream.opaque = (voidpf)0;
  79638. err = deflateInit(&stream, level);
  79639. if (err != Z_OK) return err;
  79640. err = deflate(&stream, Z_FINISH);
  79641. if (err != Z_STREAM_END) {
  79642. deflateEnd(&stream);
  79643. return err == Z_OK ? Z_BUF_ERROR : err;
  79644. }
  79645. *destLen = stream.total_out;
  79646. err = deflateEnd(&stream);
  79647. return err;
  79648. }
  79649. /* ===========================================================================
  79650. */
  79651. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79652. {
  79653. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79654. }
  79655. /* ===========================================================================
  79656. If the default memLevel or windowBits for deflateInit() is changed, then
  79657. this function needs to be updated.
  79658. */
  79659. uLong ZEXPORT compressBound (uLong sourceLen)
  79660. {
  79661. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79662. }
  79663. /*** End of inlined file: compress.c ***/
  79664. #undef DO1
  79665. #undef DO8
  79666. /*** Start of inlined file: crc32.c ***/
  79667. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79668. /*
  79669. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79670. protection on the static variables used to control the first-use generation
  79671. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79672. first call get_crc_table() to initialize the tables before allowing more than
  79673. one thread to use crc32().
  79674. */
  79675. #ifdef MAKECRCH
  79676. # include <stdio.h>
  79677. # ifndef DYNAMIC_CRC_TABLE
  79678. # define DYNAMIC_CRC_TABLE
  79679. # endif /* !DYNAMIC_CRC_TABLE */
  79680. #endif /* MAKECRCH */
  79681. /*** Start of inlined file: zutil.h ***/
  79682. /* WARNING: this file should *not* be used by applications. It is
  79683. part of the implementation of the compression library and is
  79684. subject to change. Applications should only use zlib.h.
  79685. */
  79686. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79687. #ifndef ZUTIL_H
  79688. #define ZUTIL_H
  79689. #define ZLIB_INTERNAL
  79690. #ifdef STDC
  79691. # ifndef _WIN32_WCE
  79692. # include <stddef.h>
  79693. # endif
  79694. # include <string.h>
  79695. # include <stdlib.h>
  79696. #endif
  79697. #ifdef NO_ERRNO_H
  79698. # ifdef _WIN32_WCE
  79699. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79700. * errno. We define it as a global variable to simplify porting.
  79701. * Its value is always 0 and should not be used. We rename it to
  79702. * avoid conflict with other libraries that use the same workaround.
  79703. */
  79704. # define errno z_errno
  79705. # endif
  79706. extern int errno;
  79707. #else
  79708. # ifndef _WIN32_WCE
  79709. # include <errno.h>
  79710. # endif
  79711. #endif
  79712. #ifndef local
  79713. # define local static
  79714. #endif
  79715. /* compile with -Dlocal if your debugger can't find static symbols */
  79716. typedef unsigned char uch;
  79717. typedef uch FAR uchf;
  79718. typedef unsigned short ush;
  79719. typedef ush FAR ushf;
  79720. typedef unsigned long ulg;
  79721. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79722. /* (size given to avoid silly warnings with Visual C++) */
  79723. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79724. #define ERR_RETURN(strm,err) \
  79725. return (strm->msg = (char*)ERR_MSG(err), (err))
  79726. /* To be used only when the state is known to be valid */
  79727. /* common constants */
  79728. #ifndef DEF_WBITS
  79729. # define DEF_WBITS MAX_WBITS
  79730. #endif
  79731. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79732. #if MAX_MEM_LEVEL >= 8
  79733. # define DEF_MEM_LEVEL 8
  79734. #else
  79735. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79736. #endif
  79737. /* default memLevel */
  79738. #define STORED_BLOCK 0
  79739. #define STATIC_TREES 1
  79740. #define DYN_TREES 2
  79741. /* The three kinds of block type */
  79742. #define MIN_MATCH 3
  79743. #define MAX_MATCH 258
  79744. /* The minimum and maximum match lengths */
  79745. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79746. /* target dependencies */
  79747. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79748. # define OS_CODE 0x00
  79749. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79750. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79751. /* Allow compilation with ANSI keywords only enabled */
  79752. void _Cdecl farfree( void *block );
  79753. void *_Cdecl farmalloc( unsigned long nbytes );
  79754. # else
  79755. # include <alloc.h>
  79756. # endif
  79757. # else /* MSC or DJGPP */
  79758. # include <malloc.h>
  79759. # endif
  79760. #endif
  79761. #ifdef AMIGA
  79762. # define OS_CODE 0x01
  79763. #endif
  79764. #if defined(VAXC) || defined(VMS)
  79765. # define OS_CODE 0x02
  79766. # define F_OPEN(name, mode) \
  79767. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79768. #endif
  79769. #if defined(ATARI) || defined(atarist)
  79770. # define OS_CODE 0x05
  79771. #endif
  79772. #ifdef OS2
  79773. # define OS_CODE 0x06
  79774. # ifdef M_I86
  79775. #include <malloc.h>
  79776. # endif
  79777. #endif
  79778. #if defined(MACOS) || TARGET_OS_MAC
  79779. # define OS_CODE 0x07
  79780. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79781. # include <unix.h> /* for fdopen */
  79782. # else
  79783. # ifndef fdopen
  79784. # define fdopen(fd,mode) NULL /* No fdopen() */
  79785. # endif
  79786. # endif
  79787. #endif
  79788. #ifdef TOPS20
  79789. # define OS_CODE 0x0a
  79790. #endif
  79791. #ifdef WIN32
  79792. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79793. # define OS_CODE 0x0b
  79794. # endif
  79795. #endif
  79796. #ifdef __50SERIES /* Prime/PRIMOS */
  79797. # define OS_CODE 0x0f
  79798. #endif
  79799. #if defined(_BEOS_) || defined(RISCOS)
  79800. # define fdopen(fd,mode) NULL /* No fdopen() */
  79801. #endif
  79802. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79803. # if defined(_WIN32_WCE)
  79804. # define fdopen(fd,mode) NULL /* No fdopen() */
  79805. # ifndef _PTRDIFF_T_DEFINED
  79806. typedef int ptrdiff_t;
  79807. # define _PTRDIFF_T_DEFINED
  79808. # endif
  79809. # else
  79810. # define fdopen(fd,type) _fdopen(fd,type)
  79811. # endif
  79812. #endif
  79813. /* common defaults */
  79814. #ifndef OS_CODE
  79815. # define OS_CODE 0x03 /* assume Unix */
  79816. #endif
  79817. #ifndef F_OPEN
  79818. # define F_OPEN(name, mode) fopen((name), (mode))
  79819. #endif
  79820. /* functions */
  79821. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79822. # ifndef HAVE_VSNPRINTF
  79823. # define HAVE_VSNPRINTF
  79824. # endif
  79825. #endif
  79826. #if defined(__CYGWIN__)
  79827. # ifndef HAVE_VSNPRINTF
  79828. # define HAVE_VSNPRINTF
  79829. # endif
  79830. #endif
  79831. #ifndef HAVE_VSNPRINTF
  79832. # ifdef MSDOS
  79833. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79834. but for now we just assume it doesn't. */
  79835. # define NO_vsnprintf
  79836. # endif
  79837. # ifdef __TURBOC__
  79838. # define NO_vsnprintf
  79839. # endif
  79840. # ifdef WIN32
  79841. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79842. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79843. # define vsnprintf _vsnprintf
  79844. # endif
  79845. # endif
  79846. # ifdef __SASC
  79847. # define NO_vsnprintf
  79848. # endif
  79849. #endif
  79850. #ifdef VMS
  79851. # define NO_vsnprintf
  79852. #endif
  79853. #if defined(pyr)
  79854. # define NO_MEMCPY
  79855. #endif
  79856. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79857. /* Use our own functions for small and medium model with MSC <= 5.0.
  79858. * You may have to use the same strategy for Borland C (untested).
  79859. * The __SC__ check is for Symantec.
  79860. */
  79861. # define NO_MEMCPY
  79862. #endif
  79863. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79864. # define HAVE_MEMCPY
  79865. #endif
  79866. #ifdef HAVE_MEMCPY
  79867. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79868. # define zmemcpy _fmemcpy
  79869. # define zmemcmp _fmemcmp
  79870. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79871. # else
  79872. # define zmemcpy memcpy
  79873. # define zmemcmp memcmp
  79874. # define zmemzero(dest, len) memset(dest, 0, len)
  79875. # endif
  79876. #else
  79877. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79878. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79879. extern void zmemzero OF((Bytef* dest, uInt len));
  79880. #endif
  79881. /* Diagnostic functions */
  79882. #ifdef DEBUG
  79883. # include <stdio.h>
  79884. extern int z_verbose;
  79885. extern void z_error OF((const char *m));
  79886. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79887. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79888. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79889. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79890. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79891. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79892. #else
  79893. # define Assert(cond,msg)
  79894. # define Trace(x)
  79895. # define Tracev(x)
  79896. # define Tracevv(x)
  79897. # define Tracec(c,x)
  79898. # define Tracecv(c,x)
  79899. #endif
  79900. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79901. void zcfree OF((voidpf opaque, voidpf ptr));
  79902. #define ZALLOC(strm, items, size) \
  79903. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79904. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79905. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79906. #endif /* ZUTIL_H */
  79907. /*** End of inlined file: zutil.h ***/
  79908. /* for STDC and FAR definitions */
  79909. #define local static
  79910. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79911. #ifndef NOBYFOUR
  79912. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79913. # include <limits.h>
  79914. # define BYFOUR
  79915. # if (UINT_MAX == 0xffffffffUL)
  79916. typedef unsigned int u4;
  79917. # else
  79918. # if (ULONG_MAX == 0xffffffffUL)
  79919. typedef unsigned long u4;
  79920. # else
  79921. # if (USHRT_MAX == 0xffffffffUL)
  79922. typedef unsigned short u4;
  79923. # else
  79924. # undef BYFOUR /* can't find a four-byte integer type! */
  79925. # endif
  79926. # endif
  79927. # endif
  79928. # endif /* STDC */
  79929. #endif /* !NOBYFOUR */
  79930. /* Definitions for doing the crc four data bytes at a time. */
  79931. #ifdef BYFOUR
  79932. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79933. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79934. local unsigned long crc32_little OF((unsigned long,
  79935. const unsigned char FAR *, unsigned));
  79936. local unsigned long crc32_big OF((unsigned long,
  79937. const unsigned char FAR *, unsigned));
  79938. # define TBLS 8
  79939. #else
  79940. # define TBLS 1
  79941. #endif /* BYFOUR */
  79942. /* Local functions for crc concatenation */
  79943. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79944. unsigned long vec));
  79945. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79946. #ifdef DYNAMIC_CRC_TABLE
  79947. local volatile int crc_table_empty = 1;
  79948. local unsigned long FAR crc_table[TBLS][256];
  79949. local void make_crc_table OF((void));
  79950. #ifdef MAKECRCH
  79951. local void write_table OF((FILE *, const unsigned long FAR *));
  79952. #endif /* MAKECRCH */
  79953. /*
  79954. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79955. 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.
  79956. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79957. with the lowest powers in the most significant bit. Then adding polynomials
  79958. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79959. one. If we call the above polynomial p, and represent a byte as the
  79960. polynomial q, also with the lowest power in the most significant bit (so the
  79961. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79962. where a mod b means the remainder after dividing a by b.
  79963. This calculation is done using the shift-register method of multiplying and
  79964. taking the remainder. The register is initialized to zero, and for each
  79965. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79966. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79967. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79968. out is a one). We start with the highest power (least significant bit) of
  79969. q and repeat for all eight bits of q.
  79970. The first table is simply the CRC of all possible eight bit values. This is
  79971. all the information needed to generate CRCs on data a byte at a time for all
  79972. combinations of CRC register values and incoming bytes. The remaining tables
  79973. allow for word-at-a-time CRC calculation for both big-endian and little-
  79974. endian machines, where a word is four bytes.
  79975. */
  79976. local void make_crc_table()
  79977. {
  79978. unsigned long c;
  79979. int n, k;
  79980. unsigned long poly; /* polynomial exclusive-or pattern */
  79981. /* terms of polynomial defining this crc (except x^32): */
  79982. static volatile int first = 1; /* flag to limit concurrent making */
  79983. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79984. /* See if another task is already doing this (not thread-safe, but better
  79985. than nothing -- significantly reduces duration of vulnerability in
  79986. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79987. if (first) {
  79988. first = 0;
  79989. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79990. poly = 0UL;
  79991. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79992. poly |= 1UL << (31 - p[n]);
  79993. /* generate a crc for every 8-bit value */
  79994. for (n = 0; n < 256; n++) {
  79995. c = (unsigned long)n;
  79996. for (k = 0; k < 8; k++)
  79997. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79998. crc_table[0][n] = c;
  79999. }
  80000. #ifdef BYFOUR
  80001. /* generate crc for each value followed by one, two, and three zeros,
  80002. and then the byte reversal of those as well as the first table */
  80003. for (n = 0; n < 256; n++) {
  80004. c = crc_table[0][n];
  80005. crc_table[4][n] = REV(c);
  80006. for (k = 1; k < 4; k++) {
  80007. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80008. crc_table[k][n] = c;
  80009. crc_table[k + 4][n] = REV(c);
  80010. }
  80011. }
  80012. #endif /* BYFOUR */
  80013. crc_table_empty = 0;
  80014. }
  80015. else { /* not first */
  80016. /* wait for the other guy to finish (not efficient, but rare) */
  80017. while (crc_table_empty)
  80018. ;
  80019. }
  80020. #ifdef MAKECRCH
  80021. /* write out CRC tables to crc32.h */
  80022. {
  80023. FILE *out;
  80024. out = fopen("crc32.h", "w");
  80025. if (out == NULL) return;
  80026. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80027. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80028. fprintf(out, "local const unsigned long FAR ");
  80029. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80030. write_table(out, crc_table[0]);
  80031. # ifdef BYFOUR
  80032. fprintf(out, "#ifdef BYFOUR\n");
  80033. for (k = 1; k < 8; k++) {
  80034. fprintf(out, " },\n {\n");
  80035. write_table(out, crc_table[k]);
  80036. }
  80037. fprintf(out, "#endif\n");
  80038. # endif /* BYFOUR */
  80039. fprintf(out, " }\n};\n");
  80040. fclose(out);
  80041. }
  80042. #endif /* MAKECRCH */
  80043. }
  80044. #ifdef MAKECRCH
  80045. local void write_table(out, table)
  80046. FILE *out;
  80047. const unsigned long FAR *table;
  80048. {
  80049. int n;
  80050. for (n = 0; n < 256; n++)
  80051. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80052. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80053. }
  80054. #endif /* MAKECRCH */
  80055. #else /* !DYNAMIC_CRC_TABLE */
  80056. /* ========================================================================
  80057. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80058. */
  80059. /*** Start of inlined file: crc32.h ***/
  80060. local const unsigned long FAR crc_table[TBLS][256] =
  80061. {
  80062. {
  80063. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80064. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80065. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80066. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80067. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80068. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80069. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80070. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80071. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80072. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80073. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80074. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80075. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80076. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80077. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80078. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80079. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80080. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80081. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80082. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80083. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80084. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80085. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80086. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80087. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80088. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80089. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80090. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80091. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80092. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80093. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80094. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80095. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80096. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80097. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80098. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80099. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80100. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80101. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80102. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80103. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80104. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80105. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80106. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80107. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80108. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80109. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80110. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80111. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80112. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80113. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80114. 0x2d02ef8dUL
  80115. #ifdef BYFOUR
  80116. },
  80117. {
  80118. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80119. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80120. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80121. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80122. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80123. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80124. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80125. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80126. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80127. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80128. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80129. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80130. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80131. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80132. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80133. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80134. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80135. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80136. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80137. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80138. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80139. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80140. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80141. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80142. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80143. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80144. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80145. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80146. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80147. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80148. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80149. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80150. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80151. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80152. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80153. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80154. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80155. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80156. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80157. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80158. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80159. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80160. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80161. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80162. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80163. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80164. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80165. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80166. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80167. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80168. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80169. 0x9324fd72UL
  80170. },
  80171. {
  80172. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80173. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80174. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80175. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80176. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80177. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80178. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80179. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80180. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80181. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80182. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80183. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80184. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80185. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80186. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80187. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80188. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80189. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80190. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80191. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80192. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80193. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80194. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80195. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80196. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80197. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80198. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80199. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80200. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80201. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80202. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80203. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80204. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80205. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80206. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80207. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80208. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80209. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80210. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80211. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80212. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80213. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80214. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80215. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80216. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80217. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80218. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80219. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80220. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80221. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80222. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80223. 0xbe9834edUL
  80224. },
  80225. {
  80226. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80227. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80228. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80229. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80230. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80231. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80232. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80233. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80234. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80235. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80236. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80237. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80238. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80239. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80240. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80241. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80242. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80243. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80244. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80245. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80246. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80247. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80248. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80249. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80250. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80251. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80252. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80253. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80254. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80255. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80256. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80257. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80258. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80259. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80260. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80261. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80262. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80263. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80264. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80265. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80266. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80267. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80268. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80269. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80270. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80271. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80272. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80273. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80274. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80275. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80276. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80277. 0xde0506f1UL
  80278. },
  80279. {
  80280. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80281. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80282. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80283. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80284. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80285. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80286. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80287. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80288. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80289. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80290. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80291. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80292. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80293. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80294. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80295. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80296. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80297. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80298. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80299. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80300. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80301. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80302. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80303. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80304. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80305. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80306. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80307. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80308. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80309. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80310. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80311. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80312. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80313. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80314. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80315. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80316. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80317. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80318. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80319. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80320. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80321. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80322. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80323. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80324. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80325. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80326. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80327. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80328. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80329. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80330. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80331. 0x8def022dUL
  80332. },
  80333. {
  80334. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80335. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80336. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80337. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80338. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80339. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80340. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80341. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80342. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80343. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80344. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80345. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80346. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80347. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80348. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80349. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80350. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80351. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80352. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80353. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80354. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80355. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80356. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80357. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80358. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80359. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80360. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80361. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80362. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80363. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80364. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80365. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80366. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80367. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80368. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80369. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80370. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80371. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80372. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80373. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80374. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80375. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80376. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80377. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80378. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80379. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80380. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80381. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80382. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80383. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80384. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80385. 0x72fd2493UL
  80386. },
  80387. {
  80388. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80389. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80390. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80391. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80392. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80393. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80394. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80395. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80396. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80397. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80398. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80399. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80400. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80401. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80402. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80403. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80404. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80405. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80406. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80407. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80408. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80409. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80410. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80411. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80412. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80413. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80414. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80415. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80416. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80417. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80418. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80419. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80420. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80421. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80422. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80423. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80424. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80425. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80426. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80427. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80428. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80429. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80430. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80431. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80432. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80433. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80434. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80435. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80436. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80437. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80438. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80439. 0xed3498beUL
  80440. },
  80441. {
  80442. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80443. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80444. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80445. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80446. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80447. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80448. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80449. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80450. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80451. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80452. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80453. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80454. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80455. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80456. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80457. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80458. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80459. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80460. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80461. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80462. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80463. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80464. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80465. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80466. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80467. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80468. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80469. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80470. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80471. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80472. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80473. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80474. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80475. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80476. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80477. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80478. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80479. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80480. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80481. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80482. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80483. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80484. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80485. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80486. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80487. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80488. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80489. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80490. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80491. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80492. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80493. 0xf10605deUL
  80494. #endif
  80495. }
  80496. };
  80497. /*** End of inlined file: crc32.h ***/
  80498. #endif /* DYNAMIC_CRC_TABLE */
  80499. /* =========================================================================
  80500. * This function can be used by asm versions of crc32()
  80501. */
  80502. const unsigned long FAR * ZEXPORT get_crc_table()
  80503. {
  80504. #ifdef DYNAMIC_CRC_TABLE
  80505. if (crc_table_empty)
  80506. make_crc_table();
  80507. #endif /* DYNAMIC_CRC_TABLE */
  80508. return (const unsigned long FAR *)crc_table;
  80509. }
  80510. /* ========================================================================= */
  80511. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80512. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80513. /* ========================================================================= */
  80514. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80515. {
  80516. if (buf == Z_NULL) return 0UL;
  80517. #ifdef DYNAMIC_CRC_TABLE
  80518. if (crc_table_empty)
  80519. make_crc_table();
  80520. #endif /* DYNAMIC_CRC_TABLE */
  80521. #ifdef BYFOUR
  80522. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80523. u4 endian;
  80524. endian = 1;
  80525. if (*((unsigned char *)(&endian)))
  80526. return crc32_little(crc, buf, len);
  80527. else
  80528. return crc32_big(crc, buf, len);
  80529. }
  80530. #endif /* BYFOUR */
  80531. crc = crc ^ 0xffffffffUL;
  80532. while (len >= 8) {
  80533. DO8;
  80534. len -= 8;
  80535. }
  80536. if (len) do {
  80537. DO1;
  80538. } while (--len);
  80539. return crc ^ 0xffffffffUL;
  80540. }
  80541. #ifdef BYFOUR
  80542. /* ========================================================================= */
  80543. #define DOLIT4 c ^= *buf4++; \
  80544. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80545. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80546. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80547. /* ========================================================================= */
  80548. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80549. {
  80550. register u4 c;
  80551. register const u4 FAR *buf4;
  80552. c = (u4)crc;
  80553. c = ~c;
  80554. while (len && ((ptrdiff_t)buf & 3)) {
  80555. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80556. len--;
  80557. }
  80558. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80559. while (len >= 32) {
  80560. DOLIT32;
  80561. len -= 32;
  80562. }
  80563. while (len >= 4) {
  80564. DOLIT4;
  80565. len -= 4;
  80566. }
  80567. buf = (const unsigned char FAR *)buf4;
  80568. if (len) do {
  80569. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80570. } while (--len);
  80571. c = ~c;
  80572. return (unsigned long)c;
  80573. }
  80574. /* ========================================================================= */
  80575. #define DOBIG4 c ^= *++buf4; \
  80576. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80577. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80578. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80579. /* ========================================================================= */
  80580. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80581. {
  80582. register u4 c;
  80583. register const u4 FAR *buf4;
  80584. c = REV((u4)crc);
  80585. c = ~c;
  80586. while (len && ((ptrdiff_t)buf & 3)) {
  80587. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80588. len--;
  80589. }
  80590. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80591. buf4--;
  80592. while (len >= 32) {
  80593. DOBIG32;
  80594. len -= 32;
  80595. }
  80596. while (len >= 4) {
  80597. DOBIG4;
  80598. len -= 4;
  80599. }
  80600. buf4++;
  80601. buf = (const unsigned char FAR *)buf4;
  80602. if (len) do {
  80603. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80604. } while (--len);
  80605. c = ~c;
  80606. return (unsigned long)(REV(c));
  80607. }
  80608. #endif /* BYFOUR */
  80609. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80610. /* ========================================================================= */
  80611. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80612. {
  80613. unsigned long sum;
  80614. sum = 0;
  80615. while (vec) {
  80616. if (vec & 1)
  80617. sum ^= *mat;
  80618. vec >>= 1;
  80619. mat++;
  80620. }
  80621. return sum;
  80622. }
  80623. /* ========================================================================= */
  80624. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80625. {
  80626. int n;
  80627. for (n = 0; n < GF2_DIM; n++)
  80628. square[n] = gf2_matrix_times(mat, mat[n]);
  80629. }
  80630. /* ========================================================================= */
  80631. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80632. {
  80633. int n;
  80634. unsigned long row;
  80635. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80636. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80637. /* degenerate case */
  80638. if (len2 == 0)
  80639. return crc1;
  80640. /* put operator for one zero bit in odd */
  80641. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80642. row = 1;
  80643. for (n = 1; n < GF2_DIM; n++) {
  80644. odd[n] = row;
  80645. row <<= 1;
  80646. }
  80647. /* put operator for two zero bits in even */
  80648. gf2_matrix_square(even, odd);
  80649. /* put operator for four zero bits in odd */
  80650. gf2_matrix_square(odd, even);
  80651. /* apply len2 zeros to crc1 (first square will put the operator for one
  80652. zero byte, eight zero bits, in even) */
  80653. do {
  80654. /* apply zeros operator for this bit of len2 */
  80655. gf2_matrix_square(even, odd);
  80656. if (len2 & 1)
  80657. crc1 = gf2_matrix_times(even, crc1);
  80658. len2 >>= 1;
  80659. /* if no more bits set, then done */
  80660. if (len2 == 0)
  80661. break;
  80662. /* another iteration of the loop with odd and even swapped */
  80663. gf2_matrix_square(odd, even);
  80664. if (len2 & 1)
  80665. crc1 = gf2_matrix_times(odd, crc1);
  80666. len2 >>= 1;
  80667. /* if no more bits set, then done */
  80668. } while (len2 != 0);
  80669. /* return combined crc */
  80670. crc1 ^= crc2;
  80671. return crc1;
  80672. }
  80673. /*** End of inlined file: crc32.c ***/
  80674. /*** Start of inlined file: deflate.c ***/
  80675. /*
  80676. * ALGORITHM
  80677. *
  80678. * The "deflation" process depends on being able to identify portions
  80679. * of the input text which are identical to earlier input (within a
  80680. * sliding window trailing behind the input currently being processed).
  80681. *
  80682. * The most straightforward technique turns out to be the fastest for
  80683. * most input files: try all possible matches and select the longest.
  80684. * The key feature of this algorithm is that insertions into the string
  80685. * dictionary are very simple and thus fast, and deletions are avoided
  80686. * completely. Insertions are performed at each input character, whereas
  80687. * string matches are performed only when the previous match ends. So it
  80688. * is preferable to spend more time in matches to allow very fast string
  80689. * insertions and avoid deletions. The matching algorithm for small
  80690. * strings is inspired from that of Rabin & Karp. A brute force approach
  80691. * is used to find longer strings when a small match has been found.
  80692. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80693. * (by Leonid Broukhis).
  80694. * A previous version of this file used a more sophisticated algorithm
  80695. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80696. * time, but has a larger average cost, uses more memory and is patented.
  80697. * However the F&G algorithm may be faster for some highly redundant
  80698. * files if the parameter max_chain_length (described below) is too large.
  80699. *
  80700. * ACKNOWLEDGEMENTS
  80701. *
  80702. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80703. * I found it in 'freeze' written by Leonid Broukhis.
  80704. * Thanks to many people for bug reports and testing.
  80705. *
  80706. * REFERENCES
  80707. *
  80708. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80709. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80710. *
  80711. * A description of the Rabin and Karp algorithm is given in the book
  80712. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80713. *
  80714. * Fiala,E.R., and Greene,D.H.
  80715. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80716. *
  80717. */
  80718. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80719. /*** Start of inlined file: deflate.h ***/
  80720. /* WARNING: this file should *not* be used by applications. It is
  80721. part of the implementation of the compression library and is
  80722. subject to change. Applications should only use zlib.h.
  80723. */
  80724. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80725. #ifndef DEFLATE_H
  80726. #define DEFLATE_H
  80727. /* define NO_GZIP when compiling if you want to disable gzip header and
  80728. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80729. the crc code when it is not needed. For shared libraries, gzip encoding
  80730. should be left enabled. */
  80731. #ifndef NO_GZIP
  80732. # define GZIP
  80733. #endif
  80734. #define NO_DUMMY_DECL
  80735. /* ===========================================================================
  80736. * Internal compression state.
  80737. */
  80738. #define LENGTH_CODES 29
  80739. /* number of length codes, not counting the special END_BLOCK code */
  80740. #define LITERALS 256
  80741. /* number of literal bytes 0..255 */
  80742. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80743. /* number of Literal or Length codes, including the END_BLOCK code */
  80744. #define D_CODES 30
  80745. /* number of distance codes */
  80746. #define BL_CODES 19
  80747. /* number of codes used to transfer the bit lengths */
  80748. #define HEAP_SIZE (2*L_CODES+1)
  80749. /* maximum heap size */
  80750. #define MAX_BITS 15
  80751. /* All codes must not exceed MAX_BITS bits */
  80752. #define INIT_STATE 42
  80753. #define EXTRA_STATE 69
  80754. #define NAME_STATE 73
  80755. #define COMMENT_STATE 91
  80756. #define HCRC_STATE 103
  80757. #define BUSY_STATE 113
  80758. #define FINISH_STATE 666
  80759. /* Stream status */
  80760. /* Data structure describing a single value and its code string. */
  80761. typedef struct ct_data_s {
  80762. union {
  80763. ush freq; /* frequency count */
  80764. ush code; /* bit string */
  80765. } fc;
  80766. union {
  80767. ush dad; /* father node in Huffman tree */
  80768. ush len; /* length of bit string */
  80769. } dl;
  80770. } FAR ct_data;
  80771. #define Freq fc.freq
  80772. #define Code fc.code
  80773. #define Dad dl.dad
  80774. #define Len dl.len
  80775. typedef struct static_tree_desc_s static_tree_desc;
  80776. typedef struct tree_desc_s {
  80777. ct_data *dyn_tree; /* the dynamic tree */
  80778. int max_code; /* largest code with non zero frequency */
  80779. static_tree_desc *stat_desc; /* the corresponding static tree */
  80780. } FAR tree_desc;
  80781. typedef ush Pos;
  80782. typedef Pos FAR Posf;
  80783. typedef unsigned IPos;
  80784. /* A Pos is an index in the character window. We use short instead of int to
  80785. * save space in the various tables. IPos is used only for parameter passing.
  80786. */
  80787. typedef struct internal_state {
  80788. z_streamp strm; /* pointer back to this zlib stream */
  80789. int status; /* as the name implies */
  80790. Bytef *pending_buf; /* output still pending */
  80791. ulg pending_buf_size; /* size of pending_buf */
  80792. Bytef *pending_out; /* next pending byte to output to the stream */
  80793. uInt pending; /* nb of bytes in the pending buffer */
  80794. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80795. gz_headerp gzhead; /* gzip header information to write */
  80796. uInt gzindex; /* where in extra, name, or comment */
  80797. Byte method; /* STORED (for zip only) or DEFLATED */
  80798. int last_flush; /* value of flush param for previous deflate call */
  80799. /* used by deflate.c: */
  80800. uInt w_size; /* LZ77 window size (32K by default) */
  80801. uInt w_bits; /* log2(w_size) (8..16) */
  80802. uInt w_mask; /* w_size - 1 */
  80803. Bytef *window;
  80804. /* Sliding window. Input bytes are read into the second half of the window,
  80805. * and move to the first half later to keep a dictionary of at least wSize
  80806. * bytes. With this organization, matches are limited to a distance of
  80807. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80808. * performed with a length multiple of the block size. Also, it limits
  80809. * the window size to 64K, which is quite useful on MSDOS.
  80810. * To do: use the user input buffer as sliding window.
  80811. */
  80812. ulg window_size;
  80813. /* Actual size of window: 2*wSize, except when the user input buffer
  80814. * is directly used as sliding window.
  80815. */
  80816. Posf *prev;
  80817. /* Link to older string with same hash index. To limit the size of this
  80818. * array to 64K, this link is maintained only for the last 32K strings.
  80819. * An index in this array is thus a window index modulo 32K.
  80820. */
  80821. Posf *head; /* Heads of the hash chains or NIL. */
  80822. uInt ins_h; /* hash index of string to be inserted */
  80823. uInt hash_size; /* number of elements in hash table */
  80824. uInt hash_bits; /* log2(hash_size) */
  80825. uInt hash_mask; /* hash_size-1 */
  80826. uInt hash_shift;
  80827. /* Number of bits by which ins_h must be shifted at each input
  80828. * step. It must be such that after MIN_MATCH steps, the oldest
  80829. * byte no longer takes part in the hash key, that is:
  80830. * hash_shift * MIN_MATCH >= hash_bits
  80831. */
  80832. long block_start;
  80833. /* Window position at the beginning of the current output block. Gets
  80834. * negative when the window is moved backwards.
  80835. */
  80836. uInt match_length; /* length of best match */
  80837. IPos prev_match; /* previous match */
  80838. int match_available; /* set if previous match exists */
  80839. uInt strstart; /* start of string to insert */
  80840. uInt match_start; /* start of matching string */
  80841. uInt lookahead; /* number of valid bytes ahead in window */
  80842. uInt prev_length;
  80843. /* Length of the best match at previous step. Matches not greater than this
  80844. * are discarded. This is used in the lazy match evaluation.
  80845. */
  80846. uInt max_chain_length;
  80847. /* To speed up deflation, hash chains are never searched beyond this
  80848. * length. A higher limit improves compression ratio but degrades the
  80849. * speed.
  80850. */
  80851. uInt max_lazy_match;
  80852. /* Attempt to find a better match only when the current match is strictly
  80853. * smaller than this value. This mechanism is used only for compression
  80854. * levels >= 4.
  80855. */
  80856. # define max_insert_length max_lazy_match
  80857. /* Insert new strings in the hash table only if the match length is not
  80858. * greater than this length. This saves time but degrades compression.
  80859. * max_insert_length is used only for compression levels <= 3.
  80860. */
  80861. int level; /* compression level (1..9) */
  80862. int strategy; /* favor or force Huffman coding*/
  80863. uInt good_match;
  80864. /* Use a faster search when the previous match is longer than this */
  80865. int nice_match; /* Stop searching when current match exceeds this */
  80866. /* used by trees.c: */
  80867. /* Didn't use ct_data typedef below to supress compiler warning */
  80868. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80869. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80870. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80871. struct tree_desc_s l_desc; /* desc. for literal tree */
  80872. struct tree_desc_s d_desc; /* desc. for distance tree */
  80873. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80874. ush bl_count[MAX_BITS+1];
  80875. /* number of codes at each bit length for an optimal tree */
  80876. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80877. int heap_len; /* number of elements in the heap */
  80878. int heap_max; /* element of largest frequency */
  80879. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80880. * The same heap array is used to build all trees.
  80881. */
  80882. uch depth[2*L_CODES+1];
  80883. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80884. */
  80885. uchf *l_buf; /* buffer for literals or lengths */
  80886. uInt lit_bufsize;
  80887. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80888. * limiting lit_bufsize to 64K:
  80889. * - frequencies can be kept in 16 bit counters
  80890. * - if compression is not successful for the first block, all input
  80891. * data is still in the window so we can still emit a stored block even
  80892. * when input comes from standard input. (This can also be done for
  80893. * all blocks if lit_bufsize is not greater than 32K.)
  80894. * - if compression is not successful for a file smaller than 64K, we can
  80895. * even emit a stored file instead of a stored block (saving 5 bytes).
  80896. * This is applicable only for zip (not gzip or zlib).
  80897. * - creating new Huffman trees less frequently may not provide fast
  80898. * adaptation to changes in the input data statistics. (Take for
  80899. * example a binary file with poorly compressible code followed by
  80900. * a highly compressible string table.) Smaller buffer sizes give
  80901. * fast adaptation but have of course the overhead of transmitting
  80902. * trees more frequently.
  80903. * - I can't count above 4
  80904. */
  80905. uInt last_lit; /* running index in l_buf */
  80906. ushf *d_buf;
  80907. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80908. * the same number of elements. To use different lengths, an extra flag
  80909. * array would be necessary.
  80910. */
  80911. ulg opt_len; /* bit length of current block with optimal trees */
  80912. ulg static_len; /* bit length of current block with static trees */
  80913. uInt matches; /* number of string matches in current block */
  80914. int last_eob_len; /* bit length of EOB code for last block */
  80915. #ifdef DEBUG
  80916. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80917. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80918. #endif
  80919. ush bi_buf;
  80920. /* Output buffer. bits are inserted starting at the bottom (least
  80921. * significant bits).
  80922. */
  80923. int bi_valid;
  80924. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80925. * are always zero.
  80926. */
  80927. } FAR deflate_state;
  80928. /* Output a byte on the stream.
  80929. * IN assertion: there is enough room in pending_buf.
  80930. */
  80931. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80932. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80933. /* Minimum amount of lookahead, except at the end of the input file.
  80934. * See deflate.c for comments about the MIN_MATCH+1.
  80935. */
  80936. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80937. /* In order to simplify the code, particularly on 16 bit machines, match
  80938. * distances are limited to MAX_DIST instead of WSIZE.
  80939. */
  80940. /* in trees.c */
  80941. void _tr_init OF((deflate_state *s));
  80942. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80943. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80944. int eof));
  80945. void _tr_align OF((deflate_state *s));
  80946. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80947. int eof));
  80948. #define d_code(dist) \
  80949. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80950. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80951. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80952. * used.
  80953. */
  80954. #ifndef DEBUG
  80955. /* Inline versions of _tr_tally for speed: */
  80956. #if defined(GEN_TREES_H) || !defined(STDC)
  80957. extern uch _length_code[];
  80958. extern uch _dist_code[];
  80959. #else
  80960. extern const uch _length_code[];
  80961. extern const uch _dist_code[];
  80962. #endif
  80963. # define _tr_tally_lit(s, c, flush) \
  80964. { uch cc = (c); \
  80965. s->d_buf[s->last_lit] = 0; \
  80966. s->l_buf[s->last_lit++] = cc; \
  80967. s->dyn_ltree[cc].Freq++; \
  80968. flush = (s->last_lit == s->lit_bufsize-1); \
  80969. }
  80970. # define _tr_tally_dist(s, distance, length, flush) \
  80971. { uch len = (length); \
  80972. ush dist = (distance); \
  80973. s->d_buf[s->last_lit] = dist; \
  80974. s->l_buf[s->last_lit++] = len; \
  80975. dist--; \
  80976. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80977. s->dyn_dtree[d_code(dist)].Freq++; \
  80978. flush = (s->last_lit == s->lit_bufsize-1); \
  80979. }
  80980. #else
  80981. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80982. # define _tr_tally_dist(s, distance, length, flush) \
  80983. flush = _tr_tally(s, distance, length)
  80984. #endif
  80985. #endif /* DEFLATE_H */
  80986. /*** End of inlined file: deflate.h ***/
  80987. const char deflate_copyright[] =
  80988. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80989. /*
  80990. If you use the zlib library in a product, an acknowledgment is welcome
  80991. in the documentation of your product. If for some reason you cannot
  80992. include such an acknowledgment, I would appreciate that you keep this
  80993. copyright string in the executable of your product.
  80994. */
  80995. /* ===========================================================================
  80996. * Function prototypes.
  80997. */
  80998. typedef enum {
  80999. need_more, /* block not completed, need more input or more output */
  81000. block_done, /* block flush performed */
  81001. finish_started, /* finish started, need only more output at next deflate */
  81002. finish_done /* finish done, accept no more input or output */
  81003. } block_state;
  81004. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81005. /* Compression function. Returns the block state after the call. */
  81006. local void fill_window OF((deflate_state *s));
  81007. local block_state deflate_stored OF((deflate_state *s, int flush));
  81008. local block_state deflate_fast OF((deflate_state *s, int flush));
  81009. #ifndef FASTEST
  81010. local block_state deflate_slow OF((deflate_state *s, int flush));
  81011. #endif
  81012. local void lm_init OF((deflate_state *s));
  81013. local void putShortMSB OF((deflate_state *s, uInt b));
  81014. local void flush_pending OF((z_streamp strm));
  81015. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81016. #ifndef FASTEST
  81017. #ifdef ASMV
  81018. void match_init OF((void)); /* asm code initialization */
  81019. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81020. #else
  81021. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81022. #endif
  81023. #endif
  81024. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81025. #ifdef DEBUG
  81026. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81027. int length));
  81028. #endif
  81029. /* ===========================================================================
  81030. * Local data
  81031. */
  81032. #define NIL 0
  81033. /* Tail of hash chains */
  81034. #ifndef TOO_FAR
  81035. # define TOO_FAR 4096
  81036. #endif
  81037. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81038. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81039. /* Minimum amount of lookahead, except at the end of the input file.
  81040. * See deflate.c for comments about the MIN_MATCH+1.
  81041. */
  81042. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81043. * the desired pack level (0..9). The values given below have been tuned to
  81044. * exclude worst case performance for pathological files. Better values may be
  81045. * found for specific files.
  81046. */
  81047. typedef struct config_s {
  81048. ush good_length; /* reduce lazy search above this match length */
  81049. ush max_lazy; /* do not perform lazy search above this match length */
  81050. ush nice_length; /* quit search above this match length */
  81051. ush max_chain;
  81052. compress_func func;
  81053. } config;
  81054. #ifdef FASTEST
  81055. local const config configuration_table[2] = {
  81056. /* good lazy nice chain */
  81057. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81058. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81059. #else
  81060. local const config configuration_table[10] = {
  81061. /* good lazy nice chain */
  81062. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81063. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81064. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81065. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81066. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81067. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81068. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81069. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81070. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81071. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81072. #endif
  81073. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81074. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81075. * meaning.
  81076. */
  81077. #define EQUAL 0
  81078. /* result of memcmp for equal strings */
  81079. #ifndef NO_DUMMY_DECL
  81080. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81081. #endif
  81082. /* ===========================================================================
  81083. * Update a hash value with the given input byte
  81084. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81085. * input characters, so that a running hash key can be computed from the
  81086. * previous key instead of complete recalculation each time.
  81087. */
  81088. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81089. /* ===========================================================================
  81090. * Insert string str in the dictionary and set match_head to the previous head
  81091. * of the hash chain (the most recent string with same hash key). Return
  81092. * the previous length of the hash chain.
  81093. * If this file is compiled with -DFASTEST, the compression level is forced
  81094. * to 1, and no hash chains are maintained.
  81095. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81096. * input characters and the first MIN_MATCH bytes of str are valid
  81097. * (except for the last MIN_MATCH-1 bytes of the input file).
  81098. */
  81099. #ifdef FASTEST
  81100. #define INSERT_STRING(s, str, match_head) \
  81101. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81102. match_head = s->head[s->ins_h], \
  81103. s->head[s->ins_h] = (Pos)(str))
  81104. #else
  81105. #define INSERT_STRING(s, str, match_head) \
  81106. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81107. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81108. s->head[s->ins_h] = (Pos)(str))
  81109. #endif
  81110. /* ===========================================================================
  81111. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81112. * prev[] will be initialized on the fly.
  81113. */
  81114. #define CLEAR_HASH(s) \
  81115. s->head[s->hash_size-1] = NIL; \
  81116. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81117. /* ========================================================================= */
  81118. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81119. {
  81120. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81121. Z_DEFAULT_STRATEGY, version, stream_size);
  81122. /* To do: ignore strm->next_in if we use it as window */
  81123. }
  81124. /* ========================================================================= */
  81125. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81126. {
  81127. deflate_state *s;
  81128. int wrap = 1;
  81129. static const char my_version[] = ZLIB_VERSION;
  81130. ushf *overlay;
  81131. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81132. * output size for (length,distance) codes is <= 24 bits.
  81133. */
  81134. if (version == Z_NULL || version[0] != my_version[0] ||
  81135. stream_size != sizeof(z_stream)) {
  81136. return Z_VERSION_ERROR;
  81137. }
  81138. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81139. strm->msg = Z_NULL;
  81140. if (strm->zalloc == (alloc_func)0) {
  81141. strm->zalloc = zcalloc;
  81142. strm->opaque = (voidpf)0;
  81143. }
  81144. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81145. #ifdef FASTEST
  81146. if (level != 0) level = 1;
  81147. #else
  81148. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81149. #endif
  81150. if (windowBits < 0) { /* suppress zlib wrapper */
  81151. wrap = 0;
  81152. windowBits = -windowBits;
  81153. }
  81154. #ifdef GZIP
  81155. else if (windowBits > 15) {
  81156. wrap = 2; /* write gzip wrapper instead */
  81157. windowBits -= 16;
  81158. }
  81159. #endif
  81160. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81161. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81162. strategy < 0 || strategy > Z_FIXED) {
  81163. return Z_STREAM_ERROR;
  81164. }
  81165. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81166. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81167. if (s == Z_NULL) return Z_MEM_ERROR;
  81168. strm->state = (struct internal_state FAR *)s;
  81169. s->strm = strm;
  81170. s->wrap = wrap;
  81171. s->gzhead = Z_NULL;
  81172. s->w_bits = windowBits;
  81173. s->w_size = 1 << s->w_bits;
  81174. s->w_mask = s->w_size - 1;
  81175. s->hash_bits = memLevel + 7;
  81176. s->hash_size = 1 << s->hash_bits;
  81177. s->hash_mask = s->hash_size - 1;
  81178. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81179. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81180. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81181. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81182. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81183. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81184. s->pending_buf = (uchf *) overlay;
  81185. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81186. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81187. s->pending_buf == Z_NULL) {
  81188. s->status = FINISH_STATE;
  81189. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81190. deflateEnd (strm);
  81191. return Z_MEM_ERROR;
  81192. }
  81193. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81194. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81195. s->level = level;
  81196. s->strategy = strategy;
  81197. s->method = (Byte)method;
  81198. return deflateReset(strm);
  81199. }
  81200. /* ========================================================================= */
  81201. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81202. {
  81203. deflate_state *s;
  81204. uInt length = dictLength;
  81205. uInt n;
  81206. IPos hash_head = 0;
  81207. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81208. strm->state->wrap == 2 ||
  81209. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81210. return Z_STREAM_ERROR;
  81211. s = strm->state;
  81212. if (s->wrap)
  81213. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81214. if (length < MIN_MATCH) return Z_OK;
  81215. if (length > MAX_DIST(s)) {
  81216. length = MAX_DIST(s);
  81217. dictionary += dictLength - length; /* use the tail of the dictionary */
  81218. }
  81219. zmemcpy(s->window, dictionary, length);
  81220. s->strstart = length;
  81221. s->block_start = (long)length;
  81222. /* Insert all strings in the hash table (except for the last two bytes).
  81223. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81224. * call of fill_window.
  81225. */
  81226. s->ins_h = s->window[0];
  81227. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81228. for (n = 0; n <= length - MIN_MATCH; n++) {
  81229. INSERT_STRING(s, n, hash_head);
  81230. }
  81231. if (hash_head) hash_head = 0; /* to make compiler happy */
  81232. return Z_OK;
  81233. }
  81234. /* ========================================================================= */
  81235. int ZEXPORT deflateReset (z_streamp strm)
  81236. {
  81237. deflate_state *s;
  81238. if (strm == Z_NULL || strm->state == Z_NULL ||
  81239. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81240. return Z_STREAM_ERROR;
  81241. }
  81242. strm->total_in = strm->total_out = 0;
  81243. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81244. strm->data_type = Z_UNKNOWN;
  81245. s = (deflate_state *)strm->state;
  81246. s->pending = 0;
  81247. s->pending_out = s->pending_buf;
  81248. if (s->wrap < 0) {
  81249. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81250. }
  81251. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81252. strm->adler =
  81253. #ifdef GZIP
  81254. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81255. #endif
  81256. adler32(0L, Z_NULL, 0);
  81257. s->last_flush = Z_NO_FLUSH;
  81258. _tr_init(s);
  81259. lm_init(s);
  81260. return Z_OK;
  81261. }
  81262. /* ========================================================================= */
  81263. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81264. {
  81265. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81266. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81267. strm->state->gzhead = head;
  81268. return Z_OK;
  81269. }
  81270. /* ========================================================================= */
  81271. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81272. {
  81273. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81274. strm->state->bi_valid = bits;
  81275. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81276. return Z_OK;
  81277. }
  81278. /* ========================================================================= */
  81279. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81280. {
  81281. deflate_state *s;
  81282. compress_func func;
  81283. int err = Z_OK;
  81284. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81285. s = strm->state;
  81286. #ifdef FASTEST
  81287. if (level != 0) level = 1;
  81288. #else
  81289. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81290. #endif
  81291. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81292. return Z_STREAM_ERROR;
  81293. }
  81294. func = configuration_table[s->level].func;
  81295. if (func != configuration_table[level].func && strm->total_in != 0) {
  81296. /* Flush the last buffer: */
  81297. err = deflate(strm, Z_PARTIAL_FLUSH);
  81298. }
  81299. if (s->level != level) {
  81300. s->level = level;
  81301. s->max_lazy_match = configuration_table[level].max_lazy;
  81302. s->good_match = configuration_table[level].good_length;
  81303. s->nice_match = configuration_table[level].nice_length;
  81304. s->max_chain_length = configuration_table[level].max_chain;
  81305. }
  81306. s->strategy = strategy;
  81307. return err;
  81308. }
  81309. /* ========================================================================= */
  81310. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81311. {
  81312. deflate_state *s;
  81313. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81314. s = strm->state;
  81315. s->good_match = good_length;
  81316. s->max_lazy_match = max_lazy;
  81317. s->nice_match = nice_length;
  81318. s->max_chain_length = max_chain;
  81319. return Z_OK;
  81320. }
  81321. /* =========================================================================
  81322. * For the default windowBits of 15 and memLevel of 8, this function returns
  81323. * a close to exact, as well as small, upper bound on the compressed size.
  81324. * They are coded as constants here for a reason--if the #define's are
  81325. * changed, then this function needs to be changed as well. The return
  81326. * value for 15 and 8 only works for those exact settings.
  81327. *
  81328. * For any setting other than those defaults for windowBits and memLevel,
  81329. * the value returned is a conservative worst case for the maximum expansion
  81330. * resulting from using fixed blocks instead of stored blocks, which deflate
  81331. * can emit on compressed data for some combinations of the parameters.
  81332. *
  81333. * This function could be more sophisticated to provide closer upper bounds
  81334. * for every combination of windowBits and memLevel, as well as wrap.
  81335. * But even the conservative upper bound of about 14% expansion does not
  81336. * seem onerous for output buffer allocation.
  81337. */
  81338. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81339. {
  81340. deflate_state *s;
  81341. uLong destLen;
  81342. /* conservative upper bound */
  81343. destLen = sourceLen +
  81344. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81345. /* if can't get parameters, return conservative bound */
  81346. if (strm == Z_NULL || strm->state == Z_NULL)
  81347. return destLen;
  81348. /* if not default parameters, return conservative bound */
  81349. s = strm->state;
  81350. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81351. return destLen;
  81352. /* default settings: return tight bound for that case */
  81353. return compressBound(sourceLen);
  81354. }
  81355. /* =========================================================================
  81356. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81357. * IN assertion: the stream state is correct and there is enough room in
  81358. * pending_buf.
  81359. */
  81360. local void putShortMSB (deflate_state *s, uInt b)
  81361. {
  81362. put_byte(s, (Byte)(b >> 8));
  81363. put_byte(s, (Byte)(b & 0xff));
  81364. }
  81365. /* =========================================================================
  81366. * Flush as much pending output as possible. All deflate() output goes
  81367. * through this function so some applications may wish to modify it
  81368. * to avoid allocating a large strm->next_out buffer and copying into it.
  81369. * (See also read_buf()).
  81370. */
  81371. local void flush_pending (z_streamp strm)
  81372. {
  81373. unsigned len = strm->state->pending;
  81374. if (len > strm->avail_out) len = strm->avail_out;
  81375. if (len == 0) return;
  81376. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81377. strm->next_out += len;
  81378. strm->state->pending_out += len;
  81379. strm->total_out += len;
  81380. strm->avail_out -= len;
  81381. strm->state->pending -= len;
  81382. if (strm->state->pending == 0) {
  81383. strm->state->pending_out = strm->state->pending_buf;
  81384. }
  81385. }
  81386. /* ========================================================================= */
  81387. int ZEXPORT deflate (z_streamp strm, int flush)
  81388. {
  81389. int old_flush; /* value of flush param for previous deflate call */
  81390. deflate_state *s;
  81391. if (strm == Z_NULL || strm->state == Z_NULL ||
  81392. flush > Z_FINISH || flush < 0) {
  81393. return Z_STREAM_ERROR;
  81394. }
  81395. s = strm->state;
  81396. if (strm->next_out == Z_NULL ||
  81397. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81398. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81399. ERR_RETURN(strm, Z_STREAM_ERROR);
  81400. }
  81401. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81402. s->strm = strm; /* just in case */
  81403. old_flush = s->last_flush;
  81404. s->last_flush = flush;
  81405. /* Write the header */
  81406. if (s->status == INIT_STATE) {
  81407. #ifdef GZIP
  81408. if (s->wrap == 2) {
  81409. strm->adler = crc32(0L, Z_NULL, 0);
  81410. put_byte(s, 31);
  81411. put_byte(s, 139);
  81412. put_byte(s, 8);
  81413. if (s->gzhead == NULL) {
  81414. put_byte(s, 0);
  81415. put_byte(s, 0);
  81416. put_byte(s, 0);
  81417. put_byte(s, 0);
  81418. put_byte(s, 0);
  81419. put_byte(s, s->level == 9 ? 2 :
  81420. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81421. 4 : 0));
  81422. put_byte(s, OS_CODE);
  81423. s->status = BUSY_STATE;
  81424. }
  81425. else {
  81426. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81427. (s->gzhead->hcrc ? 2 : 0) +
  81428. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81429. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81430. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81431. );
  81432. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81433. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81434. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81435. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81436. put_byte(s, s->level == 9 ? 2 :
  81437. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81438. 4 : 0));
  81439. put_byte(s, s->gzhead->os & 0xff);
  81440. if (s->gzhead->extra != NULL) {
  81441. put_byte(s, s->gzhead->extra_len & 0xff);
  81442. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81443. }
  81444. if (s->gzhead->hcrc)
  81445. strm->adler = crc32(strm->adler, s->pending_buf,
  81446. s->pending);
  81447. s->gzindex = 0;
  81448. s->status = EXTRA_STATE;
  81449. }
  81450. }
  81451. else
  81452. #endif
  81453. {
  81454. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81455. uInt level_flags;
  81456. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81457. level_flags = 0;
  81458. else if (s->level < 6)
  81459. level_flags = 1;
  81460. else if (s->level == 6)
  81461. level_flags = 2;
  81462. else
  81463. level_flags = 3;
  81464. header |= (level_flags << 6);
  81465. if (s->strstart != 0) header |= PRESET_DICT;
  81466. header += 31 - (header % 31);
  81467. s->status = BUSY_STATE;
  81468. putShortMSB(s, header);
  81469. /* Save the adler32 of the preset dictionary: */
  81470. if (s->strstart != 0) {
  81471. putShortMSB(s, (uInt)(strm->adler >> 16));
  81472. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81473. }
  81474. strm->adler = adler32(0L, Z_NULL, 0);
  81475. }
  81476. }
  81477. #ifdef GZIP
  81478. if (s->status == EXTRA_STATE) {
  81479. if (s->gzhead->extra != NULL) {
  81480. uInt beg = s->pending; /* start of bytes to update crc */
  81481. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81482. if (s->pending == s->pending_buf_size) {
  81483. if (s->gzhead->hcrc && s->pending > beg)
  81484. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81485. s->pending - beg);
  81486. flush_pending(strm);
  81487. beg = s->pending;
  81488. if (s->pending == s->pending_buf_size)
  81489. break;
  81490. }
  81491. put_byte(s, s->gzhead->extra[s->gzindex]);
  81492. s->gzindex++;
  81493. }
  81494. if (s->gzhead->hcrc && s->pending > beg)
  81495. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81496. s->pending - beg);
  81497. if (s->gzindex == s->gzhead->extra_len) {
  81498. s->gzindex = 0;
  81499. s->status = NAME_STATE;
  81500. }
  81501. }
  81502. else
  81503. s->status = NAME_STATE;
  81504. }
  81505. if (s->status == NAME_STATE) {
  81506. if (s->gzhead->name != NULL) {
  81507. uInt beg = s->pending; /* start of bytes to update crc */
  81508. int val;
  81509. do {
  81510. if (s->pending == s->pending_buf_size) {
  81511. if (s->gzhead->hcrc && s->pending > beg)
  81512. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81513. s->pending - beg);
  81514. flush_pending(strm);
  81515. beg = s->pending;
  81516. if (s->pending == s->pending_buf_size) {
  81517. val = 1;
  81518. break;
  81519. }
  81520. }
  81521. val = s->gzhead->name[s->gzindex++];
  81522. put_byte(s, val);
  81523. } while (val != 0);
  81524. if (s->gzhead->hcrc && s->pending > beg)
  81525. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81526. s->pending - beg);
  81527. if (val == 0) {
  81528. s->gzindex = 0;
  81529. s->status = COMMENT_STATE;
  81530. }
  81531. }
  81532. else
  81533. s->status = COMMENT_STATE;
  81534. }
  81535. if (s->status == COMMENT_STATE) {
  81536. if (s->gzhead->comment != NULL) {
  81537. uInt beg = s->pending; /* start of bytes to update crc */
  81538. int val;
  81539. do {
  81540. if (s->pending == s->pending_buf_size) {
  81541. if (s->gzhead->hcrc && s->pending > beg)
  81542. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81543. s->pending - beg);
  81544. flush_pending(strm);
  81545. beg = s->pending;
  81546. if (s->pending == s->pending_buf_size) {
  81547. val = 1;
  81548. break;
  81549. }
  81550. }
  81551. val = s->gzhead->comment[s->gzindex++];
  81552. put_byte(s, val);
  81553. } while (val != 0);
  81554. if (s->gzhead->hcrc && s->pending > beg)
  81555. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81556. s->pending - beg);
  81557. if (val == 0)
  81558. s->status = HCRC_STATE;
  81559. }
  81560. else
  81561. s->status = HCRC_STATE;
  81562. }
  81563. if (s->status == HCRC_STATE) {
  81564. if (s->gzhead->hcrc) {
  81565. if (s->pending + 2 > s->pending_buf_size)
  81566. flush_pending(strm);
  81567. if (s->pending + 2 <= s->pending_buf_size) {
  81568. put_byte(s, (Byte)(strm->adler & 0xff));
  81569. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81570. strm->adler = crc32(0L, Z_NULL, 0);
  81571. s->status = BUSY_STATE;
  81572. }
  81573. }
  81574. else
  81575. s->status = BUSY_STATE;
  81576. }
  81577. #endif
  81578. /* Flush as much pending output as possible */
  81579. if (s->pending != 0) {
  81580. flush_pending(strm);
  81581. if (strm->avail_out == 0) {
  81582. /* Since avail_out is 0, deflate will be called again with
  81583. * more output space, but possibly with both pending and
  81584. * avail_in equal to zero. There won't be anything to do,
  81585. * but this is not an error situation so make sure we
  81586. * return OK instead of BUF_ERROR at next call of deflate:
  81587. */
  81588. s->last_flush = -1;
  81589. return Z_OK;
  81590. }
  81591. /* Make sure there is something to do and avoid duplicate consecutive
  81592. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81593. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81594. */
  81595. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81596. flush != Z_FINISH) {
  81597. ERR_RETURN(strm, Z_BUF_ERROR);
  81598. }
  81599. /* User must not provide more input after the first FINISH: */
  81600. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81601. ERR_RETURN(strm, Z_BUF_ERROR);
  81602. }
  81603. /* Start a new block or continue the current one.
  81604. */
  81605. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81606. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81607. block_state bstate;
  81608. bstate = (*(configuration_table[s->level].func))(s, flush);
  81609. if (bstate == finish_started || bstate == finish_done) {
  81610. s->status = FINISH_STATE;
  81611. }
  81612. if (bstate == need_more || bstate == finish_started) {
  81613. if (strm->avail_out == 0) {
  81614. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81615. }
  81616. return Z_OK;
  81617. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81618. * of deflate should use the same flush parameter to make sure
  81619. * that the flush is complete. So we don't have to output an
  81620. * empty block here, this will be done at next call. This also
  81621. * ensures that for a very small output buffer, we emit at most
  81622. * one empty block.
  81623. */
  81624. }
  81625. if (bstate == block_done) {
  81626. if (flush == Z_PARTIAL_FLUSH) {
  81627. _tr_align(s);
  81628. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81629. _tr_stored_block(s, (char*)0, 0L, 0);
  81630. /* For a full flush, this empty block will be recognized
  81631. * as a special marker by inflate_sync().
  81632. */
  81633. if (flush == Z_FULL_FLUSH) {
  81634. CLEAR_HASH(s); /* forget history */
  81635. }
  81636. }
  81637. flush_pending(strm);
  81638. if (strm->avail_out == 0) {
  81639. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81640. return Z_OK;
  81641. }
  81642. }
  81643. }
  81644. Assert(strm->avail_out > 0, "bug2");
  81645. if (flush != Z_FINISH) return Z_OK;
  81646. if (s->wrap <= 0) return Z_STREAM_END;
  81647. /* Write the trailer */
  81648. #ifdef GZIP
  81649. if (s->wrap == 2) {
  81650. put_byte(s, (Byte)(strm->adler & 0xff));
  81651. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81652. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81653. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81654. put_byte(s, (Byte)(strm->total_in & 0xff));
  81655. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81656. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81657. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81658. }
  81659. else
  81660. #endif
  81661. {
  81662. putShortMSB(s, (uInt)(strm->adler >> 16));
  81663. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81664. }
  81665. flush_pending(strm);
  81666. /* If avail_out is zero, the application will call deflate again
  81667. * to flush the rest.
  81668. */
  81669. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81670. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81671. }
  81672. /* ========================================================================= */
  81673. int ZEXPORT deflateEnd (z_streamp strm)
  81674. {
  81675. int status;
  81676. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81677. status = strm->state->status;
  81678. if (status != INIT_STATE &&
  81679. status != EXTRA_STATE &&
  81680. status != NAME_STATE &&
  81681. status != COMMENT_STATE &&
  81682. status != HCRC_STATE &&
  81683. status != BUSY_STATE &&
  81684. status != FINISH_STATE) {
  81685. return Z_STREAM_ERROR;
  81686. }
  81687. /* Deallocate in reverse order of allocations: */
  81688. TRY_FREE(strm, strm->state->pending_buf);
  81689. TRY_FREE(strm, strm->state->head);
  81690. TRY_FREE(strm, strm->state->prev);
  81691. TRY_FREE(strm, strm->state->window);
  81692. ZFREE(strm, strm->state);
  81693. strm->state = Z_NULL;
  81694. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81695. }
  81696. /* =========================================================================
  81697. * Copy the source state to the destination state.
  81698. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81699. * doesn't have enough memory anyway to duplicate compression states).
  81700. */
  81701. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81702. {
  81703. #ifdef MAXSEG_64K
  81704. return Z_STREAM_ERROR;
  81705. #else
  81706. deflate_state *ds;
  81707. deflate_state *ss;
  81708. ushf *overlay;
  81709. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81710. return Z_STREAM_ERROR;
  81711. }
  81712. ss = source->state;
  81713. zmemcpy(dest, source, sizeof(z_stream));
  81714. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81715. if (ds == Z_NULL) return Z_MEM_ERROR;
  81716. dest->state = (struct internal_state FAR *) ds;
  81717. zmemcpy(ds, ss, sizeof(deflate_state));
  81718. ds->strm = dest;
  81719. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81720. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81721. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81722. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81723. ds->pending_buf = (uchf *) overlay;
  81724. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81725. ds->pending_buf == Z_NULL) {
  81726. deflateEnd (dest);
  81727. return Z_MEM_ERROR;
  81728. }
  81729. /* following zmemcpy do not work for 16-bit MSDOS */
  81730. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81731. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81732. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81733. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81734. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81735. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81736. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81737. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81738. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81739. ds->bl_desc.dyn_tree = ds->bl_tree;
  81740. return Z_OK;
  81741. #endif /* MAXSEG_64K */
  81742. }
  81743. /* ===========================================================================
  81744. * Read a new buffer from the current input stream, update the adler32
  81745. * and total number of bytes read. All deflate() input goes through
  81746. * this function so some applications may wish to modify it to avoid
  81747. * allocating a large strm->next_in buffer and copying from it.
  81748. * (See also flush_pending()).
  81749. */
  81750. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81751. {
  81752. unsigned len = strm->avail_in;
  81753. if (len > size) len = size;
  81754. if (len == 0) return 0;
  81755. strm->avail_in -= len;
  81756. if (strm->state->wrap == 1) {
  81757. strm->adler = adler32(strm->adler, strm->next_in, len);
  81758. }
  81759. #ifdef GZIP
  81760. else if (strm->state->wrap == 2) {
  81761. strm->adler = crc32(strm->adler, strm->next_in, len);
  81762. }
  81763. #endif
  81764. zmemcpy(buf, strm->next_in, len);
  81765. strm->next_in += len;
  81766. strm->total_in += len;
  81767. return (int)len;
  81768. }
  81769. /* ===========================================================================
  81770. * Initialize the "longest match" routines for a new zlib stream
  81771. */
  81772. local void lm_init (deflate_state *s)
  81773. {
  81774. s->window_size = (ulg)2L*s->w_size;
  81775. CLEAR_HASH(s);
  81776. /* Set the default configuration parameters:
  81777. */
  81778. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81779. s->good_match = configuration_table[s->level].good_length;
  81780. s->nice_match = configuration_table[s->level].nice_length;
  81781. s->max_chain_length = configuration_table[s->level].max_chain;
  81782. s->strstart = 0;
  81783. s->block_start = 0L;
  81784. s->lookahead = 0;
  81785. s->match_length = s->prev_length = MIN_MATCH-1;
  81786. s->match_available = 0;
  81787. s->ins_h = 0;
  81788. #ifndef FASTEST
  81789. #ifdef ASMV
  81790. match_init(); /* initialize the asm code */
  81791. #endif
  81792. #endif
  81793. }
  81794. #ifndef FASTEST
  81795. /* ===========================================================================
  81796. * Set match_start to the longest match starting at the given string and
  81797. * return its length. Matches shorter or equal to prev_length are discarded,
  81798. * in which case the result is equal to prev_length and match_start is
  81799. * garbage.
  81800. * IN assertions: cur_match is the head of the hash chain for the current
  81801. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81802. * OUT assertion: the match length is not greater than s->lookahead.
  81803. */
  81804. #ifndef ASMV
  81805. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81806. * match.S. The code will be functionally equivalent.
  81807. */
  81808. local uInt longest_match(deflate_state *s, IPos cur_match)
  81809. {
  81810. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81811. register Bytef *scan = s->window + s->strstart; /* current string */
  81812. register Bytef *match; /* matched string */
  81813. register int len; /* length of current match */
  81814. int best_len = s->prev_length; /* best match length so far */
  81815. int nice_match = s->nice_match; /* stop if match long enough */
  81816. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81817. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81818. /* Stop when cur_match becomes <= limit. To simplify the code,
  81819. * we prevent matches with the string of window index 0.
  81820. */
  81821. Posf *prev = s->prev;
  81822. uInt wmask = s->w_mask;
  81823. #ifdef UNALIGNED_OK
  81824. /* Compare two bytes at a time. Note: this is not always beneficial.
  81825. * Try with and without -DUNALIGNED_OK to check.
  81826. */
  81827. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81828. register ush scan_start = *(ushf*)scan;
  81829. register ush scan_end = *(ushf*)(scan+best_len-1);
  81830. #else
  81831. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81832. register Byte scan_end1 = scan[best_len-1];
  81833. register Byte scan_end = scan[best_len];
  81834. #endif
  81835. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81836. * It is easy to get rid of this optimization if necessary.
  81837. */
  81838. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81839. /* Do not waste too much time if we already have a good match: */
  81840. if (s->prev_length >= s->good_match) {
  81841. chain_length >>= 2;
  81842. }
  81843. /* Do not look for matches beyond the end of the input. This is necessary
  81844. * to make deflate deterministic.
  81845. */
  81846. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81847. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81848. do {
  81849. Assert(cur_match < s->strstart, "no future");
  81850. match = s->window + cur_match;
  81851. /* Skip to next match if the match length cannot increase
  81852. * or if the match length is less than 2. Note that the checks below
  81853. * for insufficient lookahead only occur occasionally for performance
  81854. * reasons. Therefore uninitialized memory will be accessed, and
  81855. * conditional jumps will be made that depend on those values.
  81856. * However the length of the match is limited to the lookahead, so
  81857. * the output of deflate is not affected by the uninitialized values.
  81858. */
  81859. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81860. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81861. * UNALIGNED_OK if your compiler uses a different size.
  81862. */
  81863. if (*(ushf*)(match+best_len-1) != scan_end ||
  81864. *(ushf*)match != scan_start) continue;
  81865. /* It is not necessary to compare scan[2] and match[2] since they are
  81866. * always equal when the other bytes match, given that the hash keys
  81867. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81868. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81869. * lookahead only every 4th comparison; the 128th check will be made
  81870. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81871. * necessary to put more guard bytes at the end of the window, or
  81872. * to check more often for insufficient lookahead.
  81873. */
  81874. Assert(scan[2] == match[2], "scan[2]?");
  81875. scan++, match++;
  81876. do {
  81877. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81878. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81879. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81880. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81881. scan < strend);
  81882. /* The funny "do {}" generates better code on most compilers */
  81883. /* Here, scan <= window+strstart+257 */
  81884. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81885. if (*scan == *match) scan++;
  81886. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81887. scan = strend - (MAX_MATCH-1);
  81888. #else /* UNALIGNED_OK */
  81889. if (match[best_len] != scan_end ||
  81890. match[best_len-1] != scan_end1 ||
  81891. *match != *scan ||
  81892. *++match != scan[1]) continue;
  81893. /* The check at best_len-1 can be removed because it will be made
  81894. * again later. (This heuristic is not always a win.)
  81895. * It is not necessary to compare scan[2] and match[2] since they
  81896. * are always equal when the other bytes match, given that
  81897. * the hash keys are equal and that HASH_BITS >= 8.
  81898. */
  81899. scan += 2, match++;
  81900. Assert(*scan == *match, "match[2]?");
  81901. /* We check for insufficient lookahead only every 8th comparison;
  81902. * the 256th check will be made at strstart+258.
  81903. */
  81904. do {
  81905. } while (*++scan == *++match && *++scan == *++match &&
  81906. *++scan == *++match && *++scan == *++match &&
  81907. *++scan == *++match && *++scan == *++match &&
  81908. *++scan == *++match && *++scan == *++match &&
  81909. scan < strend);
  81910. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81911. len = MAX_MATCH - (int)(strend - scan);
  81912. scan = strend - MAX_MATCH;
  81913. #endif /* UNALIGNED_OK */
  81914. if (len > best_len) {
  81915. s->match_start = cur_match;
  81916. best_len = len;
  81917. if (len >= nice_match) break;
  81918. #ifdef UNALIGNED_OK
  81919. scan_end = *(ushf*)(scan+best_len-1);
  81920. #else
  81921. scan_end1 = scan[best_len-1];
  81922. scan_end = scan[best_len];
  81923. #endif
  81924. }
  81925. } while ((cur_match = prev[cur_match & wmask]) > limit
  81926. && --chain_length != 0);
  81927. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81928. return s->lookahead;
  81929. }
  81930. #endif /* ASMV */
  81931. #endif /* FASTEST */
  81932. /* ---------------------------------------------------------------------------
  81933. * Optimized version for level == 1 or strategy == Z_RLE only
  81934. */
  81935. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81936. {
  81937. register Bytef *scan = s->window + s->strstart; /* current string */
  81938. register Bytef *match; /* matched string */
  81939. register int len; /* length of current match */
  81940. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81941. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81942. * It is easy to get rid of this optimization if necessary.
  81943. */
  81944. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81945. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81946. Assert(cur_match < s->strstart, "no future");
  81947. match = s->window + cur_match;
  81948. /* Return failure if the match length is less than 2:
  81949. */
  81950. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81951. /* The check at best_len-1 can be removed because it will be made
  81952. * again later. (This heuristic is not always a win.)
  81953. * It is not necessary to compare scan[2] and match[2] since they
  81954. * are always equal when the other bytes match, given that
  81955. * the hash keys are equal and that HASH_BITS >= 8.
  81956. */
  81957. scan += 2, match += 2;
  81958. Assert(*scan == *match, "match[2]?");
  81959. /* We check for insufficient lookahead only every 8th comparison;
  81960. * the 256th check will be made at strstart+258.
  81961. */
  81962. do {
  81963. } while (*++scan == *++match && *++scan == *++match &&
  81964. *++scan == *++match && *++scan == *++match &&
  81965. *++scan == *++match && *++scan == *++match &&
  81966. *++scan == *++match && *++scan == *++match &&
  81967. scan < strend);
  81968. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81969. len = MAX_MATCH - (int)(strend - scan);
  81970. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81971. s->match_start = cur_match;
  81972. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81973. }
  81974. #ifdef DEBUG
  81975. /* ===========================================================================
  81976. * Check that the match at match_start is indeed a match.
  81977. */
  81978. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81979. {
  81980. /* check that the match is indeed a match */
  81981. if (zmemcmp(s->window + match,
  81982. s->window + start, length) != EQUAL) {
  81983. fprintf(stderr, " start %u, match %u, length %d\n",
  81984. start, match, length);
  81985. do {
  81986. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81987. } while (--length != 0);
  81988. z_error("invalid match");
  81989. }
  81990. if (z_verbose > 1) {
  81991. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81992. do { putc(s->window[start++], stderr); } while (--length != 0);
  81993. }
  81994. }
  81995. #else
  81996. # define check_match(s, start, match, length)
  81997. #endif /* DEBUG */
  81998. /* ===========================================================================
  81999. * Fill the window when the lookahead becomes insufficient.
  82000. * Updates strstart and lookahead.
  82001. *
  82002. * IN assertion: lookahead < MIN_LOOKAHEAD
  82003. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82004. * At least one byte has been read, or avail_in == 0; reads are
  82005. * performed for at least two bytes (required for the zip translate_eol
  82006. * option -- not supported here).
  82007. */
  82008. local void fill_window (deflate_state *s)
  82009. {
  82010. register unsigned n, m;
  82011. register Posf *p;
  82012. unsigned more; /* Amount of free space at the end of the window. */
  82013. uInt wsize = s->w_size;
  82014. do {
  82015. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82016. /* Deal with !@#$% 64K limit: */
  82017. if (sizeof(int) <= 2) {
  82018. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82019. more = wsize;
  82020. } else if (more == (unsigned)(-1)) {
  82021. /* Very unlikely, but possible on 16 bit machine if
  82022. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82023. */
  82024. more--;
  82025. }
  82026. }
  82027. /* If the window is almost full and there is insufficient lookahead,
  82028. * move the upper half to the lower one to make room in the upper half.
  82029. */
  82030. if (s->strstart >= wsize+MAX_DIST(s)) {
  82031. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82032. s->match_start -= wsize;
  82033. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82034. s->block_start -= (long) wsize;
  82035. /* Slide the hash table (could be avoided with 32 bit values
  82036. at the expense of memory usage). We slide even when level == 0
  82037. to keep the hash table consistent if we switch back to level > 0
  82038. later. (Using level 0 permanently is not an optimal usage of
  82039. zlib, so we don't care about this pathological case.)
  82040. */
  82041. /* %%% avoid this when Z_RLE */
  82042. n = s->hash_size;
  82043. p = &s->head[n];
  82044. do {
  82045. m = *--p;
  82046. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82047. } while (--n);
  82048. n = wsize;
  82049. #ifndef FASTEST
  82050. p = &s->prev[n];
  82051. do {
  82052. m = *--p;
  82053. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82054. /* If n is not on any hash chain, prev[n] is garbage but
  82055. * its value will never be used.
  82056. */
  82057. } while (--n);
  82058. #endif
  82059. more += wsize;
  82060. }
  82061. if (s->strm->avail_in == 0) return;
  82062. /* If there was no sliding:
  82063. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82064. * more == window_size - lookahead - strstart
  82065. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82066. * => more >= window_size - 2*WSIZE + 2
  82067. * In the BIG_MEM or MMAP case (not yet supported),
  82068. * window_size == input_size + MIN_LOOKAHEAD &&
  82069. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82070. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82071. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82072. */
  82073. Assert(more >= 2, "more < 2");
  82074. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82075. s->lookahead += n;
  82076. /* Initialize the hash value now that we have some input: */
  82077. if (s->lookahead >= MIN_MATCH) {
  82078. s->ins_h = s->window[s->strstart];
  82079. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82080. #if MIN_MATCH != 3
  82081. Call UPDATE_HASH() MIN_MATCH-3 more times
  82082. #endif
  82083. }
  82084. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82085. * but this is not important since only literal bytes will be emitted.
  82086. */
  82087. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82088. }
  82089. /* ===========================================================================
  82090. * Flush the current block, with given end-of-file flag.
  82091. * IN assertion: strstart is set to the end of the current match.
  82092. */
  82093. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82094. _tr_flush_block(s, (s->block_start >= 0L ? \
  82095. (charf *)&s->window[(unsigned)s->block_start] : \
  82096. (charf *)Z_NULL), \
  82097. (ulg)((long)s->strstart - s->block_start), \
  82098. (eof)); \
  82099. s->block_start = s->strstart; \
  82100. flush_pending(s->strm); \
  82101. Tracev((stderr,"[FLUSH]")); \
  82102. }
  82103. /* Same but force premature exit if necessary. */
  82104. #define FLUSH_BLOCK(s, eof) { \
  82105. FLUSH_BLOCK_ONLY(s, eof); \
  82106. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82107. }
  82108. /* ===========================================================================
  82109. * Copy without compression as much as possible from the input stream, return
  82110. * the current block state.
  82111. * This function does not insert new strings in the dictionary since
  82112. * uncompressible data is probably not useful. This function is used
  82113. * only for the level=0 compression option.
  82114. * NOTE: this function should be optimized to avoid extra copying from
  82115. * window to pending_buf.
  82116. */
  82117. local block_state deflate_stored(deflate_state *s, int flush)
  82118. {
  82119. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82120. * to pending_buf_size, and each stored block has a 5 byte header:
  82121. */
  82122. ulg max_block_size = 0xffff;
  82123. ulg max_start;
  82124. if (max_block_size > s->pending_buf_size - 5) {
  82125. max_block_size = s->pending_buf_size - 5;
  82126. }
  82127. /* Copy as much as possible from input to output: */
  82128. for (;;) {
  82129. /* Fill the window as much as possible: */
  82130. if (s->lookahead <= 1) {
  82131. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82132. s->block_start >= (long)s->w_size, "slide too late");
  82133. fill_window(s);
  82134. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82135. if (s->lookahead == 0) break; /* flush the current block */
  82136. }
  82137. Assert(s->block_start >= 0L, "block gone");
  82138. s->strstart += s->lookahead;
  82139. s->lookahead = 0;
  82140. /* Emit a stored block if pending_buf will be full: */
  82141. max_start = s->block_start + max_block_size;
  82142. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82143. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82144. s->lookahead = (uInt)(s->strstart - max_start);
  82145. s->strstart = (uInt)max_start;
  82146. FLUSH_BLOCK(s, 0);
  82147. }
  82148. /* Flush if we may have to slide, otherwise block_start may become
  82149. * negative and the data will be gone:
  82150. */
  82151. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82152. FLUSH_BLOCK(s, 0);
  82153. }
  82154. }
  82155. FLUSH_BLOCK(s, flush == Z_FINISH);
  82156. return flush == Z_FINISH ? finish_done : block_done;
  82157. }
  82158. /* ===========================================================================
  82159. * Compress as much as possible from the input stream, return the current
  82160. * block state.
  82161. * This function does not perform lazy evaluation of matches and inserts
  82162. * new strings in the dictionary only for unmatched strings or for short
  82163. * matches. It is used only for the fast compression options.
  82164. */
  82165. local block_state deflate_fast(deflate_state *s, int flush)
  82166. {
  82167. IPos hash_head = NIL; /* head of the hash chain */
  82168. int bflush; /* set if current block must be flushed */
  82169. for (;;) {
  82170. /* Make sure that we always have enough lookahead, except
  82171. * at the end of the input file. We need MAX_MATCH bytes
  82172. * for the next match, plus MIN_MATCH bytes to insert the
  82173. * string following the next match.
  82174. */
  82175. if (s->lookahead < MIN_LOOKAHEAD) {
  82176. fill_window(s);
  82177. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82178. return need_more;
  82179. }
  82180. if (s->lookahead == 0) break; /* flush the current block */
  82181. }
  82182. /* Insert the string window[strstart .. strstart+2] in the
  82183. * dictionary, and set hash_head to the head of the hash chain:
  82184. */
  82185. if (s->lookahead >= MIN_MATCH) {
  82186. INSERT_STRING(s, s->strstart, hash_head);
  82187. }
  82188. /* Find the longest match, discarding those <= prev_length.
  82189. * At this point we have always match_length < MIN_MATCH
  82190. */
  82191. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82192. /* To simplify the code, we prevent matches with the string
  82193. * of window index 0 (in particular we have to avoid a match
  82194. * of the string with itself at the start of the input file).
  82195. */
  82196. #ifdef FASTEST
  82197. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82198. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82199. s->match_length = longest_match_fast (s, hash_head);
  82200. }
  82201. #else
  82202. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82203. s->match_length = longest_match (s, hash_head);
  82204. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82205. s->match_length = longest_match_fast (s, hash_head);
  82206. }
  82207. #endif
  82208. /* longest_match() or longest_match_fast() sets match_start */
  82209. }
  82210. if (s->match_length >= MIN_MATCH) {
  82211. check_match(s, s->strstart, s->match_start, s->match_length);
  82212. _tr_tally_dist(s, s->strstart - s->match_start,
  82213. s->match_length - MIN_MATCH, bflush);
  82214. s->lookahead -= s->match_length;
  82215. /* Insert new strings in the hash table only if the match length
  82216. * is not too large. This saves time but degrades compression.
  82217. */
  82218. #ifndef FASTEST
  82219. if (s->match_length <= s->max_insert_length &&
  82220. s->lookahead >= MIN_MATCH) {
  82221. s->match_length--; /* string at strstart already in table */
  82222. do {
  82223. s->strstart++;
  82224. INSERT_STRING(s, s->strstart, hash_head);
  82225. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82226. * always MIN_MATCH bytes ahead.
  82227. */
  82228. } while (--s->match_length != 0);
  82229. s->strstart++;
  82230. } else
  82231. #endif
  82232. {
  82233. s->strstart += s->match_length;
  82234. s->match_length = 0;
  82235. s->ins_h = s->window[s->strstart];
  82236. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82237. #if MIN_MATCH != 3
  82238. Call UPDATE_HASH() MIN_MATCH-3 more times
  82239. #endif
  82240. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82241. * matter since it will be recomputed at next deflate call.
  82242. */
  82243. }
  82244. } else {
  82245. /* No match, output a literal byte */
  82246. Tracevv((stderr,"%c", s->window[s->strstart]));
  82247. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82248. s->lookahead--;
  82249. s->strstart++;
  82250. }
  82251. if (bflush) FLUSH_BLOCK(s, 0);
  82252. }
  82253. FLUSH_BLOCK(s, flush == Z_FINISH);
  82254. return flush == Z_FINISH ? finish_done : block_done;
  82255. }
  82256. #ifndef FASTEST
  82257. /* ===========================================================================
  82258. * Same as above, but achieves better compression. We use a lazy
  82259. * evaluation for matches: a match is finally adopted only if there is
  82260. * no better match at the next window position.
  82261. */
  82262. local block_state deflate_slow(deflate_state *s, int flush)
  82263. {
  82264. IPos hash_head = NIL; /* head of hash chain */
  82265. int bflush; /* set if current block must be flushed */
  82266. /* Process the input block. */
  82267. for (;;) {
  82268. /* Make sure that we always have enough lookahead, except
  82269. * at the end of the input file. We need MAX_MATCH bytes
  82270. * for the next match, plus MIN_MATCH bytes to insert the
  82271. * string following the next match.
  82272. */
  82273. if (s->lookahead < MIN_LOOKAHEAD) {
  82274. fill_window(s);
  82275. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82276. return need_more;
  82277. }
  82278. if (s->lookahead == 0) break; /* flush the current block */
  82279. }
  82280. /* Insert the string window[strstart .. strstart+2] in the
  82281. * dictionary, and set hash_head to the head of the hash chain:
  82282. */
  82283. if (s->lookahead >= MIN_MATCH) {
  82284. INSERT_STRING(s, s->strstart, hash_head);
  82285. }
  82286. /* Find the longest match, discarding those <= prev_length.
  82287. */
  82288. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82289. s->match_length = MIN_MATCH-1;
  82290. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82291. s->strstart - hash_head <= MAX_DIST(s)) {
  82292. /* To simplify the code, we prevent matches with the string
  82293. * of window index 0 (in particular we have to avoid a match
  82294. * of the string with itself at the start of the input file).
  82295. */
  82296. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82297. s->match_length = longest_match (s, hash_head);
  82298. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82299. s->match_length = longest_match_fast (s, hash_head);
  82300. }
  82301. /* longest_match() or longest_match_fast() sets match_start */
  82302. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82303. #if TOO_FAR <= 32767
  82304. || (s->match_length == MIN_MATCH &&
  82305. s->strstart - s->match_start > TOO_FAR)
  82306. #endif
  82307. )) {
  82308. /* If prev_match is also MIN_MATCH, match_start is garbage
  82309. * but we will ignore the current match anyway.
  82310. */
  82311. s->match_length = MIN_MATCH-1;
  82312. }
  82313. }
  82314. /* If there was a match at the previous step and the current
  82315. * match is not better, output the previous match:
  82316. */
  82317. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82318. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82319. /* Do not insert strings in hash table beyond this. */
  82320. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82321. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82322. s->prev_length - MIN_MATCH, bflush);
  82323. /* Insert in hash table all strings up to the end of the match.
  82324. * strstart-1 and strstart are already inserted. If there is not
  82325. * enough lookahead, the last two strings are not inserted in
  82326. * the hash table.
  82327. */
  82328. s->lookahead -= s->prev_length-1;
  82329. s->prev_length -= 2;
  82330. do {
  82331. if (++s->strstart <= max_insert) {
  82332. INSERT_STRING(s, s->strstart, hash_head);
  82333. }
  82334. } while (--s->prev_length != 0);
  82335. s->match_available = 0;
  82336. s->match_length = MIN_MATCH-1;
  82337. s->strstart++;
  82338. if (bflush) FLUSH_BLOCK(s, 0);
  82339. } else if (s->match_available) {
  82340. /* If there was no match at the previous position, output a
  82341. * single literal. If there was a match but the current match
  82342. * is longer, truncate the previous match to a single literal.
  82343. */
  82344. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82345. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82346. if (bflush) {
  82347. FLUSH_BLOCK_ONLY(s, 0);
  82348. }
  82349. s->strstart++;
  82350. s->lookahead--;
  82351. if (s->strm->avail_out == 0) return need_more;
  82352. } else {
  82353. /* There is no previous match to compare with, wait for
  82354. * the next step to decide.
  82355. */
  82356. s->match_available = 1;
  82357. s->strstart++;
  82358. s->lookahead--;
  82359. }
  82360. }
  82361. Assert (flush != Z_NO_FLUSH, "no flush?");
  82362. if (s->match_available) {
  82363. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82364. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82365. s->match_available = 0;
  82366. }
  82367. FLUSH_BLOCK(s, flush == Z_FINISH);
  82368. return flush == Z_FINISH ? finish_done : block_done;
  82369. }
  82370. #endif /* FASTEST */
  82371. #if 0
  82372. /* ===========================================================================
  82373. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82374. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82375. * deflate switches away from Z_RLE.)
  82376. */
  82377. local block_state deflate_rle(s, flush)
  82378. deflate_state *s;
  82379. int flush;
  82380. {
  82381. int bflush; /* set if current block must be flushed */
  82382. uInt run; /* length of run */
  82383. uInt max; /* maximum length of run */
  82384. uInt prev; /* byte at distance one to match */
  82385. Bytef *scan; /* scan for end of run */
  82386. for (;;) {
  82387. /* Make sure that we always have enough lookahead, except
  82388. * at the end of the input file. We need MAX_MATCH bytes
  82389. * for the longest encodable run.
  82390. */
  82391. if (s->lookahead < MAX_MATCH) {
  82392. fill_window(s);
  82393. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82394. return need_more;
  82395. }
  82396. if (s->lookahead == 0) break; /* flush the current block */
  82397. }
  82398. /* See how many times the previous byte repeats */
  82399. run = 0;
  82400. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82401. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82402. scan = s->window + s->strstart - 1;
  82403. prev = *scan++;
  82404. do {
  82405. if (*scan++ != prev)
  82406. break;
  82407. } while (++run < max);
  82408. }
  82409. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82410. if (run >= MIN_MATCH) {
  82411. check_match(s, s->strstart, s->strstart - 1, run);
  82412. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82413. s->lookahead -= run;
  82414. s->strstart += run;
  82415. } else {
  82416. /* No match, output a literal byte */
  82417. Tracevv((stderr,"%c", s->window[s->strstart]));
  82418. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82419. s->lookahead--;
  82420. s->strstart++;
  82421. }
  82422. if (bflush) FLUSH_BLOCK(s, 0);
  82423. }
  82424. FLUSH_BLOCK(s, flush == Z_FINISH);
  82425. return flush == Z_FINISH ? finish_done : block_done;
  82426. }
  82427. #endif
  82428. /*** End of inlined file: deflate.c ***/
  82429. /*** Start of inlined file: inffast.c ***/
  82430. /*** Start of inlined file: inftrees.h ***/
  82431. /* WARNING: this file should *not* be used by applications. It is
  82432. part of the implementation of the compression library and is
  82433. subject to change. Applications should only use zlib.h.
  82434. */
  82435. #ifndef _INFTREES_H_
  82436. #define _INFTREES_H_
  82437. /* Structure for decoding tables. Each entry provides either the
  82438. information needed to do the operation requested by the code that
  82439. indexed that table entry, or it provides a pointer to another
  82440. table that indexes more bits of the code. op indicates whether
  82441. the entry is a pointer to another table, a literal, a length or
  82442. distance, an end-of-block, or an invalid code. For a table
  82443. pointer, the low four bits of op is the number of index bits of
  82444. that table. For a length or distance, the low four bits of op
  82445. is the number of extra bits to get after the code. bits is
  82446. the number of bits in this code or part of the code to drop off
  82447. of the bit buffer. val is the actual byte to output in the case
  82448. of a literal, the base length or distance, or the offset from
  82449. the current table to the next table. Each entry is four bytes. */
  82450. typedef struct {
  82451. unsigned char op; /* operation, extra bits, table bits */
  82452. unsigned char bits; /* bits in this part of the code */
  82453. unsigned short val; /* offset in table or code value */
  82454. } code;
  82455. /* op values as set by inflate_table():
  82456. 00000000 - literal
  82457. 0000tttt - table link, tttt != 0 is the number of table index bits
  82458. 0001eeee - length or distance, eeee is the number of extra bits
  82459. 01100000 - end of block
  82460. 01000000 - invalid code
  82461. */
  82462. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82463. exhaustive search was 1444 code structures (852 for length/literals
  82464. and 592 for distances, the latter actually the result of an
  82465. exhaustive search). The true maximum is not known, but the value
  82466. below is more than safe. */
  82467. #define ENOUGH 2048
  82468. #define MAXD 592
  82469. /* Type of code to build for inftable() */
  82470. typedef enum {
  82471. CODES,
  82472. LENS,
  82473. DISTS
  82474. } codetype;
  82475. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82476. unsigned codes, code FAR * FAR *table,
  82477. unsigned FAR *bits, unsigned short FAR *work));
  82478. #endif
  82479. /*** End of inlined file: inftrees.h ***/
  82480. /*** Start of inlined file: inflate.h ***/
  82481. /* WARNING: this file should *not* be used by applications. It is
  82482. part of the implementation of the compression library and is
  82483. subject to change. Applications should only use zlib.h.
  82484. */
  82485. #ifndef _INFLATE_H_
  82486. #define _INFLATE_H_
  82487. /* define NO_GZIP when compiling if you want to disable gzip header and
  82488. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82489. the crc code when it is not needed. For shared libraries, gzip decoding
  82490. should be left enabled. */
  82491. #ifndef NO_GZIP
  82492. # define GUNZIP
  82493. #endif
  82494. /* Possible inflate modes between inflate() calls */
  82495. typedef enum {
  82496. HEAD, /* i: waiting for magic header */
  82497. FLAGS, /* i: waiting for method and flags (gzip) */
  82498. TIME, /* i: waiting for modification time (gzip) */
  82499. OS, /* i: waiting for extra flags and operating system (gzip) */
  82500. EXLEN, /* i: waiting for extra length (gzip) */
  82501. EXTRA, /* i: waiting for extra bytes (gzip) */
  82502. NAME, /* i: waiting for end of file name (gzip) */
  82503. COMMENT, /* i: waiting for end of comment (gzip) */
  82504. HCRC, /* i: waiting for header crc (gzip) */
  82505. DICTID, /* i: waiting for dictionary check value */
  82506. DICT, /* waiting for inflateSetDictionary() call */
  82507. TYPE, /* i: waiting for type bits, including last-flag bit */
  82508. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82509. STORED, /* i: waiting for stored size (length and complement) */
  82510. COPY, /* i/o: waiting for input or output to copy stored block */
  82511. TABLE, /* i: waiting for dynamic block table lengths */
  82512. LENLENS, /* i: waiting for code length code lengths */
  82513. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82514. LEN, /* i: waiting for length/lit code */
  82515. LENEXT, /* i: waiting for length extra bits */
  82516. DIST, /* i: waiting for distance code */
  82517. DISTEXT, /* i: waiting for distance extra bits */
  82518. MATCH, /* o: waiting for output space to copy string */
  82519. LIT, /* o: waiting for output space to write literal */
  82520. CHECK, /* i: waiting for 32-bit check value */
  82521. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82522. DONE, /* finished check, done -- remain here until reset */
  82523. BAD, /* got a data error -- remain here until reset */
  82524. MEM, /* got an inflate() memory error -- remain here until reset */
  82525. SYNC /* looking for synchronization bytes to restart inflate() */
  82526. } inflate_mode;
  82527. /*
  82528. State transitions between above modes -
  82529. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82530. Process header:
  82531. HEAD -> (gzip) or (zlib)
  82532. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82533. NAME -> COMMENT -> HCRC -> TYPE
  82534. (zlib) -> DICTID or TYPE
  82535. DICTID -> DICT -> TYPE
  82536. Read deflate blocks:
  82537. TYPE -> STORED or TABLE or LEN or CHECK
  82538. STORED -> COPY -> TYPE
  82539. TABLE -> LENLENS -> CODELENS -> LEN
  82540. Read deflate codes:
  82541. LEN -> LENEXT or LIT or TYPE
  82542. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82543. LIT -> LEN
  82544. Process trailer:
  82545. CHECK -> LENGTH -> DONE
  82546. */
  82547. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82548. struct inflate_state {
  82549. inflate_mode mode; /* current inflate mode */
  82550. int last; /* true if processing last block */
  82551. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82552. int havedict; /* true if dictionary provided */
  82553. int flags; /* gzip header method and flags (0 if zlib) */
  82554. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82555. unsigned long check; /* protected copy of check value */
  82556. unsigned long total; /* protected copy of output count */
  82557. gz_headerp head; /* where to save gzip header information */
  82558. /* sliding window */
  82559. unsigned wbits; /* log base 2 of requested window size */
  82560. unsigned wsize; /* window size or zero if not using window */
  82561. unsigned whave; /* valid bytes in the window */
  82562. unsigned write; /* window write index */
  82563. unsigned char FAR *window; /* allocated sliding window, if needed */
  82564. /* bit accumulator */
  82565. unsigned long hold; /* input bit accumulator */
  82566. unsigned bits; /* number of bits in "in" */
  82567. /* for string and stored block copying */
  82568. unsigned length; /* literal or length of data to copy */
  82569. unsigned offset; /* distance back to copy string from */
  82570. /* for table and code decoding */
  82571. unsigned extra; /* extra bits needed */
  82572. /* fixed and dynamic code tables */
  82573. code const FAR *lencode; /* starting table for length/literal codes */
  82574. code const FAR *distcode; /* starting table for distance codes */
  82575. unsigned lenbits; /* index bits for lencode */
  82576. unsigned distbits; /* index bits for distcode */
  82577. /* dynamic table building */
  82578. unsigned ncode; /* number of code length code lengths */
  82579. unsigned nlen; /* number of length code lengths */
  82580. unsigned ndist; /* number of distance code lengths */
  82581. unsigned have; /* number of code lengths in lens[] */
  82582. code FAR *next; /* next available space in codes[] */
  82583. unsigned short lens[320]; /* temporary storage for code lengths */
  82584. unsigned short work[288]; /* work area for code table building */
  82585. code codes[ENOUGH]; /* space for code tables */
  82586. };
  82587. #endif
  82588. /*** End of inlined file: inflate.h ***/
  82589. /*** Start of inlined file: inffast.h ***/
  82590. /* WARNING: this file should *not* be used by applications. It is
  82591. part of the implementation of the compression library and is
  82592. subject to change. Applications should only use zlib.h.
  82593. */
  82594. void inflate_fast OF((z_streamp strm, unsigned start));
  82595. /*** End of inlined file: inffast.h ***/
  82596. #ifndef ASMINF
  82597. /* Allow machine dependent optimization for post-increment or pre-increment.
  82598. Based on testing to date,
  82599. Pre-increment preferred for:
  82600. - PowerPC G3 (Adler)
  82601. - MIPS R5000 (Randers-Pehrson)
  82602. Post-increment preferred for:
  82603. - none
  82604. No measurable difference:
  82605. - Pentium III (Anderson)
  82606. - M68060 (Nikl)
  82607. */
  82608. #ifdef POSTINC
  82609. # define OFF 0
  82610. # define PUP(a) *(a)++
  82611. #else
  82612. # define OFF 1
  82613. # define PUP(a) *++(a)
  82614. #endif
  82615. /*
  82616. Decode literal, length, and distance codes and write out the resulting
  82617. literal and match bytes until either not enough input or output is
  82618. available, an end-of-block is encountered, or a data error is encountered.
  82619. When large enough input and output buffers are supplied to inflate(), for
  82620. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82621. inflate execution time is spent in this routine.
  82622. Entry assumptions:
  82623. state->mode == LEN
  82624. strm->avail_in >= 6
  82625. strm->avail_out >= 258
  82626. start >= strm->avail_out
  82627. state->bits < 8
  82628. On return, state->mode is one of:
  82629. LEN -- ran out of enough output space or enough available input
  82630. TYPE -- reached end of block code, inflate() to interpret next block
  82631. BAD -- error in block data
  82632. Notes:
  82633. - The maximum input bits used by a length/distance pair is 15 bits for the
  82634. length code, 5 bits for the length extra, 15 bits for the distance code,
  82635. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82636. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82637. checking for available input while decoding.
  82638. - The maximum bytes that a single length/distance pair can output is 258
  82639. bytes, which is the maximum length that can be coded. inflate_fast()
  82640. requires strm->avail_out >= 258 for each loop to avoid checking for
  82641. output space.
  82642. */
  82643. void inflate_fast (z_streamp strm, unsigned start)
  82644. {
  82645. struct inflate_state FAR *state;
  82646. unsigned char FAR *in; /* local strm->next_in */
  82647. unsigned char FAR *last; /* while in < last, enough input available */
  82648. unsigned char FAR *out; /* local strm->next_out */
  82649. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82650. unsigned char FAR *end; /* while out < end, enough space available */
  82651. #ifdef INFLATE_STRICT
  82652. unsigned dmax; /* maximum distance from zlib header */
  82653. #endif
  82654. unsigned wsize; /* window size or zero if not using window */
  82655. unsigned whave; /* valid bytes in the window */
  82656. unsigned write; /* window write index */
  82657. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82658. unsigned long hold; /* local strm->hold */
  82659. unsigned bits; /* local strm->bits */
  82660. code const FAR *lcode; /* local strm->lencode */
  82661. code const FAR *dcode; /* local strm->distcode */
  82662. unsigned lmask; /* mask for first level of length codes */
  82663. unsigned dmask; /* mask for first level of distance codes */
  82664. code thisx; /* retrieved table entry */
  82665. unsigned op; /* code bits, operation, extra bits, or */
  82666. /* window position, window bytes to copy */
  82667. unsigned len; /* match length, unused bytes */
  82668. unsigned dist; /* match distance */
  82669. unsigned char FAR *from; /* where to copy match from */
  82670. /* copy state to local variables */
  82671. state = (struct inflate_state FAR *)strm->state;
  82672. in = strm->next_in - OFF;
  82673. last = in + (strm->avail_in - 5);
  82674. out = strm->next_out - OFF;
  82675. beg = out - (start - strm->avail_out);
  82676. end = out + (strm->avail_out - 257);
  82677. #ifdef INFLATE_STRICT
  82678. dmax = state->dmax;
  82679. #endif
  82680. wsize = state->wsize;
  82681. whave = state->whave;
  82682. write = state->write;
  82683. window = state->window;
  82684. hold = state->hold;
  82685. bits = state->bits;
  82686. lcode = state->lencode;
  82687. dcode = state->distcode;
  82688. lmask = (1U << state->lenbits) - 1;
  82689. dmask = (1U << state->distbits) - 1;
  82690. /* decode literals and length/distances until end-of-block or not enough
  82691. input data or output space */
  82692. do {
  82693. if (bits < 15) {
  82694. hold += (unsigned long)(PUP(in)) << bits;
  82695. bits += 8;
  82696. hold += (unsigned long)(PUP(in)) << bits;
  82697. bits += 8;
  82698. }
  82699. thisx = lcode[hold & lmask];
  82700. dolen:
  82701. op = (unsigned)(thisx.bits);
  82702. hold >>= op;
  82703. bits -= op;
  82704. op = (unsigned)(thisx.op);
  82705. if (op == 0) { /* literal */
  82706. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82707. "inflate: literal '%c'\n" :
  82708. "inflate: literal 0x%02x\n", thisx.val));
  82709. PUP(out) = (unsigned char)(thisx.val);
  82710. }
  82711. else if (op & 16) { /* length base */
  82712. len = (unsigned)(thisx.val);
  82713. op &= 15; /* number of extra bits */
  82714. if (op) {
  82715. if (bits < op) {
  82716. hold += (unsigned long)(PUP(in)) << bits;
  82717. bits += 8;
  82718. }
  82719. len += (unsigned)hold & ((1U << op) - 1);
  82720. hold >>= op;
  82721. bits -= op;
  82722. }
  82723. Tracevv((stderr, "inflate: length %u\n", len));
  82724. if (bits < 15) {
  82725. hold += (unsigned long)(PUP(in)) << bits;
  82726. bits += 8;
  82727. hold += (unsigned long)(PUP(in)) << bits;
  82728. bits += 8;
  82729. }
  82730. thisx = dcode[hold & dmask];
  82731. dodist:
  82732. op = (unsigned)(thisx.bits);
  82733. hold >>= op;
  82734. bits -= op;
  82735. op = (unsigned)(thisx.op);
  82736. if (op & 16) { /* distance base */
  82737. dist = (unsigned)(thisx.val);
  82738. op &= 15; /* number of extra bits */
  82739. if (bits < op) {
  82740. hold += (unsigned long)(PUP(in)) << bits;
  82741. bits += 8;
  82742. if (bits < op) {
  82743. hold += (unsigned long)(PUP(in)) << bits;
  82744. bits += 8;
  82745. }
  82746. }
  82747. dist += (unsigned)hold & ((1U << op) - 1);
  82748. #ifdef INFLATE_STRICT
  82749. if (dist > dmax) {
  82750. strm->msg = (char *)"invalid distance too far back";
  82751. state->mode = BAD;
  82752. break;
  82753. }
  82754. #endif
  82755. hold >>= op;
  82756. bits -= op;
  82757. Tracevv((stderr, "inflate: distance %u\n", dist));
  82758. op = (unsigned)(out - beg); /* max distance in output */
  82759. if (dist > op) { /* see if copy from window */
  82760. op = dist - op; /* distance back in window */
  82761. if (op > whave) {
  82762. strm->msg = (char *)"invalid distance too far back";
  82763. state->mode = BAD;
  82764. break;
  82765. }
  82766. from = window - OFF;
  82767. if (write == 0) { /* very common case */
  82768. from += wsize - op;
  82769. if (op < len) { /* some from window */
  82770. len -= op;
  82771. do {
  82772. PUP(out) = PUP(from);
  82773. } while (--op);
  82774. from = out - dist; /* rest from output */
  82775. }
  82776. }
  82777. else if (write < op) { /* wrap around window */
  82778. from += wsize + write - op;
  82779. op -= write;
  82780. if (op < len) { /* some from end of window */
  82781. len -= op;
  82782. do {
  82783. PUP(out) = PUP(from);
  82784. } while (--op);
  82785. from = window - OFF;
  82786. if (write < len) { /* some from start of window */
  82787. op = write;
  82788. len -= op;
  82789. do {
  82790. PUP(out) = PUP(from);
  82791. } while (--op);
  82792. from = out - dist; /* rest from output */
  82793. }
  82794. }
  82795. }
  82796. else { /* contiguous in window */
  82797. from += write - op;
  82798. if (op < len) { /* some from window */
  82799. len -= op;
  82800. do {
  82801. PUP(out) = PUP(from);
  82802. } while (--op);
  82803. from = out - dist; /* rest from output */
  82804. }
  82805. }
  82806. while (len > 2) {
  82807. PUP(out) = PUP(from);
  82808. PUP(out) = PUP(from);
  82809. PUP(out) = PUP(from);
  82810. len -= 3;
  82811. }
  82812. if (len) {
  82813. PUP(out) = PUP(from);
  82814. if (len > 1)
  82815. PUP(out) = PUP(from);
  82816. }
  82817. }
  82818. else {
  82819. from = out - dist; /* copy direct from output */
  82820. do { /* minimum length is three */
  82821. PUP(out) = PUP(from);
  82822. PUP(out) = PUP(from);
  82823. PUP(out) = PUP(from);
  82824. len -= 3;
  82825. } while (len > 2);
  82826. if (len) {
  82827. PUP(out) = PUP(from);
  82828. if (len > 1)
  82829. PUP(out) = PUP(from);
  82830. }
  82831. }
  82832. }
  82833. else if ((op & 64) == 0) { /* 2nd level distance code */
  82834. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82835. goto dodist;
  82836. }
  82837. else {
  82838. strm->msg = (char *)"invalid distance code";
  82839. state->mode = BAD;
  82840. break;
  82841. }
  82842. }
  82843. else if ((op & 64) == 0) { /* 2nd level length code */
  82844. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82845. goto dolen;
  82846. }
  82847. else if (op & 32) { /* end-of-block */
  82848. Tracevv((stderr, "inflate: end of block\n"));
  82849. state->mode = TYPE;
  82850. break;
  82851. }
  82852. else {
  82853. strm->msg = (char *)"invalid literal/length code";
  82854. state->mode = BAD;
  82855. break;
  82856. }
  82857. } while (in < last && out < end);
  82858. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82859. len = bits >> 3;
  82860. in -= len;
  82861. bits -= len << 3;
  82862. hold &= (1U << bits) - 1;
  82863. /* update state and return */
  82864. strm->next_in = in + OFF;
  82865. strm->next_out = out + OFF;
  82866. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82867. strm->avail_out = (unsigned)(out < end ?
  82868. 257 + (end - out) : 257 - (out - end));
  82869. state->hold = hold;
  82870. state->bits = bits;
  82871. return;
  82872. }
  82873. /*
  82874. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82875. - Using bit fields for code structure
  82876. - Different op definition to avoid & for extra bits (do & for table bits)
  82877. - Three separate decoding do-loops for direct, window, and write == 0
  82878. - Special case for distance > 1 copies to do overlapped load and store copy
  82879. - Explicit branch predictions (based on measured branch probabilities)
  82880. - Deferring match copy and interspersed it with decoding subsequent codes
  82881. - Swapping literal/length else
  82882. - Swapping window/direct else
  82883. - Larger unrolled copy loops (three is about right)
  82884. - Moving len -= 3 statement into middle of loop
  82885. */
  82886. #endif /* !ASMINF */
  82887. /*** End of inlined file: inffast.c ***/
  82888. #undef PULLBYTE
  82889. #undef LOAD
  82890. #undef RESTORE
  82891. #undef INITBITS
  82892. #undef NEEDBITS
  82893. #undef DROPBITS
  82894. #undef BYTEBITS
  82895. /*** Start of inlined file: inflate.c ***/
  82896. /*
  82897. * Change history:
  82898. *
  82899. * 1.2.beta0 24 Nov 2002
  82900. * - First version -- complete rewrite of inflate to simplify code, avoid
  82901. * creation of window when not needed, minimize use of window when it is
  82902. * needed, make inffast.c even faster, implement gzip decoding, and to
  82903. * improve code readability and style over the previous zlib inflate code
  82904. *
  82905. * 1.2.beta1 25 Nov 2002
  82906. * - Use pointers for available input and output checking in inffast.c
  82907. * - Remove input and output counters in inffast.c
  82908. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82909. * - Remove unnecessary second byte pull from length extra in inffast.c
  82910. * - Unroll direct copy to three copies per loop in inffast.c
  82911. *
  82912. * 1.2.beta2 4 Dec 2002
  82913. * - Change external routine names to reduce potential conflicts
  82914. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82915. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82916. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82917. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82918. *
  82919. * 1.2.beta3 22 Dec 2002
  82920. * - Add comments on state->bits assertion in inffast.c
  82921. * - Add comments on op field in inftrees.h
  82922. * - Fix bug in reuse of allocated window after inflateReset()
  82923. * - Remove bit fields--back to byte structure for speed
  82924. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82925. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82926. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82927. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82928. * - Use local copies of stream next and avail values, as well as local bit
  82929. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82930. *
  82931. * 1.2.beta4 1 Jan 2003
  82932. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82933. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82934. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82935. * - Rearrange window copies in inflate_fast() for speed and simplification
  82936. * - Unroll last copy for window match in inflate_fast()
  82937. * - Use local copies of window variables in inflate_fast() for speed
  82938. * - Pull out common write == 0 case for speed in inflate_fast()
  82939. * - Make op and len in inflate_fast() unsigned for consistency
  82940. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82941. * - Simplified bad distance check in inflate_fast()
  82942. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82943. * source file infback.c to provide a call-back interface to inflate for
  82944. * programs like gzip and unzip -- uses window as output buffer to avoid
  82945. * window copying
  82946. *
  82947. * 1.2.beta5 1 Jan 2003
  82948. * - Improved inflateBack() interface to allow the caller to provide initial
  82949. * input in strm.
  82950. * - Fixed stored blocks bug in inflateBack()
  82951. *
  82952. * 1.2.beta6 4 Jan 2003
  82953. * - Added comments in inffast.c on effectiveness of POSTINC
  82954. * - Typecasting all around to reduce compiler warnings
  82955. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82956. * make compilers happy
  82957. * - Changed type of window in inflateBackInit() to unsigned char *
  82958. *
  82959. * 1.2.beta7 27 Jan 2003
  82960. * - Changed many types to unsigned or unsigned short to avoid warnings
  82961. * - Added inflateCopy() function
  82962. *
  82963. * 1.2.0 9 Mar 2003
  82964. * - Changed inflateBack() interface to provide separate opaque descriptors
  82965. * for the in() and out() functions
  82966. * - Changed inflateBack() argument and in_func typedef to swap the length
  82967. * and buffer address return values for the input function
  82968. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82969. *
  82970. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82971. */
  82972. /*** Start of inlined file: inffast.h ***/
  82973. /* WARNING: this file should *not* be used by applications. It is
  82974. part of the implementation of the compression library and is
  82975. subject to change. Applications should only use zlib.h.
  82976. */
  82977. void inflate_fast OF((z_streamp strm, unsigned start));
  82978. /*** End of inlined file: inffast.h ***/
  82979. #ifdef MAKEFIXED
  82980. # ifndef BUILDFIXED
  82981. # define BUILDFIXED
  82982. # endif
  82983. #endif
  82984. /* function prototypes */
  82985. local void fixedtables OF((struct inflate_state FAR *state));
  82986. local int updatewindow OF((z_streamp strm, unsigned out));
  82987. #ifdef BUILDFIXED
  82988. void makefixed OF((void));
  82989. #endif
  82990. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82991. unsigned len));
  82992. int ZEXPORT inflateReset (z_streamp strm)
  82993. {
  82994. struct inflate_state FAR *state;
  82995. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82996. state = (struct inflate_state FAR *)strm->state;
  82997. strm->total_in = strm->total_out = state->total = 0;
  82998. strm->msg = Z_NULL;
  82999. strm->adler = 1; /* to support ill-conceived Java test suite */
  83000. state->mode = HEAD;
  83001. state->last = 0;
  83002. state->havedict = 0;
  83003. state->dmax = 32768U;
  83004. state->head = Z_NULL;
  83005. state->wsize = 0;
  83006. state->whave = 0;
  83007. state->write = 0;
  83008. state->hold = 0;
  83009. state->bits = 0;
  83010. state->lencode = state->distcode = state->next = state->codes;
  83011. Tracev((stderr, "inflate: reset\n"));
  83012. return Z_OK;
  83013. }
  83014. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83015. {
  83016. struct inflate_state FAR *state;
  83017. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83018. state = (struct inflate_state FAR *)strm->state;
  83019. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83020. value &= (1L << bits) - 1;
  83021. state->hold += value << state->bits;
  83022. state->bits += bits;
  83023. return Z_OK;
  83024. }
  83025. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83026. {
  83027. struct inflate_state FAR *state;
  83028. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83029. stream_size != (int)(sizeof(z_stream)))
  83030. return Z_VERSION_ERROR;
  83031. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83032. strm->msg = Z_NULL; /* in case we return an error */
  83033. if (strm->zalloc == (alloc_func)0) {
  83034. strm->zalloc = zcalloc;
  83035. strm->opaque = (voidpf)0;
  83036. }
  83037. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83038. state = (struct inflate_state FAR *)
  83039. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83040. if (state == Z_NULL) return Z_MEM_ERROR;
  83041. Tracev((stderr, "inflate: allocated\n"));
  83042. strm->state = (struct internal_state FAR *)state;
  83043. if (windowBits < 0) {
  83044. state->wrap = 0;
  83045. windowBits = -windowBits;
  83046. }
  83047. else {
  83048. state->wrap = (windowBits >> 4) + 1;
  83049. #ifdef GUNZIP
  83050. if (windowBits < 48) windowBits &= 15;
  83051. #endif
  83052. }
  83053. if (windowBits < 8 || windowBits > 15) {
  83054. ZFREE(strm, state);
  83055. strm->state = Z_NULL;
  83056. return Z_STREAM_ERROR;
  83057. }
  83058. state->wbits = (unsigned)windowBits;
  83059. state->window = Z_NULL;
  83060. return inflateReset(strm);
  83061. }
  83062. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83063. {
  83064. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83065. }
  83066. /*
  83067. Return state with length and distance decoding tables and index sizes set to
  83068. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83069. If BUILDFIXED is defined, then instead this routine builds the tables the
  83070. first time it's called, and returns those tables the first time and
  83071. thereafter. This reduces the size of the code by about 2K bytes, in
  83072. exchange for a little execution time. However, BUILDFIXED should not be
  83073. used for threaded applications, since the rewriting of the tables and virgin
  83074. may not be thread-safe.
  83075. */
  83076. local void fixedtables (struct inflate_state FAR *state)
  83077. {
  83078. #ifdef BUILDFIXED
  83079. static int virgin = 1;
  83080. static code *lenfix, *distfix;
  83081. static code fixed[544];
  83082. /* build fixed huffman tables if first call (may not be thread safe) */
  83083. if (virgin) {
  83084. unsigned sym, bits;
  83085. static code *next;
  83086. /* literal/length table */
  83087. sym = 0;
  83088. while (sym < 144) state->lens[sym++] = 8;
  83089. while (sym < 256) state->lens[sym++] = 9;
  83090. while (sym < 280) state->lens[sym++] = 7;
  83091. while (sym < 288) state->lens[sym++] = 8;
  83092. next = fixed;
  83093. lenfix = next;
  83094. bits = 9;
  83095. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83096. /* distance table */
  83097. sym = 0;
  83098. while (sym < 32) state->lens[sym++] = 5;
  83099. distfix = next;
  83100. bits = 5;
  83101. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83102. /* do this just once */
  83103. virgin = 0;
  83104. }
  83105. #else /* !BUILDFIXED */
  83106. /*** Start of inlined file: inffixed.h ***/
  83107. /* WARNING: this file should *not* be used by applications. It
  83108. is part of the implementation of the compression library and
  83109. is subject to change. Applications should only use zlib.h.
  83110. */
  83111. static const code lenfix[512] = {
  83112. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83113. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83114. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83115. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83116. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83117. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83118. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83119. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83120. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83121. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83122. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83123. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83124. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83125. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83126. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83127. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83128. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83129. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83130. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83131. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83132. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83133. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83134. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83135. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83136. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83137. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83138. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83139. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83140. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83141. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83142. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83143. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83144. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83145. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83146. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83147. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83148. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83149. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83150. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83151. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83152. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83153. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83154. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83155. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83156. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83157. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83158. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83159. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83160. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83161. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83162. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83163. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83164. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83165. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83166. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83167. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83168. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83169. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83170. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83171. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83172. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83173. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83174. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83175. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83176. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83177. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83178. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83179. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83180. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83181. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83182. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83183. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83184. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83185. {0,9,255}
  83186. };
  83187. static const code distfix[32] = {
  83188. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83189. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83190. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83191. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83192. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83193. {22,5,193},{64,5,0}
  83194. };
  83195. /*** End of inlined file: inffixed.h ***/
  83196. #endif /* BUILDFIXED */
  83197. state->lencode = lenfix;
  83198. state->lenbits = 9;
  83199. state->distcode = distfix;
  83200. state->distbits = 5;
  83201. }
  83202. #ifdef MAKEFIXED
  83203. #include <stdio.h>
  83204. /*
  83205. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83206. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83207. those tables to stdout, which would be piped to inffixed.h. A small program
  83208. can simply call makefixed to do this:
  83209. void makefixed(void);
  83210. int main(void)
  83211. {
  83212. makefixed();
  83213. return 0;
  83214. }
  83215. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83216. a.out > inffixed.h
  83217. */
  83218. void makefixed()
  83219. {
  83220. unsigned low, size;
  83221. struct inflate_state state;
  83222. fixedtables(&state);
  83223. puts(" /* inffixed.h -- table for decoding fixed codes");
  83224. puts(" * Generated automatically by makefixed().");
  83225. puts(" */");
  83226. puts("");
  83227. puts(" /* WARNING: this file should *not* be used by applications.");
  83228. puts(" It is part of the implementation of this library and is");
  83229. puts(" subject to change. Applications should only use zlib.h.");
  83230. puts(" */");
  83231. puts("");
  83232. size = 1U << 9;
  83233. printf(" static const code lenfix[%u] = {", size);
  83234. low = 0;
  83235. for (;;) {
  83236. if ((low % 7) == 0) printf("\n ");
  83237. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83238. state.lencode[low].val);
  83239. if (++low == size) break;
  83240. putchar(',');
  83241. }
  83242. puts("\n };");
  83243. size = 1U << 5;
  83244. printf("\n static const code distfix[%u] = {", size);
  83245. low = 0;
  83246. for (;;) {
  83247. if ((low % 6) == 0) printf("\n ");
  83248. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83249. state.distcode[low].val);
  83250. if (++low == size) break;
  83251. putchar(',');
  83252. }
  83253. puts("\n };");
  83254. }
  83255. #endif /* MAKEFIXED */
  83256. /*
  83257. Update the window with the last wsize (normally 32K) bytes written before
  83258. returning. If window does not exist yet, create it. This is only called
  83259. when a window is already in use, or when output has been written during this
  83260. inflate call, but the end of the deflate stream has not been reached yet.
  83261. It is also called to create a window for dictionary data when a dictionary
  83262. is loaded.
  83263. Providing output buffers larger than 32K to inflate() should provide a speed
  83264. advantage, since only the last 32K of output is copied to the sliding window
  83265. upon return from inflate(), and since all distances after the first 32K of
  83266. output will fall in the output data, making match copies simpler and faster.
  83267. The advantage may be dependent on the size of the processor's data caches.
  83268. */
  83269. local int updatewindow (z_streamp strm, unsigned out)
  83270. {
  83271. struct inflate_state FAR *state;
  83272. unsigned copy, dist;
  83273. state = (struct inflate_state FAR *)strm->state;
  83274. /* if it hasn't been done already, allocate space for the window */
  83275. if (state->window == Z_NULL) {
  83276. state->window = (unsigned char FAR *)
  83277. ZALLOC(strm, 1U << state->wbits,
  83278. sizeof(unsigned char));
  83279. if (state->window == Z_NULL) return 1;
  83280. }
  83281. /* if window not in use yet, initialize */
  83282. if (state->wsize == 0) {
  83283. state->wsize = 1U << state->wbits;
  83284. state->write = 0;
  83285. state->whave = 0;
  83286. }
  83287. /* copy state->wsize or less output bytes into the circular window */
  83288. copy = out - strm->avail_out;
  83289. if (copy >= state->wsize) {
  83290. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83291. state->write = 0;
  83292. state->whave = state->wsize;
  83293. }
  83294. else {
  83295. dist = state->wsize - state->write;
  83296. if (dist > copy) dist = copy;
  83297. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83298. copy -= dist;
  83299. if (copy) {
  83300. zmemcpy(state->window, strm->next_out - copy, copy);
  83301. state->write = copy;
  83302. state->whave = state->wsize;
  83303. }
  83304. else {
  83305. state->write += dist;
  83306. if (state->write == state->wsize) state->write = 0;
  83307. if (state->whave < state->wsize) state->whave += dist;
  83308. }
  83309. }
  83310. return 0;
  83311. }
  83312. /* Macros for inflate(): */
  83313. /* check function to use adler32() for zlib or crc32() for gzip */
  83314. #ifdef GUNZIP
  83315. # define UPDATE(check, buf, len) \
  83316. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83317. #else
  83318. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83319. #endif
  83320. /* check macros for header crc */
  83321. #ifdef GUNZIP
  83322. # define CRC2(check, word) \
  83323. do { \
  83324. hbuf[0] = (unsigned char)(word); \
  83325. hbuf[1] = (unsigned char)((word) >> 8); \
  83326. check = crc32(check, hbuf, 2); \
  83327. } while (0)
  83328. # define CRC4(check, word) \
  83329. do { \
  83330. hbuf[0] = (unsigned char)(word); \
  83331. hbuf[1] = (unsigned char)((word) >> 8); \
  83332. hbuf[2] = (unsigned char)((word) >> 16); \
  83333. hbuf[3] = (unsigned char)((word) >> 24); \
  83334. check = crc32(check, hbuf, 4); \
  83335. } while (0)
  83336. #endif
  83337. /* Load registers with state in inflate() for speed */
  83338. #define LOAD() \
  83339. do { \
  83340. put = strm->next_out; \
  83341. left = strm->avail_out; \
  83342. next = strm->next_in; \
  83343. have = strm->avail_in; \
  83344. hold = state->hold; \
  83345. bits = state->bits; \
  83346. } while (0)
  83347. /* Restore state from registers in inflate() */
  83348. #define RESTORE() \
  83349. do { \
  83350. strm->next_out = put; \
  83351. strm->avail_out = left; \
  83352. strm->next_in = next; \
  83353. strm->avail_in = have; \
  83354. state->hold = hold; \
  83355. state->bits = bits; \
  83356. } while (0)
  83357. /* Clear the input bit accumulator */
  83358. #define INITBITS() \
  83359. do { \
  83360. hold = 0; \
  83361. bits = 0; \
  83362. } while (0)
  83363. /* Get a byte of input into the bit accumulator, or return from inflate()
  83364. if there is no input available. */
  83365. #define PULLBYTE() \
  83366. do { \
  83367. if (have == 0) goto inf_leave; \
  83368. have--; \
  83369. hold += (unsigned long)(*next++) << bits; \
  83370. bits += 8; \
  83371. } while (0)
  83372. /* Assure that there are at least n bits in the bit accumulator. If there is
  83373. not enough available input to do that, then return from inflate(). */
  83374. #define NEEDBITS(n) \
  83375. do { \
  83376. while (bits < (unsigned)(n)) \
  83377. PULLBYTE(); \
  83378. } while (0)
  83379. /* Return the low n bits of the bit accumulator (n < 16) */
  83380. #define BITS(n) \
  83381. ((unsigned)hold & ((1U << (n)) - 1))
  83382. /* Remove n bits from the bit accumulator */
  83383. #define DROPBITS(n) \
  83384. do { \
  83385. hold >>= (n); \
  83386. bits -= (unsigned)(n); \
  83387. } while (0)
  83388. /* Remove zero to seven bits as needed to go to a byte boundary */
  83389. #define BYTEBITS() \
  83390. do { \
  83391. hold >>= bits & 7; \
  83392. bits -= bits & 7; \
  83393. } while (0)
  83394. /* Reverse the bytes in a 32-bit value */
  83395. #define REVERSE(q) \
  83396. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83397. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83398. /*
  83399. inflate() uses a state machine to process as much input data and generate as
  83400. much output data as possible before returning. The state machine is
  83401. structured roughly as follows:
  83402. for (;;) switch (state) {
  83403. ...
  83404. case STATEn:
  83405. if (not enough input data or output space to make progress)
  83406. return;
  83407. ... make progress ...
  83408. state = STATEm;
  83409. break;
  83410. ...
  83411. }
  83412. so when inflate() is called again, the same case is attempted again, and
  83413. if the appropriate resources are provided, the machine proceeds to the
  83414. next state. The NEEDBITS() macro is usually the way the state evaluates
  83415. whether it can proceed or should return. NEEDBITS() does the return if
  83416. the requested bits are not available. The typical use of the BITS macros
  83417. is:
  83418. NEEDBITS(n);
  83419. ... do something with BITS(n) ...
  83420. DROPBITS(n);
  83421. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83422. input left to load n bits into the accumulator, or it continues. BITS(n)
  83423. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83424. the low n bits off the accumulator. INITBITS() clears the accumulator
  83425. and sets the number of available bits to zero. BYTEBITS() discards just
  83426. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83427. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83428. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83429. if there is no input available. The decoding of variable length codes uses
  83430. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83431. code, and no more.
  83432. Some states loop until they get enough input, making sure that enough
  83433. state information is maintained to continue the loop where it left off
  83434. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83435. would all have to actually be part of the saved state in case NEEDBITS()
  83436. returns:
  83437. case STATEw:
  83438. while (want < need) {
  83439. NEEDBITS(n);
  83440. keep[want++] = BITS(n);
  83441. DROPBITS(n);
  83442. }
  83443. state = STATEx;
  83444. case STATEx:
  83445. As shown above, if the next state is also the next case, then the break
  83446. is omitted.
  83447. A state may also return if there is not enough output space available to
  83448. complete that state. Those states are copying stored data, writing a
  83449. literal byte, and copying a matching string.
  83450. When returning, a "goto inf_leave" is used to update the total counters,
  83451. update the check value, and determine whether any progress has been made
  83452. during that inflate() call in order to return the proper return code.
  83453. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83454. When there is a window, goto inf_leave will update the window with the last
  83455. output written. If a goto inf_leave occurs in the middle of decompression
  83456. and there is no window currently, goto inf_leave will create one and copy
  83457. output to the window for the next call of inflate().
  83458. In this implementation, the flush parameter of inflate() only affects the
  83459. return code (per zlib.h). inflate() always writes as much as possible to
  83460. strm->next_out, given the space available and the provided input--the effect
  83461. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83462. the allocation of and copying into a sliding window until necessary, which
  83463. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83464. stream available. So the only thing the flush parameter actually does is:
  83465. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83466. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83467. */
  83468. int ZEXPORT inflate (z_streamp strm, int flush)
  83469. {
  83470. struct inflate_state FAR *state;
  83471. unsigned char FAR *next; /* next input */
  83472. unsigned char FAR *put; /* next output */
  83473. unsigned have, left; /* available input and output */
  83474. unsigned long hold; /* bit buffer */
  83475. unsigned bits; /* bits in bit buffer */
  83476. unsigned in, out; /* save starting available input and output */
  83477. unsigned copy; /* number of stored or match bytes to copy */
  83478. unsigned char FAR *from; /* where to copy match bytes from */
  83479. code thisx; /* current decoding table entry */
  83480. code last; /* parent table entry */
  83481. unsigned len; /* length to copy for repeats, bits to drop */
  83482. int ret; /* return code */
  83483. #ifdef GUNZIP
  83484. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83485. #endif
  83486. static const unsigned short order[19] = /* permutation of code lengths */
  83487. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83488. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83489. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83490. return Z_STREAM_ERROR;
  83491. state = (struct inflate_state FAR *)strm->state;
  83492. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83493. LOAD();
  83494. in = have;
  83495. out = left;
  83496. ret = Z_OK;
  83497. for (;;)
  83498. switch (state->mode) {
  83499. case HEAD:
  83500. if (state->wrap == 0) {
  83501. state->mode = TYPEDO;
  83502. break;
  83503. }
  83504. NEEDBITS(16);
  83505. #ifdef GUNZIP
  83506. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83507. state->check = crc32(0L, Z_NULL, 0);
  83508. CRC2(state->check, hold);
  83509. INITBITS();
  83510. state->mode = FLAGS;
  83511. break;
  83512. }
  83513. state->flags = 0; /* expect zlib header */
  83514. if (state->head != Z_NULL)
  83515. state->head->done = -1;
  83516. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83517. #else
  83518. if (
  83519. #endif
  83520. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83521. strm->msg = (char *)"incorrect header check";
  83522. state->mode = BAD;
  83523. break;
  83524. }
  83525. if (BITS(4) != Z_DEFLATED) {
  83526. strm->msg = (char *)"unknown compression method";
  83527. state->mode = BAD;
  83528. break;
  83529. }
  83530. DROPBITS(4);
  83531. len = BITS(4) + 8;
  83532. if (len > state->wbits) {
  83533. strm->msg = (char *)"invalid window size";
  83534. state->mode = BAD;
  83535. break;
  83536. }
  83537. state->dmax = 1U << len;
  83538. Tracev((stderr, "inflate: zlib header ok\n"));
  83539. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83540. state->mode = hold & 0x200 ? DICTID : TYPE;
  83541. INITBITS();
  83542. break;
  83543. #ifdef GUNZIP
  83544. case FLAGS:
  83545. NEEDBITS(16);
  83546. state->flags = (int)(hold);
  83547. if ((state->flags & 0xff) != Z_DEFLATED) {
  83548. strm->msg = (char *)"unknown compression method";
  83549. state->mode = BAD;
  83550. break;
  83551. }
  83552. if (state->flags & 0xe000) {
  83553. strm->msg = (char *)"unknown header flags set";
  83554. state->mode = BAD;
  83555. break;
  83556. }
  83557. if (state->head != Z_NULL)
  83558. state->head->text = (int)((hold >> 8) & 1);
  83559. if (state->flags & 0x0200) CRC2(state->check, hold);
  83560. INITBITS();
  83561. state->mode = TIME;
  83562. case TIME:
  83563. NEEDBITS(32);
  83564. if (state->head != Z_NULL)
  83565. state->head->time = hold;
  83566. if (state->flags & 0x0200) CRC4(state->check, hold);
  83567. INITBITS();
  83568. state->mode = OS;
  83569. case OS:
  83570. NEEDBITS(16);
  83571. if (state->head != Z_NULL) {
  83572. state->head->xflags = (int)(hold & 0xff);
  83573. state->head->os = (int)(hold >> 8);
  83574. }
  83575. if (state->flags & 0x0200) CRC2(state->check, hold);
  83576. INITBITS();
  83577. state->mode = EXLEN;
  83578. case EXLEN:
  83579. if (state->flags & 0x0400) {
  83580. NEEDBITS(16);
  83581. state->length = (unsigned)(hold);
  83582. if (state->head != Z_NULL)
  83583. state->head->extra_len = (unsigned)hold;
  83584. if (state->flags & 0x0200) CRC2(state->check, hold);
  83585. INITBITS();
  83586. }
  83587. else if (state->head != Z_NULL)
  83588. state->head->extra = Z_NULL;
  83589. state->mode = EXTRA;
  83590. case EXTRA:
  83591. if (state->flags & 0x0400) {
  83592. copy = state->length;
  83593. if (copy > have) copy = have;
  83594. if (copy) {
  83595. if (state->head != Z_NULL &&
  83596. state->head->extra != Z_NULL) {
  83597. len = state->head->extra_len - state->length;
  83598. zmemcpy(state->head->extra + len, next,
  83599. len + copy > state->head->extra_max ?
  83600. state->head->extra_max - len : copy);
  83601. }
  83602. if (state->flags & 0x0200)
  83603. state->check = crc32(state->check, next, copy);
  83604. have -= copy;
  83605. next += copy;
  83606. state->length -= copy;
  83607. }
  83608. if (state->length) goto inf_leave;
  83609. }
  83610. state->length = 0;
  83611. state->mode = NAME;
  83612. case NAME:
  83613. if (state->flags & 0x0800) {
  83614. if (have == 0) goto inf_leave;
  83615. copy = 0;
  83616. do {
  83617. len = (unsigned)(next[copy++]);
  83618. if (state->head != Z_NULL &&
  83619. state->head->name != Z_NULL &&
  83620. state->length < state->head->name_max)
  83621. state->head->name[state->length++] = len;
  83622. } while (len && copy < have);
  83623. if (state->flags & 0x0200)
  83624. state->check = crc32(state->check, next, copy);
  83625. have -= copy;
  83626. next += copy;
  83627. if (len) goto inf_leave;
  83628. }
  83629. else if (state->head != Z_NULL)
  83630. state->head->name = Z_NULL;
  83631. state->length = 0;
  83632. state->mode = COMMENT;
  83633. case COMMENT:
  83634. if (state->flags & 0x1000) {
  83635. if (have == 0) goto inf_leave;
  83636. copy = 0;
  83637. do {
  83638. len = (unsigned)(next[copy++]);
  83639. if (state->head != Z_NULL &&
  83640. state->head->comment != Z_NULL &&
  83641. state->length < state->head->comm_max)
  83642. state->head->comment[state->length++] = len;
  83643. } while (len && copy < have);
  83644. if (state->flags & 0x0200)
  83645. state->check = crc32(state->check, next, copy);
  83646. have -= copy;
  83647. next += copy;
  83648. if (len) goto inf_leave;
  83649. }
  83650. else if (state->head != Z_NULL)
  83651. state->head->comment = Z_NULL;
  83652. state->mode = HCRC;
  83653. case HCRC:
  83654. if (state->flags & 0x0200) {
  83655. NEEDBITS(16);
  83656. if (hold != (state->check & 0xffff)) {
  83657. strm->msg = (char *)"header crc mismatch";
  83658. state->mode = BAD;
  83659. break;
  83660. }
  83661. INITBITS();
  83662. }
  83663. if (state->head != Z_NULL) {
  83664. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83665. state->head->done = 1;
  83666. }
  83667. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83668. state->mode = TYPE;
  83669. break;
  83670. #endif
  83671. case DICTID:
  83672. NEEDBITS(32);
  83673. strm->adler = state->check = REVERSE(hold);
  83674. INITBITS();
  83675. state->mode = DICT;
  83676. case DICT:
  83677. if (state->havedict == 0) {
  83678. RESTORE();
  83679. return Z_NEED_DICT;
  83680. }
  83681. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83682. state->mode = TYPE;
  83683. case TYPE:
  83684. if (flush == Z_BLOCK) goto inf_leave;
  83685. case TYPEDO:
  83686. if (state->last) {
  83687. BYTEBITS();
  83688. state->mode = CHECK;
  83689. break;
  83690. }
  83691. NEEDBITS(3);
  83692. state->last = BITS(1);
  83693. DROPBITS(1);
  83694. switch (BITS(2)) {
  83695. case 0: /* stored block */
  83696. Tracev((stderr, "inflate: stored block%s\n",
  83697. state->last ? " (last)" : ""));
  83698. state->mode = STORED;
  83699. break;
  83700. case 1: /* fixed block */
  83701. fixedtables(state);
  83702. Tracev((stderr, "inflate: fixed codes block%s\n",
  83703. state->last ? " (last)" : ""));
  83704. state->mode = LEN; /* decode codes */
  83705. break;
  83706. case 2: /* dynamic block */
  83707. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83708. state->last ? " (last)" : ""));
  83709. state->mode = TABLE;
  83710. break;
  83711. case 3:
  83712. strm->msg = (char *)"invalid block type";
  83713. state->mode = BAD;
  83714. }
  83715. DROPBITS(2);
  83716. break;
  83717. case STORED:
  83718. BYTEBITS(); /* go to byte boundary */
  83719. NEEDBITS(32);
  83720. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83721. strm->msg = (char *)"invalid stored block lengths";
  83722. state->mode = BAD;
  83723. break;
  83724. }
  83725. state->length = (unsigned)hold & 0xffff;
  83726. Tracev((stderr, "inflate: stored length %u\n",
  83727. state->length));
  83728. INITBITS();
  83729. state->mode = COPY;
  83730. case COPY:
  83731. copy = state->length;
  83732. if (copy) {
  83733. if (copy > have) copy = have;
  83734. if (copy > left) copy = left;
  83735. if (copy == 0) goto inf_leave;
  83736. zmemcpy(put, next, copy);
  83737. have -= copy;
  83738. next += copy;
  83739. left -= copy;
  83740. put += copy;
  83741. state->length -= copy;
  83742. break;
  83743. }
  83744. Tracev((stderr, "inflate: stored end\n"));
  83745. state->mode = TYPE;
  83746. break;
  83747. case TABLE:
  83748. NEEDBITS(14);
  83749. state->nlen = BITS(5) + 257;
  83750. DROPBITS(5);
  83751. state->ndist = BITS(5) + 1;
  83752. DROPBITS(5);
  83753. state->ncode = BITS(4) + 4;
  83754. DROPBITS(4);
  83755. #ifndef PKZIP_BUG_WORKAROUND
  83756. if (state->nlen > 286 || state->ndist > 30) {
  83757. strm->msg = (char *)"too many length or distance symbols";
  83758. state->mode = BAD;
  83759. break;
  83760. }
  83761. #endif
  83762. Tracev((stderr, "inflate: table sizes ok\n"));
  83763. state->have = 0;
  83764. state->mode = LENLENS;
  83765. case LENLENS:
  83766. while (state->have < state->ncode) {
  83767. NEEDBITS(3);
  83768. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83769. DROPBITS(3);
  83770. }
  83771. while (state->have < 19)
  83772. state->lens[order[state->have++]] = 0;
  83773. state->next = state->codes;
  83774. state->lencode = (code const FAR *)(state->next);
  83775. state->lenbits = 7;
  83776. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83777. &(state->lenbits), state->work);
  83778. if (ret) {
  83779. strm->msg = (char *)"invalid code lengths set";
  83780. state->mode = BAD;
  83781. break;
  83782. }
  83783. Tracev((stderr, "inflate: code lengths ok\n"));
  83784. state->have = 0;
  83785. state->mode = CODELENS;
  83786. case CODELENS:
  83787. while (state->have < state->nlen + state->ndist) {
  83788. for (;;) {
  83789. thisx = state->lencode[BITS(state->lenbits)];
  83790. if ((unsigned)(thisx.bits) <= bits) break;
  83791. PULLBYTE();
  83792. }
  83793. if (thisx.val < 16) {
  83794. NEEDBITS(thisx.bits);
  83795. DROPBITS(thisx.bits);
  83796. state->lens[state->have++] = thisx.val;
  83797. }
  83798. else {
  83799. if (thisx.val == 16) {
  83800. NEEDBITS(thisx.bits + 2);
  83801. DROPBITS(thisx.bits);
  83802. if (state->have == 0) {
  83803. strm->msg = (char *)"invalid bit length repeat";
  83804. state->mode = BAD;
  83805. break;
  83806. }
  83807. len = state->lens[state->have - 1];
  83808. copy = 3 + BITS(2);
  83809. DROPBITS(2);
  83810. }
  83811. else if (thisx.val == 17) {
  83812. NEEDBITS(thisx.bits + 3);
  83813. DROPBITS(thisx.bits);
  83814. len = 0;
  83815. copy = 3 + BITS(3);
  83816. DROPBITS(3);
  83817. }
  83818. else {
  83819. NEEDBITS(thisx.bits + 7);
  83820. DROPBITS(thisx.bits);
  83821. len = 0;
  83822. copy = 11 + BITS(7);
  83823. DROPBITS(7);
  83824. }
  83825. if (state->have + copy > state->nlen + state->ndist) {
  83826. strm->msg = (char *)"invalid bit length repeat";
  83827. state->mode = BAD;
  83828. break;
  83829. }
  83830. while (copy--)
  83831. state->lens[state->have++] = (unsigned short)len;
  83832. }
  83833. }
  83834. /* handle error breaks in while */
  83835. if (state->mode == BAD) break;
  83836. /* build code tables */
  83837. state->next = state->codes;
  83838. state->lencode = (code const FAR *)(state->next);
  83839. state->lenbits = 9;
  83840. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83841. &(state->lenbits), state->work);
  83842. if (ret) {
  83843. strm->msg = (char *)"invalid literal/lengths set";
  83844. state->mode = BAD;
  83845. break;
  83846. }
  83847. state->distcode = (code const FAR *)(state->next);
  83848. state->distbits = 6;
  83849. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83850. &(state->next), &(state->distbits), state->work);
  83851. if (ret) {
  83852. strm->msg = (char *)"invalid distances set";
  83853. state->mode = BAD;
  83854. break;
  83855. }
  83856. Tracev((stderr, "inflate: codes ok\n"));
  83857. state->mode = LEN;
  83858. case LEN:
  83859. if (have >= 6 && left >= 258) {
  83860. RESTORE();
  83861. inflate_fast(strm, out);
  83862. LOAD();
  83863. break;
  83864. }
  83865. for (;;) {
  83866. thisx = state->lencode[BITS(state->lenbits)];
  83867. if ((unsigned)(thisx.bits) <= bits) break;
  83868. PULLBYTE();
  83869. }
  83870. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83871. last = thisx;
  83872. for (;;) {
  83873. thisx = state->lencode[last.val +
  83874. (BITS(last.bits + last.op) >> last.bits)];
  83875. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83876. PULLBYTE();
  83877. }
  83878. DROPBITS(last.bits);
  83879. }
  83880. DROPBITS(thisx.bits);
  83881. state->length = (unsigned)thisx.val;
  83882. if ((int)(thisx.op) == 0) {
  83883. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83884. "inflate: literal '%c'\n" :
  83885. "inflate: literal 0x%02x\n", thisx.val));
  83886. state->mode = LIT;
  83887. break;
  83888. }
  83889. if (thisx.op & 32) {
  83890. Tracevv((stderr, "inflate: end of block\n"));
  83891. state->mode = TYPE;
  83892. break;
  83893. }
  83894. if (thisx.op & 64) {
  83895. strm->msg = (char *)"invalid literal/length code";
  83896. state->mode = BAD;
  83897. break;
  83898. }
  83899. state->extra = (unsigned)(thisx.op) & 15;
  83900. state->mode = LENEXT;
  83901. case LENEXT:
  83902. if (state->extra) {
  83903. NEEDBITS(state->extra);
  83904. state->length += BITS(state->extra);
  83905. DROPBITS(state->extra);
  83906. }
  83907. Tracevv((stderr, "inflate: length %u\n", state->length));
  83908. state->mode = DIST;
  83909. case DIST:
  83910. for (;;) {
  83911. thisx = state->distcode[BITS(state->distbits)];
  83912. if ((unsigned)(thisx.bits) <= bits) break;
  83913. PULLBYTE();
  83914. }
  83915. if ((thisx.op & 0xf0) == 0) {
  83916. last = thisx;
  83917. for (;;) {
  83918. thisx = state->distcode[last.val +
  83919. (BITS(last.bits + last.op) >> last.bits)];
  83920. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83921. PULLBYTE();
  83922. }
  83923. DROPBITS(last.bits);
  83924. }
  83925. DROPBITS(thisx.bits);
  83926. if (thisx.op & 64) {
  83927. strm->msg = (char *)"invalid distance code";
  83928. state->mode = BAD;
  83929. break;
  83930. }
  83931. state->offset = (unsigned)thisx.val;
  83932. state->extra = (unsigned)(thisx.op) & 15;
  83933. state->mode = DISTEXT;
  83934. case DISTEXT:
  83935. if (state->extra) {
  83936. NEEDBITS(state->extra);
  83937. state->offset += BITS(state->extra);
  83938. DROPBITS(state->extra);
  83939. }
  83940. #ifdef INFLATE_STRICT
  83941. if (state->offset > state->dmax) {
  83942. strm->msg = (char *)"invalid distance too far back";
  83943. state->mode = BAD;
  83944. break;
  83945. }
  83946. #endif
  83947. if (state->offset > state->whave + out - left) {
  83948. strm->msg = (char *)"invalid distance too far back";
  83949. state->mode = BAD;
  83950. break;
  83951. }
  83952. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83953. state->mode = MATCH;
  83954. case MATCH:
  83955. if (left == 0) goto inf_leave;
  83956. copy = out - left;
  83957. if (state->offset > copy) { /* copy from window */
  83958. copy = state->offset - copy;
  83959. if (copy > state->write) {
  83960. copy -= state->write;
  83961. from = state->window + (state->wsize - copy);
  83962. }
  83963. else
  83964. from = state->window + (state->write - copy);
  83965. if (copy > state->length) copy = state->length;
  83966. }
  83967. else { /* copy from output */
  83968. from = put - state->offset;
  83969. copy = state->length;
  83970. }
  83971. if (copy > left) copy = left;
  83972. left -= copy;
  83973. state->length -= copy;
  83974. do {
  83975. *put++ = *from++;
  83976. } while (--copy);
  83977. if (state->length == 0) state->mode = LEN;
  83978. break;
  83979. case LIT:
  83980. if (left == 0) goto inf_leave;
  83981. *put++ = (unsigned char)(state->length);
  83982. left--;
  83983. state->mode = LEN;
  83984. break;
  83985. case CHECK:
  83986. if (state->wrap) {
  83987. NEEDBITS(32);
  83988. out -= left;
  83989. strm->total_out += out;
  83990. state->total += out;
  83991. if (out)
  83992. strm->adler = state->check =
  83993. UPDATE(state->check, put - out, out);
  83994. out = left;
  83995. if ((
  83996. #ifdef GUNZIP
  83997. state->flags ? hold :
  83998. #endif
  83999. REVERSE(hold)) != state->check) {
  84000. strm->msg = (char *)"incorrect data check";
  84001. state->mode = BAD;
  84002. break;
  84003. }
  84004. INITBITS();
  84005. Tracev((stderr, "inflate: check matches trailer\n"));
  84006. }
  84007. #ifdef GUNZIP
  84008. state->mode = LENGTH;
  84009. case LENGTH:
  84010. if (state->wrap && state->flags) {
  84011. NEEDBITS(32);
  84012. if (hold != (state->total & 0xffffffffUL)) {
  84013. strm->msg = (char *)"incorrect length check";
  84014. state->mode = BAD;
  84015. break;
  84016. }
  84017. INITBITS();
  84018. Tracev((stderr, "inflate: length matches trailer\n"));
  84019. }
  84020. #endif
  84021. state->mode = DONE;
  84022. case DONE:
  84023. ret = Z_STREAM_END;
  84024. goto inf_leave;
  84025. case BAD:
  84026. ret = Z_DATA_ERROR;
  84027. goto inf_leave;
  84028. case MEM:
  84029. return Z_MEM_ERROR;
  84030. case SYNC:
  84031. default:
  84032. return Z_STREAM_ERROR;
  84033. }
  84034. /*
  84035. Return from inflate(), updating the total counts and the check value.
  84036. If there was no progress during the inflate() call, return a buffer
  84037. error. Call updatewindow() to create and/or update the window state.
  84038. Note: a memory error from inflate() is non-recoverable.
  84039. */
  84040. inf_leave:
  84041. RESTORE();
  84042. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84043. if (updatewindow(strm, out)) {
  84044. state->mode = MEM;
  84045. return Z_MEM_ERROR;
  84046. }
  84047. in -= strm->avail_in;
  84048. out -= strm->avail_out;
  84049. strm->total_in += in;
  84050. strm->total_out += out;
  84051. state->total += out;
  84052. if (state->wrap && out)
  84053. strm->adler = state->check =
  84054. UPDATE(state->check, strm->next_out - out, out);
  84055. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84056. (state->mode == TYPE ? 128 : 0);
  84057. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84058. ret = Z_BUF_ERROR;
  84059. return ret;
  84060. }
  84061. int ZEXPORT inflateEnd (z_streamp strm)
  84062. {
  84063. struct inflate_state FAR *state;
  84064. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84065. return Z_STREAM_ERROR;
  84066. state = (struct inflate_state FAR *)strm->state;
  84067. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84068. ZFREE(strm, strm->state);
  84069. strm->state = Z_NULL;
  84070. Tracev((stderr, "inflate: end\n"));
  84071. return Z_OK;
  84072. }
  84073. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84074. {
  84075. struct inflate_state FAR *state;
  84076. unsigned long id_;
  84077. /* check state */
  84078. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84079. state = (struct inflate_state FAR *)strm->state;
  84080. if (state->wrap != 0 && state->mode != DICT)
  84081. return Z_STREAM_ERROR;
  84082. /* check for correct dictionary id */
  84083. if (state->mode == DICT) {
  84084. id_ = adler32(0L, Z_NULL, 0);
  84085. id_ = adler32(id_, dictionary, dictLength);
  84086. if (id_ != state->check)
  84087. return Z_DATA_ERROR;
  84088. }
  84089. /* copy dictionary to window */
  84090. if (updatewindow(strm, strm->avail_out)) {
  84091. state->mode = MEM;
  84092. return Z_MEM_ERROR;
  84093. }
  84094. if (dictLength > state->wsize) {
  84095. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84096. state->wsize);
  84097. state->whave = state->wsize;
  84098. }
  84099. else {
  84100. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84101. dictLength);
  84102. state->whave = dictLength;
  84103. }
  84104. state->havedict = 1;
  84105. Tracev((stderr, "inflate: dictionary set\n"));
  84106. return Z_OK;
  84107. }
  84108. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84109. {
  84110. struct inflate_state FAR *state;
  84111. /* check state */
  84112. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84113. state = (struct inflate_state FAR *)strm->state;
  84114. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84115. /* save header structure */
  84116. state->head = head;
  84117. head->done = 0;
  84118. return Z_OK;
  84119. }
  84120. /*
  84121. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84122. or when out of input. When called, *have is the number of pattern bytes
  84123. found in order so far, in 0..3. On return *have is updated to the new
  84124. state. If on return *have equals four, then the pattern was found and the
  84125. return value is how many bytes were read including the last byte of the
  84126. pattern. If *have is less than four, then the pattern has not been found
  84127. yet and the return value is len. In the latter case, syncsearch() can be
  84128. called again with more data and the *have state. *have is initialized to
  84129. zero for the first call.
  84130. */
  84131. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84132. {
  84133. unsigned got;
  84134. unsigned next;
  84135. got = *have;
  84136. next = 0;
  84137. while (next < len && got < 4) {
  84138. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84139. got++;
  84140. else if (buf[next])
  84141. got = 0;
  84142. else
  84143. got = 4 - got;
  84144. next++;
  84145. }
  84146. *have = got;
  84147. return next;
  84148. }
  84149. int ZEXPORT inflateSync (z_streamp strm)
  84150. {
  84151. unsigned len; /* number of bytes to look at or looked at */
  84152. unsigned long in, out; /* temporary to save total_in and total_out */
  84153. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84154. struct inflate_state FAR *state;
  84155. /* check parameters */
  84156. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84157. state = (struct inflate_state FAR *)strm->state;
  84158. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84159. /* if first time, start search in bit buffer */
  84160. if (state->mode != SYNC) {
  84161. state->mode = SYNC;
  84162. state->hold <<= state->bits & 7;
  84163. state->bits -= state->bits & 7;
  84164. len = 0;
  84165. while (state->bits >= 8) {
  84166. buf[len++] = (unsigned char)(state->hold);
  84167. state->hold >>= 8;
  84168. state->bits -= 8;
  84169. }
  84170. state->have = 0;
  84171. syncsearch(&(state->have), buf, len);
  84172. }
  84173. /* search available input */
  84174. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84175. strm->avail_in -= len;
  84176. strm->next_in += len;
  84177. strm->total_in += len;
  84178. /* return no joy or set up to restart inflate() on a new block */
  84179. if (state->have != 4) return Z_DATA_ERROR;
  84180. in = strm->total_in; out = strm->total_out;
  84181. inflateReset(strm);
  84182. strm->total_in = in; strm->total_out = out;
  84183. state->mode = TYPE;
  84184. return Z_OK;
  84185. }
  84186. /*
  84187. Returns true if inflate is currently at the end of a block generated by
  84188. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84189. implementation to provide an additional safety check. PPP uses
  84190. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84191. block. When decompressing, PPP checks that at the end of input packet,
  84192. inflate is waiting for these length bytes.
  84193. */
  84194. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84195. {
  84196. struct inflate_state FAR *state;
  84197. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84198. state = (struct inflate_state FAR *)strm->state;
  84199. return state->mode == STORED && state->bits == 0;
  84200. }
  84201. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84202. {
  84203. struct inflate_state FAR *state;
  84204. struct inflate_state FAR *copy;
  84205. unsigned char FAR *window;
  84206. unsigned wsize;
  84207. /* check input */
  84208. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84209. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84210. return Z_STREAM_ERROR;
  84211. state = (struct inflate_state FAR *)source->state;
  84212. /* allocate space */
  84213. copy = (struct inflate_state FAR *)
  84214. ZALLOC(source, 1, sizeof(struct inflate_state));
  84215. if (copy == Z_NULL) return Z_MEM_ERROR;
  84216. window = Z_NULL;
  84217. if (state->window != Z_NULL) {
  84218. window = (unsigned char FAR *)
  84219. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84220. if (window == Z_NULL) {
  84221. ZFREE(source, copy);
  84222. return Z_MEM_ERROR;
  84223. }
  84224. }
  84225. /* copy state */
  84226. zmemcpy(dest, source, sizeof(z_stream));
  84227. zmemcpy(copy, state, sizeof(struct inflate_state));
  84228. if (state->lencode >= state->codes &&
  84229. state->lencode <= state->codes + ENOUGH - 1) {
  84230. copy->lencode = copy->codes + (state->lencode - state->codes);
  84231. copy->distcode = copy->codes + (state->distcode - state->codes);
  84232. }
  84233. copy->next = copy->codes + (state->next - state->codes);
  84234. if (window != Z_NULL) {
  84235. wsize = 1U << state->wbits;
  84236. zmemcpy(window, state->window, wsize);
  84237. }
  84238. copy->window = window;
  84239. dest->state = (struct internal_state FAR *)copy;
  84240. return Z_OK;
  84241. }
  84242. /*** End of inlined file: inflate.c ***/
  84243. /*** Start of inlined file: inftrees.c ***/
  84244. #define MAXBITS 15
  84245. const char inflate_copyright[] =
  84246. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84247. /*
  84248. If you use the zlib library in a product, an acknowledgment is welcome
  84249. in the documentation of your product. If for some reason you cannot
  84250. include such an acknowledgment, I would appreciate that you keep this
  84251. copyright string in the executable of your product.
  84252. */
  84253. /*
  84254. Build a set of tables to decode the provided canonical Huffman code.
  84255. The code lengths are lens[0..codes-1]. The result starts at *table,
  84256. whose indices are 0..2^bits-1. work is a writable array of at least
  84257. lens shorts, which is used as a work area. type is the type of code
  84258. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84259. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84260. on return points to the next available entry's address. bits is the
  84261. requested root table index bits, and on return it is the actual root
  84262. table index bits. It will differ if the request is greater than the
  84263. longest code or if it is less than the shortest code.
  84264. */
  84265. int inflate_table (codetype type,
  84266. unsigned short FAR *lens,
  84267. unsigned codes,
  84268. code FAR * FAR *table,
  84269. unsigned FAR *bits,
  84270. unsigned short FAR *work)
  84271. {
  84272. unsigned len; /* a code's length in bits */
  84273. unsigned sym; /* index of code symbols */
  84274. unsigned min, max; /* minimum and maximum code lengths */
  84275. unsigned root; /* number of index bits for root table */
  84276. unsigned curr; /* number of index bits for current table */
  84277. unsigned drop; /* code bits to drop for sub-table */
  84278. int left; /* number of prefix codes available */
  84279. unsigned used; /* code entries in table used */
  84280. unsigned huff; /* Huffman code */
  84281. unsigned incr; /* for incrementing code, index */
  84282. unsigned fill; /* index for replicating entries */
  84283. unsigned low; /* low bits for current root entry */
  84284. unsigned mask; /* mask for low root bits */
  84285. code thisx; /* table entry for duplication */
  84286. code FAR *next; /* next available space in table */
  84287. const unsigned short FAR *base; /* base value table to use */
  84288. const unsigned short FAR *extra; /* extra bits table to use */
  84289. int end; /* use base and extra for symbol > end */
  84290. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84291. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84292. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84293. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84294. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84295. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84296. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84297. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84298. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84299. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84300. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84301. 8193, 12289, 16385, 24577, 0, 0};
  84302. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84303. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84304. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84305. 28, 28, 29, 29, 64, 64};
  84306. /*
  84307. Process a set of code lengths to create a canonical Huffman code. The
  84308. code lengths are lens[0..codes-1]. Each length corresponds to the
  84309. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84310. symbols by length from short to long, and retaining the symbol order
  84311. for codes with equal lengths. Then the code starts with all zero bits
  84312. for the first code of the shortest length, and the codes are integer
  84313. increments for the same length, and zeros are appended as the length
  84314. increases. For the deflate format, these bits are stored backwards
  84315. from their more natural integer increment ordering, and so when the
  84316. decoding tables are built in the large loop below, the integer codes
  84317. are incremented backwards.
  84318. This routine assumes, but does not check, that all of the entries in
  84319. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84320. 1..MAXBITS is interpreted as that code length. zero means that that
  84321. symbol does not occur in this code.
  84322. The codes are sorted by computing a count of codes for each length,
  84323. creating from that a table of starting indices for each length in the
  84324. sorted table, and then entering the symbols in order in the sorted
  84325. table. The sorted table is work[], with that space being provided by
  84326. the caller.
  84327. The length counts are used for other purposes as well, i.e. finding
  84328. the minimum and maximum length codes, determining if there are any
  84329. codes at all, checking for a valid set of lengths, and looking ahead
  84330. at length counts to determine sub-table sizes when building the
  84331. decoding tables.
  84332. */
  84333. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84334. for (len = 0; len <= MAXBITS; len++)
  84335. count[len] = 0;
  84336. for (sym = 0; sym < codes; sym++)
  84337. count[lens[sym]]++;
  84338. /* bound code lengths, force root to be within code lengths */
  84339. root = *bits;
  84340. for (max = MAXBITS; max >= 1; max--)
  84341. if (count[max] != 0) break;
  84342. if (root > max) root = max;
  84343. if (max == 0) { /* no symbols to code at all */
  84344. thisx.op = (unsigned char)64; /* invalid code marker */
  84345. thisx.bits = (unsigned char)1;
  84346. thisx.val = (unsigned short)0;
  84347. *(*table)++ = thisx; /* make a table to force an error */
  84348. *(*table)++ = thisx;
  84349. *bits = 1;
  84350. return 0; /* no symbols, but wait for decoding to report error */
  84351. }
  84352. for (min = 1; min <= MAXBITS; min++)
  84353. if (count[min] != 0) break;
  84354. if (root < min) root = min;
  84355. /* check for an over-subscribed or incomplete set of lengths */
  84356. left = 1;
  84357. for (len = 1; len <= MAXBITS; len++) {
  84358. left <<= 1;
  84359. left -= count[len];
  84360. if (left < 0) return -1; /* over-subscribed */
  84361. }
  84362. if (left > 0 && (type == CODES || max != 1))
  84363. return -1; /* incomplete set */
  84364. /* generate offsets into symbol table for each length for sorting */
  84365. offs[1] = 0;
  84366. for (len = 1; len < MAXBITS; len++)
  84367. offs[len + 1] = offs[len] + count[len];
  84368. /* sort symbols by length, by symbol order within each length */
  84369. for (sym = 0; sym < codes; sym++)
  84370. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84371. /*
  84372. Create and fill in decoding tables. In this loop, the table being
  84373. filled is at next and has curr index bits. The code being used is huff
  84374. with length len. That code is converted to an index by dropping drop
  84375. bits off of the bottom. For codes where len is less than drop + curr,
  84376. those top drop + curr - len bits are incremented through all values to
  84377. fill the table with replicated entries.
  84378. root is the number of index bits for the root table. When len exceeds
  84379. root, sub-tables are created pointed to by the root entry with an index
  84380. of the low root bits of huff. This is saved in low to check for when a
  84381. new sub-table should be started. drop is zero when the root table is
  84382. being filled, and drop is root when sub-tables are being filled.
  84383. When a new sub-table is needed, it is necessary to look ahead in the
  84384. code lengths to determine what size sub-table is needed. The length
  84385. counts are used for this, and so count[] is decremented as codes are
  84386. entered in the tables.
  84387. used keeps track of how many table entries have been allocated from the
  84388. provided *table space. It is checked when a LENS table is being made
  84389. against the space in *table, ENOUGH, minus the maximum space needed by
  84390. the worst case distance code, MAXD. This should never happen, but the
  84391. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84392. This assumes that when type == LENS, bits == 9.
  84393. sym increments through all symbols, and the loop terminates when
  84394. all codes of length max, i.e. all codes, have been processed. This
  84395. routine permits incomplete codes, so another loop after this one fills
  84396. in the rest of the decoding tables with invalid code markers.
  84397. */
  84398. /* set up for code type */
  84399. switch (type) {
  84400. case CODES:
  84401. base = extra = work; /* dummy value--not used */
  84402. end = 19;
  84403. break;
  84404. case LENS:
  84405. base = lbase;
  84406. base -= 257;
  84407. extra = lext;
  84408. extra -= 257;
  84409. end = 256;
  84410. break;
  84411. default: /* DISTS */
  84412. base = dbase;
  84413. extra = dext;
  84414. end = -1;
  84415. }
  84416. /* initialize state for loop */
  84417. huff = 0; /* starting code */
  84418. sym = 0; /* starting code symbol */
  84419. len = min; /* starting code length */
  84420. next = *table; /* current table to fill in */
  84421. curr = root; /* current table index bits */
  84422. drop = 0; /* current bits to drop from code for index */
  84423. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84424. used = 1U << root; /* use root table entries */
  84425. mask = used - 1; /* mask for comparing low */
  84426. /* check available table space */
  84427. if (type == LENS && used >= ENOUGH - MAXD)
  84428. return 1;
  84429. /* process all codes and make table entries */
  84430. for (;;) {
  84431. /* create table entry */
  84432. thisx.bits = (unsigned char)(len - drop);
  84433. if ((int)(work[sym]) < end) {
  84434. thisx.op = (unsigned char)0;
  84435. thisx.val = work[sym];
  84436. }
  84437. else if ((int)(work[sym]) > end) {
  84438. thisx.op = (unsigned char)(extra[work[sym]]);
  84439. thisx.val = base[work[sym]];
  84440. }
  84441. else {
  84442. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84443. thisx.val = 0;
  84444. }
  84445. /* replicate for those indices with low len bits equal to huff */
  84446. incr = 1U << (len - drop);
  84447. fill = 1U << curr;
  84448. min = fill; /* save offset to next table */
  84449. do {
  84450. fill -= incr;
  84451. next[(huff >> drop) + fill] = thisx;
  84452. } while (fill != 0);
  84453. /* backwards increment the len-bit code huff */
  84454. incr = 1U << (len - 1);
  84455. while (huff & incr)
  84456. incr >>= 1;
  84457. if (incr != 0) {
  84458. huff &= incr - 1;
  84459. huff += incr;
  84460. }
  84461. else
  84462. huff = 0;
  84463. /* go to next symbol, update count, len */
  84464. sym++;
  84465. if (--(count[len]) == 0) {
  84466. if (len == max) break;
  84467. len = lens[work[sym]];
  84468. }
  84469. /* create new sub-table if needed */
  84470. if (len > root && (huff & mask) != low) {
  84471. /* if first time, transition to sub-tables */
  84472. if (drop == 0)
  84473. drop = root;
  84474. /* increment past last table */
  84475. next += min; /* here min is 1 << curr */
  84476. /* determine length of next table */
  84477. curr = len - drop;
  84478. left = (int)(1 << curr);
  84479. while (curr + drop < max) {
  84480. left -= count[curr + drop];
  84481. if (left <= 0) break;
  84482. curr++;
  84483. left <<= 1;
  84484. }
  84485. /* check for enough space */
  84486. used += 1U << curr;
  84487. if (type == LENS && used >= ENOUGH - MAXD)
  84488. return 1;
  84489. /* point entry in root table to sub-table */
  84490. low = huff & mask;
  84491. (*table)[low].op = (unsigned char)curr;
  84492. (*table)[low].bits = (unsigned char)root;
  84493. (*table)[low].val = (unsigned short)(next - *table);
  84494. }
  84495. }
  84496. /*
  84497. Fill in rest of table for incomplete codes. This loop is similar to the
  84498. loop above in incrementing huff for table indices. It is assumed that
  84499. len is equal to curr + drop, so there is no loop needed to increment
  84500. through high index bits. When the current sub-table is filled, the loop
  84501. drops back to the root table to fill in any remaining entries there.
  84502. */
  84503. thisx.op = (unsigned char)64; /* invalid code marker */
  84504. thisx.bits = (unsigned char)(len - drop);
  84505. thisx.val = (unsigned short)0;
  84506. while (huff != 0) {
  84507. /* when done with sub-table, drop back to root table */
  84508. if (drop != 0 && (huff & mask) != low) {
  84509. drop = 0;
  84510. len = root;
  84511. next = *table;
  84512. thisx.bits = (unsigned char)len;
  84513. }
  84514. /* put invalid code marker in table */
  84515. next[huff >> drop] = thisx;
  84516. /* backwards increment the len-bit code huff */
  84517. incr = 1U << (len - 1);
  84518. while (huff & incr)
  84519. incr >>= 1;
  84520. if (incr != 0) {
  84521. huff &= incr - 1;
  84522. huff += incr;
  84523. }
  84524. else
  84525. huff = 0;
  84526. }
  84527. /* set return parameters */
  84528. *table += used;
  84529. *bits = root;
  84530. return 0;
  84531. }
  84532. /*** End of inlined file: inftrees.c ***/
  84533. /*** Start of inlined file: trees.c ***/
  84534. /*
  84535. * ALGORITHM
  84536. *
  84537. * The "deflation" process uses several Huffman trees. The more
  84538. * common source values are represented by shorter bit sequences.
  84539. *
  84540. * Each code tree is stored in a compressed form which is itself
  84541. * a Huffman encoding of the lengths of all the code strings (in
  84542. * ascending order by source values). The actual code strings are
  84543. * reconstructed from the lengths in the inflate process, as described
  84544. * in the deflate specification.
  84545. *
  84546. * REFERENCES
  84547. *
  84548. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84549. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84550. *
  84551. * Storer, James A.
  84552. * Data Compression: Methods and Theory, pp. 49-50.
  84553. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84554. *
  84555. * Sedgewick, R.
  84556. * Algorithms, p290.
  84557. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84558. */
  84559. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84560. /* #define GEN_TREES_H */
  84561. #ifdef DEBUG
  84562. # include <ctype.h>
  84563. #endif
  84564. /* ===========================================================================
  84565. * Constants
  84566. */
  84567. #define MAX_BL_BITS 7
  84568. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84569. #define END_BLOCK 256
  84570. /* end of block literal code */
  84571. #define REP_3_6 16
  84572. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84573. #define REPZ_3_10 17
  84574. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84575. #define REPZ_11_138 18
  84576. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84577. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84578. = {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};
  84579. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84580. = {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};
  84581. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84582. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84583. local const uch bl_order[BL_CODES]
  84584. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84585. /* The lengths of the bit length codes are sent in order of decreasing
  84586. * probability, to avoid transmitting the lengths for unused bit length codes.
  84587. */
  84588. #define Buf_size (8 * 2*sizeof(char))
  84589. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84590. * more than 16 bits on some systems.)
  84591. */
  84592. /* ===========================================================================
  84593. * Local data. These are initialized only once.
  84594. */
  84595. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84596. #if defined(GEN_TREES_H) || !defined(STDC)
  84597. /* non ANSI compilers may not accept trees.h */
  84598. local ct_data static_ltree[L_CODES+2];
  84599. /* The static literal tree. Since the bit lengths are imposed, there is no
  84600. * need for the L_CODES extra codes used during heap construction. However
  84601. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84602. * below).
  84603. */
  84604. local ct_data static_dtree[D_CODES];
  84605. /* The static distance tree. (Actually a trivial tree since all codes use
  84606. * 5 bits.)
  84607. */
  84608. uch _dist_code[DIST_CODE_LEN];
  84609. /* Distance codes. The first 256 values correspond to the distances
  84610. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84611. * the 15 bit distances.
  84612. */
  84613. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84614. /* length code for each normalized match length (0 == MIN_MATCH) */
  84615. local int base_length[LENGTH_CODES];
  84616. /* First normalized length for each code (0 = MIN_MATCH) */
  84617. local int base_dist[D_CODES];
  84618. /* First normalized distance for each code (0 = distance of 1) */
  84619. #else
  84620. /*** Start of inlined file: trees.h ***/
  84621. local const ct_data static_ltree[L_CODES+2] = {
  84622. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84623. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84624. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84625. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84626. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84627. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84628. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84629. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84630. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84631. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84632. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84633. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84634. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84635. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84636. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84637. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84638. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84639. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84640. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84641. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84642. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84643. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84644. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84645. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84646. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84647. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84648. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84649. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84650. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84651. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84652. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84653. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84654. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84655. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84656. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84657. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84658. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84659. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84660. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84661. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84662. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84663. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84664. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84665. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84666. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84667. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84668. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84669. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84670. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84671. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84672. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84673. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84674. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84675. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84676. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84677. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84678. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84679. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84680. };
  84681. local const ct_data static_dtree[D_CODES] = {
  84682. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84683. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84684. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84685. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84686. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84687. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84688. };
  84689. const uch _dist_code[DIST_CODE_LEN] = {
  84690. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84691. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84692. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84693. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84694. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84695. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84696. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84697. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84698. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84699. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84700. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84701. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84702. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84703. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84704. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84705. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84706. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84707. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84708. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84709. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84710. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84711. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84712. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84713. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84714. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84715. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84716. };
  84717. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84718. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84719. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84720. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84721. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84722. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84723. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84724. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84725. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84726. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84727. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84728. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84729. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84730. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84731. };
  84732. local const int base_length[LENGTH_CODES] = {
  84733. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84734. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84735. };
  84736. local const int base_dist[D_CODES] = {
  84737. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84738. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84739. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84740. };
  84741. /*** End of inlined file: trees.h ***/
  84742. #endif /* GEN_TREES_H */
  84743. struct static_tree_desc_s {
  84744. const ct_data *static_tree; /* static tree or NULL */
  84745. const intf *extra_bits; /* extra bits for each code or NULL */
  84746. int extra_base; /* base index for extra_bits */
  84747. int elems; /* max number of elements in the tree */
  84748. int max_length; /* max bit length for the codes */
  84749. };
  84750. local static_tree_desc static_l_desc =
  84751. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84752. local static_tree_desc static_d_desc =
  84753. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84754. local static_tree_desc static_bl_desc =
  84755. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84756. /* ===========================================================================
  84757. * Local (static) routines in this file.
  84758. */
  84759. local void tr_static_init OF((void));
  84760. local void init_block OF((deflate_state *s));
  84761. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84762. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84763. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84764. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84765. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84766. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84767. local int build_bl_tree OF((deflate_state *s));
  84768. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84769. int blcodes));
  84770. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84771. ct_data *dtree));
  84772. local void set_data_type OF((deflate_state *s));
  84773. local unsigned bi_reverse OF((unsigned value, int length));
  84774. local void bi_windup OF((deflate_state *s));
  84775. local void bi_flush OF((deflate_state *s));
  84776. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84777. int header));
  84778. #ifdef GEN_TREES_H
  84779. local void gen_trees_header OF((void));
  84780. #endif
  84781. #ifndef DEBUG
  84782. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84783. /* Send a code of the given tree. c and tree must not have side effects */
  84784. #else /* DEBUG */
  84785. # define send_code(s, c, tree) \
  84786. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84787. send_bits(s, tree[c].Code, tree[c].Len); }
  84788. #endif
  84789. /* ===========================================================================
  84790. * Output a short LSB first on the stream.
  84791. * IN assertion: there is enough room in pendingBuf.
  84792. */
  84793. #define put_short(s, w) { \
  84794. put_byte(s, (uch)((w) & 0xff)); \
  84795. put_byte(s, (uch)((ush)(w) >> 8)); \
  84796. }
  84797. /* ===========================================================================
  84798. * Send a value on a given number of bits.
  84799. * IN assertion: length <= 16 and value fits in length bits.
  84800. */
  84801. #ifdef DEBUG
  84802. local void send_bits OF((deflate_state *s, int value, int length));
  84803. local void send_bits (deflate_state *s, int value, int length)
  84804. {
  84805. Tracevv((stderr," l %2d v %4x ", length, value));
  84806. Assert(length > 0 && length <= 15, "invalid length");
  84807. s->bits_sent += (ulg)length;
  84808. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84809. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84810. * unused bits in value.
  84811. */
  84812. if (s->bi_valid > (int)Buf_size - length) {
  84813. s->bi_buf |= (value << s->bi_valid);
  84814. put_short(s, s->bi_buf);
  84815. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84816. s->bi_valid += length - Buf_size;
  84817. } else {
  84818. s->bi_buf |= value << s->bi_valid;
  84819. s->bi_valid += length;
  84820. }
  84821. }
  84822. #else /* !DEBUG */
  84823. #define send_bits(s, value, length) \
  84824. { int len = length;\
  84825. if (s->bi_valid > (int)Buf_size - len) {\
  84826. int val = value;\
  84827. s->bi_buf |= (val << s->bi_valid);\
  84828. put_short(s, s->bi_buf);\
  84829. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84830. s->bi_valid += len - Buf_size;\
  84831. } else {\
  84832. s->bi_buf |= (value) << s->bi_valid;\
  84833. s->bi_valid += len;\
  84834. }\
  84835. }
  84836. #endif /* DEBUG */
  84837. /* the arguments must not have side effects */
  84838. /* ===========================================================================
  84839. * Initialize the various 'constant' tables.
  84840. */
  84841. local void tr_static_init()
  84842. {
  84843. #if defined(GEN_TREES_H) || !defined(STDC)
  84844. static int static_init_done = 0;
  84845. int n; /* iterates over tree elements */
  84846. int bits; /* bit counter */
  84847. int length; /* length value */
  84848. int code; /* code value */
  84849. int dist; /* distance index */
  84850. ush bl_count[MAX_BITS+1];
  84851. /* number of codes at each bit length for an optimal tree */
  84852. if (static_init_done) return;
  84853. /* For some embedded targets, global variables are not initialized: */
  84854. static_l_desc.static_tree = static_ltree;
  84855. static_l_desc.extra_bits = extra_lbits;
  84856. static_d_desc.static_tree = static_dtree;
  84857. static_d_desc.extra_bits = extra_dbits;
  84858. static_bl_desc.extra_bits = extra_blbits;
  84859. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84860. length = 0;
  84861. for (code = 0; code < LENGTH_CODES-1; code++) {
  84862. base_length[code] = length;
  84863. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84864. _length_code[length++] = (uch)code;
  84865. }
  84866. }
  84867. Assert (length == 256, "tr_static_init: length != 256");
  84868. /* Note that the length 255 (match length 258) can be represented
  84869. * in two different ways: code 284 + 5 bits or code 285, so we
  84870. * overwrite length_code[255] to use the best encoding:
  84871. */
  84872. _length_code[length-1] = (uch)code;
  84873. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84874. dist = 0;
  84875. for (code = 0 ; code < 16; code++) {
  84876. base_dist[code] = dist;
  84877. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84878. _dist_code[dist++] = (uch)code;
  84879. }
  84880. }
  84881. Assert (dist == 256, "tr_static_init: dist != 256");
  84882. dist >>= 7; /* from now on, all distances are divided by 128 */
  84883. for ( ; code < D_CODES; code++) {
  84884. base_dist[code] = dist << 7;
  84885. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84886. _dist_code[256 + dist++] = (uch)code;
  84887. }
  84888. }
  84889. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84890. /* Construct the codes of the static literal tree */
  84891. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84892. n = 0;
  84893. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84894. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84895. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84896. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84897. /* Codes 286 and 287 do not exist, but we must include them in the
  84898. * tree construction to get a canonical Huffman tree (longest code
  84899. * all ones)
  84900. */
  84901. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84902. /* The static distance tree is trivial: */
  84903. for (n = 0; n < D_CODES; n++) {
  84904. static_dtree[n].Len = 5;
  84905. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84906. }
  84907. static_init_done = 1;
  84908. # ifdef GEN_TREES_H
  84909. gen_trees_header();
  84910. # endif
  84911. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84912. }
  84913. /* ===========================================================================
  84914. * Genererate the file trees.h describing the static trees.
  84915. */
  84916. #ifdef GEN_TREES_H
  84917. # ifndef DEBUG
  84918. # include <stdio.h>
  84919. # endif
  84920. # define SEPARATOR(i, last, width) \
  84921. ((i) == (last)? "\n};\n\n" : \
  84922. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84923. void gen_trees_header()
  84924. {
  84925. FILE *header = fopen("trees.h", "w");
  84926. int i;
  84927. Assert (header != NULL, "Can't open trees.h");
  84928. fprintf(header,
  84929. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84930. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84931. for (i = 0; i < L_CODES+2; i++) {
  84932. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84933. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84934. }
  84935. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84936. for (i = 0; i < D_CODES; i++) {
  84937. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84938. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84939. }
  84940. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84941. for (i = 0; i < DIST_CODE_LEN; i++) {
  84942. fprintf(header, "%2u%s", _dist_code[i],
  84943. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84944. }
  84945. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84946. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84947. fprintf(header, "%2u%s", _length_code[i],
  84948. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84949. }
  84950. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84951. for (i = 0; i < LENGTH_CODES; i++) {
  84952. fprintf(header, "%1u%s", base_length[i],
  84953. SEPARATOR(i, LENGTH_CODES-1, 20));
  84954. }
  84955. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84956. for (i = 0; i < D_CODES; i++) {
  84957. fprintf(header, "%5u%s", base_dist[i],
  84958. SEPARATOR(i, D_CODES-1, 10));
  84959. }
  84960. fclose(header);
  84961. }
  84962. #endif /* GEN_TREES_H */
  84963. /* ===========================================================================
  84964. * Initialize the tree data structures for a new zlib stream.
  84965. */
  84966. void _tr_init(deflate_state *s)
  84967. {
  84968. tr_static_init();
  84969. s->l_desc.dyn_tree = s->dyn_ltree;
  84970. s->l_desc.stat_desc = &static_l_desc;
  84971. s->d_desc.dyn_tree = s->dyn_dtree;
  84972. s->d_desc.stat_desc = &static_d_desc;
  84973. s->bl_desc.dyn_tree = s->bl_tree;
  84974. s->bl_desc.stat_desc = &static_bl_desc;
  84975. s->bi_buf = 0;
  84976. s->bi_valid = 0;
  84977. s->last_eob_len = 8; /* enough lookahead for inflate */
  84978. #ifdef DEBUG
  84979. s->compressed_len = 0L;
  84980. s->bits_sent = 0L;
  84981. #endif
  84982. /* Initialize the first block of the first file: */
  84983. init_block(s);
  84984. }
  84985. /* ===========================================================================
  84986. * Initialize a new block.
  84987. */
  84988. local void init_block (deflate_state *s)
  84989. {
  84990. int n; /* iterates over tree elements */
  84991. /* Initialize the trees. */
  84992. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84993. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84994. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84995. s->dyn_ltree[END_BLOCK].Freq = 1;
  84996. s->opt_len = s->static_len = 0L;
  84997. s->last_lit = s->matches = 0;
  84998. }
  84999. #define SMALLEST 1
  85000. /* Index within the heap array of least frequent node in the Huffman tree */
  85001. /* ===========================================================================
  85002. * Remove the smallest element from the heap and recreate the heap with
  85003. * one less element. Updates heap and heap_len.
  85004. */
  85005. #define pqremove(s, tree, top) \
  85006. {\
  85007. top = s->heap[SMALLEST]; \
  85008. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85009. pqdownheap(s, tree, SMALLEST); \
  85010. }
  85011. /* ===========================================================================
  85012. * Compares to subtrees, using the tree depth as tie breaker when
  85013. * the subtrees have equal frequency. This minimizes the worst case length.
  85014. */
  85015. #define smaller(tree, n, m, depth) \
  85016. (tree[n].Freq < tree[m].Freq || \
  85017. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85018. /* ===========================================================================
  85019. * Restore the heap property by moving down the tree starting at node k,
  85020. * exchanging a node with the smallest of its two sons if necessary, stopping
  85021. * when the heap property is re-established (each father smaller than its
  85022. * two sons).
  85023. */
  85024. local void pqdownheap (deflate_state *s,
  85025. ct_data *tree, /* the tree to restore */
  85026. int k) /* node to move down */
  85027. {
  85028. int v = s->heap[k];
  85029. int j = k << 1; /* left son of k */
  85030. while (j <= s->heap_len) {
  85031. /* Set j to the smallest of the two sons: */
  85032. if (j < s->heap_len &&
  85033. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85034. j++;
  85035. }
  85036. /* Exit if v is smaller than both sons */
  85037. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85038. /* Exchange v with the smallest son */
  85039. s->heap[k] = s->heap[j]; k = j;
  85040. /* And continue down the tree, setting j to the left son of k */
  85041. j <<= 1;
  85042. }
  85043. s->heap[k] = v;
  85044. }
  85045. /* ===========================================================================
  85046. * Compute the optimal bit lengths for a tree and update the total bit length
  85047. * for the current block.
  85048. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85049. * above are the tree nodes sorted by increasing frequency.
  85050. * OUT assertions: the field len is set to the optimal bit length, the
  85051. * array bl_count contains the frequencies for each bit length.
  85052. * The length opt_len is updated; static_len is also updated if stree is
  85053. * not null.
  85054. */
  85055. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85056. {
  85057. ct_data *tree = desc->dyn_tree;
  85058. int max_code = desc->max_code;
  85059. const ct_data *stree = desc->stat_desc->static_tree;
  85060. const intf *extra = desc->stat_desc->extra_bits;
  85061. int base = desc->stat_desc->extra_base;
  85062. int max_length = desc->stat_desc->max_length;
  85063. int h; /* heap index */
  85064. int n, m; /* iterate over the tree elements */
  85065. int bits; /* bit length */
  85066. int xbits; /* extra bits */
  85067. ush f; /* frequency */
  85068. int overflow = 0; /* number of elements with bit length too large */
  85069. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85070. /* In a first pass, compute the optimal bit lengths (which may
  85071. * overflow in the case of the bit length tree).
  85072. */
  85073. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85074. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85075. n = s->heap[h];
  85076. bits = tree[tree[n].Dad].Len + 1;
  85077. if (bits > max_length) bits = max_length, overflow++;
  85078. tree[n].Len = (ush)bits;
  85079. /* We overwrite tree[n].Dad which is no longer needed */
  85080. if (n > max_code) continue; /* not a leaf node */
  85081. s->bl_count[bits]++;
  85082. xbits = 0;
  85083. if (n >= base) xbits = extra[n-base];
  85084. f = tree[n].Freq;
  85085. s->opt_len += (ulg)f * (bits + xbits);
  85086. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85087. }
  85088. if (overflow == 0) return;
  85089. Trace((stderr,"\nbit length overflow\n"));
  85090. /* This happens for example on obj2 and pic of the Calgary corpus */
  85091. /* Find the first bit length which could increase: */
  85092. do {
  85093. bits = max_length-1;
  85094. while (s->bl_count[bits] == 0) bits--;
  85095. s->bl_count[bits]--; /* move one leaf down the tree */
  85096. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85097. s->bl_count[max_length]--;
  85098. /* The brother of the overflow item also moves one step up,
  85099. * but this does not affect bl_count[max_length]
  85100. */
  85101. overflow -= 2;
  85102. } while (overflow > 0);
  85103. /* Now recompute all bit lengths, scanning in increasing frequency.
  85104. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85105. * lengths instead of fixing only the wrong ones. This idea is taken
  85106. * from 'ar' written by Haruhiko Okumura.)
  85107. */
  85108. for (bits = max_length; bits != 0; bits--) {
  85109. n = s->bl_count[bits];
  85110. while (n != 0) {
  85111. m = s->heap[--h];
  85112. if (m > max_code) continue;
  85113. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85114. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85115. s->opt_len += ((long)bits - (long)tree[m].Len)
  85116. *(long)tree[m].Freq;
  85117. tree[m].Len = (ush)bits;
  85118. }
  85119. n--;
  85120. }
  85121. }
  85122. }
  85123. /* ===========================================================================
  85124. * Generate the codes for a given tree and bit counts (which need not be
  85125. * optimal).
  85126. * IN assertion: the array bl_count contains the bit length statistics for
  85127. * the given tree and the field len is set for all tree elements.
  85128. * OUT assertion: the field code is set for all tree elements of non
  85129. * zero code length.
  85130. */
  85131. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85132. int max_code, /* largest code with non zero frequency */
  85133. ushf *bl_count) /* number of codes at each bit length */
  85134. {
  85135. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85136. ush code = 0; /* running code value */
  85137. int bits; /* bit index */
  85138. int n; /* code index */
  85139. /* The distribution counts are first used to generate the code values
  85140. * without bit reversal.
  85141. */
  85142. for (bits = 1; bits <= MAX_BITS; bits++) {
  85143. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85144. }
  85145. /* Check that the bit counts in bl_count are consistent. The last code
  85146. * must be all ones.
  85147. */
  85148. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85149. "inconsistent bit counts");
  85150. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85151. for (n = 0; n <= max_code; n++) {
  85152. int len = tree[n].Len;
  85153. if (len == 0) continue;
  85154. /* Now reverse the bits */
  85155. tree[n].Code = bi_reverse(next_code[len]++, len);
  85156. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85157. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85158. }
  85159. }
  85160. /* ===========================================================================
  85161. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85162. * Update the total bit length for the current block.
  85163. * IN assertion: the field freq is set for all tree elements.
  85164. * OUT assertions: the fields len and code are set to the optimal bit length
  85165. * and corresponding code. The length opt_len is updated; static_len is
  85166. * also updated if stree is not null. The field max_code is set.
  85167. */
  85168. local void build_tree (deflate_state *s,
  85169. tree_desc *desc) /* the tree descriptor */
  85170. {
  85171. ct_data *tree = desc->dyn_tree;
  85172. const ct_data *stree = desc->stat_desc->static_tree;
  85173. int elems = desc->stat_desc->elems;
  85174. int n, m; /* iterate over heap elements */
  85175. int max_code = -1; /* largest code with non zero frequency */
  85176. int node; /* new node being created */
  85177. /* Construct the initial heap, with least frequent element in
  85178. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85179. * heap[0] is not used.
  85180. */
  85181. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85182. for (n = 0; n < elems; n++) {
  85183. if (tree[n].Freq != 0) {
  85184. s->heap[++(s->heap_len)] = max_code = n;
  85185. s->depth[n] = 0;
  85186. } else {
  85187. tree[n].Len = 0;
  85188. }
  85189. }
  85190. /* The pkzip format requires that at least one distance code exists,
  85191. * and that at least one bit should be sent even if there is only one
  85192. * possible code. So to avoid special checks later on we force at least
  85193. * two codes of non zero frequency.
  85194. */
  85195. while (s->heap_len < 2) {
  85196. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85197. tree[node].Freq = 1;
  85198. s->depth[node] = 0;
  85199. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85200. /* node is 0 or 1 so it does not have extra bits */
  85201. }
  85202. desc->max_code = max_code;
  85203. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85204. * establish sub-heaps of increasing lengths:
  85205. */
  85206. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85207. /* Construct the Huffman tree by repeatedly combining the least two
  85208. * frequent nodes.
  85209. */
  85210. node = elems; /* next internal node of the tree */
  85211. do {
  85212. pqremove(s, tree, n); /* n = node of least frequency */
  85213. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85214. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85215. s->heap[--(s->heap_max)] = m;
  85216. /* Create a new node father of n and m */
  85217. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85218. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85219. s->depth[n] : s->depth[m]) + 1);
  85220. tree[n].Dad = tree[m].Dad = (ush)node;
  85221. #ifdef DUMP_BL_TREE
  85222. if (tree == s->bl_tree) {
  85223. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85224. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85225. }
  85226. #endif
  85227. /* and insert the new node in the heap */
  85228. s->heap[SMALLEST] = node++;
  85229. pqdownheap(s, tree, SMALLEST);
  85230. } while (s->heap_len >= 2);
  85231. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85232. /* At this point, the fields freq and dad are set. We can now
  85233. * generate the bit lengths.
  85234. */
  85235. gen_bitlen(s, (tree_desc *)desc);
  85236. /* The field len is now set, we can generate the bit codes */
  85237. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85238. }
  85239. /* ===========================================================================
  85240. * Scan a literal or distance tree to determine the frequencies of the codes
  85241. * in the bit length tree.
  85242. */
  85243. local void scan_tree (deflate_state *s,
  85244. ct_data *tree, /* the tree to be scanned */
  85245. int max_code) /* and its largest code of non zero frequency */
  85246. {
  85247. int n; /* iterates over all tree elements */
  85248. int prevlen = -1; /* last emitted length */
  85249. int curlen; /* length of current code */
  85250. int nextlen = tree[0].Len; /* length of next code */
  85251. int count = 0; /* repeat count of the current code */
  85252. int max_count = 7; /* max repeat count */
  85253. int min_count = 4; /* min repeat count */
  85254. if (nextlen == 0) max_count = 138, min_count = 3;
  85255. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85256. for (n = 0; n <= max_code; n++) {
  85257. curlen = nextlen; nextlen = tree[n+1].Len;
  85258. if (++count < max_count && curlen == nextlen) {
  85259. continue;
  85260. } else if (count < min_count) {
  85261. s->bl_tree[curlen].Freq += count;
  85262. } else if (curlen != 0) {
  85263. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85264. s->bl_tree[REP_3_6].Freq++;
  85265. } else if (count <= 10) {
  85266. s->bl_tree[REPZ_3_10].Freq++;
  85267. } else {
  85268. s->bl_tree[REPZ_11_138].Freq++;
  85269. }
  85270. count = 0; prevlen = curlen;
  85271. if (nextlen == 0) {
  85272. max_count = 138, min_count = 3;
  85273. } else if (curlen == nextlen) {
  85274. max_count = 6, min_count = 3;
  85275. } else {
  85276. max_count = 7, min_count = 4;
  85277. }
  85278. }
  85279. }
  85280. /* ===========================================================================
  85281. * Send a literal or distance tree in compressed form, using the codes in
  85282. * bl_tree.
  85283. */
  85284. local void send_tree (deflate_state *s,
  85285. ct_data *tree, /* the tree to be scanned */
  85286. int max_code) /* and its largest code of non zero frequency */
  85287. {
  85288. int n; /* iterates over all tree elements */
  85289. int prevlen = -1; /* last emitted length */
  85290. int curlen; /* length of current code */
  85291. int nextlen = tree[0].Len; /* length of next code */
  85292. int count = 0; /* repeat count of the current code */
  85293. int max_count = 7; /* max repeat count */
  85294. int min_count = 4; /* min repeat count */
  85295. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85296. if (nextlen == 0) max_count = 138, min_count = 3;
  85297. for (n = 0; n <= max_code; n++) {
  85298. curlen = nextlen; nextlen = tree[n+1].Len;
  85299. if (++count < max_count && curlen == nextlen) {
  85300. continue;
  85301. } else if (count < min_count) {
  85302. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85303. } else if (curlen != 0) {
  85304. if (curlen != prevlen) {
  85305. send_code(s, curlen, s->bl_tree); count--;
  85306. }
  85307. Assert(count >= 3 && count <= 6, " 3_6?");
  85308. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85309. } else if (count <= 10) {
  85310. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85311. } else {
  85312. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85313. }
  85314. count = 0; prevlen = curlen;
  85315. if (nextlen == 0) {
  85316. max_count = 138, min_count = 3;
  85317. } else if (curlen == nextlen) {
  85318. max_count = 6, min_count = 3;
  85319. } else {
  85320. max_count = 7, min_count = 4;
  85321. }
  85322. }
  85323. }
  85324. /* ===========================================================================
  85325. * Construct the Huffman tree for the bit lengths and return the index in
  85326. * bl_order of the last bit length code to send.
  85327. */
  85328. local int build_bl_tree (deflate_state *s)
  85329. {
  85330. int max_blindex; /* index of last bit length code of non zero freq */
  85331. /* Determine the bit length frequencies for literal and distance trees */
  85332. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85333. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85334. /* Build the bit length tree: */
  85335. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85336. /* opt_len now includes the length of the tree representations, except
  85337. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85338. */
  85339. /* Determine the number of bit length codes to send. The pkzip format
  85340. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85341. * 3 but the actual value used is 4.)
  85342. */
  85343. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85344. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85345. }
  85346. /* Update opt_len to include the bit length tree and counts */
  85347. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85348. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85349. s->opt_len, s->static_len));
  85350. return max_blindex;
  85351. }
  85352. /* ===========================================================================
  85353. * Send the header for a block using dynamic Huffman trees: the counts, the
  85354. * lengths of the bit length codes, the literal tree and the distance tree.
  85355. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85356. */
  85357. local void send_all_trees (deflate_state *s,
  85358. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85359. {
  85360. int rank; /* index in bl_order */
  85361. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85362. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85363. "too many codes");
  85364. Tracev((stderr, "\nbl counts: "));
  85365. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85366. send_bits(s, dcodes-1, 5);
  85367. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85368. for (rank = 0; rank < blcodes; rank++) {
  85369. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85370. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85371. }
  85372. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85373. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85374. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85375. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85376. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85377. }
  85378. /* ===========================================================================
  85379. * Send a stored block
  85380. */
  85381. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85382. {
  85383. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85384. #ifdef DEBUG
  85385. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85386. s->compressed_len += (stored_len + 4) << 3;
  85387. #endif
  85388. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85389. }
  85390. /* ===========================================================================
  85391. * Send one empty static block to give enough lookahead for inflate.
  85392. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85393. * The current inflate code requires 9 bits of lookahead. If the
  85394. * last two codes for the previous block (real code plus EOB) were coded
  85395. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85396. * the last real code. In this case we send two empty static blocks instead
  85397. * of one. (There are no problems if the previous block is stored or fixed.)
  85398. * To simplify the code, we assume the worst case of last real code encoded
  85399. * on one bit only.
  85400. */
  85401. void _tr_align (deflate_state *s)
  85402. {
  85403. send_bits(s, STATIC_TREES<<1, 3);
  85404. send_code(s, END_BLOCK, static_ltree);
  85405. #ifdef DEBUG
  85406. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85407. #endif
  85408. bi_flush(s);
  85409. /* Of the 10 bits for the empty block, we have already sent
  85410. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85411. * the EOB of the previous block) was thus at least one plus the length
  85412. * of the EOB plus what we have just sent of the empty static block.
  85413. */
  85414. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85415. send_bits(s, STATIC_TREES<<1, 3);
  85416. send_code(s, END_BLOCK, static_ltree);
  85417. #ifdef DEBUG
  85418. s->compressed_len += 10L;
  85419. #endif
  85420. bi_flush(s);
  85421. }
  85422. s->last_eob_len = 7;
  85423. }
  85424. /* ===========================================================================
  85425. * Determine the best encoding for the current block: dynamic trees, static
  85426. * trees or store, and output the encoded block to the zip file.
  85427. */
  85428. void _tr_flush_block (deflate_state *s,
  85429. charf *buf, /* input block, or NULL if too old */
  85430. ulg stored_len, /* length of input block */
  85431. int eof) /* true if this is the last block for a file */
  85432. {
  85433. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85434. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85435. /* Build the Huffman trees unless a stored block is forced */
  85436. if (s->level > 0) {
  85437. /* Check if the file is binary or text */
  85438. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85439. set_data_type(s);
  85440. /* Construct the literal and distance trees */
  85441. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85442. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85443. s->static_len));
  85444. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85445. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85446. s->static_len));
  85447. /* At this point, opt_len and static_len are the total bit lengths of
  85448. * the compressed block data, excluding the tree representations.
  85449. */
  85450. /* Build the bit length tree for the above two trees, and get the index
  85451. * in bl_order of the last bit length code to send.
  85452. */
  85453. max_blindex = build_bl_tree(s);
  85454. /* Determine the best encoding. Compute the block lengths in bytes. */
  85455. opt_lenb = (s->opt_len+3+7)>>3;
  85456. static_lenb = (s->static_len+3+7)>>3;
  85457. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85458. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85459. s->last_lit));
  85460. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85461. } else {
  85462. Assert(buf != (char*)0, "lost buf");
  85463. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85464. }
  85465. #ifdef FORCE_STORED
  85466. if (buf != (char*)0) { /* force stored block */
  85467. #else
  85468. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85469. /* 4: two words for the lengths */
  85470. #endif
  85471. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85472. * Otherwise we can't have processed more than WSIZE input bytes since
  85473. * the last block flush, because compression would have been
  85474. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85475. * transform a block into a stored block.
  85476. */
  85477. _tr_stored_block(s, buf, stored_len, eof);
  85478. #ifdef FORCE_STATIC
  85479. } else if (static_lenb >= 0) { /* force static trees */
  85480. #else
  85481. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85482. #endif
  85483. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85484. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85485. #ifdef DEBUG
  85486. s->compressed_len += 3 + s->static_len;
  85487. #endif
  85488. } else {
  85489. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85490. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85491. max_blindex+1);
  85492. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85493. #ifdef DEBUG
  85494. s->compressed_len += 3 + s->opt_len;
  85495. #endif
  85496. }
  85497. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85498. /* The above check is made mod 2^32, for files larger than 512 MB
  85499. * and uLong implemented on 32 bits.
  85500. */
  85501. init_block(s);
  85502. if (eof) {
  85503. bi_windup(s);
  85504. #ifdef DEBUG
  85505. s->compressed_len += 7; /* align on byte boundary */
  85506. #endif
  85507. }
  85508. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85509. s->compressed_len-7*eof));
  85510. }
  85511. /* ===========================================================================
  85512. * Save the match info and tally the frequency counts. Return true if
  85513. * the current block must be flushed.
  85514. */
  85515. int _tr_tally (deflate_state *s,
  85516. unsigned dist, /* distance of matched string */
  85517. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85518. {
  85519. s->d_buf[s->last_lit] = (ush)dist;
  85520. s->l_buf[s->last_lit++] = (uch)lc;
  85521. if (dist == 0) {
  85522. /* lc is the unmatched char */
  85523. s->dyn_ltree[lc].Freq++;
  85524. } else {
  85525. s->matches++;
  85526. /* Here, lc is the match length - MIN_MATCH */
  85527. dist--; /* dist = match distance - 1 */
  85528. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85529. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85530. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85531. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85532. s->dyn_dtree[d_code(dist)].Freq++;
  85533. }
  85534. #ifdef TRUNCATE_BLOCK
  85535. /* Try to guess if it is profitable to stop the current block here */
  85536. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85537. /* Compute an upper bound for the compressed length */
  85538. ulg out_length = (ulg)s->last_lit*8L;
  85539. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85540. int dcode;
  85541. for (dcode = 0; dcode < D_CODES; dcode++) {
  85542. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85543. (5L+extra_dbits[dcode]);
  85544. }
  85545. out_length >>= 3;
  85546. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85547. s->last_lit, in_length, out_length,
  85548. 100L - out_length*100L/in_length));
  85549. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85550. }
  85551. #endif
  85552. return (s->last_lit == s->lit_bufsize-1);
  85553. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85554. * on 16 bit machines and because stored blocks are restricted to
  85555. * 64K-1 bytes.
  85556. */
  85557. }
  85558. /* ===========================================================================
  85559. * Send the block data compressed using the given Huffman trees
  85560. */
  85561. local void compress_block (deflate_state *s,
  85562. ct_data *ltree, /* literal tree */
  85563. ct_data *dtree) /* distance tree */
  85564. {
  85565. unsigned dist; /* distance of matched string */
  85566. int lc; /* match length or unmatched char (if dist == 0) */
  85567. unsigned lx = 0; /* running index in l_buf */
  85568. unsigned code; /* the code to send */
  85569. int extra; /* number of extra bits to send */
  85570. if (s->last_lit != 0) do {
  85571. dist = s->d_buf[lx];
  85572. lc = s->l_buf[lx++];
  85573. if (dist == 0) {
  85574. send_code(s, lc, ltree); /* send a literal byte */
  85575. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85576. } else {
  85577. /* Here, lc is the match length - MIN_MATCH */
  85578. code = _length_code[lc];
  85579. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85580. extra = extra_lbits[code];
  85581. if (extra != 0) {
  85582. lc -= base_length[code];
  85583. send_bits(s, lc, extra); /* send the extra length bits */
  85584. }
  85585. dist--; /* dist is now the match distance - 1 */
  85586. code = d_code(dist);
  85587. Assert (code < D_CODES, "bad d_code");
  85588. send_code(s, code, dtree); /* send the distance code */
  85589. extra = extra_dbits[code];
  85590. if (extra != 0) {
  85591. dist -= base_dist[code];
  85592. send_bits(s, dist, extra); /* send the extra distance bits */
  85593. }
  85594. } /* literal or match pair ? */
  85595. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85596. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85597. "pendingBuf overflow");
  85598. } while (lx < s->last_lit);
  85599. send_code(s, END_BLOCK, ltree);
  85600. s->last_eob_len = ltree[END_BLOCK].Len;
  85601. }
  85602. /* ===========================================================================
  85603. * Set the data type to BINARY or TEXT, using a crude approximation:
  85604. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85605. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85606. * IN assertion: the fields Freq of dyn_ltree are set.
  85607. */
  85608. local void set_data_type (deflate_state *s)
  85609. {
  85610. int n;
  85611. for (n = 0; n < 9; n++)
  85612. if (s->dyn_ltree[n].Freq != 0)
  85613. break;
  85614. if (n == 9)
  85615. for (n = 14; n < 32; n++)
  85616. if (s->dyn_ltree[n].Freq != 0)
  85617. break;
  85618. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85619. }
  85620. /* ===========================================================================
  85621. * Reverse the first len bits of a code, using straightforward code (a faster
  85622. * method would use a table)
  85623. * IN assertion: 1 <= len <= 15
  85624. */
  85625. local unsigned bi_reverse (unsigned code, int len)
  85626. {
  85627. register unsigned res = 0;
  85628. do {
  85629. res |= code & 1;
  85630. code >>= 1, res <<= 1;
  85631. } while (--len > 0);
  85632. return res >> 1;
  85633. }
  85634. /* ===========================================================================
  85635. * Flush the bit buffer, keeping at most 7 bits in it.
  85636. */
  85637. local void bi_flush (deflate_state *s)
  85638. {
  85639. if (s->bi_valid == 16) {
  85640. put_short(s, s->bi_buf);
  85641. s->bi_buf = 0;
  85642. s->bi_valid = 0;
  85643. } else if (s->bi_valid >= 8) {
  85644. put_byte(s, (Byte)s->bi_buf);
  85645. s->bi_buf >>= 8;
  85646. s->bi_valid -= 8;
  85647. }
  85648. }
  85649. /* ===========================================================================
  85650. * Flush the bit buffer and align the output on a byte boundary
  85651. */
  85652. local void bi_windup (deflate_state *s)
  85653. {
  85654. if (s->bi_valid > 8) {
  85655. put_short(s, s->bi_buf);
  85656. } else if (s->bi_valid > 0) {
  85657. put_byte(s, (Byte)s->bi_buf);
  85658. }
  85659. s->bi_buf = 0;
  85660. s->bi_valid = 0;
  85661. #ifdef DEBUG
  85662. s->bits_sent = (s->bits_sent+7) & ~7;
  85663. #endif
  85664. }
  85665. /* ===========================================================================
  85666. * Copy a stored block, storing first the length and its
  85667. * one's complement if requested.
  85668. */
  85669. local void copy_block(deflate_state *s,
  85670. charf *buf, /* the input data */
  85671. unsigned len, /* its length */
  85672. int header) /* true if block header must be written */
  85673. {
  85674. bi_windup(s); /* align on byte boundary */
  85675. s->last_eob_len = 8; /* enough lookahead for inflate */
  85676. if (header) {
  85677. put_short(s, (ush)len);
  85678. put_short(s, (ush)~len);
  85679. #ifdef DEBUG
  85680. s->bits_sent += 2*16;
  85681. #endif
  85682. }
  85683. #ifdef DEBUG
  85684. s->bits_sent += (ulg)len<<3;
  85685. #endif
  85686. while (len--) {
  85687. put_byte(s, *buf++);
  85688. }
  85689. }
  85690. /*** End of inlined file: trees.c ***/
  85691. /*** Start of inlined file: zutil.c ***/
  85692. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85693. #ifndef NO_DUMMY_DECL
  85694. struct internal_state {int dummy;}; /* for buggy compilers */
  85695. #endif
  85696. const char * const z_errmsg[10] = {
  85697. "need dictionary", /* Z_NEED_DICT 2 */
  85698. "stream end", /* Z_STREAM_END 1 */
  85699. "", /* Z_OK 0 */
  85700. "file error", /* Z_ERRNO (-1) */
  85701. "stream error", /* Z_STREAM_ERROR (-2) */
  85702. "data error", /* Z_DATA_ERROR (-3) */
  85703. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85704. "buffer error", /* Z_BUF_ERROR (-5) */
  85705. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85706. ""};
  85707. /*const char * ZEXPORT zlibVersion()
  85708. {
  85709. return ZLIB_VERSION;
  85710. }
  85711. uLong ZEXPORT zlibCompileFlags()
  85712. {
  85713. uLong flags;
  85714. flags = 0;
  85715. switch (sizeof(uInt)) {
  85716. case 2: break;
  85717. case 4: flags += 1; break;
  85718. case 8: flags += 2; break;
  85719. default: flags += 3;
  85720. }
  85721. switch (sizeof(uLong)) {
  85722. case 2: break;
  85723. case 4: flags += 1 << 2; break;
  85724. case 8: flags += 2 << 2; break;
  85725. default: flags += 3 << 2;
  85726. }
  85727. switch (sizeof(voidpf)) {
  85728. case 2: break;
  85729. case 4: flags += 1 << 4; break;
  85730. case 8: flags += 2 << 4; break;
  85731. default: flags += 3 << 4;
  85732. }
  85733. switch (sizeof(z_off_t)) {
  85734. case 2: break;
  85735. case 4: flags += 1 << 6; break;
  85736. case 8: flags += 2 << 6; break;
  85737. default: flags += 3 << 6;
  85738. }
  85739. #ifdef DEBUG
  85740. flags += 1 << 8;
  85741. #endif
  85742. #if defined(ASMV) || defined(ASMINF)
  85743. flags += 1 << 9;
  85744. #endif
  85745. #ifdef ZLIB_WINAPI
  85746. flags += 1 << 10;
  85747. #endif
  85748. #ifdef BUILDFIXED
  85749. flags += 1 << 12;
  85750. #endif
  85751. #ifdef DYNAMIC_CRC_TABLE
  85752. flags += 1 << 13;
  85753. #endif
  85754. #ifdef NO_GZCOMPRESS
  85755. flags += 1L << 16;
  85756. #endif
  85757. #ifdef NO_GZIP
  85758. flags += 1L << 17;
  85759. #endif
  85760. #ifdef PKZIP_BUG_WORKAROUND
  85761. flags += 1L << 20;
  85762. #endif
  85763. #ifdef FASTEST
  85764. flags += 1L << 21;
  85765. #endif
  85766. #ifdef STDC
  85767. # ifdef NO_vsnprintf
  85768. flags += 1L << 25;
  85769. # ifdef HAS_vsprintf_void
  85770. flags += 1L << 26;
  85771. # endif
  85772. # else
  85773. # ifdef HAS_vsnprintf_void
  85774. flags += 1L << 26;
  85775. # endif
  85776. # endif
  85777. #else
  85778. flags += 1L << 24;
  85779. # ifdef NO_snprintf
  85780. flags += 1L << 25;
  85781. # ifdef HAS_sprintf_void
  85782. flags += 1L << 26;
  85783. # endif
  85784. # else
  85785. # ifdef HAS_snprintf_void
  85786. flags += 1L << 26;
  85787. # endif
  85788. # endif
  85789. #endif
  85790. return flags;
  85791. }*/
  85792. #ifdef DEBUG
  85793. # ifndef verbose
  85794. # define verbose 0
  85795. # endif
  85796. int z_verbose = verbose;
  85797. void z_error (const char *m)
  85798. {
  85799. fprintf(stderr, "%s\n", m);
  85800. exit(1);
  85801. }
  85802. #endif
  85803. /* exported to allow conversion of error code to string for compress() and
  85804. * uncompress()
  85805. */
  85806. const char * ZEXPORT zError(int err)
  85807. {
  85808. return ERR_MSG(err);
  85809. }
  85810. #if defined(_WIN32_WCE)
  85811. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85812. * errno. We define it as a global variable to simplify porting.
  85813. * Its value is always 0 and should not be used.
  85814. */
  85815. int errno = 0;
  85816. #endif
  85817. #ifndef HAVE_MEMCPY
  85818. void zmemcpy(dest, source, len)
  85819. Bytef* dest;
  85820. const Bytef* source;
  85821. uInt len;
  85822. {
  85823. if (len == 0) return;
  85824. do {
  85825. *dest++ = *source++; /* ??? to be unrolled */
  85826. } while (--len != 0);
  85827. }
  85828. int zmemcmp(s1, s2, len)
  85829. const Bytef* s1;
  85830. const Bytef* s2;
  85831. uInt len;
  85832. {
  85833. uInt j;
  85834. for (j = 0; j < len; j++) {
  85835. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85836. }
  85837. return 0;
  85838. }
  85839. void zmemzero(dest, len)
  85840. Bytef* dest;
  85841. uInt len;
  85842. {
  85843. if (len == 0) return;
  85844. do {
  85845. *dest++ = 0; /* ??? to be unrolled */
  85846. } while (--len != 0);
  85847. }
  85848. #endif
  85849. #ifdef SYS16BIT
  85850. #ifdef __TURBOC__
  85851. /* Turbo C in 16-bit mode */
  85852. # define MY_ZCALLOC
  85853. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85854. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85855. * must fix the pointer. Warning: the pointer must be put back to its
  85856. * original form in order to free it, use zcfree().
  85857. */
  85858. #define MAX_PTR 10
  85859. /* 10*64K = 640K */
  85860. local int next_ptr = 0;
  85861. typedef struct ptr_table_s {
  85862. voidpf org_ptr;
  85863. voidpf new_ptr;
  85864. } ptr_table;
  85865. local ptr_table table[MAX_PTR];
  85866. /* This table is used to remember the original form of pointers
  85867. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85868. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85869. * protected from concurrent access. This hack doesn't work anyway on
  85870. * a protected system like OS/2. Use Microsoft C instead.
  85871. */
  85872. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85873. {
  85874. voidpf buf = opaque; /* just to make some compilers happy */
  85875. ulg bsize = (ulg)items*size;
  85876. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85877. * will return a usable pointer which doesn't have to be normalized.
  85878. */
  85879. if (bsize < 65520L) {
  85880. buf = farmalloc(bsize);
  85881. if (*(ush*)&buf != 0) return buf;
  85882. } else {
  85883. buf = farmalloc(bsize + 16L);
  85884. }
  85885. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85886. table[next_ptr].org_ptr = buf;
  85887. /* Normalize the pointer to seg:0 */
  85888. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85889. *(ush*)&buf = 0;
  85890. table[next_ptr++].new_ptr = buf;
  85891. return buf;
  85892. }
  85893. void zcfree (voidpf opaque, voidpf ptr)
  85894. {
  85895. int n;
  85896. if (*(ush*)&ptr != 0) { /* object < 64K */
  85897. farfree(ptr);
  85898. return;
  85899. }
  85900. /* Find the original pointer */
  85901. for (n = 0; n < next_ptr; n++) {
  85902. if (ptr != table[n].new_ptr) continue;
  85903. farfree(table[n].org_ptr);
  85904. while (++n < next_ptr) {
  85905. table[n-1] = table[n];
  85906. }
  85907. next_ptr--;
  85908. return;
  85909. }
  85910. ptr = opaque; /* just to make some compilers happy */
  85911. Assert(0, "zcfree: ptr not found");
  85912. }
  85913. #endif /* __TURBOC__ */
  85914. #ifdef M_I86
  85915. /* Microsoft C in 16-bit mode */
  85916. # define MY_ZCALLOC
  85917. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85918. # define _halloc halloc
  85919. # define _hfree hfree
  85920. #endif
  85921. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85922. {
  85923. if (opaque) opaque = 0; /* to make compiler happy */
  85924. return _halloc((long)items, size);
  85925. }
  85926. void zcfree (voidpf opaque, voidpf ptr)
  85927. {
  85928. if (opaque) opaque = 0; /* to make compiler happy */
  85929. _hfree(ptr);
  85930. }
  85931. #endif /* M_I86 */
  85932. #endif /* SYS16BIT */
  85933. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85934. #ifndef STDC
  85935. extern voidp malloc OF((uInt size));
  85936. extern voidp calloc OF((uInt items, uInt size));
  85937. extern void free OF((voidpf ptr));
  85938. #endif
  85939. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85940. {
  85941. if (opaque) items += size - size; /* make compiler happy */
  85942. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85943. (voidpf)calloc(items, size);
  85944. }
  85945. void zcfree (voidpf opaque, voidpf ptr)
  85946. {
  85947. free(ptr);
  85948. if (opaque) return; /* make compiler happy */
  85949. }
  85950. #endif /* MY_ZCALLOC */
  85951. /*** End of inlined file: zutil.c ***/
  85952. #undef Byte
  85953. #else
  85954. #include <zlib.h>
  85955. #endif
  85956. }
  85957. #if JUCE_MSVC
  85958. #pragma warning (pop)
  85959. #endif
  85960. BEGIN_JUCE_NAMESPACE
  85961. // internal helper object that holds the zlib structures so they don't have to be
  85962. // included publicly.
  85963. class GZIPDecompressorInputStream::GZIPDecompressHelper
  85964. {
  85965. public:
  85966. GZIPDecompressHelper (const bool noWrap)
  85967. : finished (true),
  85968. needsDictionary (false),
  85969. error (true),
  85970. streamIsValid (false),
  85971. data (0),
  85972. dataSize (0)
  85973. {
  85974. using namespace zlibNamespace;
  85975. zerostruct (stream);
  85976. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85977. finished = error = ! streamIsValid;
  85978. }
  85979. ~GZIPDecompressHelper()
  85980. {
  85981. using namespace zlibNamespace;
  85982. if (streamIsValid)
  85983. inflateEnd (&stream);
  85984. }
  85985. bool needsInput() const throw() { return dataSize <= 0; }
  85986. void setInput (uint8* const data_, const int size) throw()
  85987. {
  85988. data = data_;
  85989. dataSize = size;
  85990. }
  85991. int doNextBlock (uint8* const dest, const int destSize)
  85992. {
  85993. using namespace zlibNamespace;
  85994. if (streamIsValid && data != 0 && ! finished)
  85995. {
  85996. stream.next_in = data;
  85997. stream.next_out = dest;
  85998. stream.avail_in = dataSize;
  85999. stream.avail_out = destSize;
  86000. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86001. {
  86002. case Z_STREAM_END:
  86003. finished = true;
  86004. // deliberate fall-through
  86005. case Z_OK:
  86006. data += dataSize - stream.avail_in;
  86007. dataSize = stream.avail_in;
  86008. return destSize - stream.avail_out;
  86009. case Z_NEED_DICT:
  86010. needsDictionary = true;
  86011. data += dataSize - stream.avail_in;
  86012. dataSize = stream.avail_in;
  86013. break;
  86014. case Z_DATA_ERROR:
  86015. case Z_MEM_ERROR:
  86016. error = true;
  86017. default:
  86018. break;
  86019. }
  86020. }
  86021. return 0;
  86022. }
  86023. bool finished, needsDictionary, error, streamIsValid;
  86024. enum { gzipDecompBufferSize = 32768 };
  86025. private:
  86026. zlibNamespace::z_stream stream;
  86027. uint8* data;
  86028. int dataSize;
  86029. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  86030. };
  86031. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86032. const bool deleteSourceWhenDestroyed,
  86033. const bool noWrap_,
  86034. const int64 uncompressedStreamLength_)
  86035. : sourceStream (sourceStream_),
  86036. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86037. uncompressedStreamLength (uncompressedStreamLength_),
  86038. noWrap (noWrap_),
  86039. isEof (false),
  86040. activeBufferSize (0),
  86041. originalSourcePos (sourceStream_->getPosition()),
  86042. currentPos (0),
  86043. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86044. helper (new GZIPDecompressHelper (noWrap_))
  86045. {
  86046. }
  86047. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86048. : sourceStream (&sourceStream_),
  86049. uncompressedStreamLength (-1),
  86050. noWrap (false),
  86051. isEof (false),
  86052. activeBufferSize (0),
  86053. originalSourcePos (sourceStream_.getPosition()),
  86054. currentPos (0),
  86055. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86056. helper (new GZIPDecompressHelper (false))
  86057. {
  86058. }
  86059. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86060. {
  86061. }
  86062. int64 GZIPDecompressorInputStream::getTotalLength()
  86063. {
  86064. return uncompressedStreamLength;
  86065. }
  86066. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86067. {
  86068. if ((howMany > 0) && ! isEof)
  86069. {
  86070. jassert (destBuffer != 0);
  86071. if (destBuffer != 0)
  86072. {
  86073. int numRead = 0;
  86074. uint8* d = static_cast <uint8*> (destBuffer);
  86075. while (! helper->error)
  86076. {
  86077. const int n = helper->doNextBlock (d, howMany);
  86078. currentPos += n;
  86079. if (n == 0)
  86080. {
  86081. if (helper->finished || helper->needsDictionary)
  86082. {
  86083. isEof = true;
  86084. return numRead;
  86085. }
  86086. if (helper->needsInput())
  86087. {
  86088. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86089. if (activeBufferSize > 0)
  86090. {
  86091. helper->setInput (buffer, activeBufferSize);
  86092. }
  86093. else
  86094. {
  86095. isEof = true;
  86096. return numRead;
  86097. }
  86098. }
  86099. }
  86100. else
  86101. {
  86102. numRead += n;
  86103. howMany -= n;
  86104. d += n;
  86105. if (howMany <= 0)
  86106. return numRead;
  86107. }
  86108. }
  86109. }
  86110. }
  86111. return 0;
  86112. }
  86113. bool GZIPDecompressorInputStream::isExhausted()
  86114. {
  86115. return helper->error || isEof;
  86116. }
  86117. int64 GZIPDecompressorInputStream::getPosition()
  86118. {
  86119. return currentPos;
  86120. }
  86121. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86122. {
  86123. if (newPos < currentPos)
  86124. {
  86125. // to go backwards, reset the stream and start again..
  86126. isEof = false;
  86127. activeBufferSize = 0;
  86128. currentPos = 0;
  86129. helper = new GZIPDecompressHelper (noWrap);
  86130. sourceStream->setPosition (originalSourcePos);
  86131. }
  86132. skipNextBytes (newPos - currentPos);
  86133. return true;
  86134. }
  86135. END_JUCE_NAMESPACE
  86136. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86137. #endif
  86138. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86139. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86140. #if JUCE_USE_FLAC
  86141. #if JUCE_WINDOWS
  86142. #include <windows.h>
  86143. #endif
  86144. namespace FlacNamespace
  86145. {
  86146. #if JUCE_INCLUDE_FLAC_CODE
  86147. #if JUCE_MSVC
  86148. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86149. #endif
  86150. #define FLAC__NO_DLL 1
  86151. #if ! defined (SIZE_MAX)
  86152. #define SIZE_MAX 0xffffffff
  86153. #endif
  86154. #define __STDC_LIMIT_MACROS 1
  86155. /*** Start of inlined file: all.h ***/
  86156. #ifndef FLAC__ALL_H
  86157. #define FLAC__ALL_H
  86158. /*** Start of inlined file: export.h ***/
  86159. #ifndef FLAC__EXPORT_H
  86160. #define FLAC__EXPORT_H
  86161. /** \file include/FLAC/export.h
  86162. *
  86163. * \brief
  86164. * This module contains #defines and symbols for exporting function
  86165. * calls, and providing version information and compiled-in features.
  86166. *
  86167. * See the \link flac_export export \endlink module.
  86168. */
  86169. /** \defgroup flac_export FLAC/export.h: export symbols
  86170. * \ingroup flac
  86171. *
  86172. * \brief
  86173. * This module contains #defines and symbols for exporting function
  86174. * calls, and providing version information and compiled-in features.
  86175. *
  86176. * If you are compiling with MSVC and will link to the static library
  86177. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86178. * make sure the symbols are exported properly.
  86179. *
  86180. * \{
  86181. */
  86182. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86183. #define FLAC_API
  86184. #else
  86185. #ifdef FLAC_API_EXPORTS
  86186. #define FLAC_API _declspec(dllexport)
  86187. #else
  86188. #define FLAC_API _declspec(dllimport)
  86189. #endif
  86190. #endif
  86191. /** These #defines will mirror the libtool-based library version number, see
  86192. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86193. */
  86194. #define FLAC_API_VERSION_CURRENT 10
  86195. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86196. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86197. #ifdef __cplusplus
  86198. extern "C" {
  86199. #endif
  86200. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86201. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86202. #ifdef __cplusplus
  86203. }
  86204. #endif
  86205. /* \} */
  86206. #endif
  86207. /*** End of inlined file: export.h ***/
  86208. /*** Start of inlined file: assert.h ***/
  86209. #ifndef FLAC__ASSERT_H
  86210. #define FLAC__ASSERT_H
  86211. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86212. #ifdef DEBUG
  86213. #include <assert.h>
  86214. #define FLAC__ASSERT(x) assert(x)
  86215. #define FLAC__ASSERT_DECLARATION(x) x
  86216. #else
  86217. #define FLAC__ASSERT(x)
  86218. #define FLAC__ASSERT_DECLARATION(x)
  86219. #endif
  86220. #endif
  86221. /*** End of inlined file: assert.h ***/
  86222. /*** Start of inlined file: callback.h ***/
  86223. #ifndef FLAC__CALLBACK_H
  86224. #define FLAC__CALLBACK_H
  86225. /*** Start of inlined file: ordinals.h ***/
  86226. #ifndef FLAC__ORDINALS_H
  86227. #define FLAC__ORDINALS_H
  86228. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86229. #include <inttypes.h>
  86230. #endif
  86231. typedef signed char FLAC__int8;
  86232. typedef unsigned char FLAC__uint8;
  86233. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86234. typedef __int16 FLAC__int16;
  86235. typedef __int32 FLAC__int32;
  86236. typedef __int64 FLAC__int64;
  86237. typedef unsigned __int16 FLAC__uint16;
  86238. typedef unsigned __int32 FLAC__uint32;
  86239. typedef unsigned __int64 FLAC__uint64;
  86240. #elif defined(__EMX__)
  86241. typedef short FLAC__int16;
  86242. typedef long FLAC__int32;
  86243. typedef long long FLAC__int64;
  86244. typedef unsigned short FLAC__uint16;
  86245. typedef unsigned long FLAC__uint32;
  86246. typedef unsigned long long FLAC__uint64;
  86247. #else
  86248. typedef int16_t FLAC__int16;
  86249. typedef int32_t FLAC__int32;
  86250. typedef int64_t FLAC__int64;
  86251. typedef uint16_t FLAC__uint16;
  86252. typedef uint32_t FLAC__uint32;
  86253. typedef uint64_t FLAC__uint64;
  86254. #endif
  86255. typedef int FLAC__bool;
  86256. typedef FLAC__uint8 FLAC__byte;
  86257. #ifdef true
  86258. #undef true
  86259. #endif
  86260. #ifdef false
  86261. #undef false
  86262. #endif
  86263. #ifndef __cplusplus
  86264. #define true 1
  86265. #define false 0
  86266. #endif
  86267. #endif
  86268. /*** End of inlined file: ordinals.h ***/
  86269. #include <stdlib.h> /* for size_t */
  86270. /** \file include/FLAC/callback.h
  86271. *
  86272. * \brief
  86273. * This module defines the structures for describing I/O callbacks
  86274. * to the other FLAC interfaces.
  86275. *
  86276. * See the detailed documentation for callbacks in the
  86277. * \link flac_callbacks callbacks \endlink module.
  86278. */
  86279. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86280. * \ingroup flac
  86281. *
  86282. * \brief
  86283. * This module defines the structures for describing I/O callbacks
  86284. * to the other FLAC interfaces.
  86285. *
  86286. * The purpose of the I/O callback functions is to create a common way
  86287. * for the metadata interfaces to handle I/O.
  86288. *
  86289. * Originally the metadata interfaces required filenames as the way of
  86290. * specifying FLAC files to operate on. This is problematic in some
  86291. * environments so there is an additional option to specify a set of
  86292. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86293. *
  86294. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86295. * opaque structure for a data source.
  86296. *
  86297. * The callback function prototypes are similar (but not identical) to the
  86298. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86299. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86300. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86301. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86302. * is required. \warning You generally CANNOT directly use fseek or ftell
  86303. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86304. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86305. * large files. You will have to find an equivalent function (e.g. ftello),
  86306. * or write a wrapper. The same is true for feof() since this is usually
  86307. * implemented as a macro, not as a function whose address can be taken.
  86308. *
  86309. * \{
  86310. */
  86311. #ifdef __cplusplus
  86312. extern "C" {
  86313. #endif
  86314. /** This is the opaque handle type used by the callbacks. Typically
  86315. * this is a \c FILE* or address of a file descriptor.
  86316. */
  86317. typedef void* FLAC__IOHandle;
  86318. /** Signature for the read callback.
  86319. * The signature and semantics match POSIX fread() implementations
  86320. * and can generally be used interchangeably.
  86321. *
  86322. * \param ptr The address of the read buffer.
  86323. * \param size The size of the records to be read.
  86324. * \param nmemb The number of records to be read.
  86325. * \param handle The handle to the data source.
  86326. * \retval size_t
  86327. * The number of records read.
  86328. */
  86329. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86330. /** Signature for the write callback.
  86331. * The signature and semantics match POSIX fwrite() implementations
  86332. * and can generally be used interchangeably.
  86333. *
  86334. * \param ptr The address of the write buffer.
  86335. * \param size The size of the records to be written.
  86336. * \param nmemb The number of records to be written.
  86337. * \param handle The handle to the data source.
  86338. * \retval size_t
  86339. * The number of records written.
  86340. */
  86341. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86342. /** Signature for the seek callback.
  86343. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86344. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86345. * and 32-bits wide.
  86346. *
  86347. * \param handle The handle to the data source.
  86348. * \param offset The new position, relative to \a whence
  86349. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86350. * \retval int
  86351. * \c 0 on success, \c -1 on error.
  86352. */
  86353. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86354. /** Signature for the tell callback.
  86355. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86356. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86357. * and 32-bits wide.
  86358. *
  86359. * \param handle The handle to the data source.
  86360. * \retval FLAC__int64
  86361. * The current position on success, \c -1 on error.
  86362. */
  86363. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86364. /** Signature for the EOF callback.
  86365. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86366. * on many systems, feof() is a macro, so in this case a wrapper function
  86367. * must be provided instead.
  86368. *
  86369. * \param handle The handle to the data source.
  86370. * \retval int
  86371. * \c 0 if not at end of file, nonzero if at end of file.
  86372. */
  86373. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86374. /** Signature for the close callback.
  86375. * The signature and semantics match POSIX fclose() implementations
  86376. * and can generally be used interchangeably.
  86377. *
  86378. * \param handle The handle to the data source.
  86379. * \retval int
  86380. * \c 0 on success, \c EOF on error.
  86381. */
  86382. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86383. /** A structure for holding a set of callbacks.
  86384. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86385. * describe which of the callbacks are required. The ones that are not
  86386. * required may be set to NULL.
  86387. *
  86388. * If the seek requirement for an interface is optional, you can signify that
  86389. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86390. */
  86391. typedef struct {
  86392. FLAC__IOCallback_Read read;
  86393. FLAC__IOCallback_Write write;
  86394. FLAC__IOCallback_Seek seek;
  86395. FLAC__IOCallback_Tell tell;
  86396. FLAC__IOCallback_Eof eof;
  86397. FLAC__IOCallback_Close close;
  86398. } FLAC__IOCallbacks;
  86399. /* \} */
  86400. #ifdef __cplusplus
  86401. }
  86402. #endif
  86403. #endif
  86404. /*** End of inlined file: callback.h ***/
  86405. /*** Start of inlined file: format.h ***/
  86406. #ifndef FLAC__FORMAT_H
  86407. #define FLAC__FORMAT_H
  86408. #ifdef __cplusplus
  86409. extern "C" {
  86410. #endif
  86411. /** \file include/FLAC/format.h
  86412. *
  86413. * \brief
  86414. * This module contains structure definitions for the representation
  86415. * of FLAC format components in memory. These are the basic
  86416. * structures used by the rest of the interfaces.
  86417. *
  86418. * See the detailed documentation in the
  86419. * \link flac_format format \endlink module.
  86420. */
  86421. /** \defgroup flac_format FLAC/format.h: format components
  86422. * \ingroup flac
  86423. *
  86424. * \brief
  86425. * This module contains structure definitions for the representation
  86426. * of FLAC format components in memory. These are the basic
  86427. * structures used by the rest of the interfaces.
  86428. *
  86429. * First, you should be familiar with the
  86430. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86431. * follow directly from the specification. As a user of libFLAC, the
  86432. * interesting parts really are the structures that describe the frame
  86433. * header and metadata blocks.
  86434. *
  86435. * The format structures here are very primitive, designed to store
  86436. * information in an efficient way. Reading information from the
  86437. * structures is easy but creating or modifying them directly is
  86438. * more complex. For the most part, as a user of a library, editing
  86439. * is not necessary; however, for metadata blocks it is, so there are
  86440. * convenience functions provided in the \link flac_metadata metadata
  86441. * module \endlink to simplify the manipulation of metadata blocks.
  86442. *
  86443. * \note
  86444. * It's not the best convention, but symbols ending in _LEN are in bits
  86445. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86446. * global variables because they are usually used when declaring byte
  86447. * arrays and some compilers require compile-time knowledge of array
  86448. * sizes when declared on the stack.
  86449. *
  86450. * \{
  86451. */
  86452. /*
  86453. Most of the values described in this file are defined by the FLAC
  86454. format specification. There is nothing to tune here.
  86455. */
  86456. /** The largest legal metadata type code. */
  86457. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86458. /** The minimum block size, in samples, permitted by the format. */
  86459. #define FLAC__MIN_BLOCK_SIZE (16u)
  86460. /** The maximum block size, in samples, permitted by the format. */
  86461. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86462. /** The maximum block size, in samples, permitted by the FLAC subset for
  86463. * sample rates up to 48kHz. */
  86464. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86465. /** The maximum number of channels permitted by the format. */
  86466. #define FLAC__MAX_CHANNELS (8u)
  86467. /** The minimum sample resolution permitted by the format. */
  86468. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86469. /** The maximum sample resolution permitted by the format. */
  86470. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86471. /** The maximum sample resolution permitted by libFLAC.
  86472. *
  86473. * \warning
  86474. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86475. * the reference encoder/decoder is currently limited to 24 bits because
  86476. * of prevalent 32-bit math, so make sure and use this value when
  86477. * appropriate.
  86478. */
  86479. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86480. /** The maximum sample rate permitted by the format. The value is
  86481. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86482. * as to why.
  86483. */
  86484. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86485. /** The maximum LPC order permitted by the format. */
  86486. #define FLAC__MAX_LPC_ORDER (32u)
  86487. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86488. * up to 48kHz. */
  86489. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86490. /** The minimum quantized linear predictor coefficient precision
  86491. * permitted by the format.
  86492. */
  86493. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86494. /** The maximum quantized linear predictor coefficient precision
  86495. * permitted by the format.
  86496. */
  86497. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86498. /** The maximum order of the fixed predictors permitted by the format. */
  86499. #define FLAC__MAX_FIXED_ORDER (4u)
  86500. /** The maximum Rice partition order permitted by the format. */
  86501. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86502. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86503. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86504. /** The version string of the release, stamped onto the libraries and binaries.
  86505. *
  86506. * \note
  86507. * This does not correspond to the shared library version number, which
  86508. * is used to determine binary compatibility.
  86509. */
  86510. extern FLAC_API const char *FLAC__VERSION_STRING;
  86511. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86512. * This is a NUL-terminated ASCII string; when inserted into the
  86513. * VORBIS_COMMENT the trailing null is stripped.
  86514. */
  86515. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86516. /** The byte string representation of the beginning of a FLAC stream. */
  86517. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86518. /** The 32-bit integer big-endian representation of the beginning of
  86519. * a FLAC stream.
  86520. */
  86521. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86522. /** The length of the FLAC signature in bits. */
  86523. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86524. /** The length of the FLAC signature in bytes. */
  86525. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86526. /*****************************************************************************
  86527. *
  86528. * Subframe structures
  86529. *
  86530. *****************************************************************************/
  86531. /*****************************************************************************/
  86532. /** An enumeration of the available entropy coding methods. */
  86533. typedef enum {
  86534. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86535. /**< Residual is coded by partitioning into contexts, each with it's own
  86536. * 4-bit Rice parameter. */
  86537. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86538. /**< Residual is coded by partitioning into contexts, each with it's own
  86539. * 5-bit Rice parameter. */
  86540. } FLAC__EntropyCodingMethodType;
  86541. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86542. *
  86543. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86544. * give the string equivalent. The contents should not be modified.
  86545. */
  86546. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86547. /** Contents of a Rice partitioned residual
  86548. */
  86549. typedef struct {
  86550. unsigned *parameters;
  86551. /**< The Rice parameters for each context. */
  86552. unsigned *raw_bits;
  86553. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86554. * partitions and zero for unescaped partitions.
  86555. */
  86556. unsigned capacity_by_order;
  86557. /**< The capacity of the \a parameters and \a raw_bits arrays
  86558. * specified as an order, i.e. the number of array elements
  86559. * allocated is 2 ^ \a capacity_by_order.
  86560. */
  86561. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86562. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86563. */
  86564. typedef struct {
  86565. unsigned order;
  86566. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86567. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86568. /**< The context's Rice parameters and/or raw bits. */
  86569. } FLAC__EntropyCodingMethod_PartitionedRice;
  86570. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86571. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86572. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86573. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86574. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86575. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86576. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86577. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86578. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86579. */
  86580. typedef struct {
  86581. FLAC__EntropyCodingMethodType type;
  86582. union {
  86583. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86584. } data;
  86585. } FLAC__EntropyCodingMethod;
  86586. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86587. /*****************************************************************************/
  86588. /** An enumeration of the available subframe types. */
  86589. typedef enum {
  86590. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86591. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86592. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86593. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86594. } FLAC__SubframeType;
  86595. /** Maps a FLAC__SubframeType to a C string.
  86596. *
  86597. * Using a FLAC__SubframeType as the index to this array will
  86598. * give the string equivalent. The contents should not be modified.
  86599. */
  86600. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86601. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86602. */
  86603. typedef struct {
  86604. FLAC__int32 value; /**< The constant signal value. */
  86605. } FLAC__Subframe_Constant;
  86606. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86607. */
  86608. typedef struct {
  86609. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86610. } FLAC__Subframe_Verbatim;
  86611. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86612. */
  86613. typedef struct {
  86614. FLAC__EntropyCodingMethod entropy_coding_method;
  86615. /**< The residual coding method. */
  86616. unsigned order;
  86617. /**< The polynomial order. */
  86618. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86619. /**< Warmup samples to prime the predictor, length == order. */
  86620. const FLAC__int32 *residual;
  86621. /**< The residual signal, length == (blocksize minus order) samples. */
  86622. } FLAC__Subframe_Fixed;
  86623. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86624. */
  86625. typedef struct {
  86626. FLAC__EntropyCodingMethod entropy_coding_method;
  86627. /**< The residual coding method. */
  86628. unsigned order;
  86629. /**< The FIR order. */
  86630. unsigned qlp_coeff_precision;
  86631. /**< Quantized FIR filter coefficient precision in bits. */
  86632. int quantization_level;
  86633. /**< The qlp coeff shift needed. */
  86634. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86635. /**< FIR filter coefficients. */
  86636. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86637. /**< Warmup samples to prime the predictor, length == order. */
  86638. const FLAC__int32 *residual;
  86639. /**< The residual signal, length == (blocksize minus order) samples. */
  86640. } FLAC__Subframe_LPC;
  86641. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86642. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86643. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86644. */
  86645. typedef struct {
  86646. FLAC__SubframeType type;
  86647. union {
  86648. FLAC__Subframe_Constant constant;
  86649. FLAC__Subframe_Fixed fixed;
  86650. FLAC__Subframe_LPC lpc;
  86651. FLAC__Subframe_Verbatim verbatim;
  86652. } data;
  86653. unsigned wasted_bits;
  86654. } FLAC__Subframe;
  86655. /** == 1 (bit)
  86656. *
  86657. * This used to be a zero-padding bit (hence the name
  86658. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86659. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86660. * to mean something else.
  86661. */
  86662. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86663. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86664. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86665. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86666. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86667. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86668. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86669. /*****************************************************************************/
  86670. /*****************************************************************************
  86671. *
  86672. * Frame structures
  86673. *
  86674. *****************************************************************************/
  86675. /** An enumeration of the available channel assignments. */
  86676. typedef enum {
  86677. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86678. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86679. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86680. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86681. } FLAC__ChannelAssignment;
  86682. /** Maps a FLAC__ChannelAssignment to a C string.
  86683. *
  86684. * Using a FLAC__ChannelAssignment as the index to this array will
  86685. * give the string equivalent. The contents should not be modified.
  86686. */
  86687. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86688. /** An enumeration of the possible frame numbering methods. */
  86689. typedef enum {
  86690. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86691. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86692. } FLAC__FrameNumberType;
  86693. /** Maps a FLAC__FrameNumberType to a C string.
  86694. *
  86695. * Using a FLAC__FrameNumberType as the index to this array will
  86696. * give the string equivalent. The contents should not be modified.
  86697. */
  86698. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86699. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86700. */
  86701. typedef struct {
  86702. unsigned blocksize;
  86703. /**< The number of samples per subframe. */
  86704. unsigned sample_rate;
  86705. /**< The sample rate in Hz. */
  86706. unsigned channels;
  86707. /**< The number of channels (== number of subframes). */
  86708. FLAC__ChannelAssignment channel_assignment;
  86709. /**< The channel assignment for the frame. */
  86710. unsigned bits_per_sample;
  86711. /**< The sample resolution. */
  86712. FLAC__FrameNumberType number_type;
  86713. /**< The numbering scheme used for the frame. As a convenience, the
  86714. * decoder will always convert a frame number to a sample number because
  86715. * the rules are complex. */
  86716. union {
  86717. FLAC__uint32 frame_number;
  86718. FLAC__uint64 sample_number;
  86719. } number;
  86720. /**< The frame number or sample number of first sample in frame;
  86721. * use the \a number_type value to determine which to use. */
  86722. FLAC__uint8 crc;
  86723. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86724. * of the raw frame header bytes, meaning everything before the CRC byte
  86725. * including the sync code.
  86726. */
  86727. } FLAC__FrameHeader;
  86728. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86729. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86730. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86731. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86732. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86733. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86734. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86735. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86736. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86737. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86738. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86739. */
  86740. typedef struct {
  86741. FLAC__uint16 crc;
  86742. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86743. * 0) of the bytes before the crc, back to and including the frame header
  86744. * sync code.
  86745. */
  86746. } FLAC__FrameFooter;
  86747. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86748. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86749. */
  86750. typedef struct {
  86751. FLAC__FrameHeader header;
  86752. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86753. FLAC__FrameFooter footer;
  86754. } FLAC__Frame;
  86755. /*****************************************************************************/
  86756. /*****************************************************************************
  86757. *
  86758. * Meta-data structures
  86759. *
  86760. *****************************************************************************/
  86761. /** An enumeration of the available metadata block types. */
  86762. typedef enum {
  86763. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86764. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86765. FLAC__METADATA_TYPE_PADDING = 1,
  86766. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86767. FLAC__METADATA_TYPE_APPLICATION = 2,
  86768. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86769. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86770. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86771. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86772. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86773. FLAC__METADATA_TYPE_CUESHEET = 5,
  86774. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86775. FLAC__METADATA_TYPE_PICTURE = 6,
  86776. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86777. FLAC__METADATA_TYPE_UNDEFINED = 7
  86778. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86779. } FLAC__MetadataType;
  86780. /** Maps a FLAC__MetadataType to a C string.
  86781. *
  86782. * Using a FLAC__MetadataType as the index to this array will
  86783. * give the string equivalent. The contents should not be modified.
  86784. */
  86785. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86786. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86787. */
  86788. typedef struct {
  86789. unsigned min_blocksize, max_blocksize;
  86790. unsigned min_framesize, max_framesize;
  86791. unsigned sample_rate;
  86792. unsigned channels;
  86793. unsigned bits_per_sample;
  86794. FLAC__uint64 total_samples;
  86795. FLAC__byte md5sum[16];
  86796. } FLAC__StreamMetadata_StreamInfo;
  86797. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86798. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86799. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86800. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86801. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86802. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86803. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86804. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86805. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86806. /** The total stream length of the STREAMINFO block in bytes. */
  86807. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86808. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86809. */
  86810. typedef struct {
  86811. int dummy;
  86812. /**< Conceptually this is an empty struct since we don't store the
  86813. * padding bytes. Empty structs are not allowed by some C compilers,
  86814. * hence the dummy.
  86815. */
  86816. } FLAC__StreamMetadata_Padding;
  86817. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86818. */
  86819. typedef struct {
  86820. FLAC__byte id[4];
  86821. FLAC__byte *data;
  86822. } FLAC__StreamMetadata_Application;
  86823. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86824. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86825. */
  86826. typedef struct {
  86827. FLAC__uint64 sample_number;
  86828. /**< The sample number of the target frame. */
  86829. FLAC__uint64 stream_offset;
  86830. /**< The offset, in bytes, of the target frame with respect to
  86831. * beginning of the first frame. */
  86832. unsigned frame_samples;
  86833. /**< The number of samples in the target frame. */
  86834. } FLAC__StreamMetadata_SeekPoint;
  86835. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86836. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86837. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86838. /** The total stream length of a seek point in bytes. */
  86839. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86840. /** The value used in the \a sample_number field of
  86841. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86842. * point (== 0xffffffffffffffff).
  86843. */
  86844. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86845. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86846. *
  86847. * \note From the format specification:
  86848. * - The seek points must be sorted by ascending sample number.
  86849. * - Each seek point's sample number must be the first sample of the
  86850. * target frame.
  86851. * - Each seek point's sample number must be unique within the table.
  86852. * - Existence of a SEEKTABLE block implies a correct setting of
  86853. * total_samples in the stream_info block.
  86854. * - Behavior is undefined when more than one SEEKTABLE block is
  86855. * present in a stream.
  86856. */
  86857. typedef struct {
  86858. unsigned num_points;
  86859. FLAC__StreamMetadata_SeekPoint *points;
  86860. } FLAC__StreamMetadata_SeekTable;
  86861. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86862. *
  86863. * For convenience, the APIs maintain a trailing NUL character at the end of
  86864. * \a entry which is not counted toward \a length, i.e.
  86865. * \code strlen(entry) == length \endcode
  86866. */
  86867. typedef struct {
  86868. FLAC__uint32 length;
  86869. FLAC__byte *entry;
  86870. } FLAC__StreamMetadata_VorbisComment_Entry;
  86871. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86872. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86873. */
  86874. typedef struct {
  86875. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86876. FLAC__uint32 num_comments;
  86877. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86878. } FLAC__StreamMetadata_VorbisComment;
  86879. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86880. /** FLAC CUESHEET track index structure. (See the
  86881. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86882. * the full description of each field.)
  86883. */
  86884. typedef struct {
  86885. FLAC__uint64 offset;
  86886. /**< Offset in samples, relative to the track offset, of the index
  86887. * point.
  86888. */
  86889. FLAC__byte number;
  86890. /**< The index point number. */
  86891. } FLAC__StreamMetadata_CueSheet_Index;
  86892. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86893. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86894. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86895. /** FLAC CUESHEET track structure. (See the
  86896. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86897. * the full description of each field.)
  86898. */
  86899. typedef struct {
  86900. FLAC__uint64 offset;
  86901. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86902. FLAC__byte number;
  86903. /**< The track number. */
  86904. char isrc[13];
  86905. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86906. unsigned type:1;
  86907. /**< The track type: 0 for audio, 1 for non-audio. */
  86908. unsigned pre_emphasis:1;
  86909. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86910. FLAC__byte num_indices;
  86911. /**< The number of track index points. */
  86912. FLAC__StreamMetadata_CueSheet_Index *indices;
  86913. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86914. } FLAC__StreamMetadata_CueSheet_Track;
  86915. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86916. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86917. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86918. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86919. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86920. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86921. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86922. /** FLAC CUESHEET structure. (See the
  86923. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86924. * for the full description of each field.)
  86925. */
  86926. typedef struct {
  86927. char media_catalog_number[129];
  86928. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86929. * general, the media catalog number may be 0 to 128 bytes long; any
  86930. * unused characters should be right-padded with NUL characters.
  86931. */
  86932. FLAC__uint64 lead_in;
  86933. /**< The number of lead-in samples. */
  86934. FLAC__bool is_cd;
  86935. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86936. unsigned num_tracks;
  86937. /**< The number of tracks. */
  86938. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86939. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86940. } FLAC__StreamMetadata_CueSheet;
  86941. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86942. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86943. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86944. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86945. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86946. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86947. typedef enum {
  86948. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86949. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86950. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86951. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86952. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86953. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86954. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86955. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86956. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86957. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86958. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86959. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86960. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86961. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86962. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86963. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86964. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86965. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86966. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86967. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86968. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86969. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86970. } FLAC__StreamMetadata_Picture_Type;
  86971. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86972. *
  86973. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86974. * will give the string equivalent. The contents should not be
  86975. * modified.
  86976. */
  86977. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86978. /** FLAC PICTURE structure. (See the
  86979. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86980. * for the full description of each field.)
  86981. */
  86982. typedef struct {
  86983. FLAC__StreamMetadata_Picture_Type type;
  86984. /**< The kind of picture stored. */
  86985. char *mime_type;
  86986. /**< Picture data's MIME type, in ASCII printable characters
  86987. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86988. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86989. * MIME type of '-->' is also allowed, in which case the picture
  86990. * data should be a complete URL. In file storage, the MIME type is
  86991. * stored as a 32-bit length followed by the ASCII string with no NUL
  86992. * terminator, but is converted to a plain C string in this structure
  86993. * for convenience.
  86994. */
  86995. FLAC__byte *description;
  86996. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86997. * the description is stored as a 32-bit length followed by the UTF-8
  86998. * string with no NUL terminator, but is converted to a plain C string
  86999. * in this structure for convenience.
  87000. */
  87001. FLAC__uint32 width;
  87002. /**< Picture's width in pixels. */
  87003. FLAC__uint32 height;
  87004. /**< Picture's height in pixels. */
  87005. FLAC__uint32 depth;
  87006. /**< Picture's color depth in bits-per-pixel. */
  87007. FLAC__uint32 colors;
  87008. /**< For indexed palettes (like GIF), picture's number of colors (the
  87009. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87010. */
  87011. FLAC__uint32 data_length;
  87012. /**< Length of binary picture data in bytes. */
  87013. FLAC__byte *data;
  87014. /**< Binary picture data. */
  87015. } FLAC__StreamMetadata_Picture;
  87016. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87017. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87018. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87019. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87020. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87021. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87022. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87023. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87024. /** Structure that is used when a metadata block of unknown type is loaded.
  87025. * The contents are opaque. The structure is used only internally to
  87026. * correctly handle unknown metadata.
  87027. */
  87028. typedef struct {
  87029. FLAC__byte *data;
  87030. } FLAC__StreamMetadata_Unknown;
  87031. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87032. */
  87033. typedef struct {
  87034. FLAC__MetadataType type;
  87035. /**< The type of the metadata block; used determine which member of the
  87036. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87037. * then \a data.unknown must be used. */
  87038. FLAC__bool is_last;
  87039. /**< \c true if this metadata block is the last, else \a false */
  87040. unsigned length;
  87041. /**< Length, in bytes, of the block data as it appears in the stream. */
  87042. union {
  87043. FLAC__StreamMetadata_StreamInfo stream_info;
  87044. FLAC__StreamMetadata_Padding padding;
  87045. FLAC__StreamMetadata_Application application;
  87046. FLAC__StreamMetadata_SeekTable seek_table;
  87047. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87048. FLAC__StreamMetadata_CueSheet cue_sheet;
  87049. FLAC__StreamMetadata_Picture picture;
  87050. FLAC__StreamMetadata_Unknown unknown;
  87051. } data;
  87052. /**< Polymorphic block data; use the \a type value to determine which
  87053. * to use. */
  87054. } FLAC__StreamMetadata;
  87055. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87056. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87057. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87058. /** The total stream length of a metadata block header in bytes. */
  87059. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87060. /*****************************************************************************/
  87061. /*****************************************************************************
  87062. *
  87063. * Utility functions
  87064. *
  87065. *****************************************************************************/
  87066. /** Tests that a sample rate is valid for FLAC.
  87067. *
  87068. * \param sample_rate The sample rate to test for compliance.
  87069. * \retval FLAC__bool
  87070. * \c true if the given sample rate conforms to the specification, else
  87071. * \c false.
  87072. */
  87073. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87074. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87075. * for valid sample rates are slightly more complex since the rate has to
  87076. * be expressible completely in the frame header.
  87077. *
  87078. * \param sample_rate The sample rate to test for compliance.
  87079. * \retval FLAC__bool
  87080. * \c true if the given sample rate conforms to the specification for the
  87081. * subset, else \c false.
  87082. */
  87083. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87084. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87085. * comment specification.
  87086. *
  87087. * Vorbis comment names must be composed only of characters from
  87088. * [0x20-0x3C,0x3E-0x7D].
  87089. *
  87090. * \param name A NUL-terminated string to be checked.
  87091. * \assert
  87092. * \code name != NULL \endcode
  87093. * \retval FLAC__bool
  87094. * \c false if entry name is illegal, else \c true.
  87095. */
  87096. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87097. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87098. * comment specification.
  87099. *
  87100. * Vorbis comment values must be valid UTF-8 sequences.
  87101. *
  87102. * \param value A string to be checked.
  87103. * \param length A the length of \a value in bytes. May be
  87104. * \c (unsigned)(-1) to indicate that \a value is a plain
  87105. * UTF-8 NUL-terminated string.
  87106. * \assert
  87107. * \code value != NULL \endcode
  87108. * \retval FLAC__bool
  87109. * \c false if entry name is illegal, else \c true.
  87110. */
  87111. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87112. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87113. * comment specification.
  87114. *
  87115. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87116. * 'value' must be legal according to
  87117. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87118. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87119. *
  87120. * \param entry An entry to be checked.
  87121. * \param length The length of \a entry in bytes.
  87122. * \assert
  87123. * \code value != NULL \endcode
  87124. * \retval FLAC__bool
  87125. * \c false if entry name is illegal, else \c true.
  87126. */
  87127. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87128. /** Check a seek table to see if it conforms to the FLAC specification.
  87129. * See the format specification for limits on the contents of the
  87130. * seek table.
  87131. *
  87132. * \param seek_table A pointer to a seek table to be checked.
  87133. * \assert
  87134. * \code seek_table != NULL \endcode
  87135. * \retval FLAC__bool
  87136. * \c false if seek table is illegal, else \c true.
  87137. */
  87138. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87139. /** Sort a seek table's seek points according to the format specification.
  87140. * This includes a "unique-ification" step to remove duplicates, i.e.
  87141. * seek points with identical \a sample_number values. Duplicate seek
  87142. * points are converted into placeholder points and sorted to the end of
  87143. * the table.
  87144. *
  87145. * \param seek_table A pointer to a seek table to be sorted.
  87146. * \assert
  87147. * \code seek_table != NULL \endcode
  87148. * \retval unsigned
  87149. * The number of duplicate seek points converted into placeholders.
  87150. */
  87151. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87152. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87153. * See the format specification for limits on the contents of the
  87154. * cue sheet.
  87155. *
  87156. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87157. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87158. * stringent requirements for a CD-DA (audio) disc.
  87159. * \param violation Address of a pointer to a string. If there is a
  87160. * violation, a pointer to a string explanation of the
  87161. * violation will be returned here. \a violation may be
  87162. * \c NULL if you don't need the returned string. Do not
  87163. * free the returned string; it will always point to static
  87164. * data.
  87165. * \assert
  87166. * \code cue_sheet != NULL \endcode
  87167. * \retval FLAC__bool
  87168. * \c false if cue sheet is illegal, else \c true.
  87169. */
  87170. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87171. /** Check picture data to see if it conforms to the FLAC specification.
  87172. * See the format specification for limits on the contents of the
  87173. * PICTURE block.
  87174. *
  87175. * \param picture A pointer to existing picture data to be checked.
  87176. * \param violation Address of a pointer to a string. If there is a
  87177. * violation, a pointer to a string explanation of the
  87178. * violation will be returned here. \a violation may be
  87179. * \c NULL if you don't need the returned string. Do not
  87180. * free the returned string; it will always point to static
  87181. * data.
  87182. * \assert
  87183. * \code picture != NULL \endcode
  87184. * \retval FLAC__bool
  87185. * \c false if picture data is illegal, else \c true.
  87186. */
  87187. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87188. /* \} */
  87189. #ifdef __cplusplus
  87190. }
  87191. #endif
  87192. #endif
  87193. /*** End of inlined file: format.h ***/
  87194. /*** Start of inlined file: metadata.h ***/
  87195. #ifndef FLAC__METADATA_H
  87196. #define FLAC__METADATA_H
  87197. #include <sys/types.h> /* for off_t */
  87198. /* --------------------------------------------------------------------
  87199. (For an example of how all these routines are used, see the source
  87200. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87201. metaflac in src/metaflac/)
  87202. ------------------------------------------------------------------*/
  87203. /** \file include/FLAC/metadata.h
  87204. *
  87205. * \brief
  87206. * This module provides functions for creating and manipulating FLAC
  87207. * metadata blocks in memory, and three progressively more powerful
  87208. * interfaces for traversing and editing metadata in FLAC files.
  87209. *
  87210. * See the detailed documentation for each interface in the
  87211. * \link flac_metadata metadata \endlink module.
  87212. */
  87213. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87214. * \ingroup flac
  87215. *
  87216. * \brief
  87217. * This module provides functions for creating and manipulating FLAC
  87218. * metadata blocks in memory, and three progressively more powerful
  87219. * interfaces for traversing and editing metadata in native FLAC files.
  87220. * Note that currently only the Chain interface (level 2) supports Ogg
  87221. * FLAC files, and it is read-only i.e. no writing back changed
  87222. * metadata to file.
  87223. *
  87224. * There are three metadata interfaces of increasing complexity:
  87225. *
  87226. * Level 0:
  87227. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87228. * PICTURE blocks.
  87229. *
  87230. * Level 1:
  87231. * Read-write access to all metadata blocks. This level is write-
  87232. * efficient in most cases (more on this below), and uses less memory
  87233. * than level 2.
  87234. *
  87235. * Level 2:
  87236. * Read-write access to all metadata blocks. This level is write-
  87237. * efficient in all cases, but uses more memory since all metadata for
  87238. * the whole file is read into memory and manipulated before writing
  87239. * out again.
  87240. *
  87241. * What do we mean by efficient? Since FLAC metadata appears at the
  87242. * beginning of the file, when writing metadata back to a FLAC file
  87243. * it is possible to grow or shrink the metadata such that the entire
  87244. * file must be rewritten. However, if the size remains the same during
  87245. * changes or PADDING blocks are utilized, only the metadata needs to be
  87246. * overwritten, which is much faster.
  87247. *
  87248. * Efficient means the whole file is rewritten at most one time, and only
  87249. * when necessary. Level 1 is not efficient only in the case that you
  87250. * cause more than one metadata block to grow or shrink beyond what can
  87251. * be accomodated by padding. In this case you should probably use level
  87252. * 2, which allows you to edit all the metadata for a file in memory and
  87253. * write it out all at once.
  87254. *
  87255. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87256. * front of the file.
  87257. *
  87258. * All levels access files via their filenames. In addition, level 2
  87259. * has additional alternative read and write functions that take an I/O
  87260. * handle and callbacks, for situations where access by filename is not
  87261. * possible.
  87262. *
  87263. * In addition to the three interfaces, this module defines functions for
  87264. * creating and manipulating various metadata objects in memory. As we see
  87265. * from the Format module, FLAC metadata blocks in memory are very primitive
  87266. * structures for storing information in an efficient way. Reading
  87267. * information from the structures is easy but creating or modifying them
  87268. * directly is more complex. The metadata object routines here facilitate
  87269. * this by taking care of the consistency and memory management drudgery.
  87270. *
  87271. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87272. * metadata however, you will not probably not need these.
  87273. *
  87274. * From a dependency standpoint, none of the encoders or decoders require
  87275. * the metadata module. This is so that embedded users can strip out the
  87276. * metadata module from libFLAC to reduce the size and complexity.
  87277. */
  87278. #ifdef __cplusplus
  87279. extern "C" {
  87280. #endif
  87281. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87282. * \ingroup flac_metadata
  87283. *
  87284. * \brief
  87285. * The level 0 interface consists of individual routines to read the
  87286. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87287. * only a filename.
  87288. *
  87289. * They try to skip any ID3v2 tag at the head of the file.
  87290. *
  87291. * \{
  87292. */
  87293. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87294. * will try to skip any ID3v2 tag at the head of the file.
  87295. *
  87296. * \param filename The path to the FLAC file to read.
  87297. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87298. * FLAC__StreamMetadata is a simple structure with no
  87299. * memory allocation involved, you pass the address of
  87300. * an existing structure. It need not be initialized.
  87301. * \assert
  87302. * \code filename != NULL \endcode
  87303. * \code streaminfo != NULL \endcode
  87304. * \retval FLAC__bool
  87305. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87306. * \c false if there was a memory allocation error, a file decoder error,
  87307. * or the file contained no STREAMINFO block. (A memory allocation error
  87308. * is possible because this function must set up a file decoder.)
  87309. */
  87310. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87311. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87312. * function will try to skip any ID3v2 tag at the head of the file.
  87313. *
  87314. * \param filename The path to the FLAC file to read.
  87315. * \param tags The address where the returned pointer will be
  87316. * stored. The \a tags object must be deleted by
  87317. * the caller using FLAC__metadata_object_delete().
  87318. * \assert
  87319. * \code filename != NULL \endcode
  87320. * \code tags != NULL \endcode
  87321. * \retval FLAC__bool
  87322. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87323. * and \a *tags will be set to the address of the metadata structure.
  87324. * Returns \c false if there was a memory allocation error, a file
  87325. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87326. * \a *tags will be set to \c NULL.
  87327. */
  87328. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87329. /** Read the CUESHEET metadata block of the given FLAC file. This
  87330. * function will try to skip any ID3v2 tag at the head of the file.
  87331. *
  87332. * \param filename The path to the FLAC file to read.
  87333. * \param cuesheet The address where the returned pointer will be
  87334. * stored. The \a cuesheet object must be deleted by
  87335. * the caller using FLAC__metadata_object_delete().
  87336. * \assert
  87337. * \code filename != NULL \endcode
  87338. * \code cuesheet != NULL \endcode
  87339. * \retval FLAC__bool
  87340. * \c true if a valid CUESHEET block was read from \a filename,
  87341. * and \a *cuesheet will be set to the address of the metadata
  87342. * structure. Returns \c false if there was a memory allocation
  87343. * error, a file decoder error, or the file contained no CUESHEET
  87344. * block, and \a *cuesheet will be set to \c NULL.
  87345. */
  87346. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87347. /** Read a PICTURE metadata block of the given FLAC file. This
  87348. * function will try to skip any ID3v2 tag at the head of the file.
  87349. * Since there can be more than one PICTURE block in a file, this
  87350. * function takes a number of parameters that act as constraints to
  87351. * the search. The PICTURE block with the largest area matching all
  87352. * the constraints will be returned, or \a *picture will be set to
  87353. * \c NULL if there was no such block.
  87354. *
  87355. * \param filename The path to the FLAC file to read.
  87356. * \param picture The address where the returned pointer will be
  87357. * stored. The \a picture object must be deleted by
  87358. * the caller using FLAC__metadata_object_delete().
  87359. * \param type The desired picture type. Use \c -1 to mean
  87360. * "any type".
  87361. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87362. * string will be matched exactly. Use \c NULL to
  87363. * mean "any MIME type".
  87364. * \param description The desired description. The string will be
  87365. * matched exactly. Use \c NULL to mean "any
  87366. * description".
  87367. * \param max_width The maximum width in pixels desired. Use
  87368. * \c (unsigned)(-1) to mean "any width".
  87369. * \param max_height The maximum height in pixels desired. Use
  87370. * \c (unsigned)(-1) to mean "any height".
  87371. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87372. * Use \c (unsigned)(-1) to mean "any depth".
  87373. * \param max_colors The maximum number of colors desired. Use
  87374. * \c (unsigned)(-1) to mean "any number of colors".
  87375. * \assert
  87376. * \code filename != NULL \endcode
  87377. * \code picture != NULL \endcode
  87378. * \retval FLAC__bool
  87379. * \c true if a valid PICTURE block was read from \a filename,
  87380. * and \a *picture will be set to the address of the metadata
  87381. * structure. Returns \c false if there was a memory allocation
  87382. * error, a file decoder error, or the file contained no PICTURE
  87383. * block, and \a *picture will be set to \c NULL.
  87384. */
  87385. 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);
  87386. /* \} */
  87387. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87388. * \ingroup flac_metadata
  87389. *
  87390. * \brief
  87391. * The level 1 interface provides read-write access to FLAC file metadata and
  87392. * operates directly on the FLAC file.
  87393. *
  87394. * The general usage of this interface is:
  87395. *
  87396. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87397. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87398. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87399. * see if the file is writable, or only read access is allowed.
  87400. * - Use FLAC__metadata_simple_iterator_next() and
  87401. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87402. * This is does not read the actual blocks themselves.
  87403. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87404. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87405. * forward from the front of the file.
  87406. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87407. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87408. * the current iterator position. The returned object is yours to modify
  87409. * and free.
  87410. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87411. * back. You must have write permission to the original file. Make sure to
  87412. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87413. * below.
  87414. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87415. * Use the object creation functions from
  87416. * \link flac_metadata_object here \endlink to generate new objects.
  87417. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87418. * currently referred to by the iterator, or replace it with padding.
  87419. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87420. * finished.
  87421. *
  87422. * \note
  87423. * The FLAC file remains open the whole time between
  87424. * FLAC__metadata_simple_iterator_init() and
  87425. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87426. * the file during this time.
  87427. *
  87428. * \note
  87429. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87430. * FLAC__StreamMetadata objects. These are managed automatically.
  87431. *
  87432. * \note
  87433. * If any of the modification functions
  87434. * (FLAC__metadata_simple_iterator_set_block(),
  87435. * FLAC__metadata_simple_iterator_delete_block(),
  87436. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87437. * you should delete the iterator as it may no longer be valid.
  87438. *
  87439. * \{
  87440. */
  87441. struct FLAC__Metadata_SimpleIterator;
  87442. /** The opaque structure definition for the level 1 iterator type.
  87443. * See the
  87444. * \link flac_metadata_level1 metadata level 1 module \endlink
  87445. * for a detailed description.
  87446. */
  87447. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87448. /** Status type for FLAC__Metadata_SimpleIterator.
  87449. *
  87450. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87451. */
  87452. typedef enum {
  87453. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87454. /**< The iterator is in the normal OK state */
  87455. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87456. /**< The data passed into a function violated the function's usage criteria */
  87457. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87458. /**< The iterator could not open the target file */
  87459. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87460. /**< The iterator could not find the FLAC signature at the start of the file */
  87461. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87462. /**< The iterator tried to write to a file that was not writable */
  87463. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87464. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87465. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87466. /**< The iterator encountered an error while reading the FLAC file */
  87467. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87468. /**< The iterator encountered an error while seeking in the FLAC file */
  87469. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87470. /**< The iterator encountered an error while writing the FLAC file */
  87471. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87472. /**< The iterator encountered an error renaming the FLAC file */
  87473. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87474. /**< The iterator encountered an error removing the temporary file */
  87475. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87476. /**< Memory allocation failed */
  87477. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87478. /**< The caller violated an assertion or an unexpected error occurred */
  87479. } FLAC__Metadata_SimpleIteratorStatus;
  87480. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87481. *
  87482. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87483. * will give the string equivalent. The contents should not be modified.
  87484. */
  87485. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87486. /** Create a new iterator instance.
  87487. *
  87488. * \retval FLAC__Metadata_SimpleIterator*
  87489. * \c NULL if there was an error allocating memory, else the new instance.
  87490. */
  87491. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87492. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87493. *
  87494. * \param iterator A pointer to an existing iterator.
  87495. * \assert
  87496. * \code iterator != NULL \endcode
  87497. */
  87498. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87499. /** Get the current status of the iterator. Call this after a function
  87500. * returns \c false to get the reason for the error. Also resets the status
  87501. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87502. *
  87503. * \param iterator A pointer to an existing iterator.
  87504. * \assert
  87505. * \code iterator != NULL \endcode
  87506. * \retval FLAC__Metadata_SimpleIteratorStatus
  87507. * The current status of the iterator.
  87508. */
  87509. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87510. /** Initialize the iterator to point to the first metadata block in the
  87511. * given FLAC file.
  87512. *
  87513. * \param iterator A pointer to an existing iterator.
  87514. * \param filename The path to the FLAC file.
  87515. * \param read_only If \c true, the FLAC file will be opened
  87516. * in read-only mode; if \c false, the FLAC
  87517. * file will be opened for edit even if no
  87518. * edits are performed.
  87519. * \param preserve_file_stats If \c true, the owner and modification
  87520. * time will be preserved even if the FLAC
  87521. * file is written to.
  87522. * \assert
  87523. * \code iterator != NULL \endcode
  87524. * \code filename != NULL \endcode
  87525. * \retval FLAC__bool
  87526. * \c false if a memory allocation error occurs, the file can't be
  87527. * opened, or another error occurs, else \c true.
  87528. */
  87529. 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);
  87530. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87531. * FLAC__metadata_simple_iterator_set_block() and
  87532. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87533. *
  87534. * \param iterator A pointer to an existing iterator.
  87535. * \assert
  87536. * \code iterator != NULL \endcode
  87537. * \retval FLAC__bool
  87538. * See above.
  87539. */
  87540. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87541. /** Moves the iterator forward one metadata block, returning \c false if
  87542. * already at the end.
  87543. *
  87544. * \param iterator A pointer to an existing initialized iterator.
  87545. * \assert
  87546. * \code iterator != NULL \endcode
  87547. * \a iterator has been successfully initialized with
  87548. * FLAC__metadata_simple_iterator_init()
  87549. * \retval FLAC__bool
  87550. * \c false if already at the last metadata block of the chain, else
  87551. * \c true.
  87552. */
  87553. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87554. /** Moves the iterator backward one metadata block, returning \c false if
  87555. * already at the beginning.
  87556. *
  87557. * \param iterator A pointer to an existing initialized iterator.
  87558. * \assert
  87559. * \code iterator != NULL \endcode
  87560. * \a iterator has been successfully initialized with
  87561. * FLAC__metadata_simple_iterator_init()
  87562. * \retval FLAC__bool
  87563. * \c false if already at the first metadata block of the chain, else
  87564. * \c true.
  87565. */
  87566. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87567. /** Returns a flag telling if the current metadata block is the last.
  87568. *
  87569. * \param iterator A pointer to an existing initialized iterator.
  87570. * \assert
  87571. * \code iterator != NULL \endcode
  87572. * \a iterator has been successfully initialized with
  87573. * FLAC__metadata_simple_iterator_init()
  87574. * \retval FLAC__bool
  87575. * \c true if the current metadata block is the last in the file,
  87576. * else \c false.
  87577. */
  87578. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87579. /** Get the offset of the metadata block at the current position. This
  87580. * avoids reading the actual block data which can save time for large
  87581. * blocks.
  87582. *
  87583. * \param iterator A pointer to an existing initialized iterator.
  87584. * \assert
  87585. * \code iterator != NULL \endcode
  87586. * \a iterator has been successfully initialized with
  87587. * FLAC__metadata_simple_iterator_init()
  87588. * \retval off_t
  87589. * The offset of the metadata block at the current iterator position.
  87590. * This is the byte offset relative to the beginning of the file of
  87591. * the current metadata block's header.
  87592. */
  87593. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87594. /** Get the type of the metadata block at the current position. This
  87595. * avoids reading the actual block data which can save time for large
  87596. * blocks.
  87597. *
  87598. * \param iterator A pointer to an existing initialized iterator.
  87599. * \assert
  87600. * \code iterator != NULL \endcode
  87601. * \a iterator has been successfully initialized with
  87602. * FLAC__metadata_simple_iterator_init()
  87603. * \retval FLAC__MetadataType
  87604. * The type of the metadata block at the current iterator position.
  87605. */
  87606. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87607. /** Get the length of the metadata block at the current position. This
  87608. * avoids reading the actual block data which can save time for large
  87609. * blocks.
  87610. *
  87611. * \param iterator A pointer to an existing initialized iterator.
  87612. * \assert
  87613. * \code iterator != NULL \endcode
  87614. * \a iterator has been successfully initialized with
  87615. * FLAC__metadata_simple_iterator_init()
  87616. * \retval unsigned
  87617. * The length of the metadata block at the current iterator position.
  87618. * The is same length as that in the
  87619. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87620. * i.e. the length of the metadata body that follows the header.
  87621. */
  87622. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87623. /** Get the application ID of the \c APPLICATION block at the current
  87624. * position. This avoids reading the actual block data which can save
  87625. * time for large blocks.
  87626. *
  87627. * \param iterator A pointer to an existing initialized iterator.
  87628. * \param id A pointer to a buffer of at least \c 4 bytes where
  87629. * the ID will be stored.
  87630. * \assert
  87631. * \code iterator != NULL \endcode
  87632. * \code id != NULL \endcode
  87633. * \a iterator has been successfully initialized with
  87634. * FLAC__metadata_simple_iterator_init()
  87635. * \retval FLAC__bool
  87636. * \c true if the ID was successfully read, else \c false, in which
  87637. * case you should check FLAC__metadata_simple_iterator_status() to
  87638. * find out why. If the status is
  87639. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87640. * current metadata block is not an \c APPLICATION block. Otherwise
  87641. * if the status is
  87642. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87643. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87644. * occurred and the iterator can no longer be used.
  87645. */
  87646. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87647. /** Get the metadata block at the current position. You can modify the
  87648. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87649. * write it back to the FLAC file.
  87650. *
  87651. * You must call FLAC__metadata_object_delete() on the returned object
  87652. * when you are finished with it.
  87653. *
  87654. * \param iterator A pointer to an existing initialized iterator.
  87655. * \assert
  87656. * \code iterator != NULL \endcode
  87657. * \a iterator has been successfully initialized with
  87658. * FLAC__metadata_simple_iterator_init()
  87659. * \retval FLAC__StreamMetadata*
  87660. * The current metadata block, or \c NULL if there was a memory
  87661. * allocation error.
  87662. */
  87663. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87664. /** Write a block back to the FLAC file. This function tries to be
  87665. * as efficient as possible; how the block is actually written is
  87666. * shown by the following:
  87667. *
  87668. * Existing block is a STREAMINFO block and the new block is a
  87669. * STREAMINFO block: the new block is written in place. Make sure
  87670. * you know what you're doing when changing the values of a
  87671. * STREAMINFO block.
  87672. *
  87673. * Existing block is a STREAMINFO block and the new block is a
  87674. * not a STREAMINFO block: this is an error since the first block
  87675. * must be a STREAMINFO block. Returns \c false without altering the
  87676. * file.
  87677. *
  87678. * Existing block is not a STREAMINFO block and the new block is a
  87679. * STREAMINFO block: this is an error since there may be only one
  87680. * STREAMINFO block. Returns \c false without altering the file.
  87681. *
  87682. * Existing block and new block are the same length: the existing
  87683. * block will be replaced by the new block, written in place.
  87684. *
  87685. * Existing block is longer than new block: if use_padding is \c true,
  87686. * the existing block will be overwritten in place with the new
  87687. * block followed by a PADDING block, if possible, to make the total
  87688. * size the same as the existing block. Remember that a padding
  87689. * block requires at least four bytes so if the difference in size
  87690. * between the new block and existing block is less than that, the
  87691. * entire file will have to be rewritten, using the new block's
  87692. * exact size. If use_padding is \c false, the entire file will be
  87693. * rewritten, replacing the existing block by the new block.
  87694. *
  87695. * Existing block is shorter than new block: if use_padding is \c true,
  87696. * the function will try and expand the new block into the following
  87697. * PADDING block, if it exists and doing so won't shrink the PADDING
  87698. * block to less than 4 bytes. If there is no following PADDING
  87699. * block, or it will shrink to less than 4 bytes, or use_padding is
  87700. * \c false, the entire file is rewritten, replacing the existing block
  87701. * with the new block. Note that in this case any following PADDING
  87702. * block is preserved as is.
  87703. *
  87704. * After writing the block, the iterator will remain in the same
  87705. * place, i.e. pointing to the new block.
  87706. *
  87707. * \param iterator A pointer to an existing initialized iterator.
  87708. * \param block The block to set.
  87709. * \param use_padding See above.
  87710. * \assert
  87711. * \code iterator != NULL \endcode
  87712. * \a iterator has been successfully initialized with
  87713. * FLAC__metadata_simple_iterator_init()
  87714. * \code block != NULL \endcode
  87715. * \retval FLAC__bool
  87716. * \c true if successful, else \c false.
  87717. */
  87718. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87719. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87720. * except that instead of writing over an existing block, it appends
  87721. * a block after the existing block. \a use_padding is again used to
  87722. * tell the function to try an expand into following padding in an
  87723. * attempt to avoid rewriting the entire file.
  87724. *
  87725. * This function will fail and return \c false if given a STREAMINFO
  87726. * block.
  87727. *
  87728. * After writing the block, the iterator will be pointing to the
  87729. * new block.
  87730. *
  87731. * \param iterator A pointer to an existing initialized iterator.
  87732. * \param block The block to set.
  87733. * \param use_padding See above.
  87734. * \assert
  87735. * \code iterator != NULL \endcode
  87736. * \a iterator has been successfully initialized with
  87737. * FLAC__metadata_simple_iterator_init()
  87738. * \code block != NULL \endcode
  87739. * \retval FLAC__bool
  87740. * \c true if successful, else \c false.
  87741. */
  87742. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87743. /** Deletes the block at the current position. This will cause the
  87744. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87745. * in which case the block will be replaced by an equal-sized PADDING
  87746. * block. The iterator will be left pointing to the block before the
  87747. * one just deleted.
  87748. *
  87749. * You may not delete the STREAMINFO block.
  87750. *
  87751. * \param iterator A pointer to an existing initialized iterator.
  87752. * \param use_padding See above.
  87753. * \assert
  87754. * \code iterator != NULL \endcode
  87755. * \a iterator has been successfully initialized with
  87756. * FLAC__metadata_simple_iterator_init()
  87757. * \retval FLAC__bool
  87758. * \c true if successful, else \c false.
  87759. */
  87760. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87761. /* \} */
  87762. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87763. * \ingroup flac_metadata
  87764. *
  87765. * \brief
  87766. * The level 2 interface provides read-write access to FLAC file metadata;
  87767. * all metadata is read into memory, operated on in memory, and then written
  87768. * to file, which is more efficient than level 1 when editing multiple blocks.
  87769. *
  87770. * Currently Ogg FLAC is supported for read only, via
  87771. * FLAC__metadata_chain_read_ogg() but a subsequent
  87772. * FLAC__metadata_chain_write() will fail.
  87773. *
  87774. * The general usage of this interface is:
  87775. *
  87776. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87777. * linked list of FLAC metadata blocks.
  87778. * - Read all metadata into the the chain from a FLAC file using
  87779. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87780. * check the status.
  87781. * - Optionally, consolidate the padding using
  87782. * FLAC__metadata_chain_merge_padding() or
  87783. * FLAC__metadata_chain_sort_padding().
  87784. * - Create a new iterator using FLAC__metadata_iterator_new()
  87785. * - Initialize the iterator to point to the first element in the chain
  87786. * using FLAC__metadata_iterator_init()
  87787. * - Traverse the chain using FLAC__metadata_iterator_next and
  87788. * FLAC__metadata_iterator_prev().
  87789. * - Get a block for reading or modification using
  87790. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87791. * inside the chain is returned, so the block is yours to modify.
  87792. * Changes will be reflected in the FLAC file when you write the
  87793. * chain. You can also add and delete blocks (see functions below).
  87794. * - When done, write out the chain using FLAC__metadata_chain_write().
  87795. * Make sure to read the whole comment to the function below.
  87796. * - Delete the chain using FLAC__metadata_chain_delete().
  87797. *
  87798. * \note
  87799. * Even though the FLAC file is not open while the chain is being
  87800. * manipulated, you must not alter the file externally during
  87801. * this time. The chain assumes the FLAC file will not change
  87802. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87803. * and FLAC__metadata_chain_write().
  87804. *
  87805. * \note
  87806. * Do not modify the is_last, length, or type fields of returned
  87807. * FLAC__StreamMetadata objects. These are managed automatically.
  87808. *
  87809. * \note
  87810. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87811. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87812. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87813. * become owned by the chain and they will be deleted when the chain is
  87814. * deleted.
  87815. *
  87816. * \{
  87817. */
  87818. struct FLAC__Metadata_Chain;
  87819. /** The opaque structure definition for the level 2 chain type.
  87820. */
  87821. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87822. struct FLAC__Metadata_Iterator;
  87823. /** The opaque structure definition for the level 2 iterator type.
  87824. */
  87825. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87826. typedef enum {
  87827. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87828. /**< The chain is in the normal OK state */
  87829. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87830. /**< The data passed into a function violated the function's usage criteria */
  87831. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87832. /**< The chain could not open the target file */
  87833. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87834. /**< The chain could not find the FLAC signature at the start of the file */
  87835. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87836. /**< The chain tried to write to a file that was not writable */
  87837. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87838. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87839. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87840. /**< The chain encountered an error while reading the FLAC file */
  87841. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87842. /**< The chain encountered an error while seeking in the FLAC file */
  87843. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87844. /**< The chain encountered an error while writing the FLAC file */
  87845. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87846. /**< The chain encountered an error renaming the FLAC file */
  87847. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87848. /**< The chain encountered an error removing the temporary file */
  87849. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87850. /**< Memory allocation failed */
  87851. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87852. /**< The caller violated an assertion or an unexpected error occurred */
  87853. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87854. /**< One or more of the required callbacks was NULL */
  87855. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87856. /**< FLAC__metadata_chain_write() was called on a chain read by
  87857. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87858. * or
  87859. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87860. * was called on a chain read by
  87861. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87862. * Matching read/write methods must always be used. */
  87863. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87864. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87865. * chain write requires a tempfile; use
  87866. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87867. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87868. * called when the chain write does not require a tempfile; use
  87869. * FLAC__metadata_chain_write_with_callbacks() instead.
  87870. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87871. * before writing via callbacks. */
  87872. } FLAC__Metadata_ChainStatus;
  87873. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87874. *
  87875. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87876. * will give the string equivalent. The contents should not be modified.
  87877. */
  87878. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87879. /*********** FLAC__Metadata_Chain ***********/
  87880. /** Create a new chain instance.
  87881. *
  87882. * \retval FLAC__Metadata_Chain*
  87883. * \c NULL if there was an error allocating memory, else the new instance.
  87884. */
  87885. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87886. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87887. *
  87888. * \param chain A pointer to an existing chain.
  87889. * \assert
  87890. * \code chain != NULL \endcode
  87891. */
  87892. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87893. /** Get the current status of the chain. Call this after a function
  87894. * returns \c false to get the reason for the error. Also resets the
  87895. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87896. *
  87897. * \param chain A pointer to an existing chain.
  87898. * \assert
  87899. * \code chain != NULL \endcode
  87900. * \retval FLAC__Metadata_ChainStatus
  87901. * The current status of the chain.
  87902. */
  87903. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87904. /** Read all metadata from a FLAC file into the chain.
  87905. *
  87906. * \param chain A pointer to an existing chain.
  87907. * \param filename The path to the FLAC file to read.
  87908. * \assert
  87909. * \code chain != NULL \endcode
  87910. * \code filename != NULL \endcode
  87911. * \retval FLAC__bool
  87912. * \c true if a valid list of metadata blocks was read from
  87913. * \a filename, else \c false. On failure, check the status with
  87914. * FLAC__metadata_chain_status().
  87915. */
  87916. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87917. /** Read all metadata from an Ogg FLAC file into the chain.
  87918. *
  87919. * \note Ogg FLAC metadata data writing is not supported yet and
  87920. * FLAC__metadata_chain_write() will fail.
  87921. *
  87922. * \param chain A pointer to an existing chain.
  87923. * \param filename The path to the Ogg FLAC file to read.
  87924. * \assert
  87925. * \code chain != NULL \endcode
  87926. * \code filename != NULL \endcode
  87927. * \retval FLAC__bool
  87928. * \c true if a valid list of metadata blocks was read from
  87929. * \a filename, else \c false. On failure, check the status with
  87930. * FLAC__metadata_chain_status().
  87931. */
  87932. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87933. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87934. *
  87935. * The \a handle need only be open for reading, but must be seekable.
  87936. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87937. * for Windows).
  87938. *
  87939. * \param chain A pointer to an existing chain.
  87940. * \param handle The I/O handle of the FLAC stream to read. The
  87941. * handle will NOT be closed after the metadata is read;
  87942. * that is the duty of the caller.
  87943. * \param callbacks
  87944. * A set of callbacks to use for I/O. The mandatory
  87945. * callbacks are \a read, \a seek, and \a tell.
  87946. * \assert
  87947. * \code chain != NULL \endcode
  87948. * \retval FLAC__bool
  87949. * \c true if a valid list of metadata blocks was read from
  87950. * \a handle, else \c false. On failure, check the status with
  87951. * FLAC__metadata_chain_status().
  87952. */
  87953. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87954. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87955. *
  87956. * The \a handle need only be open for reading, but must be seekable.
  87957. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87958. * for Windows).
  87959. *
  87960. * \note Ogg FLAC metadata data writing is not supported yet and
  87961. * FLAC__metadata_chain_write() will fail.
  87962. *
  87963. * \param chain A pointer to an existing chain.
  87964. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87965. * handle will NOT be closed after the metadata is read;
  87966. * that is the duty of the caller.
  87967. * \param callbacks
  87968. * A set of callbacks to use for I/O. The mandatory
  87969. * callbacks are \a read, \a seek, and \a tell.
  87970. * \assert
  87971. * \code chain != NULL \endcode
  87972. * \retval FLAC__bool
  87973. * \c true if a valid list of metadata blocks was read from
  87974. * \a handle, else \c false. On failure, check the status with
  87975. * FLAC__metadata_chain_status().
  87976. */
  87977. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87978. /** Checks if writing the given chain would require the use of a
  87979. * temporary file, or if it could be written in place.
  87980. *
  87981. * Under certain conditions, padding can be utilized so that writing
  87982. * edited metadata back to the FLAC file does not require rewriting the
  87983. * entire file. If rewriting is required, then a temporary workfile is
  87984. * required. When writing metadata using callbacks, you must check
  87985. * this function to know whether to call
  87986. * FLAC__metadata_chain_write_with_callbacks() or
  87987. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87988. * writing with FLAC__metadata_chain_write(), the temporary file is
  87989. * handled internally.
  87990. *
  87991. * \param chain A pointer to an existing chain.
  87992. * \param use_padding
  87993. * Whether or not padding will be allowed to be used
  87994. * during the write. The value of \a use_padding given
  87995. * here must match the value later passed to
  87996. * FLAC__metadata_chain_write_with_callbacks() or
  87997. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87998. * \assert
  87999. * \code chain != NULL \endcode
  88000. * \retval FLAC__bool
  88001. * \c true if writing the current chain would require a tempfile, or
  88002. * \c false if metadata can be written in place.
  88003. */
  88004. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88005. /** Write all metadata out to the FLAC file. This function tries to be as
  88006. * efficient as possible; how the metadata is actually written is shown by
  88007. * the following:
  88008. *
  88009. * If the current chain is the same size as the existing metadata, the new
  88010. * data is written in place.
  88011. *
  88012. * If the current chain is longer than the existing metadata, and
  88013. * \a use_padding is \c true, and the last block is a PADDING block of
  88014. * sufficient length, the function will truncate the final padding block
  88015. * so that the overall size of the metadata is the same as the existing
  88016. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88017. * the above conditions are met, the entire FLAC file must be rewritten.
  88018. * If you want to use padding this way it is a good idea to call
  88019. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88020. * amount of padding to work with, unless you need to preserve ordering
  88021. * of the PADDING blocks for some reason.
  88022. *
  88023. * If the current chain is shorter than the existing metadata, and
  88024. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88025. * is extended to make the overall size the same as the existing data. If
  88026. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88027. * PADDING block is added to the end of the new data to make it the same
  88028. * size as the existing data (if possible, see the note to
  88029. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88030. * and the new data is written in place. If none of the above apply or
  88031. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88032. *
  88033. * If \a preserve_file_stats is \c true, the owner and modification time will
  88034. * be preserved even if the FLAC file is written.
  88035. *
  88036. * For this write function to be used, the chain must have been read with
  88037. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88038. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88039. *
  88040. * \param chain A pointer to an existing chain.
  88041. * \param use_padding See above.
  88042. * \param preserve_file_stats See above.
  88043. * \assert
  88044. * \code chain != NULL \endcode
  88045. * \retval FLAC__bool
  88046. * \c true if the write succeeded, else \c false. On failure,
  88047. * check the status with FLAC__metadata_chain_status().
  88048. */
  88049. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88050. /** Write all metadata out to a FLAC stream via callbacks.
  88051. *
  88052. * (See FLAC__metadata_chain_write() for the details on how padding is
  88053. * used to write metadata in place if possible.)
  88054. *
  88055. * The \a handle must be open for updating and be seekable. The
  88056. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88057. * for Windows).
  88058. *
  88059. * For this write function to be used, the chain must have been read with
  88060. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88061. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88062. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88063. * \c false.
  88064. *
  88065. * \param chain A pointer to an existing chain.
  88066. * \param use_padding See FLAC__metadata_chain_write()
  88067. * \param handle The I/O handle of the FLAC stream to write. The
  88068. * handle will NOT be closed after the metadata is
  88069. * written; that is the duty of the caller.
  88070. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88071. * callbacks are \a write and \a seek.
  88072. * \assert
  88073. * \code chain != NULL \endcode
  88074. * \retval FLAC__bool
  88075. * \c true if the write succeeded, else \c false. On failure,
  88076. * check the status with FLAC__metadata_chain_status().
  88077. */
  88078. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88079. /** Write all metadata out to a FLAC stream via callbacks.
  88080. *
  88081. * (See FLAC__metadata_chain_write() for the details on how padding is
  88082. * used to write metadata in place if possible.)
  88083. *
  88084. * This version of the write-with-callbacks function must be used when
  88085. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88086. * this function, you must supply an I/O handle corresponding to the
  88087. * FLAC file to edit, and a temporary handle to which the new FLAC
  88088. * file will be written. It is the caller's job to move this temporary
  88089. * FLAC file on top of the original FLAC file to complete the metadata
  88090. * edit.
  88091. *
  88092. * The \a handle must be open for reading and be seekable. The
  88093. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88094. * for Windows).
  88095. *
  88096. * The \a temp_handle must be open for writing. The
  88097. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88098. * for Windows). It should be an empty stream, or at least positioned
  88099. * at the start-of-file (in which case it is the caller's duty to
  88100. * truncate it on return).
  88101. *
  88102. * For this write function to be used, the chain must have been read with
  88103. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88104. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88105. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88106. * \c true.
  88107. *
  88108. * \param chain A pointer to an existing chain.
  88109. * \param use_padding See FLAC__metadata_chain_write()
  88110. * \param handle The I/O handle of the original FLAC stream to read.
  88111. * The handle will NOT be closed after the metadata is
  88112. * written; that is the duty of the caller.
  88113. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88114. * The mandatory callbacks are \a read, \a seek, and
  88115. * \a eof.
  88116. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88117. * handle will NOT be closed after the metadata is
  88118. * written; that is the duty of the caller.
  88119. * \param temp_callbacks
  88120. * A set of callbacks to use for I/O on temp_handle.
  88121. * The only mandatory callback is \a write.
  88122. * \assert
  88123. * \code chain != NULL \endcode
  88124. * \retval FLAC__bool
  88125. * \c true if the write succeeded, else \c false. On failure,
  88126. * check the status with FLAC__metadata_chain_status().
  88127. */
  88128. 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);
  88129. /** Merge adjacent PADDING blocks into a single block.
  88130. *
  88131. * \note This function does not write to the FLAC file, it only
  88132. * modifies the chain.
  88133. *
  88134. * \warning Any iterator on the current chain will become invalid after this
  88135. * call. You should delete the iterator and get a new one.
  88136. *
  88137. * \param chain A pointer to an existing chain.
  88138. * \assert
  88139. * \code chain != NULL \endcode
  88140. */
  88141. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88142. /** This function will move all PADDING blocks to the end on the metadata,
  88143. * then merge them into a single block.
  88144. *
  88145. * \note This function does not write to the FLAC file, it only
  88146. * modifies the chain.
  88147. *
  88148. * \warning Any iterator on the current chain will become invalid after this
  88149. * call. You should delete the iterator and get a new one.
  88150. *
  88151. * \param chain A pointer to an existing chain.
  88152. * \assert
  88153. * \code chain != NULL \endcode
  88154. */
  88155. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88156. /*********** FLAC__Metadata_Iterator ***********/
  88157. /** Create a new iterator instance.
  88158. *
  88159. * \retval FLAC__Metadata_Iterator*
  88160. * \c NULL if there was an error allocating memory, else the new instance.
  88161. */
  88162. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88163. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88164. *
  88165. * \param iterator A pointer to an existing iterator.
  88166. * \assert
  88167. * \code iterator != NULL \endcode
  88168. */
  88169. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88170. /** Initialize the iterator to point to the first metadata block in the
  88171. * given chain.
  88172. *
  88173. * \param iterator A pointer to an existing iterator.
  88174. * \param chain A pointer to an existing and initialized (read) chain.
  88175. * \assert
  88176. * \code iterator != NULL \endcode
  88177. * \code chain != NULL \endcode
  88178. */
  88179. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88180. /** Moves the iterator forward one metadata block, returning \c false if
  88181. * already at the end.
  88182. *
  88183. * \param iterator A pointer to an existing initialized iterator.
  88184. * \assert
  88185. * \code iterator != NULL \endcode
  88186. * \a iterator has been successfully initialized with
  88187. * FLAC__metadata_iterator_init()
  88188. * \retval FLAC__bool
  88189. * \c false if already at the last metadata block of the chain, else
  88190. * \c true.
  88191. */
  88192. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88193. /** Moves the iterator backward one metadata block, returning \c false if
  88194. * already at the beginning.
  88195. *
  88196. * \param iterator A pointer to an existing initialized iterator.
  88197. * \assert
  88198. * \code iterator != NULL \endcode
  88199. * \a iterator has been successfully initialized with
  88200. * FLAC__metadata_iterator_init()
  88201. * \retval FLAC__bool
  88202. * \c false if already at the first metadata block of the chain, else
  88203. * \c true.
  88204. */
  88205. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88206. /** Get the type of the metadata block at the current position.
  88207. *
  88208. * \param iterator A pointer to an existing initialized iterator.
  88209. * \assert
  88210. * \code iterator != NULL \endcode
  88211. * \a iterator has been successfully initialized with
  88212. * FLAC__metadata_iterator_init()
  88213. * \retval FLAC__MetadataType
  88214. * The type of the metadata block at the current iterator position.
  88215. */
  88216. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88217. /** Get the metadata block at the current position. You can modify
  88218. * the block in place but must write the chain before the changes
  88219. * are reflected to the FLAC file. You do not need to call
  88220. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88221. * the pointer returned by FLAC__metadata_iterator_get_block()
  88222. * points directly into the chain.
  88223. *
  88224. * \warning
  88225. * Do not call FLAC__metadata_object_delete() on the returned object;
  88226. * to delete a block use FLAC__metadata_iterator_delete_block().
  88227. *
  88228. * \param iterator A pointer to an existing initialized iterator.
  88229. * \assert
  88230. * \code iterator != NULL \endcode
  88231. * \a iterator has been successfully initialized with
  88232. * FLAC__metadata_iterator_init()
  88233. * \retval FLAC__StreamMetadata*
  88234. * The current metadata block.
  88235. */
  88236. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88237. /** Set the metadata block at the current position, replacing the existing
  88238. * block. The new block passed in becomes owned by the chain and it will be
  88239. * deleted when the chain is deleted.
  88240. *
  88241. * \param iterator A pointer to an existing initialized iterator.
  88242. * \param block A pointer to a metadata block.
  88243. * \assert
  88244. * \code iterator != NULL \endcode
  88245. * \a iterator has been successfully initialized with
  88246. * FLAC__metadata_iterator_init()
  88247. * \code block != NULL \endcode
  88248. * \retval FLAC__bool
  88249. * \c false if the conditions in the above description are not met, or
  88250. * a memory allocation error occurs, otherwise \c true.
  88251. */
  88252. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88253. /** Removes the current block from the chain. If \a replace_with_padding is
  88254. * \c true, the block will instead be replaced with a padding block of equal
  88255. * size. You can not delete the STREAMINFO block. The iterator will be
  88256. * left pointing to the block before the one just "deleted", even if
  88257. * \a replace_with_padding is \c true.
  88258. *
  88259. * \param iterator A pointer to an existing initialized iterator.
  88260. * \param replace_with_padding See above.
  88261. * \assert
  88262. * \code iterator != NULL \endcode
  88263. * \a iterator has been successfully initialized with
  88264. * FLAC__metadata_iterator_init()
  88265. * \retval FLAC__bool
  88266. * \c false if the conditions in the above description are not met,
  88267. * otherwise \c true.
  88268. */
  88269. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88270. /** Insert a new block before the current block. You cannot insert a block
  88271. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88272. * as there can be only one, the one that already exists at the head when you
  88273. * read in a chain. The chain takes ownership of the new block and it will be
  88274. * deleted when the chain is deleted. The iterator will be left pointing to
  88275. * the new block.
  88276. *
  88277. * \param iterator A pointer to an existing initialized iterator.
  88278. * \param block A pointer to a metadata block to insert.
  88279. * \assert
  88280. * \code iterator != NULL \endcode
  88281. * \a iterator has been successfully initialized with
  88282. * FLAC__metadata_iterator_init()
  88283. * \retval FLAC__bool
  88284. * \c false if the conditions in the above description are not met, or
  88285. * a memory allocation error occurs, otherwise \c true.
  88286. */
  88287. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88288. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88289. * block as there can be only one, the one that already exists at the head when
  88290. * you read in a chain. The chain takes ownership of the new block and it will
  88291. * be deleted when the chain is deleted. The iterator will be left pointing to
  88292. * the new block.
  88293. *
  88294. * \param iterator A pointer to an existing initialized iterator.
  88295. * \param block A pointer to a metadata block to insert.
  88296. * \assert
  88297. * \code iterator != NULL \endcode
  88298. * \a iterator has been successfully initialized with
  88299. * FLAC__metadata_iterator_init()
  88300. * \retval FLAC__bool
  88301. * \c false if the conditions in the above description are not met, or
  88302. * a memory allocation error occurs, otherwise \c true.
  88303. */
  88304. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88305. /* \} */
  88306. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88307. * \ingroup flac_metadata
  88308. *
  88309. * \brief
  88310. * This module contains methods for manipulating FLAC metadata objects.
  88311. *
  88312. * Since many are variable length we have to be careful about the memory
  88313. * management. We decree that all pointers to data in the object are
  88314. * owned by the object and memory-managed by the object.
  88315. *
  88316. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88317. * functions to create all instances. When using the
  88318. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88319. * \a copy to \c true to have the function make it's own copy of the data, or
  88320. * to \c false to give the object ownership of your data. In the latter case
  88321. * your pointer must be freeable by free() and will be free()d when the object
  88322. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88323. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88324. * the length argument is 0 and the \a copy argument is \c false.
  88325. *
  88326. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88327. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88328. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88329. * case of a memory allocation error.
  88330. *
  88331. * We don't have the convenience of C++ here, so note that the library relies
  88332. * on you to keep the types straight. In other words, if you pass, for
  88333. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88334. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88335. * failure.
  88336. *
  88337. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88338. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88339. * toward the length or stored in the stream, but it can make working with plain
  88340. * comments (those that don't contain embedded-NULs in the value) easier.
  88341. * Entries passed into these functions have trailing NULs added if missing, and
  88342. * returned entries are guaranteed to have a trailing NUL.
  88343. *
  88344. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88345. * comment entry/name/value will first validate that it complies with the Vorbis
  88346. * comment specification and return false if it does not.
  88347. *
  88348. * There is no need to recalculate the length field on metadata blocks you
  88349. * have modified. They will be calculated automatically before they are
  88350. * written back to a file.
  88351. *
  88352. * \{
  88353. */
  88354. /** Create a new metadata object instance of the given type.
  88355. *
  88356. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88357. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88358. * the vendor string set (but zero comments).
  88359. *
  88360. * Do not pass in a value greater than or equal to
  88361. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88362. * doing.
  88363. *
  88364. * \param type Type of object to create
  88365. * \retval FLAC__StreamMetadata*
  88366. * \c NULL if there was an error allocating memory or the type code is
  88367. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88368. */
  88369. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88370. /** Create a copy of an existing metadata object.
  88371. *
  88372. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88373. * object is also copied. The caller takes ownership of the new block and
  88374. * is responsible for freeing it with FLAC__metadata_object_delete().
  88375. *
  88376. * \param object Pointer to object to copy.
  88377. * \assert
  88378. * \code object != NULL \endcode
  88379. * \retval FLAC__StreamMetadata*
  88380. * \c NULL if there was an error allocating memory, else the new instance.
  88381. */
  88382. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88383. /** Free a metadata object. Deletes the object pointed to by \a object.
  88384. *
  88385. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88386. * object is also deleted.
  88387. *
  88388. * \param object A pointer to an existing object.
  88389. * \assert
  88390. * \code object != NULL \endcode
  88391. */
  88392. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88393. /** Compares two metadata objects.
  88394. *
  88395. * The compare is "deep", i.e. dynamically allocated data within the
  88396. * object is also compared.
  88397. *
  88398. * \param block1 A pointer to an existing object.
  88399. * \param block2 A pointer to an existing object.
  88400. * \assert
  88401. * \code block1 != NULL \endcode
  88402. * \code block2 != NULL \endcode
  88403. * \retval FLAC__bool
  88404. * \c true if objects are identical, else \c false.
  88405. */
  88406. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88407. /** Sets the application data of an APPLICATION block.
  88408. *
  88409. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88410. * takes ownership of the pointer. The existing data will be freed if this
  88411. * function is successful, otherwise the original data will remain if \a copy
  88412. * is \c true and malloc() fails.
  88413. *
  88414. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88415. *
  88416. * \param object A pointer to an existing APPLICATION object.
  88417. * \param data A pointer to the data to set.
  88418. * \param length The length of \a data in bytes.
  88419. * \param copy See above.
  88420. * \assert
  88421. * \code object != NULL \endcode
  88422. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88423. * \code (data != NULL && length > 0) ||
  88424. * (data == NULL && length == 0 && copy == false) \endcode
  88425. * \retval FLAC__bool
  88426. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88427. */
  88428. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88429. /** Resize the seekpoint array.
  88430. *
  88431. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88432. * points will be added to the end.
  88433. *
  88434. * \param object A pointer to an existing SEEKTABLE object.
  88435. * \param new_num_points The desired length of the array; may be \c 0.
  88436. * \assert
  88437. * \code object != NULL \endcode
  88438. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88439. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88440. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88441. * \retval FLAC__bool
  88442. * \c false if memory allocation error, else \c true.
  88443. */
  88444. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88445. /** Set a seekpoint in a seektable.
  88446. *
  88447. * \param object A pointer to an existing SEEKTABLE object.
  88448. * \param point_num Index into seekpoint array to set.
  88449. * \param point The point to set.
  88450. * \assert
  88451. * \code object != NULL \endcode
  88452. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88453. * \code object->data.seek_table.num_points > point_num \endcode
  88454. */
  88455. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88456. /** Insert a seekpoint into a seektable.
  88457. *
  88458. * \param object A pointer to an existing SEEKTABLE object.
  88459. * \param point_num Index into seekpoint array to set.
  88460. * \param point The point to set.
  88461. * \assert
  88462. * \code object != NULL \endcode
  88463. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88464. * \code object->data.seek_table.num_points >= point_num \endcode
  88465. * \retval FLAC__bool
  88466. * \c false if memory allocation error, else \c true.
  88467. */
  88468. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88469. /** Delete a seekpoint from a seektable.
  88470. *
  88471. * \param object A pointer to an existing SEEKTABLE object.
  88472. * \param point_num Index into seekpoint array to set.
  88473. * \assert
  88474. * \code object != NULL \endcode
  88475. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88476. * \code object->data.seek_table.num_points > point_num \endcode
  88477. * \retval FLAC__bool
  88478. * \c false if memory allocation error, else \c true.
  88479. */
  88480. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88481. /** Check a seektable to see if it conforms to the FLAC specification.
  88482. * See the format specification for limits on the contents of the
  88483. * seektable.
  88484. *
  88485. * \param object A pointer to an existing SEEKTABLE object.
  88486. * \assert
  88487. * \code object != NULL \endcode
  88488. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88489. * \retval FLAC__bool
  88490. * \c false if seek table is illegal, else \c true.
  88491. */
  88492. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88493. /** Append a number of placeholder points to the end of a seek table.
  88494. *
  88495. * \note
  88496. * As with the other ..._seektable_template_... functions, you should
  88497. * call FLAC__metadata_object_seektable_template_sort() when finished
  88498. * to make the seek table legal.
  88499. *
  88500. * \param object A pointer to an existing SEEKTABLE object.
  88501. * \param num The number of placeholder points to append.
  88502. * \assert
  88503. * \code object != NULL \endcode
  88504. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88505. * \retval FLAC__bool
  88506. * \c false if memory allocation fails, else \c true.
  88507. */
  88508. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88509. /** Append a specific seek point template to the end of a seek table.
  88510. *
  88511. * \note
  88512. * As with the other ..._seektable_template_... functions, you should
  88513. * call FLAC__metadata_object_seektable_template_sort() when finished
  88514. * to make the seek table legal.
  88515. *
  88516. * \param object A pointer to an existing SEEKTABLE object.
  88517. * \param sample_number The sample number of the seek point template.
  88518. * \assert
  88519. * \code object != NULL \endcode
  88520. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88521. * \retval FLAC__bool
  88522. * \c false if memory allocation fails, else \c true.
  88523. */
  88524. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88525. /** Append specific seek point templates to the end of a seek table.
  88526. *
  88527. * \note
  88528. * As with the other ..._seektable_template_... functions, you should
  88529. * call FLAC__metadata_object_seektable_template_sort() when finished
  88530. * to make the seek table legal.
  88531. *
  88532. * \param object A pointer to an existing SEEKTABLE object.
  88533. * \param sample_numbers An array of sample numbers for the seek points.
  88534. * \param num The number of seek point templates to append.
  88535. * \assert
  88536. * \code object != NULL \endcode
  88537. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88538. * \retval FLAC__bool
  88539. * \c false if memory allocation fails, else \c true.
  88540. */
  88541. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88542. /** Append a set of evenly-spaced seek point templates to the end of a
  88543. * seek table.
  88544. *
  88545. * \note
  88546. * As with the other ..._seektable_template_... functions, you should
  88547. * call FLAC__metadata_object_seektable_template_sort() when finished
  88548. * to make the seek table legal.
  88549. *
  88550. * \param object A pointer to an existing SEEKTABLE object.
  88551. * \param num The number of placeholder points to append.
  88552. * \param total_samples The total number of samples to be encoded;
  88553. * the seekpoints will be spaced approximately
  88554. * \a total_samples / \a num samples apart.
  88555. * \assert
  88556. * \code object != NULL \endcode
  88557. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88558. * \code total_samples > 0 \endcode
  88559. * \retval FLAC__bool
  88560. * \c false if memory allocation fails, else \c true.
  88561. */
  88562. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88563. /** Append a set of evenly-spaced seek point templates to the end of a
  88564. * seek table.
  88565. *
  88566. * \note
  88567. * As with the other ..._seektable_template_... functions, you should
  88568. * call FLAC__metadata_object_seektable_template_sort() when finished
  88569. * to make the seek table legal.
  88570. *
  88571. * \param object A pointer to an existing SEEKTABLE object.
  88572. * \param samples The number of samples apart to space the placeholder
  88573. * points. The first point will be at sample \c 0, the
  88574. * second at sample \a samples, then 2*\a samples, and
  88575. * so on. As long as \a samples and \a total_samples
  88576. * are greater than \c 0, there will always be at least
  88577. * one seekpoint at sample \c 0.
  88578. * \param total_samples The total number of samples to be encoded;
  88579. * the seekpoints will be spaced
  88580. * \a samples samples apart.
  88581. * \assert
  88582. * \code object != NULL \endcode
  88583. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88584. * \code samples > 0 \endcode
  88585. * \code total_samples > 0 \endcode
  88586. * \retval FLAC__bool
  88587. * \c false if memory allocation fails, else \c true.
  88588. */
  88589. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88590. /** Sort a seek table's seek points according to the format specification,
  88591. * removing duplicates.
  88592. *
  88593. * \param object A pointer to a seek table to be sorted.
  88594. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88595. * If \c true, duplicates are deleted and the seek table is
  88596. * shrunk appropriately; the number of placeholder points
  88597. * present in the seek table will be the same after the call
  88598. * as before.
  88599. * \assert
  88600. * \code object != NULL \endcode
  88601. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88602. * \retval FLAC__bool
  88603. * \c false if realloc() fails, else \c true.
  88604. */
  88605. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88606. /** Sets the vendor string in a VORBIS_COMMENT block.
  88607. *
  88608. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88609. * one already.
  88610. *
  88611. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88612. * takes ownership of the \c entry.entry pointer.
  88613. *
  88614. * \note If this function returns \c false, the caller still owns the
  88615. * pointer.
  88616. *
  88617. * \param object A pointer to an existing VORBIS_COMMENT object.
  88618. * \param entry The entry to set the vendor string to.
  88619. * \param copy See above.
  88620. * \assert
  88621. * \code object != NULL \endcode
  88622. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88623. * \code (entry.entry != NULL && entry.length > 0) ||
  88624. * (entry.entry == NULL && entry.length == 0) \endcode
  88625. * \retval FLAC__bool
  88626. * \c false if memory allocation fails or \a entry does not comply with the
  88627. * Vorbis comment specification, else \c true.
  88628. */
  88629. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88630. /** Resize the comment array.
  88631. *
  88632. * If the size shrinks, elements will truncated; if it grows, new empty
  88633. * fields will be added to the end.
  88634. *
  88635. * \param object A pointer to an existing VORBIS_COMMENT object.
  88636. * \param new_num_comments The desired length of the array; may be \c 0.
  88637. * \assert
  88638. * \code object != NULL \endcode
  88639. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88640. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88641. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88642. * \retval FLAC__bool
  88643. * \c false if memory allocation fails, else \c true.
  88644. */
  88645. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88646. /** Sets a comment in a VORBIS_COMMENT block.
  88647. *
  88648. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88649. * one already.
  88650. *
  88651. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88652. * takes ownership of the \c entry.entry pointer.
  88653. *
  88654. * \note If this function returns \c false, the caller still owns the
  88655. * pointer.
  88656. *
  88657. * \param object A pointer to an existing VORBIS_COMMENT object.
  88658. * \param comment_num Index into comment array to set.
  88659. * \param entry The entry to set the comment to.
  88660. * \param copy See above.
  88661. * \assert
  88662. * \code object != NULL \endcode
  88663. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88664. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88665. * \code (entry.entry != NULL && entry.length > 0) ||
  88666. * (entry.entry == NULL && entry.length == 0) \endcode
  88667. * \retval FLAC__bool
  88668. * \c false if memory allocation fails or \a entry does not comply with the
  88669. * Vorbis comment specification, else \c true.
  88670. */
  88671. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88672. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88673. *
  88674. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88675. * one already.
  88676. *
  88677. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88678. * takes ownership of the \c entry.entry pointer.
  88679. *
  88680. * \note If this function returns \c false, the caller still owns the
  88681. * pointer.
  88682. *
  88683. * \param object A pointer to an existing VORBIS_COMMENT object.
  88684. * \param comment_num The index at which to insert the comment. The comments
  88685. * at and after \a comment_num move right one position.
  88686. * To append a comment to the end, set \a comment_num to
  88687. * \c object->data.vorbis_comment.num_comments .
  88688. * \param entry The comment to insert.
  88689. * \param copy See above.
  88690. * \assert
  88691. * \code object != NULL \endcode
  88692. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88693. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88694. * \code (entry.entry != NULL && entry.length > 0) ||
  88695. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88696. * \retval FLAC__bool
  88697. * \c false if memory allocation fails or \a entry does not comply with the
  88698. * Vorbis comment specification, else \c true.
  88699. */
  88700. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88701. /** Appends a comment to a VORBIS_COMMENT block.
  88702. *
  88703. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88704. * one already.
  88705. *
  88706. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88707. * takes ownership of the \c entry.entry pointer.
  88708. *
  88709. * \note If this function returns \c false, the caller still owns the
  88710. * pointer.
  88711. *
  88712. * \param object A pointer to an existing VORBIS_COMMENT object.
  88713. * \param entry The comment to insert.
  88714. * \param copy See above.
  88715. * \assert
  88716. * \code object != NULL \endcode
  88717. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88718. * \code (entry.entry != NULL && entry.length > 0) ||
  88719. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88720. * \retval FLAC__bool
  88721. * \c false if memory allocation fails or \a entry does not comply with the
  88722. * Vorbis comment specification, else \c true.
  88723. */
  88724. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88725. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88726. *
  88727. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88728. * one already.
  88729. *
  88730. * Depending on the the value of \a all, either all or just the first comment
  88731. * whose field name(s) match the given entry's name will be replaced by the
  88732. * given entry. If no comments match, \a entry will simply be appended.
  88733. *
  88734. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88735. * takes ownership of the \c entry.entry pointer.
  88736. *
  88737. * \note If this function returns \c false, the caller still owns the
  88738. * pointer.
  88739. *
  88740. * \param object A pointer to an existing VORBIS_COMMENT object.
  88741. * \param entry The comment to insert.
  88742. * \param all If \c true, all comments whose field name matches
  88743. * \a entry's field name will be removed, and \a entry will
  88744. * be inserted at the position of the first matching
  88745. * comment. If \c false, only the first comment whose
  88746. * field name matches \a entry's field name will be
  88747. * replaced with \a entry.
  88748. * \param copy See above.
  88749. * \assert
  88750. * \code object != NULL \endcode
  88751. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88752. * \code (entry.entry != NULL && entry.length > 0) ||
  88753. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88754. * \retval FLAC__bool
  88755. * \c false if memory allocation fails or \a entry does not comply with the
  88756. * Vorbis comment specification, else \c true.
  88757. */
  88758. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88759. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88760. *
  88761. * \param object A pointer to an existing VORBIS_COMMENT object.
  88762. * \param comment_num The index of the comment to delete.
  88763. * \assert
  88764. * \code object != NULL \endcode
  88765. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88766. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88767. * \retval FLAC__bool
  88768. * \c false if realloc() fails, else \c true.
  88769. */
  88770. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88771. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88772. *
  88773. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88774. * memory and shall be owned by the caller. For convenience the entry will
  88775. * have a terminating NUL.
  88776. *
  88777. * \param entry A pointer to a Vorbis comment entry. The entry's
  88778. * \c entry pointer should not point to allocated
  88779. * memory as it will be overwritten.
  88780. * \param field_name The field name in ASCII, \c NUL terminated.
  88781. * \param field_value The field value in UTF-8, \c NUL terminated.
  88782. * \assert
  88783. * \code entry != NULL \endcode
  88784. * \code field_name != NULL \endcode
  88785. * \code field_value != NULL \endcode
  88786. * \retval FLAC__bool
  88787. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88788. * not comply with the Vorbis comment specification, else \c true.
  88789. */
  88790. 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);
  88791. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88792. *
  88793. * The returned pointers to name and value will be allocated by malloc()
  88794. * and shall be owned by the caller.
  88795. *
  88796. * \param entry An existing Vorbis comment entry.
  88797. * \param field_name The address of where the returned pointer to the
  88798. * field name will be stored.
  88799. * \param field_value The address of where the returned pointer to the
  88800. * field value will be stored.
  88801. * \assert
  88802. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88803. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88804. * \code field_name != NULL \endcode
  88805. * \code field_value != NULL \endcode
  88806. * \retval FLAC__bool
  88807. * \c false if memory allocation fails or \a entry does not comply with the
  88808. * Vorbis comment specification, else \c true.
  88809. */
  88810. 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);
  88811. /** Check if the given Vorbis comment entry's field name matches the given
  88812. * field name.
  88813. *
  88814. * \param entry An existing Vorbis comment entry.
  88815. * \param field_name The field name to check.
  88816. * \param field_name_length The length of \a field_name, not including the
  88817. * terminating \c NUL.
  88818. * \assert
  88819. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88820. * \retval FLAC__bool
  88821. * \c true if the field names match, else \c false
  88822. */
  88823. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88824. /** Find a Vorbis comment with the given field name.
  88825. *
  88826. * The search begins at entry number \a offset; use an offset of 0 to
  88827. * search from the beginning of the comment array.
  88828. *
  88829. * \param object A pointer to an existing VORBIS_COMMENT object.
  88830. * \param offset The offset into the comment array from where to start
  88831. * the search.
  88832. * \param field_name The field name of the comment to find.
  88833. * \assert
  88834. * \code object != NULL \endcode
  88835. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88836. * \code field_name != NULL \endcode
  88837. * \retval int
  88838. * The offset in the comment array of the first comment whose field
  88839. * name matches \a field_name, or \c -1 if no match was found.
  88840. */
  88841. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88842. /** Remove first Vorbis comment matching the given field name.
  88843. *
  88844. * \param object A pointer to an existing VORBIS_COMMENT object.
  88845. * \param field_name The field name of comment to delete.
  88846. * \assert
  88847. * \code object != NULL \endcode
  88848. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88849. * \retval int
  88850. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88851. * \c 1 for one matching entry deleted.
  88852. */
  88853. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88854. /** Remove all Vorbis comments matching the given field name.
  88855. *
  88856. * \param object A pointer to an existing VORBIS_COMMENT object.
  88857. * \param field_name The field name of comments to delete.
  88858. * \assert
  88859. * \code object != NULL \endcode
  88860. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88861. * \retval int
  88862. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88863. * else the number of matching entries deleted.
  88864. */
  88865. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88866. /** Create a new CUESHEET track instance.
  88867. *
  88868. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88869. *
  88870. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88871. * \c NULL if there was an error allocating memory, else the new instance.
  88872. */
  88873. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88874. /** Create a copy of an existing CUESHEET track object.
  88875. *
  88876. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88877. * object is also copied. The caller takes ownership of the new object and
  88878. * is responsible for freeing it with
  88879. * FLAC__metadata_object_cuesheet_track_delete().
  88880. *
  88881. * \param object Pointer to object to copy.
  88882. * \assert
  88883. * \code object != NULL \endcode
  88884. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88885. * \c NULL if there was an error allocating memory, else the new instance.
  88886. */
  88887. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88888. /** Delete a CUESHEET track object
  88889. *
  88890. * \param object A pointer to an existing CUESHEET track object.
  88891. * \assert
  88892. * \code object != NULL \endcode
  88893. */
  88894. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88895. /** Resize a track's index point array.
  88896. *
  88897. * If the size shrinks, elements will truncated; if it grows, new blank
  88898. * indices will be added to the end.
  88899. *
  88900. * \param object A pointer to an existing CUESHEET object.
  88901. * \param track_num The index of the track to modify. NOTE: this is not
  88902. * necessarily the same as the track's \a number field.
  88903. * \param new_num_indices The desired length of the array; may be \c 0.
  88904. * \assert
  88905. * \code object != NULL \endcode
  88906. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88907. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88908. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88909. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88910. * \retval FLAC__bool
  88911. * \c false if memory allocation error, else \c true.
  88912. */
  88913. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88914. /** Insert an index point in a CUESHEET track at the given index.
  88915. *
  88916. * \param object A pointer to an existing CUESHEET object.
  88917. * \param track_num The index of the track to modify. NOTE: this is not
  88918. * necessarily the same as the track's \a number field.
  88919. * \param index_num The index into the track's index array at which to
  88920. * insert the index point. NOTE: this is not necessarily
  88921. * the same as the index point's \a number field. The
  88922. * indices at and after \a index_num move right one
  88923. * position. To append an index point to the end, set
  88924. * \a index_num to
  88925. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88926. * \param index The index point to insert.
  88927. * \assert
  88928. * \code object != NULL \endcode
  88929. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88930. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88931. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88932. * \retval FLAC__bool
  88933. * \c false if realloc() fails, else \c true.
  88934. */
  88935. 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);
  88936. /** Insert a blank index point in a CUESHEET track at the given index.
  88937. *
  88938. * A blank index point is one in which all field values are zero.
  88939. *
  88940. * \param object A pointer to an existing CUESHEET object.
  88941. * \param track_num The index of the track to modify. NOTE: this is not
  88942. * necessarily the same as the track's \a number field.
  88943. * \param index_num The index into the track's index array at which to
  88944. * insert the index point. NOTE: this is not necessarily
  88945. * the same as the index point's \a number field. The
  88946. * indices at and after \a index_num move right one
  88947. * position. To append an index point to the end, set
  88948. * \a index_num to
  88949. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88950. * \assert
  88951. * \code object != NULL \endcode
  88952. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88953. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88954. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88955. * \retval FLAC__bool
  88956. * \c false if realloc() fails, else \c true.
  88957. */
  88958. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88959. /** Delete an index point in a CUESHEET track at the given index.
  88960. *
  88961. * \param object A pointer to an existing CUESHEET object.
  88962. * \param track_num The index into the track array of the track to
  88963. * modify. NOTE: this is not necessarily the same
  88964. * as the track's \a number field.
  88965. * \param index_num The index into the track's index array of the index
  88966. * to delete. NOTE: this is not necessarily the same
  88967. * as the index's \a number field.
  88968. * \assert
  88969. * \code object != NULL \endcode
  88970. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88971. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88972. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88973. * \retval FLAC__bool
  88974. * \c false if realloc() fails, else \c true.
  88975. */
  88976. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88977. /** Resize the track array.
  88978. *
  88979. * If the size shrinks, elements will truncated; if it grows, new blank
  88980. * tracks will be added to the end.
  88981. *
  88982. * \param object A pointer to an existing CUESHEET object.
  88983. * \param new_num_tracks The desired length of the array; may be \c 0.
  88984. * \assert
  88985. * \code object != NULL \endcode
  88986. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88987. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88988. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88989. * \retval FLAC__bool
  88990. * \c false if memory allocation error, else \c true.
  88991. */
  88992. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88993. /** Sets a track in a CUESHEET block.
  88994. *
  88995. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88996. * takes ownership of the \a track pointer.
  88997. *
  88998. * \param object A pointer to an existing CUESHEET object.
  88999. * \param track_num Index into track array to set. NOTE: this is not
  89000. * necessarily the same as the track's \a number field.
  89001. * \param track The track to set the track to. You may safely pass in
  89002. * a const pointer if \a copy is \c true.
  89003. * \param copy See above.
  89004. * \assert
  89005. * \code object != NULL \endcode
  89006. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89007. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89008. * \code (track->indices != NULL && track->num_indices > 0) ||
  89009. * (track->indices == NULL && track->num_indices == 0)
  89010. * \retval FLAC__bool
  89011. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89012. */
  89013. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89014. /** Insert a track in a CUESHEET block at the given index.
  89015. *
  89016. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89017. * takes ownership of the \a track pointer.
  89018. *
  89019. * \param object A pointer to an existing CUESHEET object.
  89020. * \param track_num The index at which to insert the track. NOTE: this
  89021. * is not necessarily the same as the track's \a number
  89022. * field. The tracks at and after \a track_num move right
  89023. * one position. To append a track to the end, set
  89024. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89025. * \param track The track to insert. You may safely pass in a const
  89026. * pointer if \a copy is \c true.
  89027. * \param copy See above.
  89028. * \assert
  89029. * \code object != NULL \endcode
  89030. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89031. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89032. * \retval FLAC__bool
  89033. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89034. */
  89035. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89036. /** Insert a blank track in a CUESHEET block at the given index.
  89037. *
  89038. * A blank track is one in which all field values are zero.
  89039. *
  89040. * \param object A pointer to an existing CUESHEET object.
  89041. * \param track_num The index at which to insert the track. NOTE: this
  89042. * is not necessarily the same as the track's \a number
  89043. * field. The tracks at and after \a track_num move right
  89044. * one position. To append a track to the end, set
  89045. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89046. * \assert
  89047. * \code object != NULL \endcode
  89048. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89049. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89050. * \retval FLAC__bool
  89051. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89052. */
  89053. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89054. /** Delete a track in a CUESHEET block at the given index.
  89055. *
  89056. * \param object A pointer to an existing CUESHEET object.
  89057. * \param track_num The index into the track array of the track to
  89058. * delete. NOTE: this is not necessarily the same
  89059. * as the track's \a number field.
  89060. * \assert
  89061. * \code object != NULL \endcode
  89062. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89063. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89064. * \retval FLAC__bool
  89065. * \c false if realloc() fails, else \c true.
  89066. */
  89067. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89068. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89069. * See the format specification for limits on the contents of the
  89070. * cue sheet.
  89071. *
  89072. * \param object A pointer to an existing CUESHEET object.
  89073. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89074. * stringent requirements for a CD-DA (audio) disc.
  89075. * \param violation Address of a pointer to a string. If there is a
  89076. * violation, a pointer to a string explanation of the
  89077. * violation will be returned here. \a violation may be
  89078. * \c NULL if you don't need the returned string. Do not
  89079. * free the returned string; it will always point to static
  89080. * data.
  89081. * \assert
  89082. * \code object != NULL \endcode
  89083. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89084. * \retval FLAC__bool
  89085. * \c false if cue sheet is illegal, else \c true.
  89086. */
  89087. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89088. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89089. * assumes the cue sheet corresponds to a CD; the result is undefined
  89090. * if the cuesheet's is_cd bit is not set.
  89091. *
  89092. * \param object A pointer to an existing CUESHEET object.
  89093. * \assert
  89094. * \code object != NULL \endcode
  89095. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89096. * \retval FLAC__uint32
  89097. * The unsigned integer representation of the CDDB/freedb ID
  89098. */
  89099. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89100. /** Sets the MIME type of a PICTURE block.
  89101. *
  89102. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89103. * takes ownership of the pointer. The existing string will be freed if this
  89104. * function is successful, otherwise the original string will remain if \a copy
  89105. * is \c true and malloc() fails.
  89106. *
  89107. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89108. *
  89109. * \param object A pointer to an existing PICTURE object.
  89110. * \param mime_type A pointer to the MIME type string. The string must be
  89111. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89112. * is done.
  89113. * \param copy See above.
  89114. * \assert
  89115. * \code object != NULL \endcode
  89116. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89117. * \code (mime_type != NULL) \endcode
  89118. * \retval FLAC__bool
  89119. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89120. */
  89121. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89122. /** Sets the description of a PICTURE block.
  89123. *
  89124. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89125. * takes ownership of the pointer. The existing string will be freed if this
  89126. * function is successful, otherwise the original string will remain if \a copy
  89127. * is \c true and malloc() fails.
  89128. *
  89129. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89130. *
  89131. * \param object A pointer to an existing PICTURE object.
  89132. * \param description A pointer to the description string. The string must be
  89133. * valid UTF-8, NUL-terminated. No validation is done.
  89134. * \param copy See above.
  89135. * \assert
  89136. * \code object != NULL \endcode
  89137. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89138. * \code (description != NULL) \endcode
  89139. * \retval FLAC__bool
  89140. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89141. */
  89142. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89143. /** Sets the picture data of a PICTURE block.
  89144. *
  89145. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89146. * takes ownership of the pointer. Also sets the \a data_length field of the
  89147. * metadata object to what is passed in as the \a length parameter. The
  89148. * existing data will be freed if this function is successful, otherwise the
  89149. * original data and data_length will remain if \a copy is \c true and
  89150. * malloc() fails.
  89151. *
  89152. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89153. *
  89154. * \param object A pointer to an existing PICTURE object.
  89155. * \param data A pointer to the data to set.
  89156. * \param length The length of \a data in bytes.
  89157. * \param copy See above.
  89158. * \assert
  89159. * \code object != NULL \endcode
  89160. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89161. * \code (data != NULL && length > 0) ||
  89162. * (data == NULL && length == 0 && copy == false) \endcode
  89163. * \retval FLAC__bool
  89164. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89165. */
  89166. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89167. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89168. * See the format specification for limits on the contents of the
  89169. * PICTURE block.
  89170. *
  89171. * \param object A pointer to existing PICTURE block to be checked.
  89172. * \param violation Address of a pointer to a string. If there is a
  89173. * violation, a pointer to a string explanation of the
  89174. * violation will be returned here. \a violation may be
  89175. * \c NULL if you don't need the returned string. Do not
  89176. * free the returned string; it will always point to static
  89177. * data.
  89178. * \assert
  89179. * \code object != NULL \endcode
  89180. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89181. * \retval FLAC__bool
  89182. * \c false if PICTURE block is illegal, else \c true.
  89183. */
  89184. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89185. /* \} */
  89186. #ifdef __cplusplus
  89187. }
  89188. #endif
  89189. #endif
  89190. /*** End of inlined file: metadata.h ***/
  89191. /*** Start of inlined file: stream_decoder.h ***/
  89192. #ifndef FLAC__STREAM_DECODER_H
  89193. #define FLAC__STREAM_DECODER_H
  89194. #include <stdio.h> /* for FILE */
  89195. #ifdef __cplusplus
  89196. extern "C" {
  89197. #endif
  89198. /** \file include/FLAC/stream_decoder.h
  89199. *
  89200. * \brief
  89201. * This module contains the functions which implement the stream
  89202. * decoder.
  89203. *
  89204. * See the detailed documentation in the
  89205. * \link flac_stream_decoder stream decoder \endlink module.
  89206. */
  89207. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89208. * \ingroup flac
  89209. *
  89210. * \brief
  89211. * This module describes the decoder layers provided by libFLAC.
  89212. *
  89213. * The stream decoder can be used to decode complete streams either from
  89214. * the client via callbacks, or directly from a file, depending on how
  89215. * it is initialized. When decoding via callbacks, the client provides
  89216. * callbacks for reading FLAC data and writing decoded samples, and
  89217. * handling metadata and errors. If the client also supplies seek-related
  89218. * callback, the decoder function for sample-accurate seeking within the
  89219. * FLAC input is also available. When decoding from a file, the client
  89220. * needs only supply a filename or open \c FILE* and write/metadata/error
  89221. * callbacks; the rest of the callbacks are supplied internally. For more
  89222. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89223. */
  89224. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89225. * \ingroup flac_decoder
  89226. *
  89227. * \brief
  89228. * This module contains the functions which implement the stream
  89229. * decoder.
  89230. *
  89231. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89232. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89233. *
  89234. * The basic usage of this decoder is as follows:
  89235. * - The program creates an instance of a decoder using
  89236. * FLAC__stream_decoder_new().
  89237. * - The program overrides the default settings using
  89238. * FLAC__stream_decoder_set_*() functions.
  89239. * - The program initializes the instance to validate the settings and
  89240. * prepare for decoding using
  89241. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89242. * or FLAC__stream_decoder_init_file() for native FLAC,
  89243. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89244. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89245. * - The program calls the FLAC__stream_decoder_process_*() functions
  89246. * to decode data, which subsequently calls the callbacks.
  89247. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89248. * which flushes the input and output and resets the decoder to the
  89249. * uninitialized state.
  89250. * - The instance may be used again or deleted with
  89251. * FLAC__stream_decoder_delete().
  89252. *
  89253. * In more detail, the program will create a new instance by calling
  89254. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89255. * functions to override the default decoder options, and call
  89256. * one of the FLAC__stream_decoder_init_*() functions.
  89257. *
  89258. * There are three initialization functions for native FLAC, one for
  89259. * setting up the decoder to decode FLAC data from the client via
  89260. * callbacks, and two for decoding directly from a FLAC file.
  89261. *
  89262. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89263. * You must also supply several callbacks for handling I/O. Some (like
  89264. * seeking) are optional, depending on the capabilities of the input.
  89265. *
  89266. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89267. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89268. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89269. * the other callbacks internally.
  89270. *
  89271. * There are three similarly-named init functions for decoding from Ogg
  89272. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89273. * library has been built with Ogg support.
  89274. *
  89275. * Once the decoder is initialized, your program will call one of several
  89276. * functions to start the decoding process:
  89277. *
  89278. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89279. * most one metadata block or audio frame and return, calling either the
  89280. * metadata callback or write callback, respectively, once. If the decoder
  89281. * loses sync it will return with only the error callback being called.
  89282. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89283. * to process the stream from the current location and stop upon reaching
  89284. * the first audio frame. The client will get one metadata, write, or error
  89285. * callback per metadata block, audio frame, or sync error, respectively.
  89286. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89287. * to process the stream from the current location until the read callback
  89288. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89289. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89290. * write, or error callback per metadata block, audio frame, or sync error,
  89291. * respectively.
  89292. *
  89293. * When the decoder has finished decoding (normally or through an abort),
  89294. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89295. * ensures the decoder is in the correct state and frees memory. Then the
  89296. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89297. * again to decode another stream.
  89298. *
  89299. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89300. * At any point after the stream decoder has been initialized, the client can
  89301. * call this function to seek to an exact sample within the stream.
  89302. * Subsequently, the first time the write callback is called it will be
  89303. * passed a (possibly partial) block starting at that sample.
  89304. *
  89305. * If the client cannot seek via the callback interface provided, but still
  89306. * has another way of seeking, it can flush the decoder using
  89307. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89308. * through the read callback.
  89309. *
  89310. * The stream decoder also provides MD5 signature checking. If this is
  89311. * turned on before initialization, FLAC__stream_decoder_finish() will
  89312. * report when the decoded MD5 signature does not match the one stored
  89313. * in the STREAMINFO block. MD5 checking is automatically turned off
  89314. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89315. * in the STREAMINFO block or when a seek is attempted.
  89316. *
  89317. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89318. * attention. By default, the decoder only calls the metadata_callback for
  89319. * the STREAMINFO block. These functions allow you to tell the decoder
  89320. * explicitly which blocks to parse and return via the metadata_callback
  89321. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89322. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89323. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89324. * which blocks to return. Remember that metadata blocks can potentially
  89325. * be big (for example, cover art) so filtering out the ones you don't
  89326. * use can reduce the memory requirements of the decoder. Also note the
  89327. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89328. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89329. * filtering APPLICATION blocks based on the application ID.
  89330. *
  89331. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89332. * they still can legally be filtered from the metadata_callback.
  89333. *
  89334. * \note
  89335. * The "set" functions may only be called when the decoder is in the
  89336. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89337. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89338. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89339. * return \c true, otherwise \c false.
  89340. *
  89341. * \note
  89342. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89343. * defaults, including the callbacks.
  89344. *
  89345. * \{
  89346. */
  89347. /** State values for a FLAC__StreamDecoder
  89348. *
  89349. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89350. */
  89351. typedef enum {
  89352. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89353. /**< The decoder is ready to search for metadata. */
  89354. FLAC__STREAM_DECODER_READ_METADATA,
  89355. /**< The decoder is ready to or is in the process of reading metadata. */
  89356. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89357. /**< The decoder is ready to or is in the process of searching for the
  89358. * frame sync code.
  89359. */
  89360. FLAC__STREAM_DECODER_READ_FRAME,
  89361. /**< The decoder is ready to or is in the process of reading a frame. */
  89362. FLAC__STREAM_DECODER_END_OF_STREAM,
  89363. /**< The decoder has reached the end of the stream. */
  89364. FLAC__STREAM_DECODER_OGG_ERROR,
  89365. /**< An error occurred in the underlying Ogg layer. */
  89366. FLAC__STREAM_DECODER_SEEK_ERROR,
  89367. /**< An error occurred while seeking. The decoder must be flushed
  89368. * with FLAC__stream_decoder_flush() or reset with
  89369. * FLAC__stream_decoder_reset() before decoding can continue.
  89370. */
  89371. FLAC__STREAM_DECODER_ABORTED,
  89372. /**< The decoder was aborted by the read callback. */
  89373. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89374. /**< An error occurred allocating memory. The decoder is in an invalid
  89375. * state and can no longer be used.
  89376. */
  89377. FLAC__STREAM_DECODER_UNINITIALIZED
  89378. /**< The decoder is in the uninitialized state; one of the
  89379. * FLAC__stream_decoder_init_*() functions must be called before samples
  89380. * can be processed.
  89381. */
  89382. } FLAC__StreamDecoderState;
  89383. /** Maps a FLAC__StreamDecoderState to a C string.
  89384. *
  89385. * Using a FLAC__StreamDecoderState as the index to this array
  89386. * will give the string equivalent. The contents should not be modified.
  89387. */
  89388. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89389. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89390. */
  89391. typedef enum {
  89392. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89393. /**< Initialization was successful. */
  89394. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89395. /**< The library was not compiled with support for the given container
  89396. * format.
  89397. */
  89398. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89399. /**< A required callback was not supplied. */
  89400. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89401. /**< An error occurred allocating memory. */
  89402. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89403. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89404. * FLAC__stream_decoder_init_ogg_file(). */
  89405. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89406. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89407. * already initialized, usually because
  89408. * FLAC__stream_decoder_finish() was not called.
  89409. */
  89410. } FLAC__StreamDecoderInitStatus;
  89411. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89412. *
  89413. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89414. * will give the string equivalent. The contents should not be modified.
  89415. */
  89416. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89417. /** Return values for the FLAC__StreamDecoder read callback.
  89418. */
  89419. typedef enum {
  89420. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89421. /**< The read was OK and decoding can continue. */
  89422. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89423. /**< The read was attempted while at the end of the stream. Note that
  89424. * the client must only return this value when the read callback was
  89425. * called when already at the end of the stream. Otherwise, if the read
  89426. * itself moves to the end of the stream, the client should still return
  89427. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89428. * the next read callback it should return
  89429. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89430. * of \c 0.
  89431. */
  89432. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89433. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89434. } FLAC__StreamDecoderReadStatus;
  89435. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89436. *
  89437. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89438. * will give the string equivalent. The contents should not be modified.
  89439. */
  89440. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89441. /** Return values for the FLAC__StreamDecoder seek callback.
  89442. */
  89443. typedef enum {
  89444. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89445. /**< The seek was OK and decoding can continue. */
  89446. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89447. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89448. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89449. /**< Client does not support seeking. */
  89450. } FLAC__StreamDecoderSeekStatus;
  89451. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89452. *
  89453. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89454. * will give the string equivalent. The contents should not be modified.
  89455. */
  89456. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89457. /** Return values for the FLAC__StreamDecoder tell callback.
  89458. */
  89459. typedef enum {
  89460. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89461. /**< The tell was OK and decoding can continue. */
  89462. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89463. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89464. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89465. /**< Client does not support telling the position. */
  89466. } FLAC__StreamDecoderTellStatus;
  89467. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89468. *
  89469. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89470. * will give the string equivalent. The contents should not be modified.
  89471. */
  89472. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89473. /** Return values for the FLAC__StreamDecoder length callback.
  89474. */
  89475. typedef enum {
  89476. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89477. /**< The length call was OK and decoding can continue. */
  89478. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89479. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89480. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89481. /**< Client does not support reporting the length. */
  89482. } FLAC__StreamDecoderLengthStatus;
  89483. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89484. *
  89485. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89486. * will give the string equivalent. The contents should not be modified.
  89487. */
  89488. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89489. /** Return values for the FLAC__StreamDecoder write callback.
  89490. */
  89491. typedef enum {
  89492. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89493. /**< The write was OK and decoding can continue. */
  89494. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89495. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89496. } FLAC__StreamDecoderWriteStatus;
  89497. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89498. *
  89499. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89500. * will give the string equivalent. The contents should not be modified.
  89501. */
  89502. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89503. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89504. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89505. * all. The rest could be caused by bad sync (false synchronization on
  89506. * data that is not the start of a frame) or corrupted data. The error
  89507. * itself is the decoder's best guess at what happened assuming a correct
  89508. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89509. * could be caused by a correct sync on the start of a frame, but some
  89510. * data in the frame header was corrupted. Or it could be the result of
  89511. * syncing on a point the stream that looked like the starting of a frame
  89512. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89513. * could be because the decoder encountered a valid frame made by a future
  89514. * version of the encoder which it cannot parse, or because of a false
  89515. * sync making it appear as though an encountered frame was generated by
  89516. * a future encoder.
  89517. */
  89518. typedef enum {
  89519. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89520. /**< An error in the stream caused the decoder to lose synchronization. */
  89521. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89522. /**< The decoder encountered a corrupted frame header. */
  89523. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89524. /**< The frame's data did not match the CRC in the footer. */
  89525. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89526. /**< The decoder encountered reserved fields in use in the stream. */
  89527. } FLAC__StreamDecoderErrorStatus;
  89528. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89529. *
  89530. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89531. * will give the string equivalent. The contents should not be modified.
  89532. */
  89533. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89534. /***********************************************************************
  89535. *
  89536. * class FLAC__StreamDecoder
  89537. *
  89538. ***********************************************************************/
  89539. struct FLAC__StreamDecoderProtected;
  89540. struct FLAC__StreamDecoderPrivate;
  89541. /** The opaque structure definition for the stream decoder type.
  89542. * See the \link flac_stream_decoder stream decoder module \endlink
  89543. * for a detailed description.
  89544. */
  89545. typedef struct {
  89546. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89547. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89548. } FLAC__StreamDecoder;
  89549. /** Signature for the read callback.
  89550. *
  89551. * A function pointer matching this signature must be passed to
  89552. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89553. * called when the decoder needs more input data. The address of the
  89554. * buffer to be filled is supplied, along with the number of bytes the
  89555. * buffer can hold. The callback may choose to supply less data and
  89556. * modify the byte count but must be careful not to overflow the buffer.
  89557. * The callback then returns a status code chosen from
  89558. * FLAC__StreamDecoderReadStatus.
  89559. *
  89560. * Here is an example of a read callback for stdio streams:
  89561. * \code
  89562. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89563. * {
  89564. * FILE *file = ((MyClientData*)client_data)->file;
  89565. * if(*bytes > 0) {
  89566. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89567. * if(ferror(file))
  89568. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89569. * else if(*bytes == 0)
  89570. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89571. * else
  89572. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89573. * }
  89574. * else
  89575. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89576. * }
  89577. * \endcode
  89578. *
  89579. * \note In general, FLAC__StreamDecoder functions which change the
  89580. * state should not be called on the \a decoder while in the callback.
  89581. *
  89582. * \param decoder The decoder instance calling the callback.
  89583. * \param buffer A pointer to a location for the callee to store
  89584. * data to be decoded.
  89585. * \param bytes A pointer to the size of the buffer. On entry
  89586. * to the callback, it contains the maximum number
  89587. * of bytes that may be stored in \a buffer. The
  89588. * callee must set it to the actual number of bytes
  89589. * stored (0 in case of error or end-of-stream) before
  89590. * returning.
  89591. * \param client_data The callee's client data set through
  89592. * FLAC__stream_decoder_init_*().
  89593. * \retval FLAC__StreamDecoderReadStatus
  89594. * The callee's return status. Note that the callback should return
  89595. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89596. * zero bytes were read and there is no more data to be read.
  89597. */
  89598. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89599. /** Signature for the seek callback.
  89600. *
  89601. * A function pointer matching this signature may be passed to
  89602. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89603. * called when the decoder needs to seek the input stream. The decoder
  89604. * will pass the absolute byte offset to seek to, 0 meaning the
  89605. * beginning of the stream.
  89606. *
  89607. * Here is an example of a seek callback for stdio streams:
  89608. * \code
  89609. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89610. * {
  89611. * FILE *file = ((MyClientData*)client_data)->file;
  89612. * if(file == stdin)
  89613. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89614. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89615. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89616. * else
  89617. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89618. * }
  89619. * \endcode
  89620. *
  89621. * \note In general, FLAC__StreamDecoder functions which change the
  89622. * state should not be called on the \a decoder while in the callback.
  89623. *
  89624. * \param decoder The decoder instance calling the callback.
  89625. * \param absolute_byte_offset The offset from the beginning of the stream
  89626. * to seek to.
  89627. * \param client_data The callee's client data set through
  89628. * FLAC__stream_decoder_init_*().
  89629. * \retval FLAC__StreamDecoderSeekStatus
  89630. * The callee's return status.
  89631. */
  89632. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89633. /** Signature for the tell callback.
  89634. *
  89635. * A function pointer matching this signature may be passed to
  89636. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89637. * called when the decoder wants to know the current position of the
  89638. * stream. The callback should return the byte offset from the
  89639. * beginning of the stream.
  89640. *
  89641. * Here is an example of a tell callback for stdio streams:
  89642. * \code
  89643. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89644. * {
  89645. * FILE *file = ((MyClientData*)client_data)->file;
  89646. * off_t pos;
  89647. * if(file == stdin)
  89648. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89649. * else if((pos = ftello(file)) < 0)
  89650. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89651. * else {
  89652. * *absolute_byte_offset = (FLAC__uint64)pos;
  89653. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89654. * }
  89655. * }
  89656. * \endcode
  89657. *
  89658. * \note In general, FLAC__StreamDecoder functions which change the
  89659. * state should not be called on the \a decoder while in the callback.
  89660. *
  89661. * \param decoder The decoder instance calling the callback.
  89662. * \param absolute_byte_offset A pointer to storage for the current offset
  89663. * from the beginning of the stream.
  89664. * \param client_data The callee's client data set through
  89665. * FLAC__stream_decoder_init_*().
  89666. * \retval FLAC__StreamDecoderTellStatus
  89667. * The callee's return status.
  89668. */
  89669. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89670. /** Signature for the length callback.
  89671. *
  89672. * A function pointer matching this signature may be passed to
  89673. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89674. * called when the decoder wants to know the total length of the stream
  89675. * in bytes.
  89676. *
  89677. * Here is an example of a length callback for stdio streams:
  89678. * \code
  89679. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89680. * {
  89681. * FILE *file = ((MyClientData*)client_data)->file;
  89682. * struct stat filestats;
  89683. *
  89684. * if(file == stdin)
  89685. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89686. * else if(fstat(fileno(file), &filestats) != 0)
  89687. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89688. * else {
  89689. * *stream_length = (FLAC__uint64)filestats.st_size;
  89690. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89691. * }
  89692. * }
  89693. * \endcode
  89694. *
  89695. * \note In general, FLAC__StreamDecoder functions which change the
  89696. * state should not be called on the \a decoder while in the callback.
  89697. *
  89698. * \param decoder The decoder instance calling the callback.
  89699. * \param stream_length A pointer to storage for the length of the stream
  89700. * in bytes.
  89701. * \param client_data The callee's client data set through
  89702. * FLAC__stream_decoder_init_*().
  89703. * \retval FLAC__StreamDecoderLengthStatus
  89704. * The callee's return status.
  89705. */
  89706. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89707. /** Signature for the EOF callback.
  89708. *
  89709. * A function pointer matching this signature may be passed to
  89710. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89711. * called when the decoder needs to know if the end of the stream has
  89712. * been reached.
  89713. *
  89714. * Here is an example of a EOF callback for stdio streams:
  89715. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89716. * \code
  89717. * {
  89718. * FILE *file = ((MyClientData*)client_data)->file;
  89719. * return feof(file)? true : false;
  89720. * }
  89721. * \endcode
  89722. *
  89723. * \note In general, FLAC__StreamDecoder functions which change the
  89724. * state should not be called on the \a decoder while in the callback.
  89725. *
  89726. * \param decoder The decoder instance calling the callback.
  89727. * \param client_data The callee's client data set through
  89728. * FLAC__stream_decoder_init_*().
  89729. * \retval FLAC__bool
  89730. * \c true if the currently at the end of the stream, else \c false.
  89731. */
  89732. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89733. /** Signature for the write callback.
  89734. *
  89735. * A function pointer matching this signature must be passed to one of
  89736. * the FLAC__stream_decoder_init_*() functions.
  89737. * The supplied function will be called when the decoder has decoded a
  89738. * single audio frame. The decoder will pass the frame metadata as well
  89739. * as an array of pointers (one for each channel) pointing to the
  89740. * decoded audio.
  89741. *
  89742. * \note In general, FLAC__StreamDecoder functions which change the
  89743. * state should not be called on the \a decoder while in the callback.
  89744. *
  89745. * \param decoder The decoder instance calling the callback.
  89746. * \param frame The description of the decoded frame. See
  89747. * FLAC__Frame.
  89748. * \param buffer An array of pointers to decoded channels of data.
  89749. * Each pointer will point to an array of signed
  89750. * samples of length \a frame->header.blocksize.
  89751. * Channels will be ordered according to the FLAC
  89752. * specification; see the documentation for the
  89753. * <A HREF="../format.html#frame_header">frame header</A>.
  89754. * \param client_data The callee's client data set through
  89755. * FLAC__stream_decoder_init_*().
  89756. * \retval FLAC__StreamDecoderWriteStatus
  89757. * The callee's return status.
  89758. */
  89759. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89760. /** Signature for the metadata callback.
  89761. *
  89762. * A function pointer matching this signature must be passed to one of
  89763. * the FLAC__stream_decoder_init_*() functions.
  89764. * The supplied function will be called when the decoder has decoded a
  89765. * metadata block. In a valid FLAC file there will always be one
  89766. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89767. * These will be supplied by the decoder in the same order as they
  89768. * appear in the stream and always before the first audio frame (i.e.
  89769. * write callback). The metadata block that is passed in must not be
  89770. * modified, and it doesn't live beyond the callback, so you should make
  89771. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89772. * elsewhere. Since metadata blocks can potentially be large, by
  89773. * default the decoder only calls the metadata callback for the
  89774. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89775. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89776. *
  89777. * \note In general, FLAC__StreamDecoder functions which change the
  89778. * state should not be called on the \a decoder while in the callback.
  89779. *
  89780. * \param decoder The decoder instance calling the callback.
  89781. * \param metadata The decoded metadata block.
  89782. * \param client_data The callee's client data set through
  89783. * FLAC__stream_decoder_init_*().
  89784. */
  89785. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89786. /** Signature for the error callback.
  89787. *
  89788. * A function pointer matching this signature must be passed to one of
  89789. * the FLAC__stream_decoder_init_*() functions.
  89790. * The supplied function will be called whenever an error occurs during
  89791. * decoding.
  89792. *
  89793. * \note In general, FLAC__StreamDecoder functions which change the
  89794. * state should not be called on the \a decoder while in the callback.
  89795. *
  89796. * \param decoder The decoder instance calling the callback.
  89797. * \param status The error encountered by the decoder.
  89798. * \param client_data The callee's client data set through
  89799. * FLAC__stream_decoder_init_*().
  89800. */
  89801. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89802. /***********************************************************************
  89803. *
  89804. * Class constructor/destructor
  89805. *
  89806. ***********************************************************************/
  89807. /** Create a new stream decoder instance. The instance is created with
  89808. * default settings; see the individual FLAC__stream_decoder_set_*()
  89809. * functions for each setting's default.
  89810. *
  89811. * \retval FLAC__StreamDecoder*
  89812. * \c NULL if there was an error allocating memory, else the new instance.
  89813. */
  89814. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89815. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89816. *
  89817. * \param decoder A pointer to an existing decoder.
  89818. * \assert
  89819. * \code decoder != NULL \endcode
  89820. */
  89821. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89822. /***********************************************************************
  89823. *
  89824. * Public class method prototypes
  89825. *
  89826. ***********************************************************************/
  89827. /** Set the serial number for the FLAC stream within the Ogg container.
  89828. * The default behavior is to use the serial number of the first Ogg
  89829. * page. Setting a serial number here will explicitly specify which
  89830. * stream is to be decoded.
  89831. *
  89832. * \note
  89833. * This does not need to be set for native FLAC decoding.
  89834. *
  89835. * \default \c use serial number of first page
  89836. * \param decoder A decoder instance to set.
  89837. * \param serial_number See above.
  89838. * \assert
  89839. * \code decoder != NULL \endcode
  89840. * \retval FLAC__bool
  89841. * \c false if the decoder is already initialized, else \c true.
  89842. */
  89843. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89844. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89845. * compute the MD5 signature of the unencoded audio data while decoding
  89846. * and compare it to the signature from the STREAMINFO block, if it
  89847. * exists, during FLAC__stream_decoder_finish().
  89848. *
  89849. * MD5 signature checking will be turned off (until the next
  89850. * FLAC__stream_decoder_reset()) if there is no signature in the
  89851. * STREAMINFO block or when a seek is attempted.
  89852. *
  89853. * Clients that do not use the MD5 check should leave this off to speed
  89854. * up decoding.
  89855. *
  89856. * \default \c false
  89857. * \param decoder A decoder instance to set.
  89858. * \param value Flag value (see above).
  89859. * \assert
  89860. * \code decoder != NULL \endcode
  89861. * \retval FLAC__bool
  89862. * \c false if the decoder is already initialized, else \c true.
  89863. */
  89864. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89865. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89866. *
  89867. * \default By default, only the \c STREAMINFO block is returned via the
  89868. * metadata callback.
  89869. * \param decoder A decoder instance to set.
  89870. * \param type See above.
  89871. * \assert
  89872. * \code decoder != NULL \endcode
  89873. * \a type is valid
  89874. * \retval FLAC__bool
  89875. * \c false if the decoder is already initialized, else \c true.
  89876. */
  89877. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89878. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89879. * given \a id.
  89880. *
  89881. * \default By default, only the \c STREAMINFO block is returned via the
  89882. * metadata callback.
  89883. * \param decoder A decoder instance to set.
  89884. * \param id See above.
  89885. * \assert
  89886. * \code decoder != NULL \endcode
  89887. * \code id != NULL \endcode
  89888. * \retval FLAC__bool
  89889. * \c false if the decoder is already initialized, else \c true.
  89890. */
  89891. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89892. /** Direct the decoder to pass on all metadata blocks of any type.
  89893. *
  89894. * \default By default, only the \c STREAMINFO block is returned via the
  89895. * metadata callback.
  89896. * \param decoder A decoder instance to set.
  89897. * \assert
  89898. * \code decoder != NULL \endcode
  89899. * \retval FLAC__bool
  89900. * \c false if the decoder is already initialized, else \c true.
  89901. */
  89902. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89903. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89904. *
  89905. * \default By default, only the \c STREAMINFO block is returned via the
  89906. * metadata callback.
  89907. * \param decoder A decoder instance to set.
  89908. * \param type See above.
  89909. * \assert
  89910. * \code decoder != NULL \endcode
  89911. * \a type is valid
  89912. * \retval FLAC__bool
  89913. * \c false if the decoder is already initialized, else \c true.
  89914. */
  89915. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89916. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89917. * the given \a id.
  89918. *
  89919. * \default By default, only the \c STREAMINFO block is returned via the
  89920. * metadata callback.
  89921. * \param decoder A decoder instance to set.
  89922. * \param id See above.
  89923. * \assert
  89924. * \code decoder != NULL \endcode
  89925. * \code id != NULL \endcode
  89926. * \retval FLAC__bool
  89927. * \c false if the decoder is already initialized, else \c true.
  89928. */
  89929. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89930. /** Direct the decoder to filter out all metadata blocks of any type.
  89931. *
  89932. * \default By default, only the \c STREAMINFO block is returned via the
  89933. * metadata callback.
  89934. * \param decoder A decoder instance to set.
  89935. * \assert
  89936. * \code decoder != NULL \endcode
  89937. * \retval FLAC__bool
  89938. * \c false if the decoder is already initialized, else \c true.
  89939. */
  89940. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89941. /** Get the current decoder state.
  89942. *
  89943. * \param decoder A decoder instance to query.
  89944. * \assert
  89945. * \code decoder != NULL \endcode
  89946. * \retval FLAC__StreamDecoderState
  89947. * The current decoder state.
  89948. */
  89949. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89950. /** Get the current decoder state as a C string.
  89951. *
  89952. * \param decoder A decoder instance to query.
  89953. * \assert
  89954. * \code decoder != NULL \endcode
  89955. * \retval const char *
  89956. * The decoder state as a C string. Do not modify the contents.
  89957. */
  89958. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89959. /** Get the "MD5 signature checking" flag.
  89960. * This is the value of the setting, not whether or not the decoder is
  89961. * currently checking the MD5 (remember, it can be turned off automatically
  89962. * by a seek). When the decoder is reset the flag will be restored to the
  89963. * value returned by this function.
  89964. *
  89965. * \param decoder A decoder instance to query.
  89966. * \assert
  89967. * \code decoder != NULL \endcode
  89968. * \retval FLAC__bool
  89969. * See above.
  89970. */
  89971. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89972. /** Get the total number of samples in the stream being decoded.
  89973. * Will only be valid after decoding has started and will contain the
  89974. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89975. *
  89976. * \param decoder A decoder instance to query.
  89977. * \assert
  89978. * \code decoder != NULL \endcode
  89979. * \retval unsigned
  89980. * See above.
  89981. */
  89982. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89983. /** Get the current number of channels in the stream being decoded.
  89984. * Will only be valid after decoding has started and will contain the
  89985. * value from the most recently decoded frame header.
  89986. *
  89987. * \param decoder A decoder instance to query.
  89988. * \assert
  89989. * \code decoder != NULL \endcode
  89990. * \retval unsigned
  89991. * See above.
  89992. */
  89993. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89994. /** Get the current channel assignment in the stream being decoded.
  89995. * Will only be valid after decoding has started and will contain the
  89996. * value from the most recently decoded frame header.
  89997. *
  89998. * \param decoder A decoder instance to query.
  89999. * \assert
  90000. * \code decoder != NULL \endcode
  90001. * \retval FLAC__ChannelAssignment
  90002. * See above.
  90003. */
  90004. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90005. /** Get the current sample resolution in the stream being decoded.
  90006. * Will only be valid after decoding has started and will contain the
  90007. * value from the most recently decoded frame header.
  90008. *
  90009. * \param decoder A decoder instance to query.
  90010. * \assert
  90011. * \code decoder != NULL \endcode
  90012. * \retval unsigned
  90013. * See above.
  90014. */
  90015. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90016. /** Get the current sample rate in Hz of the stream being decoded.
  90017. * Will only be valid after decoding has started and will contain the
  90018. * value from the most recently decoded frame header.
  90019. *
  90020. * \param decoder A decoder instance to query.
  90021. * \assert
  90022. * \code decoder != NULL \endcode
  90023. * \retval unsigned
  90024. * See above.
  90025. */
  90026. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90027. /** Get the current blocksize of the stream being decoded.
  90028. * Will only be valid after decoding has started and will contain the
  90029. * value from the most recently decoded frame header.
  90030. *
  90031. * \param decoder A decoder instance to query.
  90032. * \assert
  90033. * \code decoder != NULL \endcode
  90034. * \retval unsigned
  90035. * See above.
  90036. */
  90037. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90038. /** Returns the decoder's current read position within the stream.
  90039. * The position is the byte offset from the start of the stream.
  90040. * Bytes before this position have been fully decoded. Note that
  90041. * there may still be undecoded bytes in the decoder's read FIFO.
  90042. * The returned position is correct even after a seek.
  90043. *
  90044. * \warning This function currently only works for native FLAC,
  90045. * not Ogg FLAC streams.
  90046. *
  90047. * \param decoder A decoder instance to query.
  90048. * \param position Address at which to return the desired position.
  90049. * \assert
  90050. * \code decoder != NULL \endcode
  90051. * \code position != NULL \endcode
  90052. * \retval FLAC__bool
  90053. * \c true if successful, \c false if the stream is not native FLAC,
  90054. * or there was an error from the 'tell' callback or it returned
  90055. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90056. */
  90057. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90058. /** Initialize the decoder instance to decode native FLAC streams.
  90059. *
  90060. * This flavor of initialization sets up the decoder to decode from a
  90061. * native FLAC stream. I/O is performed via callbacks to the client.
  90062. * For decoding from a plain file via filename or open FILE*,
  90063. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90064. * provide a simpler interface.
  90065. *
  90066. * This function should be called after FLAC__stream_decoder_new() and
  90067. * FLAC__stream_decoder_set_*() but before any of the
  90068. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90069. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90070. * if initialization succeeded.
  90071. *
  90072. * \param decoder An uninitialized decoder instance.
  90073. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90074. * pointer must not be \c NULL.
  90075. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90076. * pointer may be \c NULL if seeking is not
  90077. * supported. If \a seek_callback is not \c NULL then a
  90078. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90079. * Alternatively, a dummy seek callback that just
  90080. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90081. * may also be supplied, all though this is slightly
  90082. * less efficient for the decoder.
  90083. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90084. * pointer may be \c NULL if not supported by the client. If
  90085. * \a seek_callback is not \c NULL then a
  90086. * \a tell_callback must also be supplied.
  90087. * Alternatively, a dummy tell callback that just
  90088. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90089. * may also be supplied, all though this is slightly
  90090. * less efficient for the decoder.
  90091. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90092. * pointer may be \c NULL if not supported by the client. If
  90093. * \a seek_callback is not \c NULL then a
  90094. * \a length_callback must also be supplied.
  90095. * Alternatively, a dummy length callback that just
  90096. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90097. * may also be supplied, all though this is slightly
  90098. * less efficient for the decoder.
  90099. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90100. * pointer may be \c NULL if not supported by the client. If
  90101. * \a seek_callback is not \c NULL then a
  90102. * \a eof_callback must also be supplied.
  90103. * Alternatively, a dummy length callback that just
  90104. * returns \c false
  90105. * may also be supplied, all though this is slightly
  90106. * less efficient for the decoder.
  90107. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90108. * pointer must not be \c NULL.
  90109. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90110. * pointer may be \c NULL if the callback is not
  90111. * desired.
  90112. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90113. * pointer must not be \c NULL.
  90114. * \param client_data This value will be supplied to callbacks in their
  90115. * \a client_data argument.
  90116. * \assert
  90117. * \code decoder != NULL \endcode
  90118. * \retval FLAC__StreamDecoderInitStatus
  90119. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90120. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90121. */
  90122. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90123. FLAC__StreamDecoder *decoder,
  90124. FLAC__StreamDecoderReadCallback read_callback,
  90125. FLAC__StreamDecoderSeekCallback seek_callback,
  90126. FLAC__StreamDecoderTellCallback tell_callback,
  90127. FLAC__StreamDecoderLengthCallback length_callback,
  90128. FLAC__StreamDecoderEofCallback eof_callback,
  90129. FLAC__StreamDecoderWriteCallback write_callback,
  90130. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90131. FLAC__StreamDecoderErrorCallback error_callback,
  90132. void *client_data
  90133. );
  90134. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90135. *
  90136. * This flavor of initialization sets up the decoder to decode from a
  90137. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90138. * client. For decoding from a plain file via filename or open FILE*,
  90139. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90140. * provide a simpler interface.
  90141. *
  90142. * This function should be called after FLAC__stream_decoder_new() and
  90143. * FLAC__stream_decoder_set_*() but before any of the
  90144. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90145. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90146. * if initialization succeeded.
  90147. *
  90148. * \note Support for Ogg FLAC in the library is optional. If this
  90149. * library has been built without support for Ogg FLAC, this function
  90150. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90151. *
  90152. * \param decoder An uninitialized decoder instance.
  90153. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90154. * pointer must not be \c NULL.
  90155. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90156. * pointer may be \c NULL if seeking is not
  90157. * supported. If \a seek_callback is not \c NULL then a
  90158. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90159. * Alternatively, a dummy seek callback that just
  90160. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90161. * may also be supplied, all though this is slightly
  90162. * less efficient for the decoder.
  90163. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90164. * pointer may be \c NULL if not supported by the client. If
  90165. * \a seek_callback is not \c NULL then a
  90166. * \a tell_callback must also be supplied.
  90167. * Alternatively, a dummy tell callback that just
  90168. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90169. * may also be supplied, all though this is slightly
  90170. * less efficient for the decoder.
  90171. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90172. * pointer may be \c NULL if not supported by the client. If
  90173. * \a seek_callback is not \c NULL then a
  90174. * \a length_callback must also be supplied.
  90175. * Alternatively, a dummy length callback that just
  90176. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90177. * may also be supplied, all though this is slightly
  90178. * less efficient for the decoder.
  90179. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90180. * pointer may be \c NULL if not supported by the client. If
  90181. * \a seek_callback is not \c NULL then a
  90182. * \a eof_callback must also be supplied.
  90183. * Alternatively, a dummy length callback that just
  90184. * returns \c false
  90185. * may also be supplied, all though this is slightly
  90186. * less efficient for the decoder.
  90187. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90188. * pointer must not be \c NULL.
  90189. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90190. * pointer may be \c NULL if the callback is not
  90191. * desired.
  90192. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90193. * pointer must not be \c NULL.
  90194. * \param client_data This value will be supplied to callbacks in their
  90195. * \a client_data argument.
  90196. * \assert
  90197. * \code decoder != NULL \endcode
  90198. * \retval FLAC__StreamDecoderInitStatus
  90199. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90200. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90201. */
  90202. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90203. FLAC__StreamDecoder *decoder,
  90204. FLAC__StreamDecoderReadCallback read_callback,
  90205. FLAC__StreamDecoderSeekCallback seek_callback,
  90206. FLAC__StreamDecoderTellCallback tell_callback,
  90207. FLAC__StreamDecoderLengthCallback length_callback,
  90208. FLAC__StreamDecoderEofCallback eof_callback,
  90209. FLAC__StreamDecoderWriteCallback write_callback,
  90210. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90211. FLAC__StreamDecoderErrorCallback error_callback,
  90212. void *client_data
  90213. );
  90214. /** Initialize the decoder instance to decode native FLAC files.
  90215. *
  90216. * This flavor of initialization sets up the decoder to decode from a
  90217. * plain native FLAC file. For non-stdio streams, you must use
  90218. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90219. *
  90220. * This function should be called after FLAC__stream_decoder_new() and
  90221. * FLAC__stream_decoder_set_*() but before any of the
  90222. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90223. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90224. * if initialization succeeded.
  90225. *
  90226. * \param decoder An uninitialized decoder instance.
  90227. * \param file An open FLAC file. The file should have been
  90228. * opened with mode \c "rb" and rewound. The file
  90229. * becomes owned by the decoder and should not be
  90230. * manipulated by the client while decoding.
  90231. * Unless \a file is \c stdin, it will be closed
  90232. * when FLAC__stream_decoder_finish() is called.
  90233. * Note however that seeking will not work when
  90234. * decoding from \c stdout since it is not seekable.
  90235. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90236. * pointer must not be \c NULL.
  90237. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90238. * pointer may be \c NULL if the callback is not
  90239. * desired.
  90240. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90241. * pointer must not be \c NULL.
  90242. * \param client_data This value will be supplied to callbacks in their
  90243. * \a client_data argument.
  90244. * \assert
  90245. * \code decoder != NULL \endcode
  90246. * \code file != NULL \endcode
  90247. * \retval FLAC__StreamDecoderInitStatus
  90248. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90249. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90250. */
  90251. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90252. FLAC__StreamDecoder *decoder,
  90253. FILE *file,
  90254. FLAC__StreamDecoderWriteCallback write_callback,
  90255. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90256. FLAC__StreamDecoderErrorCallback error_callback,
  90257. void *client_data
  90258. );
  90259. /** Initialize the decoder instance to decode Ogg FLAC files.
  90260. *
  90261. * This flavor of initialization sets up the decoder to decode from a
  90262. * plain Ogg FLAC file. For non-stdio streams, you must use
  90263. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90264. *
  90265. * This function should be called after FLAC__stream_decoder_new() and
  90266. * FLAC__stream_decoder_set_*() but before any of the
  90267. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90268. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90269. * if initialization succeeded.
  90270. *
  90271. * \note Support for Ogg FLAC in the library is optional. If this
  90272. * library has been built without support for Ogg FLAC, this function
  90273. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90274. *
  90275. * \param decoder An uninitialized decoder instance.
  90276. * \param file An open FLAC file. The file should have been
  90277. * opened with mode \c "rb" and rewound. The file
  90278. * becomes owned by the decoder and should not be
  90279. * manipulated by the client while decoding.
  90280. * Unless \a file is \c stdin, it will be closed
  90281. * when FLAC__stream_decoder_finish() is called.
  90282. * Note however that seeking will not work when
  90283. * decoding from \c stdout since it is not seekable.
  90284. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90285. * pointer must not be \c NULL.
  90286. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90287. * pointer may be \c NULL if the callback is not
  90288. * desired.
  90289. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90290. * pointer must not be \c NULL.
  90291. * \param client_data This value will be supplied to callbacks in their
  90292. * \a client_data argument.
  90293. * \assert
  90294. * \code decoder != NULL \endcode
  90295. * \code file != NULL \endcode
  90296. * \retval FLAC__StreamDecoderInitStatus
  90297. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90298. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90299. */
  90300. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90301. FLAC__StreamDecoder *decoder,
  90302. FILE *file,
  90303. FLAC__StreamDecoderWriteCallback write_callback,
  90304. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90305. FLAC__StreamDecoderErrorCallback error_callback,
  90306. void *client_data
  90307. );
  90308. /** Initialize the decoder instance to decode native FLAC files.
  90309. *
  90310. * This flavor of initialization sets up the decoder to decode from a plain
  90311. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90312. * example, with Unicode filenames on Windows), you must use
  90313. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90314. * and provide callbacks for the I/O.
  90315. *
  90316. * This function should be called after FLAC__stream_decoder_new() and
  90317. * FLAC__stream_decoder_set_*() but before any of the
  90318. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90319. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90320. * if initialization succeeded.
  90321. *
  90322. * \param decoder An uninitialized decoder instance.
  90323. * \param filename The name of the file to decode from. The file will
  90324. * be opened with fopen(). Use \c NULL to decode from
  90325. * \c stdin. Note that \c stdin is not seekable.
  90326. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90327. * pointer must not be \c NULL.
  90328. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90329. * pointer may be \c NULL if the callback is not
  90330. * desired.
  90331. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90332. * pointer must not be \c NULL.
  90333. * \param client_data This value will be supplied to callbacks in their
  90334. * \a client_data argument.
  90335. * \assert
  90336. * \code decoder != NULL \endcode
  90337. * \retval FLAC__StreamDecoderInitStatus
  90338. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90339. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90340. */
  90341. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90342. FLAC__StreamDecoder *decoder,
  90343. const char *filename,
  90344. FLAC__StreamDecoderWriteCallback write_callback,
  90345. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90346. FLAC__StreamDecoderErrorCallback error_callback,
  90347. void *client_data
  90348. );
  90349. /** Initialize the decoder instance to decode Ogg FLAC files.
  90350. *
  90351. * This flavor of initialization sets up the decoder to decode from a plain
  90352. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90353. * example, with Unicode filenames on Windows), you must use
  90354. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90355. * and provide callbacks for the I/O.
  90356. *
  90357. * This function should be called after FLAC__stream_decoder_new() and
  90358. * FLAC__stream_decoder_set_*() but before any of the
  90359. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90360. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90361. * if initialization succeeded.
  90362. *
  90363. * \note Support for Ogg FLAC in the library is optional. If this
  90364. * library has been built without support for Ogg FLAC, this function
  90365. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90366. *
  90367. * \param decoder An uninitialized decoder instance.
  90368. * \param filename The name of the file to decode from. The file will
  90369. * be opened with fopen(). Use \c NULL to decode from
  90370. * \c stdin. Note that \c stdin is not seekable.
  90371. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90372. * pointer must not be \c NULL.
  90373. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90374. * pointer may be \c NULL if the callback is not
  90375. * desired.
  90376. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90377. * pointer must not be \c NULL.
  90378. * \param client_data This value will be supplied to callbacks in their
  90379. * \a client_data argument.
  90380. * \assert
  90381. * \code decoder != NULL \endcode
  90382. * \retval FLAC__StreamDecoderInitStatus
  90383. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90384. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90385. */
  90386. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90387. FLAC__StreamDecoder *decoder,
  90388. const char *filename,
  90389. FLAC__StreamDecoderWriteCallback write_callback,
  90390. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90391. FLAC__StreamDecoderErrorCallback error_callback,
  90392. void *client_data
  90393. );
  90394. /** Finish the decoding process.
  90395. * Flushes the decoding buffer, releases resources, resets the decoder
  90396. * settings to their defaults, and returns the decoder state to
  90397. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90398. *
  90399. * In the event of a prematurely-terminated decode, it is not strictly
  90400. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90401. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90402. * with a FLAC__stream_decoder_finish().
  90403. *
  90404. * \param decoder An uninitialized decoder instance.
  90405. * \assert
  90406. * \code decoder != NULL \endcode
  90407. * \retval FLAC__bool
  90408. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90409. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90410. * signature does not match the one computed by the decoder; else
  90411. * \c true.
  90412. */
  90413. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90414. /** Flush the stream input.
  90415. * The decoder's input buffer will be cleared and the state set to
  90416. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90417. * off MD5 checking.
  90418. *
  90419. * \param decoder A decoder instance.
  90420. * \assert
  90421. * \code decoder != NULL \endcode
  90422. * \retval FLAC__bool
  90423. * \c true if successful, else \c false if a memory allocation
  90424. * error occurs (in which case the state will be set to
  90425. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90426. */
  90427. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90428. /** Reset the decoding process.
  90429. * The decoder's input buffer will be cleared and the state set to
  90430. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90431. * FLAC__stream_decoder_finish() except that the settings are
  90432. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90433. * before decoding again. MD5 checking will be restored to its original
  90434. * setting.
  90435. *
  90436. * If the decoder is seekable, or was initialized with
  90437. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90438. * the decoder will also attempt to seek to the beginning of the file.
  90439. * If this rewind fails, this function will return \c false. It follows
  90440. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90441. * \c stdin.
  90442. *
  90443. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90444. * and is not seekable (i.e. no seek callback was provided or the seek
  90445. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90446. * is the duty of the client to start feeding data from the beginning of
  90447. * the stream on the next FLAC__stream_decoder_process() or
  90448. * FLAC__stream_decoder_process_interleaved() call.
  90449. *
  90450. * \param decoder A decoder instance.
  90451. * \assert
  90452. * \code decoder != NULL \endcode
  90453. * \retval FLAC__bool
  90454. * \c true if successful, else \c false if a memory allocation occurs
  90455. * (in which case the state will be set to
  90456. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90457. * occurs (the state will be unchanged).
  90458. */
  90459. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90460. /** Decode one metadata block or audio frame.
  90461. * This version instructs the decoder to decode a either a single metadata
  90462. * block or a single frame and stop, unless the callbacks return a fatal
  90463. * error or the read callback returns
  90464. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90465. *
  90466. * As the decoder needs more input it will call the read callback.
  90467. * Depending on what was decoded, the metadata or write callback will be
  90468. * called with the decoded metadata block or audio frame.
  90469. *
  90470. * Unless there is a fatal read error or end of stream, this function
  90471. * will return once one whole frame is decoded. In other words, if the
  90472. * stream is not synchronized or points to a corrupt frame header, the
  90473. * decoder will continue to try and resync until it gets to a valid
  90474. * frame, then decode one frame, then return. If the decoder points to
  90475. * a frame whose frame CRC in the frame footer does not match the
  90476. * computed frame CRC, this function will issue a
  90477. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90478. * error callback, and return, having decoded one complete, although
  90479. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90480. * correct length to the write callback.)
  90481. *
  90482. * \param decoder An initialized decoder instance.
  90483. * \assert
  90484. * \code decoder != NULL \endcode
  90485. * \retval FLAC__bool
  90486. * \c false if any fatal read, write, or memory allocation error
  90487. * occurred (meaning decoding must stop), else \c true; for more
  90488. * information about the decoder, check the decoder state with
  90489. * FLAC__stream_decoder_get_state().
  90490. */
  90491. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90492. /** Decode until the end of the metadata.
  90493. * This version instructs the decoder to decode from the current position
  90494. * and continue until all the metadata has been read, or until the
  90495. * callbacks return a fatal error or the read callback returns
  90496. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90497. *
  90498. * As the decoder needs more input it will call the read callback.
  90499. * As each metadata block is decoded, the metadata callback will be called
  90500. * with the decoded metadata.
  90501. *
  90502. * \param decoder An initialized decoder instance.
  90503. * \assert
  90504. * \code decoder != NULL \endcode
  90505. * \retval FLAC__bool
  90506. * \c false if any fatal read, write, or memory allocation error
  90507. * occurred (meaning decoding must stop), else \c true; for more
  90508. * information about the decoder, check the decoder state with
  90509. * FLAC__stream_decoder_get_state().
  90510. */
  90511. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90512. /** Decode until the end of the stream.
  90513. * This version instructs the decoder to decode from the current position
  90514. * and continue until the end of stream (the read callback returns
  90515. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90516. * callbacks return a fatal error.
  90517. *
  90518. * As the decoder needs more input it will call the read callback.
  90519. * As each metadata block and frame is decoded, the metadata or write
  90520. * callback will be called with the decoded metadata or frame.
  90521. *
  90522. * \param decoder An initialized decoder instance.
  90523. * \assert
  90524. * \code decoder != NULL \endcode
  90525. * \retval FLAC__bool
  90526. * \c false if any fatal read, write, or memory allocation error
  90527. * occurred (meaning decoding must stop), else \c true; for more
  90528. * information about the decoder, check the decoder state with
  90529. * FLAC__stream_decoder_get_state().
  90530. */
  90531. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90532. /** Skip one audio frame.
  90533. * This version instructs the decoder to 'skip' a single frame and stop,
  90534. * unless the callbacks return a fatal error or the read callback returns
  90535. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90536. *
  90537. * The decoding flow is the same as what occurs when
  90538. * FLAC__stream_decoder_process_single() is called to process an audio
  90539. * frame, except that this function does not decode the parsed data into
  90540. * PCM or call the write callback. The integrity of the frame is still
  90541. * checked the same way as in the other process functions.
  90542. *
  90543. * This function will return once one whole frame is skipped, in the
  90544. * same way that FLAC__stream_decoder_process_single() will return once
  90545. * one whole frame is decoded.
  90546. *
  90547. * This function can be used in more quickly determining FLAC frame
  90548. * boundaries when decoding of the actual data is not needed, for
  90549. * example when an application is separating a FLAC stream into frames
  90550. * for editing or storing in a container. To do this, the application
  90551. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90552. * to the next frame, then use
  90553. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90554. * boundary.
  90555. *
  90556. * This function should only be called when the stream has advanced
  90557. * past all the metadata, otherwise it will return \c false.
  90558. *
  90559. * \param decoder An initialized decoder instance not in a metadata
  90560. * state.
  90561. * \assert
  90562. * \code decoder != NULL \endcode
  90563. * \retval FLAC__bool
  90564. * \c false if any fatal read, write, or memory allocation error
  90565. * occurred (meaning decoding must stop), or if the decoder
  90566. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90567. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90568. * information about the decoder, check the decoder state with
  90569. * FLAC__stream_decoder_get_state().
  90570. */
  90571. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90572. /** Flush the input and seek to an absolute sample.
  90573. * Decoding will resume at the given sample. Note that because of
  90574. * this, the next write callback may contain a partial block. The
  90575. * client must support seeking the input or this function will fail
  90576. * and return \c false. Furthermore, if the decoder state is
  90577. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90578. * with FLAC__stream_decoder_flush() or reset with
  90579. * FLAC__stream_decoder_reset() before decoding can continue.
  90580. *
  90581. * \param decoder A decoder instance.
  90582. * \param sample The target sample number to seek to.
  90583. * \assert
  90584. * \code decoder != NULL \endcode
  90585. * \retval FLAC__bool
  90586. * \c true if successful, else \c false.
  90587. */
  90588. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90589. /* \} */
  90590. #ifdef __cplusplus
  90591. }
  90592. #endif
  90593. #endif
  90594. /*** End of inlined file: stream_decoder.h ***/
  90595. /*** Start of inlined file: stream_encoder.h ***/
  90596. #ifndef FLAC__STREAM_ENCODER_H
  90597. #define FLAC__STREAM_ENCODER_H
  90598. #include <stdio.h> /* for FILE */
  90599. #ifdef __cplusplus
  90600. extern "C" {
  90601. #endif
  90602. /** \file include/FLAC/stream_encoder.h
  90603. *
  90604. * \brief
  90605. * This module contains the functions which implement the stream
  90606. * encoder.
  90607. *
  90608. * See the detailed documentation in the
  90609. * \link flac_stream_encoder stream encoder \endlink module.
  90610. */
  90611. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90612. * \ingroup flac
  90613. *
  90614. * \brief
  90615. * This module describes the encoder layers provided by libFLAC.
  90616. *
  90617. * The stream encoder can be used to encode complete streams either to the
  90618. * client via callbacks, or directly to a file, depending on how it is
  90619. * initialized. When encoding via callbacks, the client provides a write
  90620. * callback which will be called whenever FLAC data is ready to be written.
  90621. * If the client also supplies a seek callback, the encoder will also
  90622. * automatically handle the writing back of metadata discovered while
  90623. * encoding, like stream info, seek points offsets, etc. When encoding to
  90624. * a file, the client needs only supply a filename or open \c FILE* and an
  90625. * optional progress callback for periodic notification of progress; the
  90626. * write and seek callbacks are supplied internally. For more info see the
  90627. * \link flac_stream_encoder stream encoder \endlink module.
  90628. */
  90629. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90630. * \ingroup flac_encoder
  90631. *
  90632. * \brief
  90633. * This module contains the functions which implement the stream
  90634. * encoder.
  90635. *
  90636. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90637. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90638. *
  90639. * The basic usage of this encoder is as follows:
  90640. * - The program creates an instance of an encoder using
  90641. * FLAC__stream_encoder_new().
  90642. * - The program overrides the default settings using
  90643. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90644. * functions should be called:
  90645. * - FLAC__stream_encoder_set_channels()
  90646. * - FLAC__stream_encoder_set_bits_per_sample()
  90647. * - FLAC__stream_encoder_set_sample_rate()
  90648. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90649. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90650. * - If the application wants to control the compression level or set its own
  90651. * metadata, then the following should also be called:
  90652. * - FLAC__stream_encoder_set_compression_level()
  90653. * - FLAC__stream_encoder_set_verify()
  90654. * - FLAC__stream_encoder_set_metadata()
  90655. * - The rest of the set functions should only be called if the client needs
  90656. * exact control over how the audio is compressed; thorough understanding
  90657. * of the FLAC format is necessary to achieve good results.
  90658. * - The program initializes the instance to validate the settings and
  90659. * prepare for encoding using
  90660. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90661. * or FLAC__stream_encoder_init_file() for native FLAC
  90662. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90663. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90664. * - The program calls FLAC__stream_encoder_process() or
  90665. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90666. * subsequently calls the callbacks when there is encoder data ready
  90667. * to be written.
  90668. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90669. * which causes the encoder to encode any data still in its input pipe,
  90670. * update the metadata with the final encoding statistics if output
  90671. * seeking is possible, and finally reset the encoder to the
  90672. * uninitialized state.
  90673. * - The instance may be used again or deleted with
  90674. * FLAC__stream_encoder_delete().
  90675. *
  90676. * In more detail, the stream encoder functions similarly to the
  90677. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90678. * callbacks and more options. Typically the client will create a new
  90679. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90680. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90681. * calling one of the FLAC__stream_encoder_init_*() functions.
  90682. *
  90683. * Unlike the decoders, the stream encoder has many options that can
  90684. * affect the speed and compression ratio. When setting these parameters
  90685. * you should have some basic knowledge of the format (see the
  90686. * <A HREF="../documentation.html#format">user-level documentation</A>
  90687. * or the <A HREF="../format.html">formal description</A>). The
  90688. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90689. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90690. * functions will do this, so make sure to pay attention to the state
  90691. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90692. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90693. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90694. * the constructor.
  90695. *
  90696. * There are three initialization functions for native FLAC, one for
  90697. * setting up the encoder to encode FLAC data to the client via
  90698. * callbacks, and two for encoding directly to a file.
  90699. *
  90700. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90701. * You must also supply a write callback which will be called anytime
  90702. * there is raw encoded data to write. If the client can seek the output
  90703. * it is best to also supply seek and tell callbacks, as this allows the
  90704. * encoder to go back after encoding is finished to write back
  90705. * information that was collected while encoding, like seek point offsets,
  90706. * frame sizes, etc.
  90707. *
  90708. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90709. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90710. * filename or open \c FILE*; the encoder will handle all the callbacks
  90711. * internally. You may also supply a progress callback for periodic
  90712. * notification of the encoding progress.
  90713. *
  90714. * There are three similarly-named init functions for encoding to Ogg
  90715. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90716. * library has been built with Ogg support.
  90717. *
  90718. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90719. * call the write callback several times, once with the \c fLaC signature,
  90720. * and once for each encoded metadata block. Note that for Ogg FLAC
  90721. * encoding you will usually get at least twice the number of callbacks than
  90722. * with native FLAC, one for the Ogg page header and one for the page body.
  90723. *
  90724. * After initializing the instance, the client may feed audio data to the
  90725. * encoder in one of two ways:
  90726. *
  90727. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90728. * will pass an array of pointers to buffers, one for each channel, to
  90729. * the encoder, each of the same length. The samples need not be
  90730. * block-aligned, but each channel should have the same number of samples.
  90731. * - Channel interleaved, through
  90732. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90733. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90734. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90735. * Again, the samples need not be block-aligned but they must be
  90736. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90737. * the last value channelN_sampleM.
  90738. *
  90739. * Note that for either process call, each sample in the buffers should be a
  90740. * signed integer, right-justified to the resolution set by
  90741. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90742. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90743. *
  90744. * When the client is finished encoding data, it calls
  90745. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90746. * data still in its input pipe, and call the metadata callback with the
  90747. * final encoding statistics. Then the instance may be deleted with
  90748. * FLAC__stream_encoder_delete() or initialized again to encode another
  90749. * stream.
  90750. *
  90751. * For programs that write their own metadata, but that do not know the
  90752. * actual metadata until after encoding, it is advantageous to instruct
  90753. * the encoder to write a PADDING block of the correct size, so that
  90754. * instead of rewriting the whole stream after encoding, the program can
  90755. * just overwrite the PADDING block. If only the maximum size of the
  90756. * metadata is known, the program can write a slightly larger padding
  90757. * block, then split it after encoding.
  90758. *
  90759. * Make sure you understand how lengths are calculated. All FLAC metadata
  90760. * blocks have a 4 byte header which contains the type and length. This
  90761. * length does not include the 4 bytes of the header. See the format page
  90762. * for the specification of metadata blocks and their lengths.
  90763. *
  90764. * \note
  90765. * If you are writing the FLAC data to a file via callbacks, make sure it
  90766. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90767. * after the first encoding pass, the encoder will try to seek back to the
  90768. * beginning of the stream, to the STREAMINFO block, to write some data
  90769. * there. (If using FLAC__stream_encoder_init*_file() or
  90770. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90771. *
  90772. * \note
  90773. * The "set" functions may only be called when the encoder is in the
  90774. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90775. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90776. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90777. * return \c true, otherwise \c false.
  90778. *
  90779. * \note
  90780. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90781. * defaults.
  90782. *
  90783. * \{
  90784. */
  90785. /** State values for a FLAC__StreamEncoder.
  90786. *
  90787. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90788. *
  90789. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90790. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90791. * must be deleted with FLAC__stream_encoder_delete().
  90792. */
  90793. typedef enum {
  90794. FLAC__STREAM_ENCODER_OK = 0,
  90795. /**< The encoder is in the normal OK state and samples can be processed. */
  90796. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90797. /**< The encoder is in the uninitialized state; one of the
  90798. * FLAC__stream_encoder_init_*() functions must be called before samples
  90799. * can be processed.
  90800. */
  90801. FLAC__STREAM_ENCODER_OGG_ERROR,
  90802. /**< An error occurred in the underlying Ogg layer. */
  90803. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90804. /**< An error occurred in the underlying verify stream decoder;
  90805. * check FLAC__stream_encoder_get_verify_decoder_state().
  90806. */
  90807. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90808. /**< The verify decoder detected a mismatch between the original
  90809. * audio signal and the decoded audio signal.
  90810. */
  90811. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90812. /**< One of the callbacks returned a fatal error. */
  90813. FLAC__STREAM_ENCODER_IO_ERROR,
  90814. /**< An I/O error occurred while opening/reading/writing a file.
  90815. * Check \c errno.
  90816. */
  90817. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90818. /**< An error occurred while writing the stream; usually, the
  90819. * write_callback returned an error.
  90820. */
  90821. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90822. /**< Memory allocation failed. */
  90823. } FLAC__StreamEncoderState;
  90824. /** Maps a FLAC__StreamEncoderState to a C string.
  90825. *
  90826. * Using a FLAC__StreamEncoderState as the index to this array
  90827. * will give the string equivalent. The contents should not be modified.
  90828. */
  90829. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90830. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90831. */
  90832. typedef enum {
  90833. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90834. /**< Initialization was successful. */
  90835. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90836. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90837. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90838. /**< The library was not compiled with support for the given container
  90839. * format.
  90840. */
  90841. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90842. /**< A required callback was not supplied. */
  90843. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90844. /**< The encoder has an invalid setting for number of channels. */
  90845. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90846. /**< The encoder has an invalid setting for bits-per-sample.
  90847. * FLAC supports 4-32 bps but the reference encoder currently supports
  90848. * only up to 24 bps.
  90849. */
  90850. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90851. /**< The encoder has an invalid setting for the input sample rate. */
  90852. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90853. /**< The encoder has an invalid setting for the block size. */
  90854. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90855. /**< The encoder has an invalid setting for the maximum LPC order. */
  90856. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90857. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90858. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90859. /**< The specified block size is less than the maximum LPC order. */
  90860. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90861. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90862. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90863. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90864. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90865. * - One of the metadata blocks contains an undefined type
  90866. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90867. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90868. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90869. */
  90870. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90871. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90872. * already initialized, usually because
  90873. * FLAC__stream_encoder_finish() was not called.
  90874. */
  90875. } FLAC__StreamEncoderInitStatus;
  90876. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90877. *
  90878. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90879. * will give the string equivalent. The contents should not be modified.
  90880. */
  90881. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90882. /** Return values for the FLAC__StreamEncoder read callback.
  90883. */
  90884. typedef enum {
  90885. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90886. /**< The read was OK and decoding can continue. */
  90887. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90888. /**< The read was attempted at the end of the stream. */
  90889. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90890. /**< An unrecoverable error occurred. */
  90891. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90892. /**< Client does not support reading back from the output. */
  90893. } FLAC__StreamEncoderReadStatus;
  90894. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90895. *
  90896. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90897. * will give the string equivalent. The contents should not be modified.
  90898. */
  90899. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90900. /** Return values for the FLAC__StreamEncoder write callback.
  90901. */
  90902. typedef enum {
  90903. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90904. /**< The write was OK and encoding can continue. */
  90905. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90906. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90907. } FLAC__StreamEncoderWriteStatus;
  90908. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90909. *
  90910. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90911. * will give the string equivalent. The contents should not be modified.
  90912. */
  90913. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90914. /** Return values for the FLAC__StreamEncoder seek callback.
  90915. */
  90916. typedef enum {
  90917. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90918. /**< The seek was OK and encoding can continue. */
  90919. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90920. /**< An unrecoverable error occurred. */
  90921. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90922. /**< Client does not support seeking. */
  90923. } FLAC__StreamEncoderSeekStatus;
  90924. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90925. *
  90926. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90927. * will give the string equivalent. The contents should not be modified.
  90928. */
  90929. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90930. /** Return values for the FLAC__StreamEncoder tell callback.
  90931. */
  90932. typedef enum {
  90933. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90934. /**< The tell was OK and encoding can continue. */
  90935. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90936. /**< An unrecoverable error occurred. */
  90937. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90938. /**< Client does not support seeking. */
  90939. } FLAC__StreamEncoderTellStatus;
  90940. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90941. *
  90942. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90943. * will give the string equivalent. The contents should not be modified.
  90944. */
  90945. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90946. /***********************************************************************
  90947. *
  90948. * class FLAC__StreamEncoder
  90949. *
  90950. ***********************************************************************/
  90951. struct FLAC__StreamEncoderProtected;
  90952. struct FLAC__StreamEncoderPrivate;
  90953. /** The opaque structure definition for the stream encoder type.
  90954. * See the \link flac_stream_encoder stream encoder module \endlink
  90955. * for a detailed description.
  90956. */
  90957. typedef struct {
  90958. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90959. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90960. } FLAC__StreamEncoder;
  90961. /** Signature for the read callback.
  90962. *
  90963. * A function pointer matching this signature must be passed to
  90964. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90965. * The supplied function will be called when the encoder needs to read back
  90966. * encoded data. This happens during the metadata callback, when the encoder
  90967. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90968. * while encoding. The address of the buffer to be filled is supplied, along
  90969. * with the number of bytes the buffer can hold. The callback may choose to
  90970. * supply less data and modify the byte count but must be careful not to
  90971. * overflow the buffer. The callback then returns a status code chosen from
  90972. * FLAC__StreamEncoderReadStatus.
  90973. *
  90974. * Here is an example of a read callback for stdio streams:
  90975. * \code
  90976. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90977. * {
  90978. * FILE *file = ((MyClientData*)client_data)->file;
  90979. * if(*bytes > 0) {
  90980. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90981. * if(ferror(file))
  90982. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90983. * else if(*bytes == 0)
  90984. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90985. * else
  90986. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90987. * }
  90988. * else
  90989. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90990. * }
  90991. * \endcode
  90992. *
  90993. * \note In general, FLAC__StreamEncoder functions which change the
  90994. * state should not be called on the \a encoder while in the callback.
  90995. *
  90996. * \param encoder The encoder instance calling the callback.
  90997. * \param buffer A pointer to a location for the callee to store
  90998. * data to be encoded.
  90999. * \param bytes A pointer to the size of the buffer. On entry
  91000. * to the callback, it contains the maximum number
  91001. * of bytes that may be stored in \a buffer. The
  91002. * callee must set it to the actual number of bytes
  91003. * stored (0 in case of error or end-of-stream) before
  91004. * returning.
  91005. * \param client_data The callee's client data set through
  91006. * FLAC__stream_encoder_set_client_data().
  91007. * \retval FLAC__StreamEncoderReadStatus
  91008. * The callee's return status.
  91009. */
  91010. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91011. /** Signature for the write callback.
  91012. *
  91013. * A function pointer matching this signature must be passed to
  91014. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91015. * by the encoder anytime there is raw encoded data ready to write. It may
  91016. * include metadata mixed with encoded audio frames and the data is not
  91017. * guaranteed to be aligned on frame or metadata block boundaries.
  91018. *
  91019. * The only duty of the callback is to write out the \a bytes worth of data
  91020. * in \a buffer to the current position in the output stream. The arguments
  91021. * \a samples and \a current_frame are purely informational. If \a samples
  91022. * is greater than \c 0, then \a current_frame will hold the current frame
  91023. * number that is being written; otherwise it indicates that the write
  91024. * callback is being called to write metadata.
  91025. *
  91026. * \note
  91027. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91028. * write callback will be called twice when writing each audio
  91029. * frame; once for the page header, and once for the page body.
  91030. * When writing the page header, the \a samples argument to the
  91031. * write callback will be \c 0.
  91032. *
  91033. * \note In general, FLAC__StreamEncoder functions which change the
  91034. * state should not be called on the \a encoder while in the callback.
  91035. *
  91036. * \param encoder The encoder instance calling the callback.
  91037. * \param buffer An array of encoded data of length \a bytes.
  91038. * \param bytes The byte length of \a buffer.
  91039. * \param samples The number of samples encoded by \a buffer.
  91040. * \c 0 has a special meaning; see above.
  91041. * \param current_frame The number of the current frame being encoded.
  91042. * \param client_data The callee's client data set through
  91043. * FLAC__stream_encoder_init_*().
  91044. * \retval FLAC__StreamEncoderWriteStatus
  91045. * The callee's return status.
  91046. */
  91047. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91048. /** Signature for the seek callback.
  91049. *
  91050. * A function pointer matching this signature may be passed to
  91051. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91052. * when the encoder needs to seek the output stream. The encoder will pass
  91053. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91054. *
  91055. * Here is an example of a seek callback for stdio streams:
  91056. * \code
  91057. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91058. * {
  91059. * FILE *file = ((MyClientData*)client_data)->file;
  91060. * if(file == stdin)
  91061. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91062. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91063. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91064. * else
  91065. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91066. * }
  91067. * \endcode
  91068. *
  91069. * \note In general, FLAC__StreamEncoder functions which change the
  91070. * state should not be called on the \a encoder while in the callback.
  91071. *
  91072. * \param encoder The encoder instance calling the callback.
  91073. * \param absolute_byte_offset The offset from the beginning of the stream
  91074. * to seek to.
  91075. * \param client_data The callee's client data set through
  91076. * FLAC__stream_encoder_init_*().
  91077. * \retval FLAC__StreamEncoderSeekStatus
  91078. * The callee's return status.
  91079. */
  91080. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91081. /** Signature for the tell callback.
  91082. *
  91083. * A function pointer matching this signature may be passed to
  91084. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91085. * when the encoder needs to know the current position of the output stream.
  91086. *
  91087. * \warning
  91088. * The callback must return the true current byte offset of the output to
  91089. * which the encoder is writing. If you are buffering the output, make
  91090. * sure and take this into account. If you are writing directly to a
  91091. * FILE* from your write callback, ftell() is sufficient. If you are
  91092. * writing directly to a file descriptor from your write callback, you
  91093. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91094. * these points to rewrite metadata after encoding.
  91095. *
  91096. * Here is an example of a tell callback for stdio streams:
  91097. * \code
  91098. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91099. * {
  91100. * FILE *file = ((MyClientData*)client_data)->file;
  91101. * off_t pos;
  91102. * if(file == stdin)
  91103. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91104. * else if((pos = ftello(file)) < 0)
  91105. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91106. * else {
  91107. * *absolute_byte_offset = (FLAC__uint64)pos;
  91108. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91109. * }
  91110. * }
  91111. * \endcode
  91112. *
  91113. * \note In general, FLAC__StreamEncoder functions which change the
  91114. * state should not be called on the \a encoder while in the callback.
  91115. *
  91116. * \param encoder The encoder instance calling the callback.
  91117. * \param absolute_byte_offset The address at which to store the current
  91118. * position of the output.
  91119. * \param client_data The callee's client data set through
  91120. * FLAC__stream_encoder_init_*().
  91121. * \retval FLAC__StreamEncoderTellStatus
  91122. * The callee's return status.
  91123. */
  91124. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91125. /** Signature for the metadata callback.
  91126. *
  91127. * A function pointer matching this signature may be passed to
  91128. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91129. * once at the end of encoding with the populated STREAMINFO structure. This
  91130. * is so the client can seek back to the beginning of the file and write the
  91131. * STREAMINFO block with the correct statistics after encoding (like
  91132. * minimum/maximum frame size and total samples).
  91133. *
  91134. * \note In general, FLAC__StreamEncoder functions which change the
  91135. * state should not be called on the \a encoder while in the callback.
  91136. *
  91137. * \param encoder The encoder instance calling the callback.
  91138. * \param metadata The final populated STREAMINFO block.
  91139. * \param client_data The callee's client data set through
  91140. * FLAC__stream_encoder_init_*().
  91141. */
  91142. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91143. /** Signature for the progress callback.
  91144. *
  91145. * A function pointer matching this signature may be passed to
  91146. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91147. * The supplied function will be called when the encoder has finished
  91148. * writing a frame. The \c total_frames_estimate argument to the
  91149. * callback will be based on the value from
  91150. * FLAC__stream_encoder_set_total_samples_estimate().
  91151. *
  91152. * \note In general, FLAC__StreamEncoder functions which change the
  91153. * state should not be called on the \a encoder while in the callback.
  91154. *
  91155. * \param encoder The encoder instance calling the callback.
  91156. * \param bytes_written Bytes written so far.
  91157. * \param samples_written Samples written so far.
  91158. * \param frames_written Frames written so far.
  91159. * \param total_frames_estimate The estimate of the total number of
  91160. * frames to be written.
  91161. * \param client_data The callee's client data set through
  91162. * FLAC__stream_encoder_init_*().
  91163. */
  91164. 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);
  91165. /***********************************************************************
  91166. *
  91167. * Class constructor/destructor
  91168. *
  91169. ***********************************************************************/
  91170. /** Create a new stream encoder instance. The instance is created with
  91171. * default settings; see the individual FLAC__stream_encoder_set_*()
  91172. * functions for each setting's default.
  91173. *
  91174. * \retval FLAC__StreamEncoder*
  91175. * \c NULL if there was an error allocating memory, else the new instance.
  91176. */
  91177. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91178. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91179. *
  91180. * \param encoder A pointer to an existing encoder.
  91181. * \assert
  91182. * \code encoder != NULL \endcode
  91183. */
  91184. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91185. /***********************************************************************
  91186. *
  91187. * Public class method prototypes
  91188. *
  91189. ***********************************************************************/
  91190. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91191. *
  91192. * \note
  91193. * This does not need to be set for native FLAC encoding.
  91194. *
  91195. * \note
  91196. * It is recommended to set a serial number explicitly as the default of '0'
  91197. * may collide with other streams.
  91198. *
  91199. * \default \c 0
  91200. * \param encoder An encoder instance to set.
  91201. * \param serial_number See above.
  91202. * \assert
  91203. * \code encoder != NULL \endcode
  91204. * \retval FLAC__bool
  91205. * \c false if the encoder is already initialized, else \c true.
  91206. */
  91207. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91208. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91209. * encoded output by feeding it through an internal decoder and comparing
  91210. * the original signal against the decoded signal. If a mismatch occurs,
  91211. * the process call will return \c false. Note that this will slow the
  91212. * encoding process by the extra time required for decoding and comparison.
  91213. *
  91214. * \default \c false
  91215. * \param encoder An encoder instance to set.
  91216. * \param value Flag value (see above).
  91217. * \assert
  91218. * \code encoder != NULL \endcode
  91219. * \retval FLAC__bool
  91220. * \c false if the encoder is already initialized, else \c true.
  91221. */
  91222. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91223. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91224. * the encoder will comply with the Subset and will check the
  91225. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91226. * comply. If \c false, the settings may take advantage of the full
  91227. * range that the format allows.
  91228. *
  91229. * Make sure you know what it entails before setting this to \c false.
  91230. *
  91231. * \default \c true
  91232. * \param encoder An encoder instance to set.
  91233. * \param value Flag value (see above).
  91234. * \assert
  91235. * \code encoder != NULL \endcode
  91236. * \retval FLAC__bool
  91237. * \c false if the encoder is already initialized, else \c true.
  91238. */
  91239. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91240. /** Set the number of channels to be encoded.
  91241. *
  91242. * \default \c 2
  91243. * \param encoder An encoder instance to set.
  91244. * \param value See above.
  91245. * \assert
  91246. * \code encoder != NULL \endcode
  91247. * \retval FLAC__bool
  91248. * \c false if the encoder is already initialized, else \c true.
  91249. */
  91250. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91251. /** Set the sample resolution of the input to be encoded.
  91252. *
  91253. * \warning
  91254. * Do not feed the encoder data that is wider than the value you
  91255. * set here or you will generate an invalid stream.
  91256. *
  91257. * \default \c 16
  91258. * \param encoder An encoder instance to set.
  91259. * \param value See above.
  91260. * \assert
  91261. * \code encoder != NULL \endcode
  91262. * \retval FLAC__bool
  91263. * \c false if the encoder is already initialized, else \c true.
  91264. */
  91265. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91266. /** Set the sample rate (in Hz) of the input to be encoded.
  91267. *
  91268. * \default \c 44100
  91269. * \param encoder An encoder instance to set.
  91270. * \param value See above.
  91271. * \assert
  91272. * \code encoder != NULL \endcode
  91273. * \retval FLAC__bool
  91274. * \c false if the encoder is already initialized, else \c true.
  91275. */
  91276. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91277. /** Set the compression level
  91278. *
  91279. * The compression level is roughly proportional to the amount of effort
  91280. * the encoder expends to compress the file. A higher level usually
  91281. * means more computation but higher compression. The default level is
  91282. * suitable for most applications.
  91283. *
  91284. * Currently the levels range from \c 0 (fastest, least compression) to
  91285. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91286. * treated as \c 8.
  91287. *
  91288. * This function automatically calls the following other \c _set_
  91289. * functions with appropriate values, so the client does not need to
  91290. * unless it specifically wants to override them:
  91291. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91292. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91293. * - FLAC__stream_encoder_set_apodization()
  91294. * - FLAC__stream_encoder_set_max_lpc_order()
  91295. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91296. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91297. * - FLAC__stream_encoder_set_do_escape_coding()
  91298. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91299. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91300. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91301. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91302. *
  91303. * The actual values set for each level are:
  91304. * <table>
  91305. * <tr>
  91306. * <td><b>level</b><td>
  91307. * <td>do mid-side stereo<td>
  91308. * <td>loose mid-side stereo<td>
  91309. * <td>apodization<td>
  91310. * <td>max lpc order<td>
  91311. * <td>qlp coeff precision<td>
  91312. * <td>qlp coeff prec search<td>
  91313. * <td>escape coding<td>
  91314. * <td>exhaustive model search<td>
  91315. * <td>min residual partition order<td>
  91316. * <td>max residual partition order<td>
  91317. * <td>rice parameter search dist<td>
  91318. * </tr>
  91319. * <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>
  91320. * <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>
  91321. * <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>
  91322. * <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>
  91323. * <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>
  91324. * <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>
  91325. * <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>
  91326. * <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>
  91327. * <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>
  91328. * </table>
  91329. *
  91330. * \default \c 5
  91331. * \param encoder An encoder instance to set.
  91332. * \param value See above.
  91333. * \assert
  91334. * \code encoder != NULL \endcode
  91335. * \retval FLAC__bool
  91336. * \c false if the encoder is already initialized, else \c true.
  91337. */
  91338. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91339. /** Set the blocksize to use while encoding.
  91340. *
  91341. * The number of samples to use per frame. Use \c 0 to let the encoder
  91342. * estimate a blocksize; this is usually best.
  91343. *
  91344. * \default \c 0
  91345. * \param encoder An encoder instance to set.
  91346. * \param value See above.
  91347. * \assert
  91348. * \code encoder != NULL \endcode
  91349. * \retval FLAC__bool
  91350. * \c false if the encoder is already initialized, else \c true.
  91351. */
  91352. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91353. /** Set to \c true to enable mid-side encoding on stereo input. The
  91354. * number of channels must be 2 for this to have any effect. Set to
  91355. * \c false to use only independent channel coding.
  91356. *
  91357. * \default \c false
  91358. * \param encoder An encoder instance to set.
  91359. * \param value Flag value (see above).
  91360. * \assert
  91361. * \code encoder != NULL \endcode
  91362. * \retval FLAC__bool
  91363. * \c false if the encoder is already initialized, else \c true.
  91364. */
  91365. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91366. /** Set to \c true to enable adaptive switching between mid-side and
  91367. * left-right encoding on stereo input. Set to \c false to use
  91368. * exhaustive searching. Setting this to \c true requires
  91369. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91370. * \c true in order to have any effect.
  91371. *
  91372. * \default \c false
  91373. * \param encoder An encoder instance to set.
  91374. * \param value Flag value (see above).
  91375. * \assert
  91376. * \code encoder != NULL \endcode
  91377. * \retval FLAC__bool
  91378. * \c false if the encoder is already initialized, else \c true.
  91379. */
  91380. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91381. /** Sets the apodization function(s) the encoder will use when windowing
  91382. * audio data for LPC analysis.
  91383. *
  91384. * The \a specification is a plain ASCII string which specifies exactly
  91385. * which functions to use. There may be more than one (up to 32),
  91386. * separated by \c ';' characters. Some functions take one or more
  91387. * comma-separated arguments in parentheses.
  91388. *
  91389. * The available functions are \c bartlett, \c bartlett_hann,
  91390. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91391. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91392. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91393. *
  91394. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91395. * (0<STDDEV<=0.5).
  91396. *
  91397. * For \c tukey(P), P specifies the fraction of the window that is
  91398. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91399. * corresponds to \c hann.
  91400. *
  91401. * Example specifications are \c "blackman" or
  91402. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91403. *
  91404. * Any function that is specified erroneously is silently dropped. Up
  91405. * to 32 functions are kept, the rest are dropped. If the specification
  91406. * is empty the encoder defaults to \c "tukey(0.5)".
  91407. *
  91408. * When more than one function is specified, then for every subframe the
  91409. * encoder will try each of them separately and choose the window that
  91410. * results in the smallest compressed subframe.
  91411. *
  91412. * Note that each function specified causes the encoder to occupy a
  91413. * floating point array in which to store the window.
  91414. *
  91415. * \default \c "tukey(0.5)"
  91416. * \param encoder An encoder instance to set.
  91417. * \param specification See above.
  91418. * \assert
  91419. * \code encoder != NULL \endcode
  91420. * \code specification != NULL \endcode
  91421. * \retval FLAC__bool
  91422. * \c false if the encoder is already initialized, else \c true.
  91423. */
  91424. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91425. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91426. *
  91427. * \default \c 0
  91428. * \param encoder An encoder instance to set.
  91429. * \param value See above.
  91430. * \assert
  91431. * \code encoder != NULL \endcode
  91432. * \retval FLAC__bool
  91433. * \c false if the encoder is already initialized, else \c true.
  91434. */
  91435. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91436. /** Set the precision, in bits, of the quantized linear predictor
  91437. * coefficients, or \c 0 to let the encoder select it based on the
  91438. * blocksize.
  91439. *
  91440. * \note
  91441. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91442. * be less than 32.
  91443. *
  91444. * \default \c 0
  91445. * \param encoder An encoder instance to set.
  91446. * \param value See above.
  91447. * \assert
  91448. * \code encoder != NULL \endcode
  91449. * \retval FLAC__bool
  91450. * \c false if the encoder is already initialized, else \c true.
  91451. */
  91452. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91453. /** Set to \c false to use only the specified quantized linear predictor
  91454. * coefficient precision, or \c true to search neighboring precision
  91455. * values and use the best one.
  91456. *
  91457. * \default \c false
  91458. * \param encoder An encoder instance to set.
  91459. * \param value See above.
  91460. * \assert
  91461. * \code encoder != NULL \endcode
  91462. * \retval FLAC__bool
  91463. * \c false if the encoder is already initialized, else \c true.
  91464. */
  91465. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91466. /** Deprecated. Setting this value has no effect.
  91467. *
  91468. * \default \c false
  91469. * \param encoder An encoder instance to set.
  91470. * \param value See above.
  91471. * \assert
  91472. * \code encoder != NULL \endcode
  91473. * \retval FLAC__bool
  91474. * \c false if the encoder is already initialized, else \c true.
  91475. */
  91476. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91477. /** Set to \c false to let the encoder estimate the best model order
  91478. * based on the residual signal energy, or \c true to force the
  91479. * encoder to evaluate all order models and select the best.
  91480. *
  91481. * \default \c false
  91482. * \param encoder An encoder instance to set.
  91483. * \param value See above.
  91484. * \assert
  91485. * \code encoder != NULL \endcode
  91486. * \retval FLAC__bool
  91487. * \c false if the encoder is already initialized, else \c true.
  91488. */
  91489. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91490. /** Set the minimum partition order to search when coding the residual.
  91491. * This is used in tandem with
  91492. * FLAC__stream_encoder_set_max_residual_partition_order().
  91493. *
  91494. * The partition order determines the context size in the residual.
  91495. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91496. *
  91497. * Set both min and max values to \c 0 to force a single context,
  91498. * whose Rice parameter is based on the residual signal variance.
  91499. * Otherwise, set a min and max order, and the encoder will search
  91500. * all orders, using the mean of each context for its Rice parameter,
  91501. * and use the best.
  91502. *
  91503. * \default \c 0
  91504. * \param encoder An encoder instance to set.
  91505. * \param value See above.
  91506. * \assert
  91507. * \code encoder != NULL \endcode
  91508. * \retval FLAC__bool
  91509. * \c false if the encoder is already initialized, else \c true.
  91510. */
  91511. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91512. /** Set the maximum partition order to search when coding the residual.
  91513. * This is used in tandem with
  91514. * FLAC__stream_encoder_set_min_residual_partition_order().
  91515. *
  91516. * The partition order determines the context size in the residual.
  91517. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91518. *
  91519. * Set both min and max values to \c 0 to force a single context,
  91520. * whose Rice parameter is based on the residual signal variance.
  91521. * Otherwise, set a min and max order, and the encoder will search
  91522. * all orders, using the mean of each context for its Rice parameter,
  91523. * and use the best.
  91524. *
  91525. * \default \c 0
  91526. * \param encoder An encoder instance to set.
  91527. * \param value See above.
  91528. * \assert
  91529. * \code encoder != NULL \endcode
  91530. * \retval FLAC__bool
  91531. * \c false if the encoder is already initialized, else \c true.
  91532. */
  91533. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91534. /** Deprecated. Setting this value has no effect.
  91535. *
  91536. * \default \c 0
  91537. * \param encoder An encoder instance to set.
  91538. * \param value See above.
  91539. * \assert
  91540. * \code encoder != NULL \endcode
  91541. * \retval FLAC__bool
  91542. * \c false if the encoder is already initialized, else \c true.
  91543. */
  91544. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91545. /** Set an estimate of the total samples that will be encoded.
  91546. * This is merely an estimate and may be set to \c 0 if unknown.
  91547. * This value will be written to the STREAMINFO block before encoding,
  91548. * and can remove the need for the caller to rewrite the value later
  91549. * if the value is known before encoding.
  91550. *
  91551. * \default \c 0
  91552. * \param encoder An encoder instance to set.
  91553. * \param value See above.
  91554. * \assert
  91555. * \code encoder != NULL \endcode
  91556. * \retval FLAC__bool
  91557. * \c false if the encoder is already initialized, else \c true.
  91558. */
  91559. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91560. /** Set the metadata blocks to be emitted to the stream before encoding.
  91561. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91562. * array of pointers to metadata blocks. The array is non-const since
  91563. * the encoder may need to change the \a is_last flag inside them, and
  91564. * in some cases update seek point offsets. Otherwise, the encoder will
  91565. * not modify or free the blocks. It is up to the caller to free the
  91566. * metadata blocks after encoding finishes.
  91567. *
  91568. * \note
  91569. * The encoder stores only copies of the pointers in the \a metadata array;
  91570. * the metadata blocks themselves must survive at least until after
  91571. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91572. *
  91573. * \note
  91574. * The STREAMINFO block is always written and no STREAMINFO block may
  91575. * occur in the supplied array.
  91576. *
  91577. * \note
  91578. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91579. * in the \a metadata array, but the client has specified that it does not
  91580. * support seeking, then the SEEKTABLE will be written verbatim. However
  91581. * by itself this is not very useful as the client will not know the stream
  91582. * offsets for the seekpoints ahead of time. In order to get a proper
  91583. * seektable the client must support seeking. See next note.
  91584. *
  91585. * \note
  91586. * SEEKTABLE blocks are handled specially. Since you will not know
  91587. * the values for the seek point stream offsets, you should pass in
  91588. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91589. * required sample numbers (or placeholder points), with \c 0 for the
  91590. * \a frame_samples and \a stream_offset fields for each point. If the
  91591. * client has specified that it supports seeking by providing a seek
  91592. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91593. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91594. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91595. * then while it is encoding the encoder will fill the stream offsets in
  91596. * for you and when encoding is finished, it will seek back and write the
  91597. * real values into the SEEKTABLE block in the stream. There are helper
  91598. * routines for manipulating seektable template blocks; see metadata.h:
  91599. * FLAC__metadata_object_seektable_template_*(). If the client does
  91600. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91601. * will slow down or remove the ability to seek in the FLAC stream.
  91602. *
  91603. * \note
  91604. * The encoder instance \b will modify the first \c SEEKTABLE block
  91605. * as it transforms the template to a valid seektable while encoding,
  91606. * but it is still up to the caller to free all metadata blocks after
  91607. * encoding.
  91608. *
  91609. * \note
  91610. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91611. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91612. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91613. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91614. * block is present in the \a metadata array, libFLAC will write an
  91615. * empty one, containing only the vendor string.
  91616. *
  91617. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91618. * the second metadata block of the stream. The encoder already supplies
  91619. * the STREAMINFO block automatically. If \a metadata does not contain a
  91620. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91621. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91622. * first, the init function will reorder \a metadata by moving the
  91623. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91624. * blocks will remain as they were.
  91625. *
  91626. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91627. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91628. * return \c false.
  91629. *
  91630. * \default \c NULL, 0
  91631. * \param encoder An encoder instance to set.
  91632. * \param metadata See above.
  91633. * \param num_blocks See above.
  91634. * \assert
  91635. * \code encoder != NULL \endcode
  91636. * \retval FLAC__bool
  91637. * \c false if the encoder is already initialized, else \c true.
  91638. * \c false if the encoder is already initialized, or if
  91639. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91640. */
  91641. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91642. /** Get the current encoder state.
  91643. *
  91644. * \param encoder An encoder instance to query.
  91645. * \assert
  91646. * \code encoder != NULL \endcode
  91647. * \retval FLAC__StreamEncoderState
  91648. * The current encoder state.
  91649. */
  91650. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91651. /** Get the state of the verify stream decoder.
  91652. * Useful when the stream encoder state is
  91653. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91654. *
  91655. * \param encoder An encoder instance to query.
  91656. * \assert
  91657. * \code encoder != NULL \endcode
  91658. * \retval FLAC__StreamDecoderState
  91659. * The verify stream decoder state.
  91660. */
  91661. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91662. /** Get the current encoder state as a C string.
  91663. * This version automatically resolves
  91664. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91665. * verify decoder's state.
  91666. *
  91667. * \param encoder A encoder instance to query.
  91668. * \assert
  91669. * \code encoder != NULL \endcode
  91670. * \retval const char *
  91671. * The encoder state as a C string. Do not modify the contents.
  91672. */
  91673. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91674. /** Get relevant values about the nature of a verify decoder error.
  91675. * Useful when the stream encoder state is
  91676. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91677. * be addresses in which the stats will be returned, or NULL if value
  91678. * is not desired.
  91679. *
  91680. * \param encoder An encoder instance to query.
  91681. * \param absolute_sample The absolute sample number of the mismatch.
  91682. * \param frame_number The number of the frame in which the mismatch occurred.
  91683. * \param channel The channel in which the mismatch occurred.
  91684. * \param sample The number of the sample (relative to the frame) in
  91685. * which the mismatch occurred.
  91686. * \param expected The expected value for the sample in question.
  91687. * \param got The actual value returned by the decoder.
  91688. * \assert
  91689. * \code encoder != NULL \endcode
  91690. */
  91691. 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);
  91692. /** Get the "verify" flag.
  91693. *
  91694. * \param encoder An encoder instance to query.
  91695. * \assert
  91696. * \code encoder != NULL \endcode
  91697. * \retval FLAC__bool
  91698. * See FLAC__stream_encoder_set_verify().
  91699. */
  91700. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91701. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91702. *
  91703. * \param encoder An encoder instance to query.
  91704. * \assert
  91705. * \code encoder != NULL \endcode
  91706. * \retval FLAC__bool
  91707. * See FLAC__stream_encoder_set_streamable_subset().
  91708. */
  91709. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91710. /** Get the number of input channels being processed.
  91711. *
  91712. * \param encoder An encoder instance to query.
  91713. * \assert
  91714. * \code encoder != NULL \endcode
  91715. * \retval unsigned
  91716. * See FLAC__stream_encoder_set_channels().
  91717. */
  91718. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91719. /** Get the input sample resolution setting.
  91720. *
  91721. * \param encoder An encoder instance to query.
  91722. * \assert
  91723. * \code encoder != NULL \endcode
  91724. * \retval unsigned
  91725. * See FLAC__stream_encoder_set_bits_per_sample().
  91726. */
  91727. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91728. /** Get the input sample rate setting.
  91729. *
  91730. * \param encoder An encoder instance to query.
  91731. * \assert
  91732. * \code encoder != NULL \endcode
  91733. * \retval unsigned
  91734. * See FLAC__stream_encoder_set_sample_rate().
  91735. */
  91736. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91737. /** Get the blocksize setting.
  91738. *
  91739. * \param encoder An encoder instance to query.
  91740. * \assert
  91741. * \code encoder != NULL \endcode
  91742. * \retval unsigned
  91743. * See FLAC__stream_encoder_set_blocksize().
  91744. */
  91745. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91746. /** Get the "mid/side stereo coding" flag.
  91747. *
  91748. * \param encoder An encoder instance to query.
  91749. * \assert
  91750. * \code encoder != NULL \endcode
  91751. * \retval FLAC__bool
  91752. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91753. */
  91754. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91755. /** Get the "adaptive mid/side switching" flag.
  91756. *
  91757. * \param encoder An encoder instance to query.
  91758. * \assert
  91759. * \code encoder != NULL \endcode
  91760. * \retval FLAC__bool
  91761. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91762. */
  91763. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91764. /** Get the maximum LPC order setting.
  91765. *
  91766. * \param encoder An encoder instance to query.
  91767. * \assert
  91768. * \code encoder != NULL \endcode
  91769. * \retval unsigned
  91770. * See FLAC__stream_encoder_set_max_lpc_order().
  91771. */
  91772. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91773. /** Get the quantized linear predictor coefficient precision setting.
  91774. *
  91775. * \param encoder An encoder instance to query.
  91776. * \assert
  91777. * \code encoder != NULL \endcode
  91778. * \retval unsigned
  91779. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91780. */
  91781. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91782. /** Get the qlp coefficient precision search flag.
  91783. *
  91784. * \param encoder An encoder instance to query.
  91785. * \assert
  91786. * \code encoder != NULL \endcode
  91787. * \retval FLAC__bool
  91788. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91789. */
  91790. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91791. /** Get the "escape coding" flag.
  91792. *
  91793. * \param encoder An encoder instance to query.
  91794. * \assert
  91795. * \code encoder != NULL \endcode
  91796. * \retval FLAC__bool
  91797. * See FLAC__stream_encoder_set_do_escape_coding().
  91798. */
  91799. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91800. /** Get the exhaustive model search flag.
  91801. *
  91802. * \param encoder An encoder instance to query.
  91803. * \assert
  91804. * \code encoder != NULL \endcode
  91805. * \retval FLAC__bool
  91806. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91807. */
  91808. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91809. /** Get the minimum residual partition order setting.
  91810. *
  91811. * \param encoder An encoder instance to query.
  91812. * \assert
  91813. * \code encoder != NULL \endcode
  91814. * \retval unsigned
  91815. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91816. */
  91817. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91818. /** Get maximum residual partition order setting.
  91819. *
  91820. * \param encoder An encoder instance to query.
  91821. * \assert
  91822. * \code encoder != NULL \endcode
  91823. * \retval unsigned
  91824. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91825. */
  91826. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91827. /** Get the Rice parameter search distance setting.
  91828. *
  91829. * \param encoder An encoder instance to query.
  91830. * \assert
  91831. * \code encoder != NULL \endcode
  91832. * \retval unsigned
  91833. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91834. */
  91835. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91836. /** Get the previously set estimate of the total samples to be encoded.
  91837. * The encoder merely mimics back the value given to
  91838. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91839. * other way of knowing how many samples the client will encode.
  91840. *
  91841. * \param encoder An encoder instance to set.
  91842. * \assert
  91843. * \code encoder != NULL \endcode
  91844. * \retval FLAC__uint64
  91845. * See FLAC__stream_encoder_get_total_samples_estimate().
  91846. */
  91847. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91848. /** Initialize the encoder instance to encode native FLAC streams.
  91849. *
  91850. * This flavor of initialization sets up the encoder to encode to a
  91851. * native FLAC stream. I/O is performed via callbacks to the client.
  91852. * For encoding to a plain file via filename or open \c FILE*,
  91853. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91854. * provide a simpler interface.
  91855. *
  91856. * This function should be called after FLAC__stream_encoder_new() and
  91857. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91858. * or FLAC__stream_encoder_process_interleaved().
  91859. * initialization succeeded.
  91860. *
  91861. * The call to FLAC__stream_encoder_init_stream() currently will also
  91862. * immediately call the write callback several times, once with the \c fLaC
  91863. * signature, and once for each encoded metadata block.
  91864. *
  91865. * \param encoder An uninitialized encoder instance.
  91866. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91867. * pointer must not be \c NULL.
  91868. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91869. * pointer may be \c NULL if seeking is not
  91870. * supported. The encoder uses seeking to go back
  91871. * and write some some stream statistics to the
  91872. * STREAMINFO block; this is recommended but not
  91873. * necessary to create a valid FLAC stream. If
  91874. * \a seek_callback is not \c NULL then a
  91875. * \a tell_callback must also be supplied.
  91876. * Alternatively, a dummy seek callback that just
  91877. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91878. * may also be supplied, all though this is slightly
  91879. * less efficient for the encoder.
  91880. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91881. * pointer may be \c NULL if seeking is not
  91882. * supported. If \a seek_callback is \c NULL then
  91883. * this argument will be ignored. If
  91884. * \a seek_callback is not \c NULL then a
  91885. * \a tell_callback must also be supplied.
  91886. * Alternatively, a dummy tell callback that just
  91887. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91888. * may also be supplied, all though this is slightly
  91889. * less efficient for the encoder.
  91890. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91891. * pointer may be \c NULL if the callback is not
  91892. * desired. If the client provides a seek callback,
  91893. * this function is not necessary as the encoder
  91894. * will automatically seek back and update the
  91895. * STREAMINFO block. It may also be \c NULL if the
  91896. * client does not support seeking, since it will
  91897. * have no way of going back to update the
  91898. * STREAMINFO. However the client can still supply
  91899. * a callback if it would like to know the details
  91900. * from the STREAMINFO.
  91901. * \param client_data This value will be supplied to callbacks in their
  91902. * \a client_data argument.
  91903. * \assert
  91904. * \code encoder != NULL \endcode
  91905. * \retval FLAC__StreamEncoderInitStatus
  91906. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91907. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91908. */
  91909. 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);
  91910. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91911. *
  91912. * This flavor of initialization sets up the encoder to encode to a FLAC
  91913. * stream in an Ogg container. I/O is performed via callbacks to the
  91914. * client. For encoding to a plain file via filename or open \c FILE*,
  91915. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91916. * provide a simpler interface.
  91917. *
  91918. * This function should be called after FLAC__stream_encoder_new() and
  91919. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91920. * or FLAC__stream_encoder_process_interleaved().
  91921. * initialization succeeded.
  91922. *
  91923. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91924. * immediately call the write callback several times to write the metadata
  91925. * packets.
  91926. *
  91927. * \param encoder An uninitialized encoder instance.
  91928. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91929. * pointer must not be \c NULL if \a seek_callback
  91930. * is non-NULL since they are both needed to be
  91931. * able to write data back to the Ogg FLAC stream
  91932. * in the post-encode phase.
  91933. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91934. * pointer must not be \c NULL.
  91935. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91936. * pointer may be \c NULL if seeking is not
  91937. * supported. The encoder uses seeking to go back
  91938. * and write some some stream statistics to the
  91939. * STREAMINFO block; this is recommended but not
  91940. * necessary to create a valid FLAC stream. If
  91941. * \a seek_callback is not \c NULL then a
  91942. * \a tell_callback must also be supplied.
  91943. * Alternatively, a dummy seek callback that just
  91944. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91945. * may also be supplied, all though this is slightly
  91946. * less efficient for the encoder.
  91947. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91948. * pointer may be \c NULL if seeking is not
  91949. * supported. If \a seek_callback is \c NULL then
  91950. * this argument will be ignored. If
  91951. * \a seek_callback is not \c NULL then a
  91952. * \a tell_callback must also be supplied.
  91953. * Alternatively, a dummy tell callback that just
  91954. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91955. * may also be supplied, all though this is slightly
  91956. * less efficient for the encoder.
  91957. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91958. * pointer may be \c NULL if the callback is not
  91959. * desired. If the client provides a seek callback,
  91960. * this function is not necessary as the encoder
  91961. * will automatically seek back and update the
  91962. * STREAMINFO block. It may also be \c NULL if the
  91963. * client does not support seeking, since it will
  91964. * have no way of going back to update the
  91965. * STREAMINFO. However the client can still supply
  91966. * a callback if it would like to know the details
  91967. * from the STREAMINFO.
  91968. * \param client_data This value will be supplied to callbacks in their
  91969. * \a client_data argument.
  91970. * \assert
  91971. * \code encoder != NULL \endcode
  91972. * \retval FLAC__StreamEncoderInitStatus
  91973. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91974. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91975. */
  91976. 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);
  91977. /** Initialize the encoder instance to encode native FLAC files.
  91978. *
  91979. * This flavor of initialization sets up the encoder to encode to a
  91980. * plain native FLAC file. For non-stdio streams, you must use
  91981. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91982. *
  91983. * This function should be called after FLAC__stream_encoder_new() and
  91984. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91985. * or FLAC__stream_encoder_process_interleaved().
  91986. * initialization succeeded.
  91987. *
  91988. * \param encoder An uninitialized encoder instance.
  91989. * \param file An open file. The file should have been opened
  91990. * with mode \c "w+b" and rewound. The file
  91991. * becomes owned by the encoder and should not be
  91992. * manipulated by the client while encoding.
  91993. * Unless \a file is \c stdout, it will be closed
  91994. * when FLAC__stream_encoder_finish() is called.
  91995. * Note however that a proper SEEKTABLE cannot be
  91996. * created when encoding to \c stdout since it is
  91997. * not seekable.
  91998. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91999. * pointer may be \c NULL if the callback is not
  92000. * desired.
  92001. * \param client_data This value will be supplied to callbacks in their
  92002. * \a client_data argument.
  92003. * \assert
  92004. * \code encoder != NULL \endcode
  92005. * \code file != NULL \endcode
  92006. * \retval FLAC__StreamEncoderInitStatus
  92007. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92008. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92009. */
  92010. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92011. /** Initialize the encoder instance to encode Ogg FLAC files.
  92012. *
  92013. * This flavor of initialization sets up the encoder to encode to a
  92014. * plain Ogg FLAC file. For non-stdio streams, you must use
  92015. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92016. *
  92017. * This function should be called after FLAC__stream_encoder_new() and
  92018. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92019. * or FLAC__stream_encoder_process_interleaved().
  92020. * initialization succeeded.
  92021. *
  92022. * \param encoder An uninitialized encoder instance.
  92023. * \param file An open file. The file should have been opened
  92024. * with mode \c "w+b" and rewound. The file
  92025. * becomes owned by the encoder and should not be
  92026. * manipulated by the client while encoding.
  92027. * Unless \a file is \c stdout, it will be closed
  92028. * when FLAC__stream_encoder_finish() is called.
  92029. * Note however that a proper SEEKTABLE cannot be
  92030. * created when encoding to \c stdout since it is
  92031. * not seekable.
  92032. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92033. * pointer may be \c NULL if the callback is not
  92034. * desired.
  92035. * \param client_data This value will be supplied to callbacks in their
  92036. * \a client_data argument.
  92037. * \assert
  92038. * \code encoder != NULL \endcode
  92039. * \code file != NULL \endcode
  92040. * \retval FLAC__StreamEncoderInitStatus
  92041. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92042. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92043. */
  92044. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92045. /** Initialize the encoder instance to encode native FLAC files.
  92046. *
  92047. * This flavor of initialization sets up the encoder to encode to a plain
  92048. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92049. * with Unicode filenames on Windows), you must use
  92050. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92051. * and provide callbacks for the I/O.
  92052. *
  92053. * This function should be called after FLAC__stream_encoder_new() and
  92054. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92055. * or FLAC__stream_encoder_process_interleaved().
  92056. * initialization succeeded.
  92057. *
  92058. * \param encoder An uninitialized encoder instance.
  92059. * \param filename The name of the file to encode to. The file will
  92060. * be opened with fopen(). Use \c NULL to encode to
  92061. * \c stdout. Note however that a proper SEEKTABLE
  92062. * cannot be created when encoding to \c stdout since
  92063. * it is not seekable.
  92064. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92065. * pointer may be \c NULL if the callback is not
  92066. * desired.
  92067. * \param client_data This value will be supplied to callbacks in their
  92068. * \a client_data argument.
  92069. * \assert
  92070. * \code encoder != NULL \endcode
  92071. * \retval FLAC__StreamEncoderInitStatus
  92072. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92073. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92074. */
  92075. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92076. /** Initialize the encoder instance to encode Ogg FLAC files.
  92077. *
  92078. * This flavor of initialization sets up the encoder to encode to a plain
  92079. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92080. * with Unicode filenames on Windows), you must use
  92081. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92082. * and provide callbacks for the I/O.
  92083. *
  92084. * This function should be called after FLAC__stream_encoder_new() and
  92085. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92086. * or FLAC__stream_encoder_process_interleaved().
  92087. * initialization succeeded.
  92088. *
  92089. * \param encoder An uninitialized encoder instance.
  92090. * \param filename The name of the file to encode to. The file will
  92091. * be opened with fopen(). Use \c NULL to encode to
  92092. * \c stdout. Note however that a proper SEEKTABLE
  92093. * cannot be created when encoding to \c stdout since
  92094. * it is not seekable.
  92095. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92096. * pointer may be \c NULL if the callback is not
  92097. * desired.
  92098. * \param client_data This value will be supplied to callbacks in their
  92099. * \a client_data argument.
  92100. * \assert
  92101. * \code encoder != NULL \endcode
  92102. * \retval FLAC__StreamEncoderInitStatus
  92103. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92104. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92105. */
  92106. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92107. /** Finish the encoding process.
  92108. * Flushes the encoding buffer, releases resources, resets the encoder
  92109. * settings to their defaults, and returns the encoder state to
  92110. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92111. * one or more write callbacks before returning, and will generate
  92112. * a metadata callback.
  92113. *
  92114. * Note that in the course of processing the last frame, errors can
  92115. * occur, so the caller should be sure to check the return value to
  92116. * ensure the file was encoded properly.
  92117. *
  92118. * In the event of a prematurely-terminated encode, it is not strictly
  92119. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92120. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92121. * with a FLAC__stream_encoder_finish().
  92122. *
  92123. * \param encoder An uninitialized encoder instance.
  92124. * \assert
  92125. * \code encoder != NULL \endcode
  92126. * \retval FLAC__bool
  92127. * \c false if an error occurred processing the last frame; or if verify
  92128. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92129. * verify mismatch; else \c true. If \c false, caller should check the
  92130. * state with FLAC__stream_encoder_get_state() for more information
  92131. * about the error.
  92132. */
  92133. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92134. /** Submit data for encoding.
  92135. * This version allows you to supply the input data via an array of
  92136. * pointers, each pointer pointing to an array of \a samples samples
  92137. * representing one channel. The samples need not be block-aligned,
  92138. * but each channel should have the same number of samples. Each sample
  92139. * should be a signed integer, right-justified to the resolution set by
  92140. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92141. * resolution is 16 bits per sample, the samples should all be in the
  92142. * range [-32768,32767].
  92143. *
  92144. * For applications where channel order is important, channels must
  92145. * follow the order as described in the
  92146. * <A HREF="../format.html#frame_header">frame header</A>.
  92147. *
  92148. * \param encoder An initialized encoder instance in the OK state.
  92149. * \param buffer An array of pointers to each channel's signal.
  92150. * \param samples The number of samples in one channel.
  92151. * \assert
  92152. * \code encoder != NULL \endcode
  92153. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92154. * \retval FLAC__bool
  92155. * \c true if successful, else \c false; in this case, check the
  92156. * encoder state with FLAC__stream_encoder_get_state() to see what
  92157. * went wrong.
  92158. */
  92159. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92160. /** Submit data for encoding.
  92161. * This version allows you to supply the input data where the channels
  92162. * are interleaved into a single array (i.e. channel0_sample0,
  92163. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92164. * The samples need not be block-aligned but they must be
  92165. * sample-aligned, i.e. the first value should be channel0_sample0
  92166. * and the last value channelN_sampleM. Each sample should be a signed
  92167. * integer, right-justified to the resolution set by
  92168. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92169. * resolution is 16 bits per sample, the samples should all be in the
  92170. * range [-32768,32767].
  92171. *
  92172. * For applications where channel order is important, channels must
  92173. * follow the order as described in the
  92174. * <A HREF="../format.html#frame_header">frame header</A>.
  92175. *
  92176. * \param encoder An initialized encoder instance in the OK state.
  92177. * \param buffer An array of channel-interleaved data (see above).
  92178. * \param samples The number of samples in one channel, the same as for
  92179. * FLAC__stream_encoder_process(). For example, if
  92180. * encoding two channels, \c 1000 \a samples corresponds
  92181. * to a \a buffer of 2000 values.
  92182. * \assert
  92183. * \code encoder != NULL \endcode
  92184. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92185. * \retval FLAC__bool
  92186. * \c true if successful, else \c false; in this case, check the
  92187. * encoder state with FLAC__stream_encoder_get_state() to see what
  92188. * went wrong.
  92189. */
  92190. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92191. /* \} */
  92192. #ifdef __cplusplus
  92193. }
  92194. #endif
  92195. #endif
  92196. /*** End of inlined file: stream_encoder.h ***/
  92197. #ifdef _MSC_VER
  92198. /* OPT: an MSVC built-in would be better */
  92199. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92200. {
  92201. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92202. return (x>>16) | (x<<16);
  92203. }
  92204. #endif
  92205. #if defined(_MSC_VER) && defined(_X86_)
  92206. /* OPT: an MSVC built-in would be better */
  92207. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92208. {
  92209. __asm {
  92210. mov edx, start
  92211. mov ecx, len
  92212. test ecx, ecx
  92213. loop1:
  92214. jz done1
  92215. mov eax, [edx]
  92216. bswap eax
  92217. mov [edx], eax
  92218. add edx, 4
  92219. dec ecx
  92220. jmp short loop1
  92221. done1:
  92222. }
  92223. }
  92224. #endif
  92225. /** \mainpage
  92226. *
  92227. * \section intro Introduction
  92228. *
  92229. * This is the documentation for the FLAC C and C++ APIs. It is
  92230. * highly interconnected; this introduction should give you a top
  92231. * level idea of the structure and how to find the information you
  92232. * need. As a prerequisite you should have at least a basic
  92233. * knowledge of the FLAC format, documented
  92234. * <A HREF="../format.html">here</A>.
  92235. *
  92236. * \section c_api FLAC C API
  92237. *
  92238. * The FLAC C API is the interface to libFLAC, a set of structures
  92239. * describing the components of FLAC streams, and functions for
  92240. * encoding and decoding streams, as well as manipulating FLAC
  92241. * metadata in files. The public include files will be installed
  92242. * in your include area (for example /usr/include/FLAC/...).
  92243. *
  92244. * By writing a little code and linking against libFLAC, it is
  92245. * relatively easy to add FLAC support to another program. The
  92246. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92247. * Complete source code of libFLAC as well as the command-line
  92248. * encoder and plugins is available and is a useful source of
  92249. * examples.
  92250. *
  92251. * Aside from encoders and decoders, libFLAC provides a powerful
  92252. * metadata interface for manipulating metadata in FLAC files. It
  92253. * allows the user to add, delete, and modify FLAC metadata blocks
  92254. * and it can automatically take advantage of PADDING blocks to avoid
  92255. * rewriting the entire FLAC file when changing the size of the
  92256. * metadata.
  92257. *
  92258. * libFLAC usually only requires the standard C library and C math
  92259. * library. In particular, threading is not used so there is no
  92260. * dependency on a thread library. However, libFLAC does not use
  92261. * global variables and should be thread-safe.
  92262. *
  92263. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92264. * However the metadata editing interfaces currently have limited
  92265. * read-only support for Ogg FLAC files.
  92266. *
  92267. * \section cpp_api FLAC C++ API
  92268. *
  92269. * The FLAC C++ API is a set of classes that encapsulate the
  92270. * structures and functions in libFLAC. They provide slightly more
  92271. * functionality with respect to metadata but are otherwise
  92272. * equivalent. For the most part, they share the same usage as
  92273. * their counterparts in libFLAC, and the FLAC C API documentation
  92274. * can be used as a supplement. The public include files
  92275. * for the C++ API will be installed in your include area (for
  92276. * example /usr/include/FLAC++/...).
  92277. *
  92278. * libFLAC++ is also licensed under
  92279. * <A HREF="../license.html">Xiph's BSD license</A>.
  92280. *
  92281. * \section getting_started Getting Started
  92282. *
  92283. * A good starting point for learning the API is to browse through
  92284. * the <A HREF="modules.html">modules</A>. Modules are logical
  92285. * groupings of related functions or classes, which correspond roughly
  92286. * to header files or sections of header files. Each module includes a
  92287. * detailed description of the general usage of its functions or
  92288. * classes.
  92289. *
  92290. * From there you can go on to look at the documentation of
  92291. * individual functions. You can see different views of the individual
  92292. * functions through the links in top bar across this page.
  92293. *
  92294. * If you prefer a more hands-on approach, you can jump right to some
  92295. * <A HREF="../documentation_example_code.html">example code</A>.
  92296. *
  92297. * \section porting_guide Porting Guide
  92298. *
  92299. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92300. * has been introduced which gives detailed instructions on how to
  92301. * port your code to newer versions of FLAC.
  92302. *
  92303. * \section embedded_developers Embedded Developers
  92304. *
  92305. * libFLAC has grown larger over time as more functionality has been
  92306. * included, but much of it may be unnecessary for a particular embedded
  92307. * implementation. Unused parts may be pruned by some simple editing of
  92308. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92309. * metadata interface are all independent from each other.
  92310. *
  92311. * It is easiest to just describe the dependencies:
  92312. *
  92313. * - All modules depend on the \link flac_format Format \endlink module.
  92314. * - The decoders and encoders depend on the bitbuffer.
  92315. * - The decoder is independent of the encoder. The encoder uses the
  92316. * decoder because of the verify feature, but this can be removed if
  92317. * not needed.
  92318. * - Parts of the metadata interface require the stream decoder (but not
  92319. * the encoder).
  92320. * - Ogg support is selectable through the compile time macro
  92321. * \c FLAC__HAS_OGG.
  92322. *
  92323. * For example, if your application only requires the stream decoder, no
  92324. * encoder, and no metadata interface, you can remove the stream encoder
  92325. * and the metadata interface, which will greatly reduce the size of the
  92326. * library.
  92327. *
  92328. * Also, there are several places in the libFLAC code with comments marked
  92329. * with "OPT:" where a #define can be changed to enable code that might be
  92330. * faster on a specific platform. Experimenting with these can yield faster
  92331. * binaries.
  92332. */
  92333. /** \defgroup porting Porting Guide for New Versions
  92334. *
  92335. * This module describes differences in the library interfaces from
  92336. * version to version. It assists in the porting of code that uses
  92337. * the libraries to newer versions of FLAC.
  92338. *
  92339. * One simple facility for making porting easier that has been added
  92340. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92341. * library's includes (e.g. \c include/FLAC/export.h). The
  92342. * \c #defines mirror the libraries'
  92343. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92344. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92345. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92346. * These can be used to support multiple versions of an API during the
  92347. * transition phase, e.g.
  92348. *
  92349. * \code
  92350. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92351. * legacy code
  92352. * #else
  92353. * new code
  92354. * #endif
  92355. * \endcode
  92356. *
  92357. * The the source will work for multiple versions and the legacy code can
  92358. * easily be removed when the transition is complete.
  92359. *
  92360. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92361. * include/FLAC/export.h), which can be used to determine whether or not
  92362. * the library has been compiled with support for Ogg FLAC. This is
  92363. * simpler than trying to call an Ogg init function and catching the
  92364. * error.
  92365. */
  92366. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92367. * \ingroup porting
  92368. *
  92369. * \brief
  92370. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92371. *
  92372. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92373. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92374. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92375. * decoding layers and three encoding layers have been merged into a
  92376. * single stream decoder and stream encoder. That is, the functionality
  92377. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92378. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92379. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92380. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92381. * is there is now a single API that can be used to encode or decode
  92382. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92383. * on both seekable and non-seekable streams.
  92384. *
  92385. * Instead of creating an encoder or decoder of a certain layer, now the
  92386. * client will always create a FLAC__StreamEncoder or
  92387. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92388. * initialization function. For example, for the decoder,
  92389. * FLAC__stream_decoder_init() has been replaced by
  92390. * FLAC__stream_decoder_init_stream(). This init function takes
  92391. * callbacks for the I/O, and the seeking callbacks are optional. This
  92392. * allows the client to use the same object for seekable and
  92393. * non-seekable streams. For decoding a FLAC file directly, the client
  92394. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92395. * and fewer callbacks; most of the other callbacks are supplied
  92396. * internally. For situations where fopen()ing by filename is not
  92397. * possible (e.g. Unicode filenames on Windows) the client can instead
  92398. * open the file itself and supply the FILE* to
  92399. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92400. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92401. * Since the callbacks and client data are now passed to the init
  92402. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92403. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92404. * rest of the calls to the decoder are the same as before.
  92405. *
  92406. * There are counterpart init functions for Ogg FLAC, e.g.
  92407. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92408. * and callbacks are the same as for native FLAC.
  92409. *
  92410. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92411. * been set up like so:
  92412. *
  92413. * \code
  92414. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92415. * if(decoder == NULL) do_something;
  92416. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92417. * [... other settings ...]
  92418. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92419. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92420. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92421. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92422. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92423. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92424. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92425. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92426. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92427. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92428. * \endcode
  92429. *
  92430. * In FLAC 1.1.3 it is like this:
  92431. *
  92432. * \code
  92433. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92434. * if(decoder == NULL) do_something;
  92435. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92436. * [... other settings ...]
  92437. * if(FLAC__stream_decoder_init_stream(
  92438. * decoder,
  92439. * my_read_callback,
  92440. * my_seek_callback, // or NULL
  92441. * my_tell_callback, // or NULL
  92442. * my_length_callback, // or NULL
  92443. * my_eof_callback, // or NULL
  92444. * my_write_callback,
  92445. * my_metadata_callback, // or NULL
  92446. * my_error_callback,
  92447. * my_client_data
  92448. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92449. * \endcode
  92450. *
  92451. * or you could do;
  92452. *
  92453. * \code
  92454. * [...]
  92455. * FILE *file = fopen("somefile.flac","rb");
  92456. * if(file == NULL) do_somthing;
  92457. * if(FLAC__stream_decoder_init_FILE(
  92458. * decoder,
  92459. * file,
  92460. * my_write_callback,
  92461. * my_metadata_callback, // or NULL
  92462. * my_error_callback,
  92463. * my_client_data
  92464. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92465. * \endcode
  92466. *
  92467. * or just:
  92468. *
  92469. * \code
  92470. * [...]
  92471. * if(FLAC__stream_decoder_init_file(
  92472. * decoder,
  92473. * "somefile.flac",
  92474. * my_write_callback,
  92475. * my_metadata_callback, // or NULL
  92476. * my_error_callback,
  92477. * my_client_data
  92478. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92479. * \endcode
  92480. *
  92481. * Another small change to the decoder is in how it handles unparseable
  92482. * streams. Before, when the decoder found an unparseable stream
  92483. * (reserved for when the decoder encounters a stream from a future
  92484. * encoder that it can't parse), it changed the state to
  92485. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92486. * drops sync and calls the error callback with a new error code
  92487. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92488. * more robust. If your error callback does not discriminate on the the
  92489. * error state, your code does not need to be changed.
  92490. *
  92491. * The encoder now has a new setting:
  92492. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92493. * method used to window the data before LPC analysis. You only need to
  92494. * add a call to this function if the default is not suitable. There
  92495. * are also two new convenience functions that may be useful:
  92496. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92497. * FLAC__metadata_get_cuesheet().
  92498. *
  92499. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92500. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92501. * is now \c size_t instead of \c unsigned.
  92502. */
  92503. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92504. * \ingroup porting
  92505. *
  92506. * \brief
  92507. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92508. *
  92509. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92510. * There was a slight change in the implementation of
  92511. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92512. * of the \a metadata array of pointers so the client no longer needs
  92513. * to maintain it after the call. The objects themselves that are
  92514. * pointed to by the array are still not copied though and must be
  92515. * maintained until the call to FLAC__stream_encoder_finish().
  92516. */
  92517. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92518. * \ingroup porting
  92519. *
  92520. * \brief
  92521. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92522. *
  92523. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92524. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92525. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92526. *
  92527. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92528. * has changed to reflect the conversion of one of the reserved bits
  92529. * into active use. It used to be \c 2 and now is \c 1. However the
  92530. * FLAC frame header length has not changed, so to skip the proper
  92531. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92532. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92533. */
  92534. /** \defgroup flac FLAC C API
  92535. *
  92536. * The FLAC C API is the interface to libFLAC, a set of structures
  92537. * describing the components of FLAC streams, and functions for
  92538. * encoding and decoding streams, as well as manipulating FLAC
  92539. * metadata in files.
  92540. *
  92541. * You should start with the format components as all other modules
  92542. * are dependent on it.
  92543. */
  92544. #endif
  92545. /*** End of inlined file: all.h ***/
  92546. /*** Start of inlined file: bitmath.c ***/
  92547. /*** Start of inlined file: juce_FlacHeader.h ***/
  92548. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92549. // tasks..
  92550. #define VERSION "1.2.1"
  92551. #define FLAC__NO_DLL 1
  92552. #if JUCE_MSVC
  92553. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92554. #endif
  92555. #if JUCE_MAC
  92556. #define FLAC__SYS_DARWIN 1
  92557. #endif
  92558. /*** End of inlined file: juce_FlacHeader.h ***/
  92559. #if JUCE_USE_FLAC
  92560. #if HAVE_CONFIG_H
  92561. # include <config.h>
  92562. #endif
  92563. /*** Start of inlined file: bitmath.h ***/
  92564. #ifndef FLAC__PRIVATE__BITMATH_H
  92565. #define FLAC__PRIVATE__BITMATH_H
  92566. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92567. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92568. unsigned FLAC__bitmath_silog2(int v);
  92569. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92570. #endif
  92571. /*** End of inlined file: bitmath.h ***/
  92572. /* An example of what FLAC__bitmath_ilog2() computes:
  92573. *
  92574. * ilog2( 0) = assertion failure
  92575. * ilog2( 1) = 0
  92576. * ilog2( 2) = 1
  92577. * ilog2( 3) = 1
  92578. * ilog2( 4) = 2
  92579. * ilog2( 5) = 2
  92580. * ilog2( 6) = 2
  92581. * ilog2( 7) = 2
  92582. * ilog2( 8) = 3
  92583. * ilog2( 9) = 3
  92584. * ilog2(10) = 3
  92585. * ilog2(11) = 3
  92586. * ilog2(12) = 3
  92587. * ilog2(13) = 3
  92588. * ilog2(14) = 3
  92589. * ilog2(15) = 3
  92590. * ilog2(16) = 4
  92591. * ilog2(17) = 4
  92592. * ilog2(18) = 4
  92593. */
  92594. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92595. {
  92596. unsigned l = 0;
  92597. FLAC__ASSERT(v > 0);
  92598. while(v >>= 1)
  92599. l++;
  92600. return l;
  92601. }
  92602. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92603. {
  92604. unsigned l = 0;
  92605. FLAC__ASSERT(v > 0);
  92606. while(v >>= 1)
  92607. l++;
  92608. return l;
  92609. }
  92610. /* An example of what FLAC__bitmath_silog2() computes:
  92611. *
  92612. * silog2(-10) = 5
  92613. * silog2(- 9) = 5
  92614. * silog2(- 8) = 4
  92615. * silog2(- 7) = 4
  92616. * silog2(- 6) = 4
  92617. * silog2(- 5) = 4
  92618. * silog2(- 4) = 3
  92619. * silog2(- 3) = 3
  92620. * silog2(- 2) = 2
  92621. * silog2(- 1) = 2
  92622. * silog2( 0) = 0
  92623. * silog2( 1) = 2
  92624. * silog2( 2) = 3
  92625. * silog2( 3) = 3
  92626. * silog2( 4) = 4
  92627. * silog2( 5) = 4
  92628. * silog2( 6) = 4
  92629. * silog2( 7) = 4
  92630. * silog2( 8) = 5
  92631. * silog2( 9) = 5
  92632. * silog2( 10) = 5
  92633. */
  92634. unsigned FLAC__bitmath_silog2(int v)
  92635. {
  92636. while(1) {
  92637. if(v == 0) {
  92638. return 0;
  92639. }
  92640. else if(v > 0) {
  92641. unsigned l = 0;
  92642. while(v) {
  92643. l++;
  92644. v >>= 1;
  92645. }
  92646. return l+1;
  92647. }
  92648. else if(v == -1) {
  92649. return 2;
  92650. }
  92651. else {
  92652. v++;
  92653. v = -v;
  92654. }
  92655. }
  92656. }
  92657. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92658. {
  92659. while(1) {
  92660. if(v == 0) {
  92661. return 0;
  92662. }
  92663. else if(v > 0) {
  92664. unsigned l = 0;
  92665. while(v) {
  92666. l++;
  92667. v >>= 1;
  92668. }
  92669. return l+1;
  92670. }
  92671. else if(v == -1) {
  92672. return 2;
  92673. }
  92674. else {
  92675. v++;
  92676. v = -v;
  92677. }
  92678. }
  92679. }
  92680. #endif
  92681. /*** End of inlined file: bitmath.c ***/
  92682. /*** Start of inlined file: bitreader.c ***/
  92683. /*** Start of inlined file: juce_FlacHeader.h ***/
  92684. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92685. // tasks..
  92686. #define VERSION "1.2.1"
  92687. #define FLAC__NO_DLL 1
  92688. #if JUCE_MSVC
  92689. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92690. #endif
  92691. #if JUCE_MAC
  92692. #define FLAC__SYS_DARWIN 1
  92693. #endif
  92694. /*** End of inlined file: juce_FlacHeader.h ***/
  92695. #if JUCE_USE_FLAC
  92696. #if HAVE_CONFIG_H
  92697. # include <config.h>
  92698. #endif
  92699. #include <stdlib.h> /* for malloc() */
  92700. #include <string.h> /* for memcpy(), memset() */
  92701. #ifdef _MSC_VER
  92702. #include <winsock.h> /* for ntohl() */
  92703. #elif defined FLAC__SYS_DARWIN
  92704. #include <machine/endian.h> /* for ntohl() */
  92705. #elif defined __MINGW32__
  92706. #include <winsock.h> /* for ntohl() */
  92707. #else
  92708. #include <netinet/in.h> /* for ntohl() */
  92709. #endif
  92710. /*** Start of inlined file: bitreader.h ***/
  92711. #ifndef FLAC__PRIVATE__BITREADER_H
  92712. #define FLAC__PRIVATE__BITREADER_H
  92713. #include <stdio.h> /* for FILE */
  92714. /*** Start of inlined file: cpu.h ***/
  92715. #ifndef FLAC__PRIVATE__CPU_H
  92716. #define FLAC__PRIVATE__CPU_H
  92717. #ifdef HAVE_CONFIG_H
  92718. #include <config.h>
  92719. #endif
  92720. typedef enum {
  92721. FLAC__CPUINFO_TYPE_IA32,
  92722. FLAC__CPUINFO_TYPE_PPC,
  92723. FLAC__CPUINFO_TYPE_UNKNOWN
  92724. } FLAC__CPUInfo_Type;
  92725. typedef struct {
  92726. FLAC__bool cpuid;
  92727. FLAC__bool bswap;
  92728. FLAC__bool cmov;
  92729. FLAC__bool mmx;
  92730. FLAC__bool fxsr;
  92731. FLAC__bool sse;
  92732. FLAC__bool sse2;
  92733. FLAC__bool sse3;
  92734. FLAC__bool ssse3;
  92735. FLAC__bool _3dnow;
  92736. FLAC__bool ext3dnow;
  92737. FLAC__bool extmmx;
  92738. } FLAC__CPUInfo_IA32;
  92739. typedef struct {
  92740. FLAC__bool altivec;
  92741. FLAC__bool ppc64;
  92742. } FLAC__CPUInfo_PPC;
  92743. typedef struct {
  92744. FLAC__bool use_asm;
  92745. FLAC__CPUInfo_Type type;
  92746. union {
  92747. FLAC__CPUInfo_IA32 ia32;
  92748. FLAC__CPUInfo_PPC ppc;
  92749. } data;
  92750. } FLAC__CPUInfo;
  92751. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92752. #ifndef FLAC__NO_ASM
  92753. #ifdef FLAC__CPU_IA32
  92754. #ifdef FLAC__HAS_NASM
  92755. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92756. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92757. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92758. #endif
  92759. #endif
  92760. #endif
  92761. #endif
  92762. /*** End of inlined file: cpu.h ***/
  92763. /*
  92764. * opaque structure definition
  92765. */
  92766. struct FLAC__BitReader;
  92767. typedef struct FLAC__BitReader FLAC__BitReader;
  92768. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92769. /*
  92770. * construction, deletion, initialization, etc functions
  92771. */
  92772. FLAC__BitReader *FLAC__bitreader_new(void);
  92773. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92774. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92775. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92776. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92777. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92778. /*
  92779. * CRC functions
  92780. */
  92781. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92782. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92783. /*
  92784. * info functions
  92785. */
  92786. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92787. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92788. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92789. /*
  92790. * read functions
  92791. */
  92792. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92793. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92794. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92795. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92796. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92797. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92798. 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! */
  92799. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92800. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92801. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92802. #ifndef FLAC__NO_ASM
  92803. # ifdef FLAC__CPU_IA32
  92804. # ifdef FLAC__HAS_NASM
  92805. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92806. # endif
  92807. # endif
  92808. #endif
  92809. #if 0 /* UNUSED */
  92810. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92811. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92812. #endif
  92813. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92814. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92815. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92816. #endif
  92817. /*** End of inlined file: bitreader.h ***/
  92818. /*** Start of inlined file: crc.h ***/
  92819. #ifndef FLAC__PRIVATE__CRC_H
  92820. #define FLAC__PRIVATE__CRC_H
  92821. /* 8 bit CRC generator, MSB shifted first
  92822. ** polynomial = x^8 + x^2 + x^1 + x^0
  92823. ** init = 0
  92824. */
  92825. extern FLAC__byte const FLAC__crc8_table[256];
  92826. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92827. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92828. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92829. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92830. /* 16 bit CRC generator, MSB shifted first
  92831. ** polynomial = x^16 + x^15 + x^2 + x^0
  92832. ** init = 0
  92833. */
  92834. extern unsigned FLAC__crc16_table[256];
  92835. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92836. /* this alternate may be faster on some systems/compilers */
  92837. #if 0
  92838. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92839. #endif
  92840. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92841. #endif
  92842. /*** End of inlined file: crc.h ***/
  92843. /* Things should be fastest when this matches the machine word size */
  92844. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92845. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92846. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92847. typedef FLAC__uint32 brword;
  92848. #define FLAC__BYTES_PER_WORD 4
  92849. #define FLAC__BITS_PER_WORD 32
  92850. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92851. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92852. #if WORDS_BIGENDIAN
  92853. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92854. #else
  92855. #if defined (_MSC_VER) && defined (_X86_)
  92856. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92857. #else
  92858. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92859. #endif
  92860. #endif
  92861. /* counts the # of zero MSBs in a word */
  92862. #define COUNT_ZERO_MSBS(word) ( \
  92863. (word) <= 0xffff ? \
  92864. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92865. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92866. )
  92867. /* this alternate might be slightly faster on some systems/compilers: */
  92868. #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])) )
  92869. /*
  92870. * This should be at least twice as large as the largest number of words
  92871. * required to represent any 'number' (in any encoding) you are going to
  92872. * read. With FLAC this is on the order of maybe a few hundred bits.
  92873. * If the buffer is smaller than that, the decoder won't be able to read
  92874. * in a whole number that is in a variable length encoding (e.g. Rice).
  92875. * But to be practical it should be at least 1K bytes.
  92876. *
  92877. * Increase this number to decrease the number of read callbacks, at the
  92878. * expense of using more memory. Or decrease for the reverse effect,
  92879. * keeping in mind the limit from the first paragraph. The optimal size
  92880. * also depends on the CPU cache size and other factors; some twiddling
  92881. * may be necessary to squeeze out the best performance.
  92882. */
  92883. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92884. static const unsigned char byte_to_unary_table[] = {
  92885. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92886. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92887. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92888. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92889. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92890. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92891. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92892. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92901. };
  92902. #ifdef min
  92903. #undef min
  92904. #endif
  92905. #define min(x,y) ((x)<(y)?(x):(y))
  92906. #ifdef max
  92907. #undef max
  92908. #endif
  92909. #define max(x,y) ((x)>(y)?(x):(y))
  92910. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92911. #ifdef _MSC_VER
  92912. #define FLAC__U64L(x) x
  92913. #else
  92914. #define FLAC__U64L(x) x##LLU
  92915. #endif
  92916. #ifndef FLaC__INLINE
  92917. #define FLaC__INLINE
  92918. #endif
  92919. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92920. struct FLAC__BitReader {
  92921. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92922. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92923. brword *buffer;
  92924. unsigned capacity; /* in words */
  92925. unsigned words; /* # of completed words in buffer */
  92926. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92927. unsigned consumed_words; /* #words ... */
  92928. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92929. unsigned read_crc16; /* the running frame CRC */
  92930. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92931. FLAC__BitReaderReadCallback read_callback;
  92932. void *client_data;
  92933. FLAC__CPUInfo cpu_info;
  92934. };
  92935. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92936. {
  92937. register unsigned crc = br->read_crc16;
  92938. #if FLAC__BYTES_PER_WORD == 4
  92939. switch(br->crc16_align) {
  92940. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92941. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92942. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92943. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92944. }
  92945. #elif FLAC__BYTES_PER_WORD == 8
  92946. switch(br->crc16_align) {
  92947. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92948. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92949. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92950. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92951. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92952. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92953. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92954. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92955. }
  92956. #else
  92957. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92958. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92959. br->read_crc16 = crc;
  92960. #endif
  92961. br->crc16_align = 0;
  92962. }
  92963. /* would be static except it needs to be called by asm routines */
  92964. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92965. {
  92966. unsigned start, end;
  92967. size_t bytes;
  92968. FLAC__byte *target;
  92969. /* first shift the unconsumed buffer data toward the front as much as possible */
  92970. if(br->consumed_words > 0) {
  92971. start = br->consumed_words;
  92972. end = br->words + (br->bytes? 1:0);
  92973. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92974. br->words -= start;
  92975. br->consumed_words = 0;
  92976. }
  92977. /*
  92978. * set the target for reading, taking into account word alignment and endianness
  92979. */
  92980. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92981. if(bytes == 0)
  92982. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92983. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92984. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92985. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92986. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92987. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92988. * ^^-------target, bytes=3
  92989. * on LE machines, have to byteswap the odd tail word so nothing is
  92990. * overwritten:
  92991. */
  92992. #if WORDS_BIGENDIAN
  92993. #else
  92994. if(br->bytes)
  92995. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92996. #endif
  92997. /* now it looks like:
  92998. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92999. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93000. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93001. * ^^-------target, bytes=3
  93002. */
  93003. /* read in the data; note that the callback may return a smaller number of bytes */
  93004. if(!br->read_callback(target, &bytes, br->client_data))
  93005. return false;
  93006. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93007. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93008. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93009. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93010. * now have to byteswap on LE machines:
  93011. */
  93012. #if WORDS_BIGENDIAN
  93013. #else
  93014. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93015. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93016. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93017. start = br->words;
  93018. local_swap32_block_(br->buffer + start, end - start);
  93019. }
  93020. else
  93021. # endif
  93022. for(start = br->words; start < end; start++)
  93023. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93024. #endif
  93025. /* now it looks like:
  93026. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93027. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93028. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93029. * finally we'll update the reader values:
  93030. */
  93031. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93032. br->words = end / FLAC__BYTES_PER_WORD;
  93033. br->bytes = end % FLAC__BYTES_PER_WORD;
  93034. return true;
  93035. }
  93036. /***********************************************************************
  93037. *
  93038. * Class constructor/destructor
  93039. *
  93040. ***********************************************************************/
  93041. FLAC__BitReader *FLAC__bitreader_new(void)
  93042. {
  93043. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93044. /* calloc() implies:
  93045. memset(br, 0, sizeof(FLAC__BitReader));
  93046. br->buffer = 0;
  93047. br->capacity = 0;
  93048. br->words = br->bytes = 0;
  93049. br->consumed_words = br->consumed_bits = 0;
  93050. br->read_callback = 0;
  93051. br->client_data = 0;
  93052. */
  93053. return br;
  93054. }
  93055. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93056. {
  93057. FLAC__ASSERT(0 != br);
  93058. FLAC__bitreader_free(br);
  93059. free(br);
  93060. }
  93061. /***********************************************************************
  93062. *
  93063. * Public class methods
  93064. *
  93065. ***********************************************************************/
  93066. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93067. {
  93068. FLAC__ASSERT(0 != br);
  93069. br->words = br->bytes = 0;
  93070. br->consumed_words = br->consumed_bits = 0;
  93071. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93072. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93073. if(br->buffer == 0)
  93074. return false;
  93075. br->read_callback = rcb;
  93076. br->client_data = cd;
  93077. br->cpu_info = cpu;
  93078. return true;
  93079. }
  93080. void FLAC__bitreader_free(FLAC__BitReader *br)
  93081. {
  93082. FLAC__ASSERT(0 != br);
  93083. if(0 != br->buffer)
  93084. free(br->buffer);
  93085. br->buffer = 0;
  93086. br->capacity = 0;
  93087. br->words = br->bytes = 0;
  93088. br->consumed_words = br->consumed_bits = 0;
  93089. br->read_callback = 0;
  93090. br->client_data = 0;
  93091. }
  93092. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93093. {
  93094. br->words = br->bytes = 0;
  93095. br->consumed_words = br->consumed_bits = 0;
  93096. return true;
  93097. }
  93098. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93099. {
  93100. unsigned i, j;
  93101. if(br == 0) {
  93102. fprintf(out, "bitreader is NULL\n");
  93103. }
  93104. else {
  93105. 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);
  93106. for(i = 0; i < br->words; i++) {
  93107. fprintf(out, "%08X: ", i);
  93108. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93109. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93110. fprintf(out, ".");
  93111. else
  93112. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93113. fprintf(out, "\n");
  93114. }
  93115. if(br->bytes > 0) {
  93116. fprintf(out, "%08X: ", i);
  93117. for(j = 0; j < br->bytes*8; j++)
  93118. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93119. fprintf(out, ".");
  93120. else
  93121. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93122. fprintf(out, "\n");
  93123. }
  93124. }
  93125. }
  93126. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93127. {
  93128. FLAC__ASSERT(0 != br);
  93129. FLAC__ASSERT(0 != br->buffer);
  93130. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93131. br->read_crc16 = (unsigned)seed;
  93132. br->crc16_align = br->consumed_bits;
  93133. }
  93134. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93135. {
  93136. FLAC__ASSERT(0 != br);
  93137. FLAC__ASSERT(0 != br->buffer);
  93138. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93139. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93140. /* CRC any tail bytes in a partially-consumed word */
  93141. if(br->consumed_bits) {
  93142. const brword tail = br->buffer[br->consumed_words];
  93143. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93144. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93145. }
  93146. return br->read_crc16;
  93147. }
  93148. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93149. {
  93150. return ((br->consumed_bits & 7) == 0);
  93151. }
  93152. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93153. {
  93154. return 8 - (br->consumed_bits & 7);
  93155. }
  93156. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93157. {
  93158. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93159. }
  93160. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93161. {
  93162. FLAC__ASSERT(0 != br);
  93163. FLAC__ASSERT(0 != br->buffer);
  93164. FLAC__ASSERT(bits <= 32);
  93165. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93166. FLAC__ASSERT(br->consumed_words <= br->words);
  93167. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93168. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93169. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93170. *val = 0;
  93171. return true;
  93172. }
  93173. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93174. if(!bitreader_read_from_client_(br))
  93175. return false;
  93176. }
  93177. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93178. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93179. if(br->consumed_bits) {
  93180. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93181. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93182. const brword word = br->buffer[br->consumed_words];
  93183. if(bits < n) {
  93184. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93185. br->consumed_bits += bits;
  93186. return true;
  93187. }
  93188. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93189. bits -= n;
  93190. crc16_update_word_(br, word);
  93191. br->consumed_words++;
  93192. br->consumed_bits = 0;
  93193. 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 */
  93194. *val <<= bits;
  93195. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93196. br->consumed_bits = bits;
  93197. }
  93198. return true;
  93199. }
  93200. else {
  93201. const brword word = br->buffer[br->consumed_words];
  93202. if(bits < FLAC__BITS_PER_WORD) {
  93203. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93204. br->consumed_bits = bits;
  93205. return true;
  93206. }
  93207. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93208. *val = word;
  93209. crc16_update_word_(br, word);
  93210. br->consumed_words++;
  93211. return true;
  93212. }
  93213. }
  93214. else {
  93215. /* in this case we're starting our read at a partial tail word;
  93216. * the reader has guaranteed that we have at least 'bits' bits
  93217. * available to read, which makes this case simpler.
  93218. */
  93219. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93220. if(br->consumed_bits) {
  93221. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93222. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93223. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93224. br->consumed_bits += bits;
  93225. return true;
  93226. }
  93227. else {
  93228. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93229. br->consumed_bits += bits;
  93230. return true;
  93231. }
  93232. }
  93233. }
  93234. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93235. {
  93236. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93237. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93238. return false;
  93239. /* sign-extend: */
  93240. *val <<= (32-bits);
  93241. *val >>= (32-bits);
  93242. return true;
  93243. }
  93244. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93245. {
  93246. FLAC__uint32 hi, lo;
  93247. if(bits > 32) {
  93248. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93249. return false;
  93250. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93251. return false;
  93252. *val = hi;
  93253. *val <<= 32;
  93254. *val |= lo;
  93255. }
  93256. else {
  93257. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93258. return false;
  93259. *val = lo;
  93260. }
  93261. return true;
  93262. }
  93263. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93264. {
  93265. FLAC__uint32 x8, x32 = 0;
  93266. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93267. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93268. return false;
  93269. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93270. return false;
  93271. x32 |= (x8 << 8);
  93272. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93273. return false;
  93274. x32 |= (x8 << 16);
  93275. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93276. return false;
  93277. x32 |= (x8 << 24);
  93278. *val = x32;
  93279. return true;
  93280. }
  93281. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93282. {
  93283. /*
  93284. * OPT: a faster implementation is possible but probably not that useful
  93285. * since this is only called a couple of times in the metadata readers.
  93286. */
  93287. FLAC__ASSERT(0 != br);
  93288. FLAC__ASSERT(0 != br->buffer);
  93289. if(bits > 0) {
  93290. const unsigned n = br->consumed_bits & 7;
  93291. unsigned m;
  93292. FLAC__uint32 x;
  93293. if(n != 0) {
  93294. m = min(8-n, bits);
  93295. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93296. return false;
  93297. bits -= m;
  93298. }
  93299. m = bits / 8;
  93300. if(m > 0) {
  93301. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93302. return false;
  93303. bits %= 8;
  93304. }
  93305. if(bits > 0) {
  93306. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93307. return false;
  93308. }
  93309. }
  93310. return true;
  93311. }
  93312. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93313. {
  93314. FLAC__uint32 x;
  93315. FLAC__ASSERT(0 != br);
  93316. FLAC__ASSERT(0 != br->buffer);
  93317. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93318. /* step 1: skip over partial head word to get word aligned */
  93319. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93320. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93321. return false;
  93322. nvals--;
  93323. }
  93324. if(0 == nvals)
  93325. return true;
  93326. /* step 2: skip whole words in chunks */
  93327. while(nvals >= FLAC__BYTES_PER_WORD) {
  93328. if(br->consumed_words < br->words) {
  93329. br->consumed_words++;
  93330. nvals -= FLAC__BYTES_PER_WORD;
  93331. }
  93332. else if(!bitreader_read_from_client_(br))
  93333. return false;
  93334. }
  93335. /* step 3: skip any remainder from partial tail bytes */
  93336. while(nvals) {
  93337. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93338. return false;
  93339. nvals--;
  93340. }
  93341. return true;
  93342. }
  93343. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93344. {
  93345. FLAC__uint32 x;
  93346. FLAC__ASSERT(0 != br);
  93347. FLAC__ASSERT(0 != br->buffer);
  93348. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93349. /* step 1: read from partial head word to get word aligned */
  93350. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93351. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93352. return false;
  93353. *val++ = (FLAC__byte)x;
  93354. nvals--;
  93355. }
  93356. if(0 == nvals)
  93357. return true;
  93358. /* step 2: read whole words in chunks */
  93359. while(nvals >= FLAC__BYTES_PER_WORD) {
  93360. if(br->consumed_words < br->words) {
  93361. const brword word = br->buffer[br->consumed_words++];
  93362. #if FLAC__BYTES_PER_WORD == 4
  93363. val[0] = (FLAC__byte)(word >> 24);
  93364. val[1] = (FLAC__byte)(word >> 16);
  93365. val[2] = (FLAC__byte)(word >> 8);
  93366. val[3] = (FLAC__byte)word;
  93367. #elif FLAC__BYTES_PER_WORD == 8
  93368. val[0] = (FLAC__byte)(word >> 56);
  93369. val[1] = (FLAC__byte)(word >> 48);
  93370. val[2] = (FLAC__byte)(word >> 40);
  93371. val[3] = (FLAC__byte)(word >> 32);
  93372. val[4] = (FLAC__byte)(word >> 24);
  93373. val[5] = (FLAC__byte)(word >> 16);
  93374. val[6] = (FLAC__byte)(word >> 8);
  93375. val[7] = (FLAC__byte)word;
  93376. #else
  93377. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93378. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93379. #endif
  93380. val += FLAC__BYTES_PER_WORD;
  93381. nvals -= FLAC__BYTES_PER_WORD;
  93382. }
  93383. else if(!bitreader_read_from_client_(br))
  93384. return false;
  93385. }
  93386. /* step 3: read any remainder from partial tail bytes */
  93387. while(nvals) {
  93388. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93389. return false;
  93390. *val++ = (FLAC__byte)x;
  93391. nvals--;
  93392. }
  93393. return true;
  93394. }
  93395. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93396. #if 0 /* slow but readable version */
  93397. {
  93398. unsigned bit;
  93399. FLAC__ASSERT(0 != br);
  93400. FLAC__ASSERT(0 != br->buffer);
  93401. *val = 0;
  93402. while(1) {
  93403. if(!FLAC__bitreader_read_bit(br, &bit))
  93404. return false;
  93405. if(bit)
  93406. break;
  93407. else
  93408. *val++;
  93409. }
  93410. return true;
  93411. }
  93412. #else
  93413. {
  93414. unsigned i;
  93415. FLAC__ASSERT(0 != br);
  93416. FLAC__ASSERT(0 != br->buffer);
  93417. *val = 0;
  93418. while(1) {
  93419. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93420. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93421. if(b) {
  93422. i = COUNT_ZERO_MSBS(b);
  93423. *val += i;
  93424. i++;
  93425. br->consumed_bits += i;
  93426. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93427. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93428. br->consumed_words++;
  93429. br->consumed_bits = 0;
  93430. }
  93431. return true;
  93432. }
  93433. else {
  93434. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93435. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93436. br->consumed_words++;
  93437. br->consumed_bits = 0;
  93438. /* didn't find stop bit yet, have to keep going... */
  93439. }
  93440. }
  93441. /* at this point we've eaten up all the whole words; have to try
  93442. * reading through any tail bytes before calling the read callback.
  93443. * this is a repeat of the above logic adjusted for the fact we
  93444. * don't have a whole word. note though if the client is feeding
  93445. * us data a byte at a time (unlikely), br->consumed_bits may not
  93446. * be zero.
  93447. */
  93448. if(br->bytes) {
  93449. const unsigned end = br->bytes * 8;
  93450. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93451. if(b) {
  93452. i = COUNT_ZERO_MSBS(b);
  93453. *val += i;
  93454. i++;
  93455. br->consumed_bits += i;
  93456. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93457. return true;
  93458. }
  93459. else {
  93460. *val += end - br->consumed_bits;
  93461. br->consumed_bits += end;
  93462. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93463. /* didn't find stop bit yet, have to keep going... */
  93464. }
  93465. }
  93466. if(!bitreader_read_from_client_(br))
  93467. return false;
  93468. }
  93469. }
  93470. #endif
  93471. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93472. {
  93473. FLAC__uint32 lsbs = 0, msbs = 0;
  93474. unsigned uval;
  93475. FLAC__ASSERT(0 != br);
  93476. FLAC__ASSERT(0 != br->buffer);
  93477. FLAC__ASSERT(parameter <= 31);
  93478. /* read the unary MSBs and end bit */
  93479. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93480. return false;
  93481. /* read the binary LSBs */
  93482. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93483. return false;
  93484. /* compose the value */
  93485. uval = (msbs << parameter) | lsbs;
  93486. if(uval & 1)
  93487. *val = -((int)(uval >> 1)) - 1;
  93488. else
  93489. *val = (int)(uval >> 1);
  93490. return true;
  93491. }
  93492. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93493. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93494. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93495. /* OPT: possibly faster version for use with MSVC */
  93496. #ifdef _MSC_VER
  93497. {
  93498. unsigned i;
  93499. unsigned uval = 0;
  93500. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93501. /* try and get br->consumed_words and br->consumed_bits into register;
  93502. * must remember to flush them back to *br before calling other
  93503. * bitwriter functions that use them, and before returning */
  93504. register unsigned cwords;
  93505. register unsigned cbits;
  93506. FLAC__ASSERT(0 != br);
  93507. FLAC__ASSERT(0 != br->buffer);
  93508. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93509. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93510. FLAC__ASSERT(parameter < 32);
  93511. /* 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 */
  93512. if(nvals == 0)
  93513. return true;
  93514. cbits = br->consumed_bits;
  93515. cwords = br->consumed_words;
  93516. while(1) {
  93517. /* read unary part */
  93518. while(1) {
  93519. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93520. brword b = br->buffer[cwords] << cbits;
  93521. if(b) {
  93522. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93523. __asm {
  93524. bsr eax, b
  93525. not eax
  93526. and eax, 31
  93527. mov i, eax
  93528. }
  93529. #else
  93530. i = COUNT_ZERO_MSBS(b);
  93531. #endif
  93532. uval += i;
  93533. bits = parameter;
  93534. i++;
  93535. cbits += i;
  93536. if(cbits == FLAC__BITS_PER_WORD) {
  93537. crc16_update_word_(br, br->buffer[cwords]);
  93538. cwords++;
  93539. cbits = 0;
  93540. }
  93541. goto break1;
  93542. }
  93543. else {
  93544. uval += FLAC__BITS_PER_WORD - cbits;
  93545. crc16_update_word_(br, br->buffer[cwords]);
  93546. cwords++;
  93547. cbits = 0;
  93548. /* didn't find stop bit yet, have to keep going... */
  93549. }
  93550. }
  93551. /* at this point we've eaten up all the whole words; have to try
  93552. * reading through any tail bytes before calling the read callback.
  93553. * this is a repeat of the above logic adjusted for the fact we
  93554. * don't have a whole word. note though if the client is feeding
  93555. * us data a byte at a time (unlikely), br->consumed_bits may not
  93556. * be zero.
  93557. */
  93558. if(br->bytes) {
  93559. const unsigned end = br->bytes * 8;
  93560. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93561. if(b) {
  93562. i = COUNT_ZERO_MSBS(b);
  93563. uval += i;
  93564. bits = parameter;
  93565. i++;
  93566. cbits += i;
  93567. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93568. goto break1;
  93569. }
  93570. else {
  93571. uval += end - cbits;
  93572. cbits += end;
  93573. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93574. /* didn't find stop bit yet, have to keep going... */
  93575. }
  93576. }
  93577. /* flush registers and read; bitreader_read_from_client_() does
  93578. * not touch br->consumed_bits at all but we still need to set
  93579. * it in case it fails and we have to return false.
  93580. */
  93581. br->consumed_bits = cbits;
  93582. br->consumed_words = cwords;
  93583. if(!bitreader_read_from_client_(br))
  93584. return false;
  93585. cwords = br->consumed_words;
  93586. }
  93587. break1:
  93588. /* read binary part */
  93589. FLAC__ASSERT(cwords <= br->words);
  93590. if(bits) {
  93591. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93592. /* flush registers and read; bitreader_read_from_client_() does
  93593. * not touch br->consumed_bits at all but we still need to set
  93594. * it in case it fails and we have to return false.
  93595. */
  93596. br->consumed_bits = cbits;
  93597. br->consumed_words = cwords;
  93598. if(!bitreader_read_from_client_(br))
  93599. return false;
  93600. cwords = br->consumed_words;
  93601. }
  93602. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93603. if(cbits) {
  93604. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93605. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93606. const brword word = br->buffer[cwords];
  93607. if(bits < n) {
  93608. uval <<= bits;
  93609. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93610. cbits += bits;
  93611. goto break2;
  93612. }
  93613. uval <<= n;
  93614. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93615. bits -= n;
  93616. crc16_update_word_(br, word);
  93617. cwords++;
  93618. cbits = 0;
  93619. 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 */
  93620. uval <<= bits;
  93621. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93622. cbits = bits;
  93623. }
  93624. goto break2;
  93625. }
  93626. else {
  93627. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93628. uval <<= bits;
  93629. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93630. cbits = bits;
  93631. goto break2;
  93632. }
  93633. }
  93634. else {
  93635. /* in this case we're starting our read at a partial tail word;
  93636. * the reader has guaranteed that we have at least 'bits' bits
  93637. * available to read, which makes this case simpler.
  93638. */
  93639. uval <<= bits;
  93640. if(cbits) {
  93641. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93642. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93643. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93644. cbits += bits;
  93645. goto break2;
  93646. }
  93647. else {
  93648. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93649. cbits += bits;
  93650. goto break2;
  93651. }
  93652. }
  93653. }
  93654. break2:
  93655. /* compose the value */
  93656. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93657. /* are we done? */
  93658. --nvals;
  93659. if(nvals == 0) {
  93660. br->consumed_bits = cbits;
  93661. br->consumed_words = cwords;
  93662. return true;
  93663. }
  93664. uval = 0;
  93665. ++vals;
  93666. }
  93667. }
  93668. #else
  93669. {
  93670. unsigned i;
  93671. unsigned uval = 0;
  93672. /* try and get br->consumed_words and br->consumed_bits into register;
  93673. * must remember to flush them back to *br before calling other
  93674. * bitwriter functions that use them, and before returning */
  93675. register unsigned cwords;
  93676. register unsigned cbits;
  93677. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93678. FLAC__ASSERT(0 != br);
  93679. FLAC__ASSERT(0 != br->buffer);
  93680. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93681. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93682. FLAC__ASSERT(parameter < 32);
  93683. /* 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 */
  93684. if(nvals == 0)
  93685. return true;
  93686. cbits = br->consumed_bits;
  93687. cwords = br->consumed_words;
  93688. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93689. while(1) {
  93690. /* read unary part */
  93691. while(1) {
  93692. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93693. brword b = br->buffer[cwords] << cbits;
  93694. if(b) {
  93695. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93696. asm volatile (
  93697. "bsrl %1, %0;"
  93698. "notl %0;"
  93699. "andl $31, %0;"
  93700. : "=r"(i)
  93701. : "r"(b)
  93702. );
  93703. #else
  93704. i = COUNT_ZERO_MSBS(b);
  93705. #endif
  93706. uval += i;
  93707. cbits += i;
  93708. cbits++; /* skip over stop bit */
  93709. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93710. crc16_update_word_(br, br->buffer[cwords]);
  93711. cwords++;
  93712. cbits = 0;
  93713. }
  93714. goto break1;
  93715. }
  93716. else {
  93717. uval += FLAC__BITS_PER_WORD - cbits;
  93718. crc16_update_word_(br, br->buffer[cwords]);
  93719. cwords++;
  93720. cbits = 0;
  93721. /* didn't find stop bit yet, have to keep going... */
  93722. }
  93723. }
  93724. /* at this point we've eaten up all the whole words; have to try
  93725. * reading through any tail bytes before calling the read callback.
  93726. * this is a repeat of the above logic adjusted for the fact we
  93727. * don't have a whole word. note though if the client is feeding
  93728. * us data a byte at a time (unlikely), br->consumed_bits may not
  93729. * be zero.
  93730. */
  93731. if(br->bytes) {
  93732. const unsigned end = br->bytes * 8;
  93733. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93734. if(b) {
  93735. i = COUNT_ZERO_MSBS(b);
  93736. uval += i;
  93737. cbits += i;
  93738. cbits++; /* skip over stop bit */
  93739. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93740. goto break1;
  93741. }
  93742. else {
  93743. uval += end - cbits;
  93744. cbits += end;
  93745. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93746. /* didn't find stop bit yet, have to keep going... */
  93747. }
  93748. }
  93749. /* flush registers and read; bitreader_read_from_client_() does
  93750. * not touch br->consumed_bits at all but we still need to set
  93751. * it in case it fails and we have to return false.
  93752. */
  93753. br->consumed_bits = cbits;
  93754. br->consumed_words = cwords;
  93755. if(!bitreader_read_from_client_(br))
  93756. return false;
  93757. cwords = br->consumed_words;
  93758. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93759. /* + uval to offset our count by the # of unary bits already
  93760. * consumed before the read, because we will add these back
  93761. * in all at once at break1
  93762. */
  93763. }
  93764. break1:
  93765. ucbits -= uval;
  93766. ucbits--; /* account for stop bit */
  93767. /* read binary part */
  93768. FLAC__ASSERT(cwords <= br->words);
  93769. if(parameter) {
  93770. while(ucbits < parameter) {
  93771. /* flush registers and read; bitreader_read_from_client_() does
  93772. * not touch br->consumed_bits at all but we still need to set
  93773. * it in case it fails and we have to return false.
  93774. */
  93775. br->consumed_bits = cbits;
  93776. br->consumed_words = cwords;
  93777. if(!bitreader_read_from_client_(br))
  93778. return false;
  93779. cwords = br->consumed_words;
  93780. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93781. }
  93782. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93783. if(cbits) {
  93784. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93785. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93786. const brword word = br->buffer[cwords];
  93787. if(parameter < n) {
  93788. uval <<= parameter;
  93789. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93790. cbits += parameter;
  93791. }
  93792. else {
  93793. uval <<= n;
  93794. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93795. crc16_update_word_(br, word);
  93796. cwords++;
  93797. cbits = parameter - n;
  93798. 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 */
  93799. uval <<= cbits;
  93800. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93801. }
  93802. }
  93803. }
  93804. else {
  93805. cbits = parameter;
  93806. uval <<= parameter;
  93807. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93808. }
  93809. }
  93810. else {
  93811. /* in this case we're starting our read at a partial tail word;
  93812. * the reader has guaranteed that we have at least 'parameter'
  93813. * bits available to read, which makes this case simpler.
  93814. */
  93815. uval <<= parameter;
  93816. if(cbits) {
  93817. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93818. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93819. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93820. cbits += parameter;
  93821. }
  93822. else {
  93823. cbits = parameter;
  93824. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93825. }
  93826. }
  93827. }
  93828. ucbits -= parameter;
  93829. /* compose the value */
  93830. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93831. /* are we done? */
  93832. --nvals;
  93833. if(nvals == 0) {
  93834. br->consumed_bits = cbits;
  93835. br->consumed_words = cwords;
  93836. return true;
  93837. }
  93838. uval = 0;
  93839. ++vals;
  93840. }
  93841. }
  93842. #endif
  93843. #if 0 /* UNUSED */
  93844. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93845. {
  93846. FLAC__uint32 lsbs = 0, msbs = 0;
  93847. unsigned bit, uval, k;
  93848. FLAC__ASSERT(0 != br);
  93849. FLAC__ASSERT(0 != br->buffer);
  93850. k = FLAC__bitmath_ilog2(parameter);
  93851. /* read the unary MSBs and end bit */
  93852. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93853. return false;
  93854. /* read the binary LSBs */
  93855. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93856. return false;
  93857. if(parameter == 1u<<k) {
  93858. /* compose the value */
  93859. uval = (msbs << k) | lsbs;
  93860. }
  93861. else {
  93862. unsigned d = (1 << (k+1)) - parameter;
  93863. if(lsbs >= d) {
  93864. if(!FLAC__bitreader_read_bit(br, &bit))
  93865. return false;
  93866. lsbs <<= 1;
  93867. lsbs |= bit;
  93868. lsbs -= d;
  93869. }
  93870. /* compose the value */
  93871. uval = msbs * parameter + lsbs;
  93872. }
  93873. /* unfold unsigned to signed */
  93874. if(uval & 1)
  93875. *val = -((int)(uval >> 1)) - 1;
  93876. else
  93877. *val = (int)(uval >> 1);
  93878. return true;
  93879. }
  93880. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93881. {
  93882. FLAC__uint32 lsbs, msbs = 0;
  93883. unsigned bit, k;
  93884. FLAC__ASSERT(0 != br);
  93885. FLAC__ASSERT(0 != br->buffer);
  93886. k = FLAC__bitmath_ilog2(parameter);
  93887. /* read the unary MSBs and end bit */
  93888. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93889. return false;
  93890. /* read the binary LSBs */
  93891. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93892. return false;
  93893. if(parameter == 1u<<k) {
  93894. /* compose the value */
  93895. *val = (msbs << k) | lsbs;
  93896. }
  93897. else {
  93898. unsigned d = (1 << (k+1)) - parameter;
  93899. if(lsbs >= d) {
  93900. if(!FLAC__bitreader_read_bit(br, &bit))
  93901. return false;
  93902. lsbs <<= 1;
  93903. lsbs |= bit;
  93904. lsbs -= d;
  93905. }
  93906. /* compose the value */
  93907. *val = msbs * parameter + lsbs;
  93908. }
  93909. return true;
  93910. }
  93911. #endif /* UNUSED */
  93912. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93913. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93914. {
  93915. FLAC__uint32 v = 0;
  93916. FLAC__uint32 x;
  93917. unsigned i;
  93918. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93919. return false;
  93920. if(raw)
  93921. raw[(*rawlen)++] = (FLAC__byte)x;
  93922. if(!(x & 0x80)) { /* 0xxxxxxx */
  93923. v = x;
  93924. i = 0;
  93925. }
  93926. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93927. v = x & 0x1F;
  93928. i = 1;
  93929. }
  93930. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93931. v = x & 0x0F;
  93932. i = 2;
  93933. }
  93934. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93935. v = x & 0x07;
  93936. i = 3;
  93937. }
  93938. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93939. v = x & 0x03;
  93940. i = 4;
  93941. }
  93942. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93943. v = x & 0x01;
  93944. i = 5;
  93945. }
  93946. else {
  93947. *val = 0xffffffff;
  93948. return true;
  93949. }
  93950. for( ; i; i--) {
  93951. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93952. return false;
  93953. if(raw)
  93954. raw[(*rawlen)++] = (FLAC__byte)x;
  93955. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93956. *val = 0xffffffff;
  93957. return true;
  93958. }
  93959. v <<= 6;
  93960. v |= (x & 0x3F);
  93961. }
  93962. *val = v;
  93963. return true;
  93964. }
  93965. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93966. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93967. {
  93968. FLAC__uint64 v = 0;
  93969. FLAC__uint32 x;
  93970. unsigned i;
  93971. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93972. return false;
  93973. if(raw)
  93974. raw[(*rawlen)++] = (FLAC__byte)x;
  93975. if(!(x & 0x80)) { /* 0xxxxxxx */
  93976. v = x;
  93977. i = 0;
  93978. }
  93979. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93980. v = x & 0x1F;
  93981. i = 1;
  93982. }
  93983. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93984. v = x & 0x0F;
  93985. i = 2;
  93986. }
  93987. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93988. v = x & 0x07;
  93989. i = 3;
  93990. }
  93991. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93992. v = x & 0x03;
  93993. i = 4;
  93994. }
  93995. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93996. v = x & 0x01;
  93997. i = 5;
  93998. }
  93999. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94000. v = 0;
  94001. i = 6;
  94002. }
  94003. else {
  94004. *val = FLAC__U64L(0xffffffffffffffff);
  94005. return true;
  94006. }
  94007. for( ; i; i--) {
  94008. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94009. return false;
  94010. if(raw)
  94011. raw[(*rawlen)++] = (FLAC__byte)x;
  94012. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94013. *val = FLAC__U64L(0xffffffffffffffff);
  94014. return true;
  94015. }
  94016. v <<= 6;
  94017. v |= (x & 0x3F);
  94018. }
  94019. *val = v;
  94020. return true;
  94021. }
  94022. #endif
  94023. /*** End of inlined file: bitreader.c ***/
  94024. /*** Start of inlined file: bitwriter.c ***/
  94025. /*** Start of inlined file: juce_FlacHeader.h ***/
  94026. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94027. // tasks..
  94028. #define VERSION "1.2.1"
  94029. #define FLAC__NO_DLL 1
  94030. #if JUCE_MSVC
  94031. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94032. #endif
  94033. #if JUCE_MAC
  94034. #define FLAC__SYS_DARWIN 1
  94035. #endif
  94036. /*** End of inlined file: juce_FlacHeader.h ***/
  94037. #if JUCE_USE_FLAC
  94038. #if HAVE_CONFIG_H
  94039. # include <config.h>
  94040. #endif
  94041. #include <stdlib.h> /* for malloc() */
  94042. #include <string.h> /* for memcpy(), memset() */
  94043. #ifdef _MSC_VER
  94044. #include <winsock.h> /* for ntohl() */
  94045. #elif defined FLAC__SYS_DARWIN
  94046. #include <machine/endian.h> /* for ntohl() */
  94047. #elif defined __MINGW32__
  94048. #include <winsock.h> /* for ntohl() */
  94049. #else
  94050. #include <netinet/in.h> /* for ntohl() */
  94051. #endif
  94052. #if 0 /* UNUSED */
  94053. #endif
  94054. /*** Start of inlined file: bitwriter.h ***/
  94055. #ifndef FLAC__PRIVATE__BITWRITER_H
  94056. #define FLAC__PRIVATE__BITWRITER_H
  94057. #include <stdio.h> /* for FILE */
  94058. /*
  94059. * opaque structure definition
  94060. */
  94061. struct FLAC__BitWriter;
  94062. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94063. /*
  94064. * construction, deletion, initialization, etc functions
  94065. */
  94066. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94067. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94068. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94069. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94070. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94071. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94072. /*
  94073. * CRC functions
  94074. *
  94075. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94076. */
  94077. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94078. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94079. /*
  94080. * info functions
  94081. */
  94082. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94083. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94084. /*
  94085. * direct buffer access
  94086. *
  94087. * there may be no calls on the bitwriter between get and release.
  94088. * the bitwriter continues to own the returned buffer.
  94089. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94090. */
  94091. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94092. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94093. /*
  94094. * write functions
  94095. */
  94096. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94097. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94098. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94099. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94100. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94101. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94102. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94103. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94104. #if 0 /* UNUSED */
  94105. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94106. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94107. #endif
  94108. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94109. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94110. #if 0 /* UNUSED */
  94111. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94112. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94113. #endif
  94114. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94115. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94116. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94117. #endif
  94118. /*** End of inlined file: bitwriter.h ***/
  94119. /*** Start of inlined file: alloc.h ***/
  94120. #ifndef FLAC__SHARE__ALLOC_H
  94121. #define FLAC__SHARE__ALLOC_H
  94122. #if HAVE_CONFIG_H
  94123. # include <config.h>
  94124. #endif
  94125. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94126. * before #including this file, otherwise SIZE_MAX might not be defined
  94127. */
  94128. #include <limits.h> /* for SIZE_MAX */
  94129. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94130. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94131. #endif
  94132. #include <stdlib.h> /* for size_t, malloc(), etc */
  94133. #ifndef SIZE_MAX
  94134. # ifndef SIZE_T_MAX
  94135. # ifdef _MSC_VER
  94136. # define SIZE_T_MAX UINT_MAX
  94137. # else
  94138. # error
  94139. # endif
  94140. # endif
  94141. # define SIZE_MAX SIZE_T_MAX
  94142. #endif
  94143. #ifndef FLaC__INLINE
  94144. #define FLaC__INLINE
  94145. #endif
  94146. /* avoid malloc()ing 0 bytes, see:
  94147. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94148. */
  94149. static FLaC__INLINE void *safe_malloc_(size_t size)
  94150. {
  94151. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94152. if(!size)
  94153. size++;
  94154. return malloc(size);
  94155. }
  94156. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94157. {
  94158. if(!nmemb || !size)
  94159. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94160. return calloc(nmemb, size);
  94161. }
  94162. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94163. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94164. {
  94165. size2 += size1;
  94166. if(size2 < size1)
  94167. return 0;
  94168. return safe_malloc_(size2);
  94169. }
  94170. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94171. {
  94172. size2 += size1;
  94173. if(size2 < size1)
  94174. return 0;
  94175. size3 += size2;
  94176. if(size3 < size2)
  94177. return 0;
  94178. return safe_malloc_(size3);
  94179. }
  94180. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94181. {
  94182. size2 += size1;
  94183. if(size2 < size1)
  94184. return 0;
  94185. size3 += size2;
  94186. if(size3 < size2)
  94187. return 0;
  94188. size4 += size3;
  94189. if(size4 < size3)
  94190. return 0;
  94191. return safe_malloc_(size4);
  94192. }
  94193. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94194. #if 0
  94195. needs support for cases where sizeof(size_t) != 4
  94196. {
  94197. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94198. if(sizeof(size_t) == 4) {
  94199. if ((double)size1 * (double)size2 < 4294967296.0)
  94200. return malloc(size1*size2);
  94201. }
  94202. return 0;
  94203. }
  94204. #else
  94205. /* better? */
  94206. {
  94207. if(!size1 || !size2)
  94208. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94209. if(size1 > SIZE_MAX / size2)
  94210. return 0;
  94211. return malloc(size1*size2);
  94212. }
  94213. #endif
  94214. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94215. {
  94216. if(!size1 || !size2 || !size3)
  94217. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94218. if(size1 > SIZE_MAX / size2)
  94219. return 0;
  94220. size1 *= size2;
  94221. if(size1 > SIZE_MAX / size3)
  94222. return 0;
  94223. return malloc(size1*size3);
  94224. }
  94225. /* size1*size2 + size3 */
  94226. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94227. {
  94228. if(!size1 || !size2)
  94229. return safe_malloc_(size3);
  94230. if(size1 > SIZE_MAX / size2)
  94231. return 0;
  94232. return safe_malloc_add_2op_(size1*size2, size3);
  94233. }
  94234. /* size1 * (size2 + size3) */
  94235. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94236. {
  94237. if(!size1 || (!size2 && !size3))
  94238. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94239. size2 += size3;
  94240. if(size2 < size3)
  94241. return 0;
  94242. return safe_malloc_mul_2op_(size1, size2);
  94243. }
  94244. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94245. {
  94246. size2 += size1;
  94247. if(size2 < size1)
  94248. return 0;
  94249. return realloc(ptr, size2);
  94250. }
  94251. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94252. {
  94253. size2 += size1;
  94254. if(size2 < size1)
  94255. return 0;
  94256. size3 += size2;
  94257. if(size3 < size2)
  94258. return 0;
  94259. return realloc(ptr, size3);
  94260. }
  94261. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94262. {
  94263. size2 += size1;
  94264. if(size2 < size1)
  94265. return 0;
  94266. size3 += size2;
  94267. if(size3 < size2)
  94268. return 0;
  94269. size4 += size3;
  94270. if(size4 < size3)
  94271. return 0;
  94272. return realloc(ptr, size4);
  94273. }
  94274. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94275. {
  94276. if(!size1 || !size2)
  94277. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94278. if(size1 > SIZE_MAX / size2)
  94279. return 0;
  94280. return realloc(ptr, size1*size2);
  94281. }
  94282. /* size1 * (size2 + size3) */
  94283. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94284. {
  94285. if(!size1 || (!size2 && !size3))
  94286. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94287. size2 += size3;
  94288. if(size2 < size3)
  94289. return 0;
  94290. return safe_realloc_mul_2op_(ptr, size1, size2);
  94291. }
  94292. #endif
  94293. /*** End of inlined file: alloc.h ***/
  94294. /* Things should be fastest when this matches the machine word size */
  94295. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94296. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94297. typedef FLAC__uint32 bwword;
  94298. #define FLAC__BYTES_PER_WORD 4
  94299. #define FLAC__BITS_PER_WORD 32
  94300. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94301. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94302. #if WORDS_BIGENDIAN
  94303. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94304. #else
  94305. #ifdef _MSC_VER
  94306. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94307. #else
  94308. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94309. #endif
  94310. #endif
  94311. /*
  94312. * The default capacity here doesn't matter too much. The buffer always grows
  94313. * to hold whatever is written to it. Usually the encoder will stop adding at
  94314. * a frame or metadata block, then write that out and clear the buffer for the
  94315. * next one.
  94316. */
  94317. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94318. /* When growing, increment 4K at a time */
  94319. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94320. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94321. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94322. #ifdef min
  94323. #undef min
  94324. #endif
  94325. #define min(x,y) ((x)<(y)?(x):(y))
  94326. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94327. #ifdef _MSC_VER
  94328. #define FLAC__U64L(x) x
  94329. #else
  94330. #define FLAC__U64L(x) x##LLU
  94331. #endif
  94332. #ifndef FLaC__INLINE
  94333. #define FLaC__INLINE
  94334. #endif
  94335. struct FLAC__BitWriter {
  94336. bwword *buffer;
  94337. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94338. unsigned capacity; /* capacity of buffer in words */
  94339. unsigned words; /* # of complete words in buffer */
  94340. unsigned bits; /* # of used bits in accum */
  94341. };
  94342. /* * WATCHOUT: The current implementation only grows the buffer. */
  94343. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94344. {
  94345. unsigned new_capacity;
  94346. bwword *new_buffer;
  94347. FLAC__ASSERT(0 != bw);
  94348. FLAC__ASSERT(0 != bw->buffer);
  94349. /* calculate total words needed to store 'bits_to_add' additional bits */
  94350. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94351. /* it's possible (due to pessimism in the growth estimation that
  94352. * leads to this call) that we don't actually need to grow
  94353. */
  94354. if(bw->capacity >= new_capacity)
  94355. return true;
  94356. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94357. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94358. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94359. /* make sure we got everything right */
  94360. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94361. FLAC__ASSERT(new_capacity > bw->capacity);
  94362. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94363. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94364. if(new_buffer == 0)
  94365. return false;
  94366. bw->buffer = new_buffer;
  94367. bw->capacity = new_capacity;
  94368. return true;
  94369. }
  94370. /***********************************************************************
  94371. *
  94372. * Class constructor/destructor
  94373. *
  94374. ***********************************************************************/
  94375. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94376. {
  94377. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94378. /* note that calloc() sets all members to 0 for us */
  94379. return bw;
  94380. }
  94381. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94382. {
  94383. FLAC__ASSERT(0 != bw);
  94384. FLAC__bitwriter_free(bw);
  94385. free(bw);
  94386. }
  94387. /***********************************************************************
  94388. *
  94389. * Public class methods
  94390. *
  94391. ***********************************************************************/
  94392. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94393. {
  94394. FLAC__ASSERT(0 != bw);
  94395. bw->words = bw->bits = 0;
  94396. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94397. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94398. if(bw->buffer == 0)
  94399. return false;
  94400. return true;
  94401. }
  94402. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94403. {
  94404. FLAC__ASSERT(0 != bw);
  94405. if(0 != bw->buffer)
  94406. free(bw->buffer);
  94407. bw->buffer = 0;
  94408. bw->capacity = 0;
  94409. bw->words = bw->bits = 0;
  94410. }
  94411. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94412. {
  94413. bw->words = bw->bits = 0;
  94414. }
  94415. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94416. {
  94417. unsigned i, j;
  94418. if(bw == 0) {
  94419. fprintf(out, "bitwriter is NULL\n");
  94420. }
  94421. else {
  94422. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94423. for(i = 0; i < bw->words; i++) {
  94424. fprintf(out, "%08X: ", i);
  94425. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94426. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94427. fprintf(out, "\n");
  94428. }
  94429. if(bw->bits > 0) {
  94430. fprintf(out, "%08X: ", i);
  94431. for(j = 0; j < bw->bits; j++)
  94432. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94433. fprintf(out, "\n");
  94434. }
  94435. }
  94436. }
  94437. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94438. {
  94439. const FLAC__byte *buffer;
  94440. size_t bytes;
  94441. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94442. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94443. return false;
  94444. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94445. FLAC__bitwriter_release_buffer(bw);
  94446. return true;
  94447. }
  94448. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94449. {
  94450. const FLAC__byte *buffer;
  94451. size_t bytes;
  94452. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94453. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94454. return false;
  94455. *crc = FLAC__crc8(buffer, bytes);
  94456. FLAC__bitwriter_release_buffer(bw);
  94457. return true;
  94458. }
  94459. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94460. {
  94461. return ((bw->bits & 7) == 0);
  94462. }
  94463. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94464. {
  94465. return FLAC__TOTAL_BITS(bw);
  94466. }
  94467. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94468. {
  94469. FLAC__ASSERT((bw->bits & 7) == 0);
  94470. /* double protection */
  94471. if(bw->bits & 7)
  94472. return false;
  94473. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94474. if(bw->bits) {
  94475. FLAC__ASSERT(bw->words <= bw->capacity);
  94476. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94477. return false;
  94478. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94479. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94480. }
  94481. /* now we can just return what we have */
  94482. *buffer = (FLAC__byte*)bw->buffer;
  94483. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94484. return true;
  94485. }
  94486. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94487. {
  94488. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94489. * get-mode' flag could be added everywhere and then cleared here
  94490. */
  94491. (void)bw;
  94492. }
  94493. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94494. {
  94495. unsigned n;
  94496. FLAC__ASSERT(0 != bw);
  94497. FLAC__ASSERT(0 != bw->buffer);
  94498. if(bits == 0)
  94499. return true;
  94500. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94501. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94502. return false;
  94503. /* first part gets to word alignment */
  94504. if(bw->bits) {
  94505. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94506. bw->accum <<= n;
  94507. bits -= n;
  94508. bw->bits += n;
  94509. if(bw->bits == FLAC__BITS_PER_WORD) {
  94510. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94511. bw->bits = 0;
  94512. }
  94513. else
  94514. return true;
  94515. }
  94516. /* do whole words */
  94517. while(bits >= FLAC__BITS_PER_WORD) {
  94518. bw->buffer[bw->words++] = 0;
  94519. bits -= FLAC__BITS_PER_WORD;
  94520. }
  94521. /* do any leftovers */
  94522. if(bits > 0) {
  94523. bw->accum = 0;
  94524. bw->bits = bits;
  94525. }
  94526. return true;
  94527. }
  94528. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94529. {
  94530. register unsigned left;
  94531. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94532. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94533. FLAC__ASSERT(0 != bw);
  94534. FLAC__ASSERT(0 != bw->buffer);
  94535. FLAC__ASSERT(bits <= 32);
  94536. if(bits == 0)
  94537. return true;
  94538. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94539. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94540. return false;
  94541. left = FLAC__BITS_PER_WORD - bw->bits;
  94542. if(bits < left) {
  94543. bw->accum <<= bits;
  94544. bw->accum |= val;
  94545. bw->bits += bits;
  94546. }
  94547. 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 */
  94548. bw->accum <<= left;
  94549. bw->accum |= val >> (bw->bits = bits - left);
  94550. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94551. bw->accum = val;
  94552. }
  94553. else {
  94554. bw->accum = val;
  94555. bw->bits = 0;
  94556. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94557. }
  94558. return true;
  94559. }
  94560. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94561. {
  94562. /* zero-out unused bits */
  94563. if(bits < 32)
  94564. val &= (~(0xffffffff << bits));
  94565. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94566. }
  94567. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94568. {
  94569. /* this could be a little faster but it's not used for much */
  94570. if(bits > 32) {
  94571. return
  94572. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94573. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94574. }
  94575. else
  94576. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94577. }
  94578. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94579. {
  94580. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94581. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94582. return false;
  94583. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94584. return false;
  94585. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94586. return false;
  94587. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94588. return false;
  94589. return true;
  94590. }
  94591. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94592. {
  94593. unsigned i;
  94594. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94595. for(i = 0; i < nvals; i++) {
  94596. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94597. return false;
  94598. }
  94599. return true;
  94600. }
  94601. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94602. {
  94603. if(val < 32)
  94604. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94605. else
  94606. return
  94607. FLAC__bitwriter_write_zeroes(bw, val) &&
  94608. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94609. }
  94610. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94611. {
  94612. FLAC__uint32 uval;
  94613. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94614. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94615. uval = (val<<1) ^ (val>>31);
  94616. return 1 + parameter + (uval >> parameter);
  94617. }
  94618. #if 0 /* UNUSED */
  94619. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94620. {
  94621. unsigned bits, msbs, uval;
  94622. unsigned k;
  94623. FLAC__ASSERT(parameter > 0);
  94624. /* fold signed to unsigned */
  94625. if(val < 0)
  94626. uval = (unsigned)(((-(++val)) << 1) + 1);
  94627. else
  94628. uval = (unsigned)(val << 1);
  94629. k = FLAC__bitmath_ilog2(parameter);
  94630. if(parameter == 1u<<k) {
  94631. FLAC__ASSERT(k <= 30);
  94632. msbs = uval >> k;
  94633. bits = 1 + k + msbs;
  94634. }
  94635. else {
  94636. unsigned q, r, d;
  94637. d = (1 << (k+1)) - parameter;
  94638. q = uval / parameter;
  94639. r = uval - (q * parameter);
  94640. bits = 1 + q + k;
  94641. if(r >= d)
  94642. bits++;
  94643. }
  94644. return bits;
  94645. }
  94646. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94647. {
  94648. unsigned bits, msbs;
  94649. unsigned k;
  94650. FLAC__ASSERT(parameter > 0);
  94651. k = FLAC__bitmath_ilog2(parameter);
  94652. if(parameter == 1u<<k) {
  94653. FLAC__ASSERT(k <= 30);
  94654. msbs = uval >> k;
  94655. bits = 1 + k + msbs;
  94656. }
  94657. else {
  94658. unsigned q, r, d;
  94659. d = (1 << (k+1)) - parameter;
  94660. q = uval / parameter;
  94661. r = uval - (q * parameter);
  94662. bits = 1 + q + k;
  94663. if(r >= d)
  94664. bits++;
  94665. }
  94666. return bits;
  94667. }
  94668. #endif /* UNUSED */
  94669. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94670. {
  94671. unsigned total_bits, interesting_bits, msbs;
  94672. FLAC__uint32 uval, pattern;
  94673. FLAC__ASSERT(0 != bw);
  94674. FLAC__ASSERT(0 != bw->buffer);
  94675. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94676. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94677. uval = (val<<1) ^ (val>>31);
  94678. msbs = uval >> parameter;
  94679. interesting_bits = 1 + parameter;
  94680. total_bits = interesting_bits + msbs;
  94681. pattern = 1 << parameter; /* the unary end bit */
  94682. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94683. if(total_bits <= 32)
  94684. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94685. else
  94686. return
  94687. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94688. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94689. }
  94690. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94691. {
  94692. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94693. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94694. FLAC__uint32 uval;
  94695. unsigned left;
  94696. const unsigned lsbits = 1 + parameter;
  94697. unsigned msbits;
  94698. FLAC__ASSERT(0 != bw);
  94699. FLAC__ASSERT(0 != bw->buffer);
  94700. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94701. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94702. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94703. while(nvals) {
  94704. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94705. uval = (*vals<<1) ^ (*vals>>31);
  94706. msbits = uval >> parameter;
  94707. #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) */
  94708. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94709. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94710. bw->bits = bw->bits + msbits + lsbits;
  94711. uval |= mask1; /* set stop bit */
  94712. uval &= mask2; /* mask off unused top bits */
  94713. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94714. bw->accum <<= msbits;
  94715. bw->accum <<= lsbits;
  94716. bw->accum |= uval;
  94717. if(bw->bits == FLAC__BITS_PER_WORD) {
  94718. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94719. bw->bits = 0;
  94720. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94721. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94722. FLAC__ASSERT(bw->capacity == bw->words);
  94723. return false;
  94724. }
  94725. }
  94726. }
  94727. else {
  94728. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94729. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94730. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94731. bw->bits = bw->bits + msbits + lsbits;
  94732. uval |= mask1; /* set stop bit */
  94733. uval &= mask2; /* mask off unused top bits */
  94734. bw->accum <<= msbits + lsbits;
  94735. bw->accum |= uval;
  94736. }
  94737. else {
  94738. #endif
  94739. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94740. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94741. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94742. return false;
  94743. if(msbits) {
  94744. /* first part gets to word alignment */
  94745. if(bw->bits) {
  94746. left = FLAC__BITS_PER_WORD - bw->bits;
  94747. if(msbits < left) {
  94748. bw->accum <<= msbits;
  94749. bw->bits += msbits;
  94750. goto break1;
  94751. }
  94752. else {
  94753. bw->accum <<= left;
  94754. msbits -= left;
  94755. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94756. bw->bits = 0;
  94757. }
  94758. }
  94759. /* do whole words */
  94760. while(msbits >= FLAC__BITS_PER_WORD) {
  94761. bw->buffer[bw->words++] = 0;
  94762. msbits -= FLAC__BITS_PER_WORD;
  94763. }
  94764. /* do any leftovers */
  94765. if(msbits > 0) {
  94766. bw->accum = 0;
  94767. bw->bits = msbits;
  94768. }
  94769. }
  94770. break1:
  94771. uval |= mask1; /* set stop bit */
  94772. uval &= mask2; /* mask off unused top bits */
  94773. left = FLAC__BITS_PER_WORD - bw->bits;
  94774. if(lsbits < left) {
  94775. bw->accum <<= lsbits;
  94776. bw->accum |= uval;
  94777. bw->bits += lsbits;
  94778. }
  94779. else {
  94780. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94781. * be > lsbits (because of previous assertions) so it would have
  94782. * triggered the (lsbits<left) case above.
  94783. */
  94784. FLAC__ASSERT(bw->bits);
  94785. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94786. bw->accum <<= left;
  94787. bw->accum |= uval >> (bw->bits = lsbits - left);
  94788. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94789. bw->accum = uval;
  94790. }
  94791. #if 1
  94792. }
  94793. #endif
  94794. vals++;
  94795. nvals--;
  94796. }
  94797. return true;
  94798. }
  94799. #if 0 /* UNUSED */
  94800. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94801. {
  94802. unsigned total_bits, msbs, uval;
  94803. unsigned k;
  94804. FLAC__ASSERT(0 != bw);
  94805. FLAC__ASSERT(0 != bw->buffer);
  94806. FLAC__ASSERT(parameter > 0);
  94807. /* fold signed to unsigned */
  94808. if(val < 0)
  94809. uval = (unsigned)(((-(++val)) << 1) + 1);
  94810. else
  94811. uval = (unsigned)(val << 1);
  94812. k = FLAC__bitmath_ilog2(parameter);
  94813. if(parameter == 1u<<k) {
  94814. unsigned pattern;
  94815. FLAC__ASSERT(k <= 30);
  94816. msbs = uval >> k;
  94817. total_bits = 1 + k + msbs;
  94818. pattern = 1 << k; /* the unary end bit */
  94819. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94820. if(total_bits <= 32) {
  94821. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94822. return false;
  94823. }
  94824. else {
  94825. /* write the unary MSBs */
  94826. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94827. return false;
  94828. /* write the unary end bit and binary LSBs */
  94829. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94830. return false;
  94831. }
  94832. }
  94833. else {
  94834. unsigned q, r, d;
  94835. d = (1 << (k+1)) - parameter;
  94836. q = uval / parameter;
  94837. r = uval - (q * parameter);
  94838. /* write the unary MSBs */
  94839. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94840. return false;
  94841. /* write the unary end bit */
  94842. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94843. return false;
  94844. /* write the binary LSBs */
  94845. if(r >= d) {
  94846. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94847. return false;
  94848. }
  94849. else {
  94850. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94851. return false;
  94852. }
  94853. }
  94854. return true;
  94855. }
  94856. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94857. {
  94858. unsigned total_bits, msbs;
  94859. unsigned k;
  94860. FLAC__ASSERT(0 != bw);
  94861. FLAC__ASSERT(0 != bw->buffer);
  94862. FLAC__ASSERT(parameter > 0);
  94863. k = FLAC__bitmath_ilog2(parameter);
  94864. if(parameter == 1u<<k) {
  94865. unsigned pattern;
  94866. FLAC__ASSERT(k <= 30);
  94867. msbs = uval >> k;
  94868. total_bits = 1 + k + msbs;
  94869. pattern = 1 << k; /* the unary end bit */
  94870. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94871. if(total_bits <= 32) {
  94872. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94873. return false;
  94874. }
  94875. else {
  94876. /* write the unary MSBs */
  94877. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94878. return false;
  94879. /* write the unary end bit and binary LSBs */
  94880. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94881. return false;
  94882. }
  94883. }
  94884. else {
  94885. unsigned q, r, d;
  94886. d = (1 << (k+1)) - parameter;
  94887. q = uval / parameter;
  94888. r = uval - (q * parameter);
  94889. /* write the unary MSBs */
  94890. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94891. return false;
  94892. /* write the unary end bit */
  94893. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94894. return false;
  94895. /* write the binary LSBs */
  94896. if(r >= d) {
  94897. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94898. return false;
  94899. }
  94900. else {
  94901. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94902. return false;
  94903. }
  94904. }
  94905. return true;
  94906. }
  94907. #endif /* UNUSED */
  94908. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94909. {
  94910. FLAC__bool ok = 1;
  94911. FLAC__ASSERT(0 != bw);
  94912. FLAC__ASSERT(0 != bw->buffer);
  94913. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94914. if(val < 0x80) {
  94915. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94916. }
  94917. else if(val < 0x800) {
  94918. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94919. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94920. }
  94921. else if(val < 0x10000) {
  94922. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94923. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94924. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94925. }
  94926. else if(val < 0x200000) {
  94927. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94928. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94929. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94930. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94931. }
  94932. else if(val < 0x4000000) {
  94933. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94934. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94935. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94936. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94937. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94938. }
  94939. else {
  94940. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94941. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94942. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94943. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94944. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94945. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94946. }
  94947. return ok;
  94948. }
  94949. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94950. {
  94951. FLAC__bool ok = 1;
  94952. FLAC__ASSERT(0 != bw);
  94953. FLAC__ASSERT(0 != bw->buffer);
  94954. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94955. if(val < 0x80) {
  94956. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94957. }
  94958. else if(val < 0x800) {
  94959. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94960. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94961. }
  94962. else if(val < 0x10000) {
  94963. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94964. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94965. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94966. }
  94967. else if(val < 0x200000) {
  94968. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94969. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94970. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94971. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94972. }
  94973. else if(val < 0x4000000) {
  94974. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94975. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94976. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94977. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94978. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94979. }
  94980. else if(val < 0x80000000) {
  94981. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94982. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94983. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94984. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94985. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94986. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94987. }
  94988. else {
  94989. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94990. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94991. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94992. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94993. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94994. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94995. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94996. }
  94997. return ok;
  94998. }
  94999. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95000. {
  95001. /* 0-pad to byte boundary */
  95002. if(bw->bits & 7u)
  95003. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95004. else
  95005. return true;
  95006. }
  95007. #endif
  95008. /*** End of inlined file: bitwriter.c ***/
  95009. /*** Start of inlined file: cpu.c ***/
  95010. /*** Start of inlined file: juce_FlacHeader.h ***/
  95011. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95012. // tasks..
  95013. #define VERSION "1.2.1"
  95014. #define FLAC__NO_DLL 1
  95015. #if JUCE_MSVC
  95016. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95017. #endif
  95018. #if JUCE_MAC
  95019. #define FLAC__SYS_DARWIN 1
  95020. #endif
  95021. /*** End of inlined file: juce_FlacHeader.h ***/
  95022. #if JUCE_USE_FLAC
  95023. #if HAVE_CONFIG_H
  95024. # include <config.h>
  95025. #endif
  95026. #include <stdlib.h>
  95027. #include <stdio.h>
  95028. #if defined FLAC__CPU_IA32
  95029. # include <signal.h>
  95030. #elif defined FLAC__CPU_PPC
  95031. # if !defined FLAC__NO_ASM
  95032. # if defined FLAC__SYS_DARWIN
  95033. # include <sys/sysctl.h>
  95034. # include <mach/mach.h>
  95035. # include <mach/mach_host.h>
  95036. # include <mach/host_info.h>
  95037. # include <mach/machine.h>
  95038. # ifndef CPU_SUBTYPE_POWERPC_970
  95039. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95040. # endif
  95041. # else /* FLAC__SYS_DARWIN */
  95042. # include <signal.h>
  95043. # include <setjmp.h>
  95044. static sigjmp_buf jmpbuf;
  95045. static volatile sig_atomic_t canjump = 0;
  95046. static void sigill_handler (int sig)
  95047. {
  95048. if (!canjump) {
  95049. signal (sig, SIG_DFL);
  95050. raise (sig);
  95051. }
  95052. canjump = 0;
  95053. siglongjmp (jmpbuf, 1);
  95054. }
  95055. # endif /* FLAC__SYS_DARWIN */
  95056. # endif /* FLAC__NO_ASM */
  95057. #endif /* FLAC__CPU_PPC */
  95058. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95059. #include <sys/param.h>
  95060. #include <sys/sysctl.h>
  95061. #include <machine/cpu.h>
  95062. #endif
  95063. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95064. #include <sys/types.h>
  95065. #include <sys/sysctl.h>
  95066. #endif
  95067. #if defined(__APPLE__)
  95068. /* how to get sysctlbyname()? */
  95069. #endif
  95070. /* these are flags in EDX of CPUID AX=00000001 */
  95071. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95072. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95073. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95074. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95075. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95076. /* these are flags in ECX of CPUID AX=00000001 */
  95077. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95078. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95079. /* these are flags in EDX of CPUID AX=80000001 */
  95080. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95081. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95082. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95083. /*
  95084. * Extra stuff needed for detection of OS support for SSE on IA-32
  95085. */
  95086. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95087. # if defined(__linux__)
  95088. /*
  95089. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95090. * modify the return address to jump over the offending SSE instruction
  95091. * and also the operation following it that indicates the instruction
  95092. * executed successfully. In this way we use no global variables and
  95093. * stay thread-safe.
  95094. *
  95095. * 3 + 3 + 6:
  95096. * 3 bytes for "xorps xmm0,xmm0"
  95097. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95098. * 6 bytes extra in case our estimate is wrong
  95099. * 12 bytes puts us in the NOP "landing zone"
  95100. */
  95101. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95102. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95103. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95104. {
  95105. (void)signal;
  95106. sc.eip += 3 + 3 + 6;
  95107. }
  95108. # else
  95109. # include <sys/ucontext.h>
  95110. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95111. {
  95112. (void)signal, (void)si;
  95113. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95114. }
  95115. # endif
  95116. # elif defined(_MSC_VER)
  95117. # include <windows.h>
  95118. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95119. # ifdef USE_TRY_CATCH_FLAVOR
  95120. # else
  95121. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95122. {
  95123. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95124. ep->ContextRecord->Eip += 3 + 3 + 6;
  95125. return EXCEPTION_CONTINUE_EXECUTION;
  95126. }
  95127. return EXCEPTION_CONTINUE_SEARCH;
  95128. }
  95129. # endif
  95130. # endif
  95131. #endif
  95132. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95133. {
  95134. /*
  95135. * IA32-specific
  95136. */
  95137. #ifdef FLAC__CPU_IA32
  95138. info->type = FLAC__CPUINFO_TYPE_IA32;
  95139. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95140. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95141. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95142. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95143. info->data.ia32.cmov = false;
  95144. info->data.ia32.mmx = false;
  95145. info->data.ia32.fxsr = false;
  95146. info->data.ia32.sse = false;
  95147. info->data.ia32.sse2 = false;
  95148. info->data.ia32.sse3 = false;
  95149. info->data.ia32.ssse3 = false;
  95150. info->data.ia32._3dnow = false;
  95151. info->data.ia32.ext3dnow = false;
  95152. info->data.ia32.extmmx = false;
  95153. if(info->data.ia32.cpuid) {
  95154. /* http://www.sandpile.org/ia32/cpuid.htm */
  95155. FLAC__uint32 flags_edx, flags_ecx;
  95156. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95157. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95158. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95159. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95160. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95161. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95162. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95163. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95164. #ifdef FLAC__USE_3DNOW
  95165. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95166. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95167. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95168. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95169. #else
  95170. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95171. #endif
  95172. #ifdef DEBUG
  95173. fprintf(stderr, "CPU info (IA-32):\n");
  95174. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95175. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95176. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95177. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95178. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95179. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95180. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95181. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95182. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95183. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95184. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95185. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95186. #endif
  95187. /*
  95188. * now have to check for OS support of SSE/SSE2
  95189. */
  95190. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95191. #if defined FLAC__NO_SSE_OS
  95192. /* assume user knows better than us; turn it off */
  95193. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95194. #elif defined FLAC__SSE_OS
  95195. /* assume user knows better than us; leave as detected above */
  95196. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95197. int sse = 0;
  95198. size_t len;
  95199. /* at least one of these must work: */
  95200. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95201. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95202. if(!sse)
  95203. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95204. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95205. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95206. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95207. size_t len = sizeof(val);
  95208. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95209. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95210. else { /* double-check SSE2 */
  95211. mib[1] = CPU_SSE2;
  95212. len = sizeof(val);
  95213. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95214. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95215. }
  95216. # else
  95217. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95218. # endif
  95219. #elif defined(__linux__)
  95220. int sse = 0;
  95221. struct sigaction sigill_save;
  95222. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95223. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95224. #else
  95225. struct sigaction sigill_sse;
  95226. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95227. __sigemptyset(&sigill_sse.sa_mask);
  95228. 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 */
  95229. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95230. #endif
  95231. {
  95232. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95233. /* see sigill_handler_sse_os() for an explanation of the following: */
  95234. asm volatile (
  95235. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95236. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95237. "incl %0\n\t" /* SIGILL handler will jump over this */
  95238. /* landing zone */
  95239. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95240. "nop\n\t"
  95241. "nop\n\t"
  95242. "nop\n\t"
  95243. "nop\n\t"
  95244. "nop\n\t"
  95245. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95246. "nop\n\t"
  95247. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95248. : "=r"(sse)
  95249. : "r"(sse)
  95250. );
  95251. sigaction(SIGILL, &sigill_save, NULL);
  95252. }
  95253. if(!sse)
  95254. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95255. #elif defined(_MSC_VER)
  95256. # ifdef USE_TRY_CATCH_FLAVOR
  95257. _try {
  95258. __asm {
  95259. # if _MSC_VER <= 1200
  95260. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95261. _emit 0x0F
  95262. _emit 0x57
  95263. _emit 0xC0
  95264. # else
  95265. xorps xmm0,xmm0
  95266. # endif
  95267. }
  95268. }
  95269. _except(EXCEPTION_EXECUTE_HANDLER) {
  95270. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95271. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95272. }
  95273. # else
  95274. int sse = 0;
  95275. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95276. /* see GCC version above for explanation */
  95277. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95278. /* http://www.codeproject.com/cpp/gccasm.asp */
  95279. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95280. __asm {
  95281. # if _MSC_VER <= 1200
  95282. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95283. _emit 0x0F
  95284. _emit 0x57
  95285. _emit 0xC0
  95286. # else
  95287. xorps xmm0,xmm0
  95288. # endif
  95289. inc sse
  95290. nop
  95291. nop
  95292. nop
  95293. nop
  95294. nop
  95295. nop
  95296. nop
  95297. nop
  95298. nop
  95299. }
  95300. SetUnhandledExceptionFilter(save);
  95301. if(!sse)
  95302. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95303. # endif
  95304. #else
  95305. /* no way to test, disable to be safe */
  95306. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95307. #endif
  95308. #ifdef DEBUG
  95309. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95310. #endif
  95311. }
  95312. }
  95313. #else
  95314. info->use_asm = false;
  95315. #endif
  95316. /*
  95317. * PPC-specific
  95318. */
  95319. #elif defined FLAC__CPU_PPC
  95320. info->type = FLAC__CPUINFO_TYPE_PPC;
  95321. # if !defined FLAC__NO_ASM
  95322. info->use_asm = true;
  95323. # ifdef FLAC__USE_ALTIVEC
  95324. # if defined FLAC__SYS_DARWIN
  95325. {
  95326. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95327. size_t len = sizeof(val);
  95328. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95329. }
  95330. {
  95331. host_basic_info_data_t hostInfo;
  95332. mach_msg_type_number_t infoCount;
  95333. infoCount = HOST_BASIC_INFO_COUNT;
  95334. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95335. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95336. }
  95337. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95338. {
  95339. /* no Darwin, do it the brute-force way */
  95340. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95341. info->data.ppc.altivec = 0;
  95342. info->data.ppc.ppc64 = 0;
  95343. signal (SIGILL, sigill_handler);
  95344. canjump = 0;
  95345. if (!sigsetjmp (jmpbuf, 1)) {
  95346. canjump = 1;
  95347. asm volatile (
  95348. "mtspr 256, %0\n\t"
  95349. "vand %%v0, %%v0, %%v0"
  95350. :
  95351. : "r" (-1)
  95352. );
  95353. info->data.ppc.altivec = 1;
  95354. }
  95355. canjump = 0;
  95356. if (!sigsetjmp (jmpbuf, 1)) {
  95357. int x = 0;
  95358. canjump = 1;
  95359. /* PPC64 hardware implements the cntlzd instruction */
  95360. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95361. info->data.ppc.ppc64 = 1;
  95362. }
  95363. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95364. }
  95365. # endif
  95366. # else /* !FLAC__USE_ALTIVEC */
  95367. info->data.ppc.altivec = 0;
  95368. info->data.ppc.ppc64 = 0;
  95369. # endif
  95370. # else
  95371. info->use_asm = false;
  95372. # endif
  95373. /*
  95374. * unknown CPI
  95375. */
  95376. #else
  95377. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95378. info->use_asm = false;
  95379. #endif
  95380. }
  95381. #endif
  95382. /*** End of inlined file: cpu.c ***/
  95383. /*** Start of inlined file: crc.c ***/
  95384. /*** Start of inlined file: juce_FlacHeader.h ***/
  95385. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95386. // tasks..
  95387. #define VERSION "1.2.1"
  95388. #define FLAC__NO_DLL 1
  95389. #if JUCE_MSVC
  95390. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95391. #endif
  95392. #if JUCE_MAC
  95393. #define FLAC__SYS_DARWIN 1
  95394. #endif
  95395. /*** End of inlined file: juce_FlacHeader.h ***/
  95396. #if JUCE_USE_FLAC
  95397. #if HAVE_CONFIG_H
  95398. # include <config.h>
  95399. #endif
  95400. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95401. FLAC__byte const FLAC__crc8_table[256] = {
  95402. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95403. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95404. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95405. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95406. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95407. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95408. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95409. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95410. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95411. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95412. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95413. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95414. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95415. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95416. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95417. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95418. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95419. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95420. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95421. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95422. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95423. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95424. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95425. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95426. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95427. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95428. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95429. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95430. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95431. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95432. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95433. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95434. };
  95435. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95436. unsigned FLAC__crc16_table[256] = {
  95437. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95438. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95439. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95440. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95441. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95442. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95443. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95444. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95445. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95446. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95447. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95448. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95449. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95450. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95451. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95452. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95453. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95454. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95455. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95456. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95457. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95458. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95459. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95460. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95461. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95462. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95463. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95464. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95465. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95466. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95467. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95468. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95469. };
  95470. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95471. {
  95472. *crc = FLAC__crc8_table[*crc ^ data];
  95473. }
  95474. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95475. {
  95476. while(len--)
  95477. *crc = FLAC__crc8_table[*crc ^ *data++];
  95478. }
  95479. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95480. {
  95481. FLAC__uint8 crc = 0;
  95482. while(len--)
  95483. crc = FLAC__crc8_table[crc ^ *data++];
  95484. return crc;
  95485. }
  95486. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95487. {
  95488. unsigned crc = 0;
  95489. while(len--)
  95490. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95491. return crc;
  95492. }
  95493. #endif
  95494. /*** End of inlined file: crc.c ***/
  95495. /*** Start of inlined file: fixed.c ***/
  95496. /*** Start of inlined file: juce_FlacHeader.h ***/
  95497. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95498. // tasks..
  95499. #define VERSION "1.2.1"
  95500. #define FLAC__NO_DLL 1
  95501. #if JUCE_MSVC
  95502. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95503. #endif
  95504. #if JUCE_MAC
  95505. #define FLAC__SYS_DARWIN 1
  95506. #endif
  95507. /*** End of inlined file: juce_FlacHeader.h ***/
  95508. #if JUCE_USE_FLAC
  95509. #if HAVE_CONFIG_H
  95510. # include <config.h>
  95511. #endif
  95512. #include <math.h>
  95513. #include <string.h>
  95514. /*** Start of inlined file: fixed.h ***/
  95515. #ifndef FLAC__PRIVATE__FIXED_H
  95516. #define FLAC__PRIVATE__FIXED_H
  95517. #ifdef HAVE_CONFIG_H
  95518. #include <config.h>
  95519. #endif
  95520. /*** Start of inlined file: float.h ***/
  95521. #ifndef FLAC__PRIVATE__FLOAT_H
  95522. #define FLAC__PRIVATE__FLOAT_H
  95523. #ifdef HAVE_CONFIG_H
  95524. #include <config.h>
  95525. #endif
  95526. /*
  95527. * These typedefs make it easier to ensure that integer versions of
  95528. * the library really only contain integer operations. All the code
  95529. * in libFLAC should use FLAC__float and FLAC__double in place of
  95530. * float and double, and be protected by checks of the macro
  95531. * FLAC__INTEGER_ONLY_LIBRARY.
  95532. *
  95533. * FLAC__real is the basic floating point type used in LPC analysis.
  95534. */
  95535. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95536. typedef double FLAC__double;
  95537. typedef float FLAC__float;
  95538. /*
  95539. * WATCHOUT: changing FLAC__real will change the signatures of many
  95540. * functions that have assembly language equivalents and break them.
  95541. */
  95542. typedef float FLAC__real;
  95543. #else
  95544. /*
  95545. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95546. * for the integer part and lower 16 bits for the fractional part.
  95547. */
  95548. typedef FLAC__int32 FLAC__fixedpoint;
  95549. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95550. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95551. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95552. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95553. extern const FLAC__fixedpoint FLAC__FP_E;
  95554. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95555. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95556. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95557. /*
  95558. * FLAC__fixedpoint_log2()
  95559. * --------------------------------------------------------------------
  95560. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95561. * algorithm by Knuth for x >= 1.0
  95562. *
  95563. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95564. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95565. *
  95566. * 'precision' roughly limits the number of iterations that are done;
  95567. * use (unsigned)(-1) for maximum precision.
  95568. *
  95569. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95570. * function will punt and return 0.
  95571. *
  95572. * The return value will also have 'fracbits' fractional bits.
  95573. */
  95574. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95575. #endif
  95576. #endif
  95577. /*** End of inlined file: float.h ***/
  95578. /*** Start of inlined file: format.h ***/
  95579. #ifndef FLAC__PRIVATE__FORMAT_H
  95580. #define FLAC__PRIVATE__FORMAT_H
  95581. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95582. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95583. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95584. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95585. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95586. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95587. #endif
  95588. /*** End of inlined file: format.h ***/
  95589. /*
  95590. * FLAC__fixed_compute_best_predictor()
  95591. * --------------------------------------------------------------------
  95592. * Compute the best fixed predictor and the expected bits-per-sample
  95593. * of the residual signal for each order. The _wide() version uses
  95594. * 64-bit integers which is statistically necessary when bits-per-
  95595. * sample + log2(blocksize) > 30
  95596. *
  95597. * IN data[0,data_len-1]
  95598. * IN data_len
  95599. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95600. */
  95601. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95602. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95603. # ifndef FLAC__NO_ASM
  95604. # ifdef FLAC__CPU_IA32
  95605. # ifdef FLAC__HAS_NASM
  95606. 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]);
  95607. # endif
  95608. # endif
  95609. # endif
  95610. 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]);
  95611. #else
  95612. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95613. 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]);
  95614. #endif
  95615. /*
  95616. * FLAC__fixed_compute_residual()
  95617. * --------------------------------------------------------------------
  95618. * Compute the residual signal obtained from sutracting the predicted
  95619. * signal from the original.
  95620. *
  95621. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95622. * IN data_len length of original signal
  95623. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95624. * OUT residual[0,data_len-1] residual signal
  95625. */
  95626. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95627. /*
  95628. * FLAC__fixed_restore_signal()
  95629. * --------------------------------------------------------------------
  95630. * Restore the original signal by summing the residual and the
  95631. * predictor.
  95632. *
  95633. * IN residual[0,data_len-1] residual signal
  95634. * IN data_len length of original signal
  95635. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95636. * *** IMPORTANT: the caller must pass in the historical samples:
  95637. * IN data[-order,-1] previously-reconstructed historical samples
  95638. * OUT data[0,data_len-1] original signal
  95639. */
  95640. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95641. #endif
  95642. /*** End of inlined file: fixed.h ***/
  95643. #ifndef M_LN2
  95644. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95645. #define M_LN2 0.69314718055994530942
  95646. #endif
  95647. #ifdef min
  95648. #undef min
  95649. #endif
  95650. #define min(x,y) ((x) < (y)? (x) : (y))
  95651. #ifdef local_abs
  95652. #undef local_abs
  95653. #endif
  95654. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95655. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95656. /* rbps stands for residual bits per sample
  95657. *
  95658. * (ln(2) * err)
  95659. * rbps = log (-----------)
  95660. * 2 ( n )
  95661. */
  95662. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95663. {
  95664. FLAC__uint32 rbps;
  95665. unsigned bits; /* the number of bits required to represent a number */
  95666. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95667. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95668. FLAC__ASSERT(err > 0);
  95669. FLAC__ASSERT(n > 0);
  95670. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95671. if(err <= n)
  95672. return 0;
  95673. /*
  95674. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95675. * These allow us later to know we won't lose too much precision in the
  95676. * fixed-point division (err<<fracbits)/n.
  95677. */
  95678. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95679. err <<= fracbits;
  95680. err /= n;
  95681. /* err now holds err/n with fracbits fractional bits */
  95682. /*
  95683. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95684. * our purposes.
  95685. */
  95686. FLAC__ASSERT(err > 0);
  95687. bits = FLAC__bitmath_ilog2(err)+1;
  95688. if(bits > 16) {
  95689. err >>= (bits-16);
  95690. fracbits -= (bits-16);
  95691. }
  95692. rbps = (FLAC__uint32)err;
  95693. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95694. rbps *= FLAC__FP_LN2;
  95695. fracbits += 16;
  95696. FLAC__ASSERT(fracbits >= 0);
  95697. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95698. {
  95699. const int f = fracbits & 3;
  95700. if(f) {
  95701. rbps >>= f;
  95702. fracbits -= f;
  95703. }
  95704. }
  95705. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95706. if(rbps == 0)
  95707. return 0;
  95708. /*
  95709. * The return value must have 16 fractional bits. Since the whole part
  95710. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95711. * must be >= -3, these assertion allows us to be able to shift rbps
  95712. * left if necessary to get 16 fracbits without losing any bits of the
  95713. * whole part of rbps.
  95714. *
  95715. * There is a slight chance due to accumulated error that the whole part
  95716. * will require 6 bits, so we use 6 in the assertion. Really though as
  95717. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95718. */
  95719. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95720. FLAC__ASSERT(fracbits >= -3);
  95721. /* now shift the decimal point into place */
  95722. if(fracbits < 16)
  95723. return rbps << (16-fracbits);
  95724. else if(fracbits > 16)
  95725. return rbps >> (fracbits-16);
  95726. else
  95727. return rbps;
  95728. }
  95729. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95730. {
  95731. FLAC__uint32 rbps;
  95732. unsigned bits; /* the number of bits required to represent a number */
  95733. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95734. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95735. FLAC__ASSERT(err > 0);
  95736. FLAC__ASSERT(n > 0);
  95737. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95738. if(err <= n)
  95739. return 0;
  95740. /*
  95741. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95742. * These allow us later to know we won't lose too much precision in the
  95743. * fixed-point division (err<<fracbits)/n.
  95744. */
  95745. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95746. err <<= fracbits;
  95747. err /= n;
  95748. /* err now holds err/n with fracbits fractional bits */
  95749. /*
  95750. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95751. * our purposes.
  95752. */
  95753. FLAC__ASSERT(err > 0);
  95754. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95755. if(bits > 16) {
  95756. err >>= (bits-16);
  95757. fracbits -= (bits-16);
  95758. }
  95759. rbps = (FLAC__uint32)err;
  95760. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95761. rbps *= FLAC__FP_LN2;
  95762. fracbits += 16;
  95763. FLAC__ASSERT(fracbits >= 0);
  95764. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95765. {
  95766. const int f = fracbits & 3;
  95767. if(f) {
  95768. rbps >>= f;
  95769. fracbits -= f;
  95770. }
  95771. }
  95772. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95773. if(rbps == 0)
  95774. return 0;
  95775. /*
  95776. * The return value must have 16 fractional bits. Since the whole part
  95777. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95778. * must be >= -3, these assertion allows us to be able to shift rbps
  95779. * left if necessary to get 16 fracbits without losing any bits of the
  95780. * whole part of rbps.
  95781. *
  95782. * There is a slight chance due to accumulated error that the whole part
  95783. * will require 6 bits, so we use 6 in the assertion. Really though as
  95784. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95785. */
  95786. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95787. FLAC__ASSERT(fracbits >= -3);
  95788. /* now shift the decimal point into place */
  95789. if(fracbits < 16)
  95790. return rbps << (16-fracbits);
  95791. else if(fracbits > 16)
  95792. return rbps >> (fracbits-16);
  95793. else
  95794. return rbps;
  95795. }
  95796. #endif
  95797. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95798. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95799. #else
  95800. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95801. #endif
  95802. {
  95803. FLAC__int32 last_error_0 = data[-1];
  95804. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95805. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95806. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95807. FLAC__int32 error, save;
  95808. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95809. unsigned i, order;
  95810. for(i = 0; i < data_len; i++) {
  95811. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95812. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95813. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95814. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95815. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95816. }
  95817. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95818. order = 0;
  95819. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95820. order = 1;
  95821. else if(total_error_2 < min(total_error_3, total_error_4))
  95822. order = 2;
  95823. else if(total_error_3 < total_error_4)
  95824. order = 3;
  95825. else
  95826. order = 4;
  95827. /* Estimate the expected number of bits per residual signal sample. */
  95828. /* 'total_error*' is linearly related to the variance of the residual */
  95829. /* signal, so we use it directly to compute E(|x|) */
  95830. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95831. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95832. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95833. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95834. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95835. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95836. 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);
  95837. 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);
  95838. 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);
  95839. 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);
  95840. 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);
  95841. #else
  95842. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95843. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95844. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95845. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95846. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95847. #endif
  95848. return order;
  95849. }
  95850. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95851. 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])
  95852. #else
  95853. 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])
  95854. #endif
  95855. {
  95856. FLAC__int32 last_error_0 = data[-1];
  95857. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95858. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95859. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95860. FLAC__int32 error, save;
  95861. /* total_error_* are 64-bits to avoid overflow when encoding
  95862. * erratic signals when the bits-per-sample and blocksize are
  95863. * large.
  95864. */
  95865. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95866. unsigned i, order;
  95867. for(i = 0; i < data_len; i++) {
  95868. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95869. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95870. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95871. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95872. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95873. }
  95874. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95875. order = 0;
  95876. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95877. order = 1;
  95878. else if(total_error_2 < min(total_error_3, total_error_4))
  95879. order = 2;
  95880. else if(total_error_3 < total_error_4)
  95881. order = 3;
  95882. else
  95883. order = 4;
  95884. /* Estimate the expected number of bits per residual signal sample. */
  95885. /* 'total_error*' is linearly related to the variance of the residual */
  95886. /* signal, so we use it directly to compute E(|x|) */
  95887. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95888. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95889. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95890. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95891. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95892. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95893. #if defined _MSC_VER || defined __MINGW32__
  95894. /* with MSVC you have to spoon feed it the casting */
  95895. 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);
  95896. 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);
  95897. 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);
  95898. 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);
  95899. 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);
  95900. #else
  95901. 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);
  95902. 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);
  95903. 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);
  95904. 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);
  95905. 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);
  95906. #endif
  95907. #else
  95908. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95909. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95910. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95911. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95912. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95913. #endif
  95914. return order;
  95915. }
  95916. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95917. {
  95918. const int idata_len = (int)data_len;
  95919. int i;
  95920. switch(order) {
  95921. case 0:
  95922. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95923. memcpy(residual, data, sizeof(residual[0])*data_len);
  95924. break;
  95925. case 1:
  95926. for(i = 0; i < idata_len; i++)
  95927. residual[i] = data[i] - data[i-1];
  95928. break;
  95929. case 2:
  95930. for(i = 0; i < idata_len; i++)
  95931. #if 1 /* OPT: may be faster with some compilers on some systems */
  95932. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95933. #else
  95934. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95935. #endif
  95936. break;
  95937. case 3:
  95938. for(i = 0; i < idata_len; i++)
  95939. #if 1 /* OPT: may be faster with some compilers on some systems */
  95940. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95941. #else
  95942. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95943. #endif
  95944. break;
  95945. case 4:
  95946. for(i = 0; i < idata_len; i++)
  95947. #if 1 /* OPT: may be faster with some compilers on some systems */
  95948. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95949. #else
  95950. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95951. #endif
  95952. break;
  95953. default:
  95954. FLAC__ASSERT(0);
  95955. }
  95956. }
  95957. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95958. {
  95959. int i, idata_len = (int)data_len;
  95960. switch(order) {
  95961. case 0:
  95962. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95963. memcpy(data, residual, sizeof(residual[0])*data_len);
  95964. break;
  95965. case 1:
  95966. for(i = 0; i < idata_len; i++)
  95967. data[i] = residual[i] + data[i-1];
  95968. break;
  95969. case 2:
  95970. for(i = 0; i < idata_len; i++)
  95971. #if 1 /* OPT: may be faster with some compilers on some systems */
  95972. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95973. #else
  95974. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95975. #endif
  95976. break;
  95977. case 3:
  95978. for(i = 0; i < idata_len; i++)
  95979. #if 1 /* OPT: may be faster with some compilers on some systems */
  95980. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95981. #else
  95982. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95983. #endif
  95984. break;
  95985. case 4:
  95986. for(i = 0; i < idata_len; i++)
  95987. #if 1 /* OPT: may be faster with some compilers on some systems */
  95988. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95989. #else
  95990. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95991. #endif
  95992. break;
  95993. default:
  95994. FLAC__ASSERT(0);
  95995. }
  95996. }
  95997. #endif
  95998. /*** End of inlined file: fixed.c ***/
  95999. /*** Start of inlined file: float.c ***/
  96000. /*** Start of inlined file: juce_FlacHeader.h ***/
  96001. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96002. // tasks..
  96003. #define VERSION "1.2.1"
  96004. #define FLAC__NO_DLL 1
  96005. #if JUCE_MSVC
  96006. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96007. #endif
  96008. #if JUCE_MAC
  96009. #define FLAC__SYS_DARWIN 1
  96010. #endif
  96011. /*** End of inlined file: juce_FlacHeader.h ***/
  96012. #if JUCE_USE_FLAC
  96013. #if HAVE_CONFIG_H
  96014. # include <config.h>
  96015. #endif
  96016. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96017. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96018. #ifdef _MSC_VER
  96019. #define FLAC__U64L(x) x
  96020. #else
  96021. #define FLAC__U64L(x) x##LLU
  96022. #endif
  96023. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96024. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96025. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96026. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96027. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96028. /* Lookup tables for Knuth's logarithm algorithm */
  96029. #define LOG2_LOOKUP_PRECISION 16
  96030. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96031. {
  96032. /*
  96033. * 0 fraction bits
  96034. */
  96035. /* undefined */ 0x00000000,
  96036. /* lg(2/1) = */ 0x00000001,
  96037. /* lg(4/3) = */ 0x00000000,
  96038. /* lg(8/7) = */ 0x00000000,
  96039. /* lg(16/15) = */ 0x00000000,
  96040. /* lg(32/31) = */ 0x00000000,
  96041. /* lg(64/63) = */ 0x00000000,
  96042. /* lg(128/127) = */ 0x00000000,
  96043. /* lg(256/255) = */ 0x00000000,
  96044. /* lg(512/511) = */ 0x00000000,
  96045. /* lg(1024/1023) = */ 0x00000000,
  96046. /* lg(2048/2047) = */ 0x00000000,
  96047. /* lg(4096/4095) = */ 0x00000000,
  96048. /* lg(8192/8191) = */ 0x00000000,
  96049. /* lg(16384/16383) = */ 0x00000000,
  96050. /* lg(32768/32767) = */ 0x00000000
  96051. },
  96052. {
  96053. /*
  96054. * 4 fraction bits
  96055. */
  96056. /* undefined */ 0x00000000,
  96057. /* lg(2/1) = */ 0x00000010,
  96058. /* lg(4/3) = */ 0x00000007,
  96059. /* lg(8/7) = */ 0x00000003,
  96060. /* lg(16/15) = */ 0x00000001,
  96061. /* lg(32/31) = */ 0x00000001,
  96062. /* lg(64/63) = */ 0x00000000,
  96063. /* lg(128/127) = */ 0x00000000,
  96064. /* lg(256/255) = */ 0x00000000,
  96065. /* lg(512/511) = */ 0x00000000,
  96066. /* lg(1024/1023) = */ 0x00000000,
  96067. /* lg(2048/2047) = */ 0x00000000,
  96068. /* lg(4096/4095) = */ 0x00000000,
  96069. /* lg(8192/8191) = */ 0x00000000,
  96070. /* lg(16384/16383) = */ 0x00000000,
  96071. /* lg(32768/32767) = */ 0x00000000
  96072. },
  96073. {
  96074. /*
  96075. * 8 fraction bits
  96076. */
  96077. /* undefined */ 0x00000000,
  96078. /* lg(2/1) = */ 0x00000100,
  96079. /* lg(4/3) = */ 0x0000006a,
  96080. /* lg(8/7) = */ 0x00000031,
  96081. /* lg(16/15) = */ 0x00000018,
  96082. /* lg(32/31) = */ 0x0000000c,
  96083. /* lg(64/63) = */ 0x00000006,
  96084. /* lg(128/127) = */ 0x00000003,
  96085. /* lg(256/255) = */ 0x00000001,
  96086. /* lg(512/511) = */ 0x00000001,
  96087. /* lg(1024/1023) = */ 0x00000000,
  96088. /* lg(2048/2047) = */ 0x00000000,
  96089. /* lg(4096/4095) = */ 0x00000000,
  96090. /* lg(8192/8191) = */ 0x00000000,
  96091. /* lg(16384/16383) = */ 0x00000000,
  96092. /* lg(32768/32767) = */ 0x00000000
  96093. },
  96094. {
  96095. /*
  96096. * 12 fraction bits
  96097. */
  96098. /* undefined */ 0x00000000,
  96099. /* lg(2/1) = */ 0x00001000,
  96100. /* lg(4/3) = */ 0x000006a4,
  96101. /* lg(8/7) = */ 0x00000315,
  96102. /* lg(16/15) = */ 0x0000017d,
  96103. /* lg(32/31) = */ 0x000000bc,
  96104. /* lg(64/63) = */ 0x0000005d,
  96105. /* lg(128/127) = */ 0x0000002e,
  96106. /* lg(256/255) = */ 0x00000017,
  96107. /* lg(512/511) = */ 0x0000000c,
  96108. /* lg(1024/1023) = */ 0x00000006,
  96109. /* lg(2048/2047) = */ 0x00000003,
  96110. /* lg(4096/4095) = */ 0x00000001,
  96111. /* lg(8192/8191) = */ 0x00000001,
  96112. /* lg(16384/16383) = */ 0x00000000,
  96113. /* lg(32768/32767) = */ 0x00000000
  96114. },
  96115. {
  96116. /*
  96117. * 16 fraction bits
  96118. */
  96119. /* undefined */ 0x00000000,
  96120. /* lg(2/1) = */ 0x00010000,
  96121. /* lg(4/3) = */ 0x00006a40,
  96122. /* lg(8/7) = */ 0x00003151,
  96123. /* lg(16/15) = */ 0x000017d6,
  96124. /* lg(32/31) = */ 0x00000bba,
  96125. /* lg(64/63) = */ 0x000005d1,
  96126. /* lg(128/127) = */ 0x000002e6,
  96127. /* lg(256/255) = */ 0x00000172,
  96128. /* lg(512/511) = */ 0x000000b9,
  96129. /* lg(1024/1023) = */ 0x0000005c,
  96130. /* lg(2048/2047) = */ 0x0000002e,
  96131. /* lg(4096/4095) = */ 0x00000017,
  96132. /* lg(8192/8191) = */ 0x0000000c,
  96133. /* lg(16384/16383) = */ 0x00000006,
  96134. /* lg(32768/32767) = */ 0x00000003
  96135. },
  96136. {
  96137. /*
  96138. * 20 fraction bits
  96139. */
  96140. /* undefined */ 0x00000000,
  96141. /* lg(2/1) = */ 0x00100000,
  96142. /* lg(4/3) = */ 0x0006a3fe,
  96143. /* lg(8/7) = */ 0x00031513,
  96144. /* lg(16/15) = */ 0x00017d60,
  96145. /* lg(32/31) = */ 0x0000bb9d,
  96146. /* lg(64/63) = */ 0x00005d10,
  96147. /* lg(128/127) = */ 0x00002e59,
  96148. /* lg(256/255) = */ 0x00001721,
  96149. /* lg(512/511) = */ 0x00000b8e,
  96150. /* lg(1024/1023) = */ 0x000005c6,
  96151. /* lg(2048/2047) = */ 0x000002e3,
  96152. /* lg(4096/4095) = */ 0x00000171,
  96153. /* lg(8192/8191) = */ 0x000000b9,
  96154. /* lg(16384/16383) = */ 0x0000005c,
  96155. /* lg(32768/32767) = */ 0x0000002e
  96156. },
  96157. {
  96158. /*
  96159. * 24 fraction bits
  96160. */
  96161. /* undefined */ 0x00000000,
  96162. /* lg(2/1) = */ 0x01000000,
  96163. /* lg(4/3) = */ 0x006a3fe6,
  96164. /* lg(8/7) = */ 0x00315130,
  96165. /* lg(16/15) = */ 0x0017d605,
  96166. /* lg(32/31) = */ 0x000bb9ca,
  96167. /* lg(64/63) = */ 0x0005d0fc,
  96168. /* lg(128/127) = */ 0x0002e58f,
  96169. /* lg(256/255) = */ 0x0001720e,
  96170. /* lg(512/511) = */ 0x0000b8d8,
  96171. /* lg(1024/1023) = */ 0x00005c61,
  96172. /* lg(2048/2047) = */ 0x00002e2d,
  96173. /* lg(4096/4095) = */ 0x00001716,
  96174. /* lg(8192/8191) = */ 0x00000b8b,
  96175. /* lg(16384/16383) = */ 0x000005c5,
  96176. /* lg(32768/32767) = */ 0x000002e3
  96177. },
  96178. {
  96179. /*
  96180. * 28 fraction bits
  96181. */
  96182. /* undefined */ 0x00000000,
  96183. /* lg(2/1) = */ 0x10000000,
  96184. /* lg(4/3) = */ 0x06a3fe5c,
  96185. /* lg(8/7) = */ 0x03151301,
  96186. /* lg(16/15) = */ 0x017d6049,
  96187. /* lg(32/31) = */ 0x00bb9ca6,
  96188. /* lg(64/63) = */ 0x005d0fba,
  96189. /* lg(128/127) = */ 0x002e58f7,
  96190. /* lg(256/255) = */ 0x001720da,
  96191. /* lg(512/511) = */ 0x000b8d87,
  96192. /* lg(1024/1023) = */ 0x0005c60b,
  96193. /* lg(2048/2047) = */ 0x0002e2d7,
  96194. /* lg(4096/4095) = */ 0x00017160,
  96195. /* lg(8192/8191) = */ 0x0000b8ad,
  96196. /* lg(16384/16383) = */ 0x00005c56,
  96197. /* lg(32768/32767) = */ 0x00002e2b
  96198. }
  96199. };
  96200. #if 0
  96201. static const FLAC__uint64 log2_lookup_wide[] = {
  96202. {
  96203. /*
  96204. * 32 fraction bits
  96205. */
  96206. /* undefined */ 0x00000000,
  96207. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96208. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96209. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96210. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96211. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96212. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96213. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96214. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96215. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96216. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96217. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96218. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96219. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96220. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96221. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96222. },
  96223. {
  96224. /*
  96225. * 48 fraction bits
  96226. */
  96227. /* undefined */ 0x00000000,
  96228. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96229. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96230. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96231. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96232. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96233. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96234. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96235. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96236. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96237. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96238. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96239. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96240. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96241. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96242. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96243. }
  96244. };
  96245. #endif
  96246. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96247. {
  96248. const FLAC__uint32 ONE = (1u << fracbits);
  96249. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96250. FLAC__ASSERT(fracbits < 32);
  96251. FLAC__ASSERT((fracbits & 0x3) == 0);
  96252. if(x < ONE)
  96253. return 0;
  96254. if(precision > LOG2_LOOKUP_PRECISION)
  96255. precision = LOG2_LOOKUP_PRECISION;
  96256. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96257. {
  96258. FLAC__uint32 y = 0;
  96259. FLAC__uint32 z = x >> 1, k = 1;
  96260. while (x > ONE && k < precision) {
  96261. if (x - z >= ONE) {
  96262. x -= z;
  96263. z = x >> k;
  96264. y += table[k];
  96265. }
  96266. else {
  96267. z >>= 1;
  96268. k++;
  96269. }
  96270. }
  96271. return y;
  96272. }
  96273. }
  96274. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96275. #endif
  96276. /*** End of inlined file: float.c ***/
  96277. /*** Start of inlined file: format.c ***/
  96278. /*** Start of inlined file: juce_FlacHeader.h ***/
  96279. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96280. // tasks..
  96281. #define VERSION "1.2.1"
  96282. #define FLAC__NO_DLL 1
  96283. #if JUCE_MSVC
  96284. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96285. #endif
  96286. #if JUCE_MAC
  96287. #define FLAC__SYS_DARWIN 1
  96288. #endif
  96289. /*** End of inlined file: juce_FlacHeader.h ***/
  96290. #if JUCE_USE_FLAC
  96291. #if HAVE_CONFIG_H
  96292. # include <config.h>
  96293. #endif
  96294. #include <stdio.h>
  96295. #include <stdlib.h> /* for qsort() */
  96296. #include <string.h> /* for memset() */
  96297. #ifndef FLaC__INLINE
  96298. #define FLaC__INLINE
  96299. #endif
  96300. #ifdef min
  96301. #undef min
  96302. #endif
  96303. #define min(a,b) ((a)<(b)?(a):(b))
  96304. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96305. #ifdef _MSC_VER
  96306. #define FLAC__U64L(x) x
  96307. #else
  96308. #define FLAC__U64L(x) x##LLU
  96309. #endif
  96310. /* VERSION should come from configure */
  96311. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96312. ;
  96313. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96314. /* yet one more hack because of MSVC6: */
  96315. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96316. #else
  96317. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96318. #endif
  96319. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96320. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96321. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96322. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96323. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96324. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96325. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96326. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96327. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96328. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96329. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96330. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96331. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96332. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96333. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96334. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96335. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96336. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96337. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96338. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96339. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96340. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96341. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96342. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96343. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96344. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96345. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96346. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96347. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96348. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96349. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96350. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96351. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96352. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96353. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96354. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96355. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96356. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96357. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96358. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96359. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96360. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96361. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96362. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96363. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96364. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96365. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96366. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96367. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96368. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96369. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96370. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96371. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96372. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96373. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96374. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96375. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96376. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96377. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96378. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96379. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96380. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96381. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96382. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96383. "PARTITIONED_RICE",
  96384. "PARTITIONED_RICE2"
  96385. };
  96386. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96387. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96388. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96389. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96390. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96391. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96392. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96393. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96394. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96395. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96396. "CONSTANT",
  96397. "VERBATIM",
  96398. "FIXED",
  96399. "LPC"
  96400. };
  96401. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96402. "INDEPENDENT",
  96403. "LEFT_SIDE",
  96404. "RIGHT_SIDE",
  96405. "MID_SIDE"
  96406. };
  96407. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96408. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96409. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96410. };
  96411. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96412. "STREAMINFO",
  96413. "PADDING",
  96414. "APPLICATION",
  96415. "SEEKTABLE",
  96416. "VORBIS_COMMENT",
  96417. "CUESHEET",
  96418. "PICTURE"
  96419. };
  96420. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96421. "Other",
  96422. "32x32 pixels 'file icon' (PNG only)",
  96423. "Other file icon",
  96424. "Cover (front)",
  96425. "Cover (back)",
  96426. "Leaflet page",
  96427. "Media (e.g. label side of CD)",
  96428. "Lead artist/lead performer/soloist",
  96429. "Artist/performer",
  96430. "Conductor",
  96431. "Band/Orchestra",
  96432. "Composer",
  96433. "Lyricist/text writer",
  96434. "Recording Location",
  96435. "During recording",
  96436. "During performance",
  96437. "Movie/video screen capture",
  96438. "A bright coloured fish",
  96439. "Illustration",
  96440. "Band/artist logotype",
  96441. "Publisher/Studio logotype"
  96442. };
  96443. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96444. {
  96445. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96446. return false;
  96447. }
  96448. else
  96449. return true;
  96450. }
  96451. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96452. {
  96453. if(
  96454. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96455. (
  96456. sample_rate >= (1u << 16) &&
  96457. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96458. )
  96459. ) {
  96460. return false;
  96461. }
  96462. else
  96463. return true;
  96464. }
  96465. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96466. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96467. {
  96468. unsigned i;
  96469. FLAC__uint64 prev_sample_number = 0;
  96470. FLAC__bool got_prev = false;
  96471. FLAC__ASSERT(0 != seek_table);
  96472. for(i = 0; i < seek_table->num_points; i++) {
  96473. if(got_prev) {
  96474. if(
  96475. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96476. seek_table->points[i].sample_number <= prev_sample_number
  96477. )
  96478. return false;
  96479. }
  96480. prev_sample_number = seek_table->points[i].sample_number;
  96481. got_prev = true;
  96482. }
  96483. return true;
  96484. }
  96485. /* used as the sort predicate for qsort() */
  96486. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96487. {
  96488. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96489. if(l->sample_number == r->sample_number)
  96490. return 0;
  96491. else if(l->sample_number < r->sample_number)
  96492. return -1;
  96493. else
  96494. return 1;
  96495. }
  96496. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96497. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96498. {
  96499. unsigned i, j;
  96500. FLAC__bool first;
  96501. FLAC__ASSERT(0 != seek_table);
  96502. /* sort the seekpoints */
  96503. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96504. /* uniquify the seekpoints */
  96505. first = true;
  96506. for(i = j = 0; i < seek_table->num_points; i++) {
  96507. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96508. if(!first) {
  96509. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96510. continue;
  96511. }
  96512. }
  96513. first = false;
  96514. seek_table->points[j++] = seek_table->points[i];
  96515. }
  96516. for(i = j; i < seek_table->num_points; i++) {
  96517. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96518. seek_table->points[i].stream_offset = 0;
  96519. seek_table->points[i].frame_samples = 0;
  96520. }
  96521. return j;
  96522. }
  96523. /*
  96524. * also disallows non-shortest-form encodings, c.f.
  96525. * http://www.unicode.org/versions/corrigendum1.html
  96526. * and a more clear explanation at the end of this section:
  96527. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96528. */
  96529. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96530. {
  96531. FLAC__ASSERT(0 != utf8);
  96532. if ((utf8[0] & 0x80) == 0) {
  96533. return 1;
  96534. }
  96535. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96536. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96537. return 0;
  96538. return 2;
  96539. }
  96540. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96541. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96542. return 0;
  96543. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96544. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96545. return 0;
  96546. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96547. return 0;
  96548. return 3;
  96549. }
  96550. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96551. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96552. return 0;
  96553. return 4;
  96554. }
  96555. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96556. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96557. return 0;
  96558. return 5;
  96559. }
  96560. 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) {
  96561. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96562. return 0;
  96563. return 6;
  96564. }
  96565. else {
  96566. return 0;
  96567. }
  96568. }
  96569. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96570. {
  96571. char c;
  96572. for(c = *name; c; c = *(++name))
  96573. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96574. return false;
  96575. return true;
  96576. }
  96577. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96578. {
  96579. if(length == (unsigned)(-1)) {
  96580. while(*value) {
  96581. unsigned n = utf8len_(value);
  96582. if(n == 0)
  96583. return false;
  96584. value += n;
  96585. }
  96586. }
  96587. else {
  96588. const FLAC__byte *end = value + length;
  96589. while(value < end) {
  96590. unsigned n = utf8len_(value);
  96591. if(n == 0)
  96592. return false;
  96593. value += n;
  96594. }
  96595. if(value != end)
  96596. return false;
  96597. }
  96598. return true;
  96599. }
  96600. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96601. {
  96602. const FLAC__byte *s, *end;
  96603. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96604. if(*s < 0x20 || *s > 0x7D)
  96605. return false;
  96606. }
  96607. if(s == end)
  96608. return false;
  96609. s++; /* skip '=' */
  96610. while(s < end) {
  96611. unsigned n = utf8len_(s);
  96612. if(n == 0)
  96613. return false;
  96614. s += n;
  96615. }
  96616. if(s != end)
  96617. return false;
  96618. return true;
  96619. }
  96620. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96621. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96622. {
  96623. unsigned i, j;
  96624. if(check_cd_da_subset) {
  96625. if(cue_sheet->lead_in < 2 * 44100) {
  96626. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96627. return false;
  96628. }
  96629. if(cue_sheet->lead_in % 588 != 0) {
  96630. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96631. return false;
  96632. }
  96633. }
  96634. if(cue_sheet->num_tracks == 0) {
  96635. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96636. return false;
  96637. }
  96638. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96639. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96640. return false;
  96641. }
  96642. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96643. if(cue_sheet->tracks[i].number == 0) {
  96644. if(violation) *violation = "cue sheet may not have a track number 0";
  96645. return false;
  96646. }
  96647. if(check_cd_da_subset) {
  96648. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96649. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96650. return false;
  96651. }
  96652. }
  96653. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96654. if(violation) {
  96655. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96656. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96657. else
  96658. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96659. }
  96660. return false;
  96661. }
  96662. if(i < cue_sheet->num_tracks - 1) {
  96663. if(cue_sheet->tracks[i].num_indices == 0) {
  96664. if(violation) *violation = "cue sheet track must have at least one index point";
  96665. return false;
  96666. }
  96667. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96668. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96669. return false;
  96670. }
  96671. }
  96672. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96673. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96674. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96675. return false;
  96676. }
  96677. if(j > 0) {
  96678. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96679. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96680. return false;
  96681. }
  96682. }
  96683. }
  96684. }
  96685. return true;
  96686. }
  96687. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96688. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96689. {
  96690. char *p;
  96691. FLAC__byte *b;
  96692. for(p = picture->mime_type; *p; p++) {
  96693. if(*p < 0x20 || *p > 0x7e) {
  96694. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96695. return false;
  96696. }
  96697. }
  96698. for(b = picture->description; *b; ) {
  96699. unsigned n = utf8len_(b);
  96700. if(n == 0) {
  96701. if(violation) *violation = "description string must be valid UTF-8";
  96702. return false;
  96703. }
  96704. b += n;
  96705. }
  96706. return true;
  96707. }
  96708. /*
  96709. * These routines are private to libFLAC
  96710. */
  96711. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96712. {
  96713. return
  96714. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96715. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96716. blocksize,
  96717. predictor_order
  96718. );
  96719. }
  96720. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96721. {
  96722. unsigned max_rice_partition_order = 0;
  96723. while(!(blocksize & 1)) {
  96724. max_rice_partition_order++;
  96725. blocksize >>= 1;
  96726. }
  96727. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96728. }
  96729. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96730. {
  96731. unsigned max_rice_partition_order = limit;
  96732. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96733. max_rice_partition_order--;
  96734. FLAC__ASSERT(
  96735. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96736. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96737. );
  96738. return max_rice_partition_order;
  96739. }
  96740. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96741. {
  96742. FLAC__ASSERT(0 != object);
  96743. object->parameters = 0;
  96744. object->raw_bits = 0;
  96745. object->capacity_by_order = 0;
  96746. }
  96747. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96748. {
  96749. FLAC__ASSERT(0 != object);
  96750. if(0 != object->parameters)
  96751. free(object->parameters);
  96752. if(0 != object->raw_bits)
  96753. free(object->raw_bits);
  96754. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96755. }
  96756. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96757. {
  96758. FLAC__ASSERT(0 != object);
  96759. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96760. if(object->capacity_by_order < max_partition_order) {
  96761. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96762. return false;
  96763. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96764. return false;
  96765. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96766. object->capacity_by_order = max_partition_order;
  96767. }
  96768. return true;
  96769. }
  96770. #endif
  96771. /*** End of inlined file: format.c ***/
  96772. /*** Start of inlined file: lpc_flac.c ***/
  96773. /*** Start of inlined file: juce_FlacHeader.h ***/
  96774. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96775. // tasks..
  96776. #define VERSION "1.2.1"
  96777. #define FLAC__NO_DLL 1
  96778. #if JUCE_MSVC
  96779. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96780. #endif
  96781. #if JUCE_MAC
  96782. #define FLAC__SYS_DARWIN 1
  96783. #endif
  96784. /*** End of inlined file: juce_FlacHeader.h ***/
  96785. #if JUCE_USE_FLAC
  96786. #if HAVE_CONFIG_H
  96787. # include <config.h>
  96788. #endif
  96789. #include <math.h>
  96790. /*** Start of inlined file: lpc.h ***/
  96791. #ifndef FLAC__PRIVATE__LPC_H
  96792. #define FLAC__PRIVATE__LPC_H
  96793. #ifdef HAVE_CONFIG_H
  96794. #include <config.h>
  96795. #endif
  96796. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96797. /*
  96798. * FLAC__lpc_window_data()
  96799. * --------------------------------------------------------------------
  96800. * Applies the given window to the data.
  96801. * OPT: asm implementation
  96802. *
  96803. * IN in[0,data_len-1]
  96804. * IN window[0,data_len-1]
  96805. * OUT out[0,lag-1]
  96806. * IN data_len
  96807. */
  96808. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96809. /*
  96810. * FLAC__lpc_compute_autocorrelation()
  96811. * --------------------------------------------------------------------
  96812. * Compute the autocorrelation for lags between 0 and lag-1.
  96813. * Assumes data[] outside of [0,data_len-1] == 0.
  96814. * Asserts that lag > 0.
  96815. *
  96816. * IN data[0,data_len-1]
  96817. * IN data_len
  96818. * IN 0 < lag <= data_len
  96819. * OUT autoc[0,lag-1]
  96820. */
  96821. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96822. #ifndef FLAC__NO_ASM
  96823. # ifdef FLAC__CPU_IA32
  96824. # ifdef FLAC__HAS_NASM
  96825. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96826. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96827. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96828. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96829. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96830. # endif
  96831. # endif
  96832. #endif
  96833. /*
  96834. * FLAC__lpc_compute_lp_coefficients()
  96835. * --------------------------------------------------------------------
  96836. * Computes LP coefficients for orders 1..max_order.
  96837. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96838. * and there is no point in calculating a predictor.
  96839. *
  96840. * IN autoc[0,max_order] autocorrelation values
  96841. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96842. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96843. * *** IMPORTANT:
  96844. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96845. * OUT error[0,max_order-1] error for each order (more
  96846. * specifically, the variance of
  96847. * the error signal times # of
  96848. * samples in the signal)
  96849. *
  96850. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96851. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96852. * in lp_coeff[7][0,7], etc.
  96853. */
  96854. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96855. /*
  96856. * FLAC__lpc_quantize_coefficients()
  96857. * --------------------------------------------------------------------
  96858. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96859. * must be less than 32 (sizeof(FLAC__int32)*8).
  96860. *
  96861. * IN lp_coeff[0,order-1] LP coefficients
  96862. * IN order LP order
  96863. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96864. * desired precision (in bits, including sign
  96865. * bit) of largest coefficient
  96866. * OUT qlp_coeff[0,order-1] quantized coefficients
  96867. * OUT shift # of bits to shift right to get approximated
  96868. * LP coefficients. NOTE: could be negative.
  96869. * RETURN 0 => quantization OK
  96870. * 1 => coefficients require too much shifting for *shift to
  96871. * fit in the LPC subframe header. 'shift' is unset.
  96872. * 2 => coefficients are all zero, which is bad. 'shift' is
  96873. * unset.
  96874. */
  96875. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96876. /*
  96877. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96878. * --------------------------------------------------------------------
  96879. * Compute the residual signal obtained from sutracting the predicted
  96880. * signal from the original.
  96881. *
  96882. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96883. * IN data_len length of original signal
  96884. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96885. * IN order > 0 LP order
  96886. * IN lp_quantization quantization of LP coefficients in bits
  96887. * OUT residual[0,data_len-1] residual signal
  96888. */
  96889. 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[]);
  96890. 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[]);
  96891. #ifndef FLAC__NO_ASM
  96892. # ifdef FLAC__CPU_IA32
  96893. # ifdef FLAC__HAS_NASM
  96894. 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[]);
  96895. 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[]);
  96896. # endif
  96897. # endif
  96898. #endif
  96899. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96900. /*
  96901. * FLAC__lpc_restore_signal()
  96902. * --------------------------------------------------------------------
  96903. * Restore the original signal by summing the residual and the
  96904. * predictor.
  96905. *
  96906. * IN residual[0,data_len-1] residual signal
  96907. * IN data_len length of original signal
  96908. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96909. * IN order > 0 LP order
  96910. * IN lp_quantization quantization of LP coefficients in bits
  96911. * *** IMPORTANT: the caller must pass in the historical samples:
  96912. * IN data[-order,-1] previously-reconstructed historical samples
  96913. * OUT data[0,data_len-1] original signal
  96914. */
  96915. 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[]);
  96916. 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[]);
  96917. #ifndef FLAC__NO_ASM
  96918. # ifdef FLAC__CPU_IA32
  96919. # ifdef FLAC__HAS_NASM
  96920. 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[]);
  96921. 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[]);
  96922. # endif /* FLAC__HAS_NASM */
  96923. # elif defined FLAC__CPU_PPC
  96924. 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[]);
  96925. 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[]);
  96926. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96927. #endif /* FLAC__NO_ASM */
  96928. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96929. /*
  96930. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96931. * --------------------------------------------------------------------
  96932. * Compute the expected number of bits per residual signal sample
  96933. * based on the LP error (which is related to the residual variance).
  96934. *
  96935. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96936. * IN total_samples > 0 # of samples in residual signal
  96937. * RETURN expected bits per sample
  96938. */
  96939. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96940. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96941. /*
  96942. * FLAC__lpc_compute_best_order()
  96943. * --------------------------------------------------------------------
  96944. * Compute the best order from the array of signal errors returned
  96945. * during coefficient computation.
  96946. *
  96947. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96948. * IN max_order > 0 max LP order
  96949. * IN total_samples > 0 # of samples in residual signal
  96950. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96951. * (includes warmup sample size and quantized LP coefficient)
  96952. * RETURN [1,max_order] best order
  96953. */
  96954. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96955. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96956. #endif
  96957. /*** End of inlined file: lpc.h ***/
  96958. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96959. #include <stdio.h>
  96960. #endif
  96961. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96962. #ifndef M_LN2
  96963. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96964. #define M_LN2 0.69314718055994530942
  96965. #endif
  96966. /* OPT: #undef'ing this may improve the speed on some architectures */
  96967. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96968. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96969. {
  96970. unsigned i;
  96971. for(i = 0; i < data_len; i++)
  96972. out[i] = in[i] * window[i];
  96973. }
  96974. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96975. {
  96976. /* a readable, but slower, version */
  96977. #if 0
  96978. FLAC__real d;
  96979. unsigned i;
  96980. FLAC__ASSERT(lag > 0);
  96981. FLAC__ASSERT(lag <= data_len);
  96982. /*
  96983. * Technically we should subtract the mean first like so:
  96984. * for(i = 0; i < data_len; i++)
  96985. * data[i] -= mean;
  96986. * but it appears not to make enough of a difference to matter, and
  96987. * most signals are already closely centered around zero
  96988. */
  96989. while(lag--) {
  96990. for(i = lag, d = 0.0; i < data_len; i++)
  96991. d += data[i] * data[i - lag];
  96992. autoc[lag] = d;
  96993. }
  96994. #endif
  96995. /*
  96996. * this version tends to run faster because of better data locality
  96997. * ('data_len' is usually much larger than 'lag')
  96998. */
  96999. FLAC__real d;
  97000. unsigned sample, coeff;
  97001. const unsigned limit = data_len - lag;
  97002. FLAC__ASSERT(lag > 0);
  97003. FLAC__ASSERT(lag <= data_len);
  97004. for(coeff = 0; coeff < lag; coeff++)
  97005. autoc[coeff] = 0.0;
  97006. for(sample = 0; sample <= limit; sample++) {
  97007. d = data[sample];
  97008. for(coeff = 0; coeff < lag; coeff++)
  97009. autoc[coeff] += d * data[sample+coeff];
  97010. }
  97011. for(; sample < data_len; sample++) {
  97012. d = data[sample];
  97013. for(coeff = 0; coeff < data_len - sample; coeff++)
  97014. autoc[coeff] += d * data[sample+coeff];
  97015. }
  97016. }
  97017. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97018. {
  97019. unsigned i, j;
  97020. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97021. FLAC__ASSERT(0 != max_order);
  97022. FLAC__ASSERT(0 < *max_order);
  97023. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97024. FLAC__ASSERT(autoc[0] != 0.0);
  97025. err = autoc[0];
  97026. for(i = 0; i < *max_order; i++) {
  97027. /* Sum up this iteration's reflection coefficient. */
  97028. r = -autoc[i+1];
  97029. for(j = 0; j < i; j++)
  97030. r -= lpc[j] * autoc[i-j];
  97031. ref[i] = (r/=err);
  97032. /* Update LPC coefficients and total error. */
  97033. lpc[i]=r;
  97034. for(j = 0; j < (i>>1); j++) {
  97035. FLAC__double tmp = lpc[j];
  97036. lpc[j] += r * lpc[i-1-j];
  97037. lpc[i-1-j] += r * tmp;
  97038. }
  97039. if(i & 1)
  97040. lpc[j] += lpc[j] * r;
  97041. err *= (1.0 - r * r);
  97042. /* save this order */
  97043. for(j = 0; j <= i; j++)
  97044. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97045. error[i] = err;
  97046. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97047. if(err == 0.0) {
  97048. *max_order = i+1;
  97049. return;
  97050. }
  97051. }
  97052. }
  97053. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97054. {
  97055. unsigned i;
  97056. FLAC__double cmax;
  97057. FLAC__int32 qmax, qmin;
  97058. FLAC__ASSERT(precision > 0);
  97059. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97060. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97061. precision--;
  97062. qmax = 1 << precision;
  97063. qmin = -qmax;
  97064. qmax--;
  97065. /* calc cmax = max( |lp_coeff[i]| ) */
  97066. cmax = 0.0;
  97067. for(i = 0; i < order; i++) {
  97068. const FLAC__double d = fabs(lp_coeff[i]);
  97069. if(d > cmax)
  97070. cmax = d;
  97071. }
  97072. if(cmax <= 0.0) {
  97073. /* => coefficients are all 0, which means our constant-detect didn't work */
  97074. return 2;
  97075. }
  97076. else {
  97077. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97078. const int min_shiftlimit = -max_shiftlimit - 1;
  97079. int log2cmax;
  97080. (void)frexp(cmax, &log2cmax);
  97081. log2cmax--;
  97082. *shift = (int)precision - log2cmax - 1;
  97083. if(*shift > max_shiftlimit)
  97084. *shift = max_shiftlimit;
  97085. else if(*shift < min_shiftlimit)
  97086. return 1;
  97087. }
  97088. if(*shift >= 0) {
  97089. FLAC__double error = 0.0;
  97090. FLAC__int32 q;
  97091. for(i = 0; i < order; i++) {
  97092. error += lp_coeff[i] * (1 << *shift);
  97093. #if 1 /* unfortunately lround() is C99 */
  97094. if(error >= 0.0)
  97095. q = (FLAC__int32)(error + 0.5);
  97096. else
  97097. q = (FLAC__int32)(error - 0.5);
  97098. #else
  97099. q = lround(error);
  97100. #endif
  97101. #ifdef FLAC__OVERFLOW_DETECT
  97102. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97103. 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]);
  97104. else if(q < qmin)
  97105. 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]);
  97106. #endif
  97107. if(q > qmax)
  97108. q = qmax;
  97109. else if(q < qmin)
  97110. q = qmin;
  97111. error -= q;
  97112. qlp_coeff[i] = q;
  97113. }
  97114. }
  97115. /* negative shift is very rare but due to design flaw, negative shift is
  97116. * a NOP in the decoder, so it must be handled specially by scaling down
  97117. * coeffs
  97118. */
  97119. else {
  97120. const int nshift = -(*shift);
  97121. FLAC__double error = 0.0;
  97122. FLAC__int32 q;
  97123. #ifdef DEBUG
  97124. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97125. #endif
  97126. for(i = 0; i < order; i++) {
  97127. error += lp_coeff[i] / (1 << nshift);
  97128. #if 1 /* unfortunately lround() is C99 */
  97129. if(error >= 0.0)
  97130. q = (FLAC__int32)(error + 0.5);
  97131. else
  97132. q = (FLAC__int32)(error - 0.5);
  97133. #else
  97134. q = lround(error);
  97135. #endif
  97136. #ifdef FLAC__OVERFLOW_DETECT
  97137. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97138. 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]);
  97139. else if(q < qmin)
  97140. 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]);
  97141. #endif
  97142. if(q > qmax)
  97143. q = qmax;
  97144. else if(q < qmin)
  97145. q = qmin;
  97146. error -= q;
  97147. qlp_coeff[i] = q;
  97148. }
  97149. *shift = 0;
  97150. }
  97151. return 0;
  97152. }
  97153. 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[])
  97154. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97155. {
  97156. FLAC__int64 sumo;
  97157. unsigned i, j;
  97158. FLAC__int32 sum;
  97159. const FLAC__int32 *history;
  97160. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97161. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97162. for(i=0;i<order;i++)
  97163. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97164. fprintf(stderr,"\n");
  97165. #endif
  97166. FLAC__ASSERT(order > 0);
  97167. for(i = 0; i < data_len; i++) {
  97168. sumo = 0;
  97169. sum = 0;
  97170. history = data;
  97171. for(j = 0; j < order; j++) {
  97172. sum += qlp_coeff[j] * (*(--history));
  97173. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97174. #if defined _MSC_VER
  97175. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97176. 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);
  97177. #else
  97178. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97179. 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);
  97180. #endif
  97181. }
  97182. *(residual++) = *(data++) - (sum >> lp_quantization);
  97183. }
  97184. /* Here's a slower but clearer version:
  97185. for(i = 0; i < data_len; i++) {
  97186. sum = 0;
  97187. for(j = 0; j < order; j++)
  97188. sum += qlp_coeff[j] * data[i-j-1];
  97189. residual[i] = data[i] - (sum >> lp_quantization);
  97190. }
  97191. */
  97192. }
  97193. #else /* fully unrolled version for normal use */
  97194. {
  97195. int i;
  97196. FLAC__int32 sum;
  97197. FLAC__ASSERT(order > 0);
  97198. FLAC__ASSERT(order <= 32);
  97199. /*
  97200. * We do unique versions up to 12th order since that's the subset limit.
  97201. * Also they are roughly ordered to match frequency of occurrence to
  97202. * minimize branching.
  97203. */
  97204. if(order <= 12) {
  97205. if(order > 8) {
  97206. if(order > 10) {
  97207. if(order == 12) {
  97208. for(i = 0; i < (int)data_len; i++) {
  97209. sum = 0;
  97210. sum += qlp_coeff[11] * data[i-12];
  97211. sum += qlp_coeff[10] * data[i-11];
  97212. sum += qlp_coeff[9] * data[i-10];
  97213. sum += qlp_coeff[8] * data[i-9];
  97214. sum += qlp_coeff[7] * data[i-8];
  97215. sum += qlp_coeff[6] * data[i-7];
  97216. sum += qlp_coeff[5] * data[i-6];
  97217. sum += qlp_coeff[4] * data[i-5];
  97218. sum += qlp_coeff[3] * data[i-4];
  97219. sum += qlp_coeff[2] * data[i-3];
  97220. sum += qlp_coeff[1] * data[i-2];
  97221. sum += qlp_coeff[0] * data[i-1];
  97222. residual[i] = data[i] - (sum >> lp_quantization);
  97223. }
  97224. }
  97225. else { /* order == 11 */
  97226. for(i = 0; i < (int)data_len; i++) {
  97227. sum = 0;
  97228. sum += qlp_coeff[10] * data[i-11];
  97229. sum += qlp_coeff[9] * data[i-10];
  97230. sum += qlp_coeff[8] * data[i-9];
  97231. sum += qlp_coeff[7] * data[i-8];
  97232. sum += qlp_coeff[6] * data[i-7];
  97233. sum += qlp_coeff[5] * data[i-6];
  97234. sum += qlp_coeff[4] * data[i-5];
  97235. sum += qlp_coeff[3] * data[i-4];
  97236. sum += qlp_coeff[2] * data[i-3];
  97237. sum += qlp_coeff[1] * data[i-2];
  97238. sum += qlp_coeff[0] * data[i-1];
  97239. residual[i] = data[i] - (sum >> lp_quantization);
  97240. }
  97241. }
  97242. }
  97243. else {
  97244. if(order == 10) {
  97245. for(i = 0; i < (int)data_len; i++) {
  97246. sum = 0;
  97247. sum += qlp_coeff[9] * data[i-10];
  97248. sum += qlp_coeff[8] * data[i-9];
  97249. sum += qlp_coeff[7] * data[i-8];
  97250. sum += qlp_coeff[6] * data[i-7];
  97251. sum += qlp_coeff[5] * data[i-6];
  97252. sum += qlp_coeff[4] * data[i-5];
  97253. sum += qlp_coeff[3] * data[i-4];
  97254. sum += qlp_coeff[2] * data[i-3];
  97255. sum += qlp_coeff[1] * data[i-2];
  97256. sum += qlp_coeff[0] * data[i-1];
  97257. residual[i] = data[i] - (sum >> lp_quantization);
  97258. }
  97259. }
  97260. else { /* order == 9 */
  97261. for(i = 0; i < (int)data_len; i++) {
  97262. sum = 0;
  97263. sum += qlp_coeff[8] * data[i-9];
  97264. sum += qlp_coeff[7] * data[i-8];
  97265. sum += qlp_coeff[6] * data[i-7];
  97266. sum += qlp_coeff[5] * data[i-6];
  97267. sum += qlp_coeff[4] * data[i-5];
  97268. sum += qlp_coeff[3] * data[i-4];
  97269. sum += qlp_coeff[2] * data[i-3];
  97270. sum += qlp_coeff[1] * data[i-2];
  97271. sum += qlp_coeff[0] * data[i-1];
  97272. residual[i] = data[i] - (sum >> lp_quantization);
  97273. }
  97274. }
  97275. }
  97276. }
  97277. else if(order > 4) {
  97278. if(order > 6) {
  97279. if(order == 8) {
  97280. for(i = 0; i < (int)data_len; i++) {
  97281. sum = 0;
  97282. sum += qlp_coeff[7] * data[i-8];
  97283. sum += qlp_coeff[6] * data[i-7];
  97284. sum += qlp_coeff[5] * data[i-6];
  97285. sum += qlp_coeff[4] * data[i-5];
  97286. sum += qlp_coeff[3] * data[i-4];
  97287. sum += qlp_coeff[2] * data[i-3];
  97288. sum += qlp_coeff[1] * data[i-2];
  97289. sum += qlp_coeff[0] * data[i-1];
  97290. residual[i] = data[i] - (sum >> lp_quantization);
  97291. }
  97292. }
  97293. else { /* order == 7 */
  97294. for(i = 0; i < (int)data_len; i++) {
  97295. sum = 0;
  97296. sum += qlp_coeff[6] * data[i-7];
  97297. sum += qlp_coeff[5] * data[i-6];
  97298. sum += qlp_coeff[4] * data[i-5];
  97299. sum += qlp_coeff[3] * data[i-4];
  97300. sum += qlp_coeff[2] * data[i-3];
  97301. sum += qlp_coeff[1] * data[i-2];
  97302. sum += qlp_coeff[0] * data[i-1];
  97303. residual[i] = data[i] - (sum >> lp_quantization);
  97304. }
  97305. }
  97306. }
  97307. else {
  97308. if(order == 6) {
  97309. for(i = 0; i < (int)data_len; i++) {
  97310. sum = 0;
  97311. sum += qlp_coeff[5] * data[i-6];
  97312. sum += qlp_coeff[4] * data[i-5];
  97313. sum += qlp_coeff[3] * data[i-4];
  97314. sum += qlp_coeff[2] * data[i-3];
  97315. sum += qlp_coeff[1] * data[i-2];
  97316. sum += qlp_coeff[0] * data[i-1];
  97317. residual[i] = data[i] - (sum >> lp_quantization);
  97318. }
  97319. }
  97320. else { /* order == 5 */
  97321. for(i = 0; i < (int)data_len; i++) {
  97322. sum = 0;
  97323. sum += qlp_coeff[4] * data[i-5];
  97324. sum += qlp_coeff[3] * data[i-4];
  97325. sum += qlp_coeff[2] * data[i-3];
  97326. sum += qlp_coeff[1] * data[i-2];
  97327. sum += qlp_coeff[0] * data[i-1];
  97328. residual[i] = data[i] - (sum >> lp_quantization);
  97329. }
  97330. }
  97331. }
  97332. }
  97333. else {
  97334. if(order > 2) {
  97335. if(order == 4) {
  97336. for(i = 0; i < (int)data_len; i++) {
  97337. sum = 0;
  97338. sum += qlp_coeff[3] * data[i-4];
  97339. sum += qlp_coeff[2] * data[i-3];
  97340. sum += qlp_coeff[1] * data[i-2];
  97341. sum += qlp_coeff[0] * data[i-1];
  97342. residual[i] = data[i] - (sum >> lp_quantization);
  97343. }
  97344. }
  97345. else { /* order == 3 */
  97346. for(i = 0; i < (int)data_len; i++) {
  97347. sum = 0;
  97348. sum += qlp_coeff[2] * data[i-3];
  97349. sum += qlp_coeff[1] * data[i-2];
  97350. sum += qlp_coeff[0] * data[i-1];
  97351. residual[i] = data[i] - (sum >> lp_quantization);
  97352. }
  97353. }
  97354. }
  97355. else {
  97356. if(order == 2) {
  97357. for(i = 0; i < (int)data_len; i++) {
  97358. sum = 0;
  97359. sum += qlp_coeff[1] * data[i-2];
  97360. sum += qlp_coeff[0] * data[i-1];
  97361. residual[i] = data[i] - (sum >> lp_quantization);
  97362. }
  97363. }
  97364. else { /* order == 1 */
  97365. for(i = 0; i < (int)data_len; i++)
  97366. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97367. }
  97368. }
  97369. }
  97370. }
  97371. else { /* order > 12 */
  97372. for(i = 0; i < (int)data_len; i++) {
  97373. sum = 0;
  97374. switch(order) {
  97375. case 32: sum += qlp_coeff[31] * data[i-32];
  97376. case 31: sum += qlp_coeff[30] * data[i-31];
  97377. case 30: sum += qlp_coeff[29] * data[i-30];
  97378. case 29: sum += qlp_coeff[28] * data[i-29];
  97379. case 28: sum += qlp_coeff[27] * data[i-28];
  97380. case 27: sum += qlp_coeff[26] * data[i-27];
  97381. case 26: sum += qlp_coeff[25] * data[i-26];
  97382. case 25: sum += qlp_coeff[24] * data[i-25];
  97383. case 24: sum += qlp_coeff[23] * data[i-24];
  97384. case 23: sum += qlp_coeff[22] * data[i-23];
  97385. case 22: sum += qlp_coeff[21] * data[i-22];
  97386. case 21: sum += qlp_coeff[20] * data[i-21];
  97387. case 20: sum += qlp_coeff[19] * data[i-20];
  97388. case 19: sum += qlp_coeff[18] * data[i-19];
  97389. case 18: sum += qlp_coeff[17] * data[i-18];
  97390. case 17: sum += qlp_coeff[16] * data[i-17];
  97391. case 16: sum += qlp_coeff[15] * data[i-16];
  97392. case 15: sum += qlp_coeff[14] * data[i-15];
  97393. case 14: sum += qlp_coeff[13] * data[i-14];
  97394. case 13: sum += qlp_coeff[12] * data[i-13];
  97395. sum += qlp_coeff[11] * data[i-12];
  97396. sum += qlp_coeff[10] * data[i-11];
  97397. sum += qlp_coeff[ 9] * data[i-10];
  97398. sum += qlp_coeff[ 8] * data[i- 9];
  97399. sum += qlp_coeff[ 7] * data[i- 8];
  97400. sum += qlp_coeff[ 6] * data[i- 7];
  97401. sum += qlp_coeff[ 5] * data[i- 6];
  97402. sum += qlp_coeff[ 4] * data[i- 5];
  97403. sum += qlp_coeff[ 3] * data[i- 4];
  97404. sum += qlp_coeff[ 2] * data[i- 3];
  97405. sum += qlp_coeff[ 1] * data[i- 2];
  97406. sum += qlp_coeff[ 0] * data[i- 1];
  97407. }
  97408. residual[i] = data[i] - (sum >> lp_quantization);
  97409. }
  97410. }
  97411. }
  97412. #endif
  97413. 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[])
  97414. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97415. {
  97416. unsigned i, j;
  97417. FLAC__int64 sum;
  97418. const FLAC__int32 *history;
  97419. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97420. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97421. for(i=0;i<order;i++)
  97422. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97423. fprintf(stderr,"\n");
  97424. #endif
  97425. FLAC__ASSERT(order > 0);
  97426. for(i = 0; i < data_len; i++) {
  97427. sum = 0;
  97428. history = data;
  97429. for(j = 0; j < order; j++)
  97430. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97431. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97432. #if defined _MSC_VER
  97433. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97434. #else
  97435. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97436. #endif
  97437. break;
  97438. }
  97439. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97440. #if defined _MSC_VER
  97441. 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));
  97442. #else
  97443. 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)));
  97444. #endif
  97445. break;
  97446. }
  97447. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97448. }
  97449. }
  97450. #else /* fully unrolled version for normal use */
  97451. {
  97452. int i;
  97453. FLAC__int64 sum;
  97454. FLAC__ASSERT(order > 0);
  97455. FLAC__ASSERT(order <= 32);
  97456. /*
  97457. * We do unique versions up to 12th order since that's the subset limit.
  97458. * Also they are roughly ordered to match frequency of occurrence to
  97459. * minimize branching.
  97460. */
  97461. if(order <= 12) {
  97462. if(order > 8) {
  97463. if(order > 10) {
  97464. if(order == 12) {
  97465. for(i = 0; i < (int)data_len; i++) {
  97466. sum = 0;
  97467. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97468. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97469. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97470. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97471. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97472. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97473. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97474. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97475. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97476. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97477. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97478. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97479. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97480. }
  97481. }
  97482. else { /* order == 11 */
  97483. for(i = 0; i < (int)data_len; i++) {
  97484. sum = 0;
  97485. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97486. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97487. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97488. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97489. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97490. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97491. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97492. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97493. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97494. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97495. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97496. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97497. }
  97498. }
  97499. }
  97500. else {
  97501. if(order == 10) {
  97502. for(i = 0; i < (int)data_len; i++) {
  97503. sum = 0;
  97504. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97505. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97506. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97507. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97508. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97509. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97510. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97511. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97512. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97513. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97514. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97515. }
  97516. }
  97517. else { /* order == 9 */
  97518. for(i = 0; i < (int)data_len; i++) {
  97519. sum = 0;
  97520. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97521. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97522. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97523. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97524. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97525. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97526. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97527. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97528. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97529. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97530. }
  97531. }
  97532. }
  97533. }
  97534. else if(order > 4) {
  97535. if(order > 6) {
  97536. if(order == 8) {
  97537. for(i = 0; i < (int)data_len; i++) {
  97538. sum = 0;
  97539. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97540. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97541. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97542. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97543. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97544. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97545. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97546. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97547. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97548. }
  97549. }
  97550. else { /* order == 7 */
  97551. for(i = 0; i < (int)data_len; i++) {
  97552. sum = 0;
  97553. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97554. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97555. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97556. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97557. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97558. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97559. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97560. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97561. }
  97562. }
  97563. }
  97564. else {
  97565. if(order == 6) {
  97566. for(i = 0; i < (int)data_len; i++) {
  97567. sum = 0;
  97568. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97569. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97570. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97571. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97572. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97573. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97574. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97575. }
  97576. }
  97577. else { /* order == 5 */
  97578. for(i = 0; i < (int)data_len; i++) {
  97579. sum = 0;
  97580. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97581. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97582. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97583. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97584. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97585. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97586. }
  97587. }
  97588. }
  97589. }
  97590. else {
  97591. if(order > 2) {
  97592. if(order == 4) {
  97593. for(i = 0; i < (int)data_len; i++) {
  97594. sum = 0;
  97595. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97596. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97597. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97598. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97599. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97600. }
  97601. }
  97602. else { /* order == 3 */
  97603. for(i = 0; i < (int)data_len; i++) {
  97604. sum = 0;
  97605. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97606. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97607. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97608. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97609. }
  97610. }
  97611. }
  97612. else {
  97613. if(order == 2) {
  97614. for(i = 0; i < (int)data_len; i++) {
  97615. sum = 0;
  97616. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97617. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97618. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97619. }
  97620. }
  97621. else { /* order == 1 */
  97622. for(i = 0; i < (int)data_len; i++)
  97623. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97624. }
  97625. }
  97626. }
  97627. }
  97628. else { /* order > 12 */
  97629. for(i = 0; i < (int)data_len; i++) {
  97630. sum = 0;
  97631. switch(order) {
  97632. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97633. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97634. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97635. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97636. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97637. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97638. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97639. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97640. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97641. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97642. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97643. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97644. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97645. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97646. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97647. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97648. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97649. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97650. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97651. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97652. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97653. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97654. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97655. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97656. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97657. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97658. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97659. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97660. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97661. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97662. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97663. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97664. }
  97665. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97666. }
  97667. }
  97668. }
  97669. #endif
  97670. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97671. 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[])
  97672. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97673. {
  97674. FLAC__int64 sumo;
  97675. unsigned i, j;
  97676. FLAC__int32 sum;
  97677. const FLAC__int32 *r = residual, *history;
  97678. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97679. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97680. for(i=0;i<order;i++)
  97681. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97682. fprintf(stderr,"\n");
  97683. #endif
  97684. FLAC__ASSERT(order > 0);
  97685. for(i = 0; i < data_len; i++) {
  97686. sumo = 0;
  97687. sum = 0;
  97688. history = data;
  97689. for(j = 0; j < order; j++) {
  97690. sum += qlp_coeff[j] * (*(--history));
  97691. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97692. #if defined _MSC_VER
  97693. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97694. 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);
  97695. #else
  97696. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97697. 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);
  97698. #endif
  97699. }
  97700. *(data++) = *(r++) + (sum >> lp_quantization);
  97701. }
  97702. /* Here's a slower but clearer version:
  97703. for(i = 0; i < data_len; i++) {
  97704. sum = 0;
  97705. for(j = 0; j < order; j++)
  97706. sum += qlp_coeff[j] * data[i-j-1];
  97707. data[i] = residual[i] + (sum >> lp_quantization);
  97708. }
  97709. */
  97710. }
  97711. #else /* fully unrolled version for normal use */
  97712. {
  97713. int i;
  97714. FLAC__int32 sum;
  97715. FLAC__ASSERT(order > 0);
  97716. FLAC__ASSERT(order <= 32);
  97717. /*
  97718. * We do unique versions up to 12th order since that's the subset limit.
  97719. * Also they are roughly ordered to match frequency of occurrence to
  97720. * minimize branching.
  97721. */
  97722. if(order <= 12) {
  97723. if(order > 8) {
  97724. if(order > 10) {
  97725. if(order == 12) {
  97726. for(i = 0; i < (int)data_len; i++) {
  97727. sum = 0;
  97728. sum += qlp_coeff[11] * data[i-12];
  97729. sum += qlp_coeff[10] * data[i-11];
  97730. sum += qlp_coeff[9] * data[i-10];
  97731. sum += qlp_coeff[8] * data[i-9];
  97732. sum += qlp_coeff[7] * data[i-8];
  97733. sum += qlp_coeff[6] * data[i-7];
  97734. sum += qlp_coeff[5] * data[i-6];
  97735. sum += qlp_coeff[4] * data[i-5];
  97736. sum += qlp_coeff[3] * data[i-4];
  97737. sum += qlp_coeff[2] * data[i-3];
  97738. sum += qlp_coeff[1] * data[i-2];
  97739. sum += qlp_coeff[0] * data[i-1];
  97740. data[i] = residual[i] + (sum >> lp_quantization);
  97741. }
  97742. }
  97743. else { /* order == 11 */
  97744. for(i = 0; i < (int)data_len; i++) {
  97745. sum = 0;
  97746. sum += qlp_coeff[10] * data[i-11];
  97747. sum += qlp_coeff[9] * data[i-10];
  97748. sum += qlp_coeff[8] * data[i-9];
  97749. sum += qlp_coeff[7] * data[i-8];
  97750. sum += qlp_coeff[6] * data[i-7];
  97751. sum += qlp_coeff[5] * data[i-6];
  97752. sum += qlp_coeff[4] * data[i-5];
  97753. sum += qlp_coeff[3] * data[i-4];
  97754. sum += qlp_coeff[2] * data[i-3];
  97755. sum += qlp_coeff[1] * data[i-2];
  97756. sum += qlp_coeff[0] * data[i-1];
  97757. data[i] = residual[i] + (sum >> lp_quantization);
  97758. }
  97759. }
  97760. }
  97761. else {
  97762. if(order == 10) {
  97763. for(i = 0; i < (int)data_len; i++) {
  97764. sum = 0;
  97765. sum += qlp_coeff[9] * data[i-10];
  97766. sum += qlp_coeff[8] * data[i-9];
  97767. sum += qlp_coeff[7] * data[i-8];
  97768. sum += qlp_coeff[6] * data[i-7];
  97769. sum += qlp_coeff[5] * data[i-6];
  97770. sum += qlp_coeff[4] * data[i-5];
  97771. sum += qlp_coeff[3] * data[i-4];
  97772. sum += qlp_coeff[2] * data[i-3];
  97773. sum += qlp_coeff[1] * data[i-2];
  97774. sum += qlp_coeff[0] * data[i-1];
  97775. data[i] = residual[i] + (sum >> lp_quantization);
  97776. }
  97777. }
  97778. else { /* order == 9 */
  97779. for(i = 0; i < (int)data_len; i++) {
  97780. sum = 0;
  97781. sum += qlp_coeff[8] * data[i-9];
  97782. sum += qlp_coeff[7] * data[i-8];
  97783. sum += qlp_coeff[6] * data[i-7];
  97784. sum += qlp_coeff[5] * data[i-6];
  97785. sum += qlp_coeff[4] * data[i-5];
  97786. sum += qlp_coeff[3] * data[i-4];
  97787. sum += qlp_coeff[2] * data[i-3];
  97788. sum += qlp_coeff[1] * data[i-2];
  97789. sum += qlp_coeff[0] * data[i-1];
  97790. data[i] = residual[i] + (sum >> lp_quantization);
  97791. }
  97792. }
  97793. }
  97794. }
  97795. else if(order > 4) {
  97796. if(order > 6) {
  97797. if(order == 8) {
  97798. for(i = 0; i < (int)data_len; i++) {
  97799. sum = 0;
  97800. sum += qlp_coeff[7] * data[i-8];
  97801. sum += qlp_coeff[6] * data[i-7];
  97802. sum += qlp_coeff[5] * data[i-6];
  97803. sum += qlp_coeff[4] * data[i-5];
  97804. sum += qlp_coeff[3] * data[i-4];
  97805. sum += qlp_coeff[2] * data[i-3];
  97806. sum += qlp_coeff[1] * data[i-2];
  97807. sum += qlp_coeff[0] * data[i-1];
  97808. data[i] = residual[i] + (sum >> lp_quantization);
  97809. }
  97810. }
  97811. else { /* order == 7 */
  97812. for(i = 0; i < (int)data_len; i++) {
  97813. sum = 0;
  97814. sum += qlp_coeff[6] * data[i-7];
  97815. sum += qlp_coeff[5] * data[i-6];
  97816. sum += qlp_coeff[4] * data[i-5];
  97817. sum += qlp_coeff[3] * data[i-4];
  97818. sum += qlp_coeff[2] * data[i-3];
  97819. sum += qlp_coeff[1] * data[i-2];
  97820. sum += qlp_coeff[0] * data[i-1];
  97821. data[i] = residual[i] + (sum >> lp_quantization);
  97822. }
  97823. }
  97824. }
  97825. else {
  97826. if(order == 6) {
  97827. for(i = 0; i < (int)data_len; i++) {
  97828. sum = 0;
  97829. sum += qlp_coeff[5] * data[i-6];
  97830. sum += qlp_coeff[4] * data[i-5];
  97831. sum += qlp_coeff[3] * data[i-4];
  97832. sum += qlp_coeff[2] * data[i-3];
  97833. sum += qlp_coeff[1] * data[i-2];
  97834. sum += qlp_coeff[0] * data[i-1];
  97835. data[i] = residual[i] + (sum >> lp_quantization);
  97836. }
  97837. }
  97838. else { /* order == 5 */
  97839. for(i = 0; i < (int)data_len; i++) {
  97840. sum = 0;
  97841. sum += qlp_coeff[4] * data[i-5];
  97842. sum += qlp_coeff[3] * data[i-4];
  97843. sum += qlp_coeff[2] * data[i-3];
  97844. sum += qlp_coeff[1] * data[i-2];
  97845. sum += qlp_coeff[0] * data[i-1];
  97846. data[i] = residual[i] + (sum >> lp_quantization);
  97847. }
  97848. }
  97849. }
  97850. }
  97851. else {
  97852. if(order > 2) {
  97853. if(order == 4) {
  97854. for(i = 0; i < (int)data_len; i++) {
  97855. sum = 0;
  97856. sum += qlp_coeff[3] * data[i-4];
  97857. sum += qlp_coeff[2] * data[i-3];
  97858. sum += qlp_coeff[1] * data[i-2];
  97859. sum += qlp_coeff[0] * data[i-1];
  97860. data[i] = residual[i] + (sum >> lp_quantization);
  97861. }
  97862. }
  97863. else { /* order == 3 */
  97864. for(i = 0; i < (int)data_len; i++) {
  97865. sum = 0;
  97866. sum += qlp_coeff[2] * data[i-3];
  97867. sum += qlp_coeff[1] * data[i-2];
  97868. sum += qlp_coeff[0] * data[i-1];
  97869. data[i] = residual[i] + (sum >> lp_quantization);
  97870. }
  97871. }
  97872. }
  97873. else {
  97874. if(order == 2) {
  97875. for(i = 0; i < (int)data_len; i++) {
  97876. sum = 0;
  97877. sum += qlp_coeff[1] * data[i-2];
  97878. sum += qlp_coeff[0] * data[i-1];
  97879. data[i] = residual[i] + (sum >> lp_quantization);
  97880. }
  97881. }
  97882. else { /* order == 1 */
  97883. for(i = 0; i < (int)data_len; i++)
  97884. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97885. }
  97886. }
  97887. }
  97888. }
  97889. else { /* order > 12 */
  97890. for(i = 0; i < (int)data_len; i++) {
  97891. sum = 0;
  97892. switch(order) {
  97893. case 32: sum += qlp_coeff[31] * data[i-32];
  97894. case 31: sum += qlp_coeff[30] * data[i-31];
  97895. case 30: sum += qlp_coeff[29] * data[i-30];
  97896. case 29: sum += qlp_coeff[28] * data[i-29];
  97897. case 28: sum += qlp_coeff[27] * data[i-28];
  97898. case 27: sum += qlp_coeff[26] * data[i-27];
  97899. case 26: sum += qlp_coeff[25] * data[i-26];
  97900. case 25: sum += qlp_coeff[24] * data[i-25];
  97901. case 24: sum += qlp_coeff[23] * data[i-24];
  97902. case 23: sum += qlp_coeff[22] * data[i-23];
  97903. case 22: sum += qlp_coeff[21] * data[i-22];
  97904. case 21: sum += qlp_coeff[20] * data[i-21];
  97905. case 20: sum += qlp_coeff[19] * data[i-20];
  97906. case 19: sum += qlp_coeff[18] * data[i-19];
  97907. case 18: sum += qlp_coeff[17] * data[i-18];
  97908. case 17: sum += qlp_coeff[16] * data[i-17];
  97909. case 16: sum += qlp_coeff[15] * data[i-16];
  97910. case 15: sum += qlp_coeff[14] * data[i-15];
  97911. case 14: sum += qlp_coeff[13] * data[i-14];
  97912. case 13: sum += qlp_coeff[12] * data[i-13];
  97913. sum += qlp_coeff[11] * data[i-12];
  97914. sum += qlp_coeff[10] * data[i-11];
  97915. sum += qlp_coeff[ 9] * data[i-10];
  97916. sum += qlp_coeff[ 8] * data[i- 9];
  97917. sum += qlp_coeff[ 7] * data[i- 8];
  97918. sum += qlp_coeff[ 6] * data[i- 7];
  97919. sum += qlp_coeff[ 5] * data[i- 6];
  97920. sum += qlp_coeff[ 4] * data[i- 5];
  97921. sum += qlp_coeff[ 3] * data[i- 4];
  97922. sum += qlp_coeff[ 2] * data[i- 3];
  97923. sum += qlp_coeff[ 1] * data[i- 2];
  97924. sum += qlp_coeff[ 0] * data[i- 1];
  97925. }
  97926. data[i] = residual[i] + (sum >> lp_quantization);
  97927. }
  97928. }
  97929. }
  97930. #endif
  97931. 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[])
  97932. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97933. {
  97934. unsigned i, j;
  97935. FLAC__int64 sum;
  97936. const FLAC__int32 *r = residual, *history;
  97937. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97938. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97939. for(i=0;i<order;i++)
  97940. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97941. fprintf(stderr,"\n");
  97942. #endif
  97943. FLAC__ASSERT(order > 0);
  97944. for(i = 0; i < data_len; i++) {
  97945. sum = 0;
  97946. history = data;
  97947. for(j = 0; j < order; j++)
  97948. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97949. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97950. #ifdef _MSC_VER
  97951. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97952. #else
  97953. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97954. #endif
  97955. break;
  97956. }
  97957. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97958. #ifdef _MSC_VER
  97959. 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));
  97960. #else
  97961. 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)));
  97962. #endif
  97963. break;
  97964. }
  97965. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97966. }
  97967. }
  97968. #else /* fully unrolled version for normal use */
  97969. {
  97970. int i;
  97971. FLAC__int64 sum;
  97972. FLAC__ASSERT(order > 0);
  97973. FLAC__ASSERT(order <= 32);
  97974. /*
  97975. * We do unique versions up to 12th order since that's the subset limit.
  97976. * Also they are roughly ordered to match frequency of occurrence to
  97977. * minimize branching.
  97978. */
  97979. if(order <= 12) {
  97980. if(order > 8) {
  97981. if(order > 10) {
  97982. if(order == 12) {
  97983. for(i = 0; i < (int)data_len; i++) {
  97984. sum = 0;
  97985. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97986. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97987. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97988. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97989. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97990. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97991. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97992. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97993. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97994. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97995. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97996. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97997. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97998. }
  97999. }
  98000. else { /* order == 11 */
  98001. for(i = 0; i < (int)data_len; i++) {
  98002. sum = 0;
  98003. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98004. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98005. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98006. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98007. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98008. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98009. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98010. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98011. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98012. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98013. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98014. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98015. }
  98016. }
  98017. }
  98018. else {
  98019. if(order == 10) {
  98020. for(i = 0; i < (int)data_len; i++) {
  98021. sum = 0;
  98022. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98023. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98024. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98025. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98026. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98027. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98028. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98029. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98030. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98031. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98032. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98033. }
  98034. }
  98035. else { /* order == 9 */
  98036. for(i = 0; i < (int)data_len; i++) {
  98037. sum = 0;
  98038. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98039. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98040. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98041. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98042. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98043. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98044. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98045. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98046. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98047. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98048. }
  98049. }
  98050. }
  98051. }
  98052. else if(order > 4) {
  98053. if(order > 6) {
  98054. if(order == 8) {
  98055. for(i = 0; i < (int)data_len; i++) {
  98056. sum = 0;
  98057. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98058. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98059. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98060. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98061. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98062. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98063. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98064. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98065. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98066. }
  98067. }
  98068. else { /* order == 7 */
  98069. for(i = 0; i < (int)data_len; i++) {
  98070. sum = 0;
  98071. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98072. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98073. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98074. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98075. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98076. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98077. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98078. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98079. }
  98080. }
  98081. }
  98082. else {
  98083. if(order == 6) {
  98084. for(i = 0; i < (int)data_len; i++) {
  98085. sum = 0;
  98086. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98087. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98088. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98089. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98090. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98091. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98092. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98093. }
  98094. }
  98095. else { /* order == 5 */
  98096. for(i = 0; i < (int)data_len; i++) {
  98097. sum = 0;
  98098. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98099. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98100. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98101. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98102. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98103. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98104. }
  98105. }
  98106. }
  98107. }
  98108. else {
  98109. if(order > 2) {
  98110. if(order == 4) {
  98111. for(i = 0; i < (int)data_len; i++) {
  98112. sum = 0;
  98113. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98114. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98115. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98116. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98117. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98118. }
  98119. }
  98120. else { /* order == 3 */
  98121. for(i = 0; i < (int)data_len; i++) {
  98122. sum = 0;
  98123. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98124. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98125. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98126. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98127. }
  98128. }
  98129. }
  98130. else {
  98131. if(order == 2) {
  98132. for(i = 0; i < (int)data_len; i++) {
  98133. sum = 0;
  98134. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98135. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98136. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98137. }
  98138. }
  98139. else { /* order == 1 */
  98140. for(i = 0; i < (int)data_len; i++)
  98141. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98142. }
  98143. }
  98144. }
  98145. }
  98146. else { /* order > 12 */
  98147. for(i = 0; i < (int)data_len; i++) {
  98148. sum = 0;
  98149. switch(order) {
  98150. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98151. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98152. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98153. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98154. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98155. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98156. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98157. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98158. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98159. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98160. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98161. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98162. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98163. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98164. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98165. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98166. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98167. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98168. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98169. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98170. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98171. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98172. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98173. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98174. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98175. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98176. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98177. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98178. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98179. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98180. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98181. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98182. }
  98183. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98184. }
  98185. }
  98186. }
  98187. #endif
  98188. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98189. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98190. {
  98191. FLAC__double error_scale;
  98192. FLAC__ASSERT(total_samples > 0);
  98193. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98194. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98195. }
  98196. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98197. {
  98198. if(lpc_error > 0.0) {
  98199. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98200. if(bps >= 0.0)
  98201. return bps;
  98202. else
  98203. return 0.0;
  98204. }
  98205. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98206. return 1e32;
  98207. }
  98208. else {
  98209. return 0.0;
  98210. }
  98211. }
  98212. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98213. {
  98214. 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 */
  98215. FLAC__double bits, best_bits, error_scale;
  98216. FLAC__ASSERT(max_order > 0);
  98217. FLAC__ASSERT(total_samples > 0);
  98218. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98219. best_index = 0;
  98220. best_bits = (unsigned)(-1);
  98221. for(index = 0, order = 1; index < max_order; index++, order++) {
  98222. 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);
  98223. if(bits < best_bits) {
  98224. best_index = index;
  98225. best_bits = bits;
  98226. }
  98227. }
  98228. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98229. }
  98230. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98231. #endif
  98232. /*** End of inlined file: lpc_flac.c ***/
  98233. /*** Start of inlined file: md5.c ***/
  98234. /*** Start of inlined file: juce_FlacHeader.h ***/
  98235. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98236. // tasks..
  98237. #define VERSION "1.2.1"
  98238. #define FLAC__NO_DLL 1
  98239. #if JUCE_MSVC
  98240. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98241. #endif
  98242. #if JUCE_MAC
  98243. #define FLAC__SYS_DARWIN 1
  98244. #endif
  98245. /*** End of inlined file: juce_FlacHeader.h ***/
  98246. #if JUCE_USE_FLAC
  98247. #if HAVE_CONFIG_H
  98248. # include <config.h>
  98249. #endif
  98250. #include <stdlib.h> /* for malloc() */
  98251. #include <string.h> /* for memcpy() */
  98252. /*** Start of inlined file: md5.h ***/
  98253. #ifndef FLAC__PRIVATE__MD5_H
  98254. #define FLAC__PRIVATE__MD5_H
  98255. /*
  98256. * This is the header file for the MD5 message-digest algorithm.
  98257. * The algorithm is due to Ron Rivest. This code was
  98258. * written by Colin Plumb in 1993, no copyright is claimed.
  98259. * This code is in the public domain; do with it what you wish.
  98260. *
  98261. * Equivalent code is available from RSA Data Security, Inc.
  98262. * This code has been tested against that, and is equivalent,
  98263. * except that you don't need to include two pages of legalese
  98264. * with every copy.
  98265. *
  98266. * To compute the message digest of a chunk of bytes, declare an
  98267. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98268. * needed on buffers full of bytes, and then call MD5Final, which
  98269. * will fill a supplied 16-byte array with the digest.
  98270. *
  98271. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98272. * header definitions; now uses stuff from dpkg's config.h
  98273. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98274. * Still in the public domain.
  98275. *
  98276. * Josh Coalson: made some changes to integrate with libFLAC.
  98277. * Still in the public domain, with no warranty.
  98278. */
  98279. typedef struct {
  98280. FLAC__uint32 in[16];
  98281. FLAC__uint32 buf[4];
  98282. FLAC__uint32 bytes[2];
  98283. FLAC__byte *internal_buf;
  98284. size_t capacity;
  98285. } FLAC__MD5Context;
  98286. void FLAC__MD5Init(FLAC__MD5Context *context);
  98287. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98288. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98289. #endif
  98290. /*** End of inlined file: md5.h ***/
  98291. #ifndef FLaC__INLINE
  98292. #define FLaC__INLINE
  98293. #endif
  98294. /*
  98295. * This code implements the MD5 message-digest algorithm.
  98296. * The algorithm is due to Ron Rivest. This code was
  98297. * written by Colin Plumb in 1993, no copyright is claimed.
  98298. * This code is in the public domain; do with it what you wish.
  98299. *
  98300. * Equivalent code is available from RSA Data Security, Inc.
  98301. * This code has been tested against that, and is equivalent,
  98302. * except that you don't need to include two pages of legalese
  98303. * with every copy.
  98304. *
  98305. * To compute the message digest of a chunk of bytes, declare an
  98306. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98307. * needed on buffers full of bytes, and then call MD5Final, which
  98308. * will fill a supplied 16-byte array with the digest.
  98309. *
  98310. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98311. * definitions; now uses stuff from dpkg's config.h.
  98312. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98313. * Still in the public domain.
  98314. *
  98315. * Josh Coalson: made some changes to integrate with libFLAC.
  98316. * Still in the public domain.
  98317. */
  98318. /* The four core functions - F1 is optimized somewhat */
  98319. /* #define F1(x, y, z) (x & y | ~x & z) */
  98320. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98321. #define F2(x, y, z) F1(z, x, y)
  98322. #define F3(x, y, z) (x ^ y ^ z)
  98323. #define F4(x, y, z) (y ^ (x | ~z))
  98324. /* This is the central step in the MD5 algorithm. */
  98325. #define MD5STEP(f,w,x,y,z,in,s) \
  98326. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98327. /*
  98328. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98329. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98330. * the data and converts bytes into longwords for this routine.
  98331. */
  98332. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98333. {
  98334. register FLAC__uint32 a, b, c, d;
  98335. a = buf[0];
  98336. b = buf[1];
  98337. c = buf[2];
  98338. d = buf[3];
  98339. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98340. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98341. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98342. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98343. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98344. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98345. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98346. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98347. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98348. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98349. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98350. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98351. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98352. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98353. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98354. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98355. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98356. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98357. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98358. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98359. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98360. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98361. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98362. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98363. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98364. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98365. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98366. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98367. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98368. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98369. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98370. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98371. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98372. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98373. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98374. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98375. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98376. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98377. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98378. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98379. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98380. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98381. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98382. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98383. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98384. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98385. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98386. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98387. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98388. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98389. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98390. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98391. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98392. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98393. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98394. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98395. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98396. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98397. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98398. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98399. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98400. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98401. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98402. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98403. buf[0] += a;
  98404. buf[1] += b;
  98405. buf[2] += c;
  98406. buf[3] += d;
  98407. }
  98408. #if WORDS_BIGENDIAN
  98409. //@@@@@@ OPT: use bswap/intrinsics
  98410. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98411. {
  98412. register FLAC__uint32 x;
  98413. do {
  98414. x = *buf;
  98415. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98416. *buf++ = (x >> 16) | (x << 16);
  98417. } while (--words);
  98418. }
  98419. static void byteSwapX16(FLAC__uint32 *buf)
  98420. {
  98421. register FLAC__uint32 x;
  98422. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98423. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98424. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98425. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98426. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98427. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98428. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98429. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98430. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98431. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98432. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98433. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98434. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98435. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98436. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98437. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98438. }
  98439. #else
  98440. #define byteSwap(buf, words)
  98441. #define byteSwapX16(buf)
  98442. #endif
  98443. /*
  98444. * Update context to reflect the concatenation of another buffer full
  98445. * of bytes.
  98446. */
  98447. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98448. {
  98449. FLAC__uint32 t;
  98450. /* Update byte count */
  98451. t = ctx->bytes[0];
  98452. if ((ctx->bytes[0] = t + len) < t)
  98453. ctx->bytes[1]++; /* Carry from low to high */
  98454. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98455. if (t > len) {
  98456. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98457. return;
  98458. }
  98459. /* First chunk is an odd size */
  98460. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98461. byteSwapX16(ctx->in);
  98462. FLAC__MD5Transform(ctx->buf, ctx->in);
  98463. buf += t;
  98464. len -= t;
  98465. /* Process data in 64-byte chunks */
  98466. while (len >= 64) {
  98467. memcpy(ctx->in, buf, 64);
  98468. byteSwapX16(ctx->in);
  98469. FLAC__MD5Transform(ctx->buf, ctx->in);
  98470. buf += 64;
  98471. len -= 64;
  98472. }
  98473. /* Handle any remaining bytes of data. */
  98474. memcpy(ctx->in, buf, len);
  98475. }
  98476. /*
  98477. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98478. * initialization constants.
  98479. */
  98480. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98481. {
  98482. ctx->buf[0] = 0x67452301;
  98483. ctx->buf[1] = 0xefcdab89;
  98484. ctx->buf[2] = 0x98badcfe;
  98485. ctx->buf[3] = 0x10325476;
  98486. ctx->bytes[0] = 0;
  98487. ctx->bytes[1] = 0;
  98488. ctx->internal_buf = 0;
  98489. ctx->capacity = 0;
  98490. }
  98491. /*
  98492. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98493. * 1 0* (64-bit count of bits processed, MSB-first)
  98494. */
  98495. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98496. {
  98497. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98498. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98499. /* Set the first char of padding to 0x80. There is always room. */
  98500. *p++ = 0x80;
  98501. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98502. count = 56 - 1 - count;
  98503. if (count < 0) { /* Padding forces an extra block */
  98504. memset(p, 0, count + 8);
  98505. byteSwapX16(ctx->in);
  98506. FLAC__MD5Transform(ctx->buf, ctx->in);
  98507. p = (FLAC__byte *)ctx->in;
  98508. count = 56;
  98509. }
  98510. memset(p, 0, count);
  98511. byteSwap(ctx->in, 14);
  98512. /* Append length in bits and transform */
  98513. ctx->in[14] = ctx->bytes[0] << 3;
  98514. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98515. FLAC__MD5Transform(ctx->buf, ctx->in);
  98516. byteSwap(ctx->buf, 4);
  98517. memcpy(digest, ctx->buf, 16);
  98518. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98519. if(0 != ctx->internal_buf) {
  98520. free(ctx->internal_buf);
  98521. ctx->internal_buf = 0;
  98522. ctx->capacity = 0;
  98523. }
  98524. }
  98525. /*
  98526. * Convert the incoming audio signal to a byte stream
  98527. */
  98528. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98529. {
  98530. unsigned channel, sample;
  98531. register FLAC__int32 a_word;
  98532. register FLAC__byte *buf_ = buf;
  98533. #if WORDS_BIGENDIAN
  98534. #else
  98535. if(channels == 2 && bytes_per_sample == 2) {
  98536. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98537. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98538. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98539. *buf1_ = (FLAC__int16)signal[1][sample];
  98540. }
  98541. else if(channels == 1 && bytes_per_sample == 2) {
  98542. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98543. for(sample = 0; sample < samples; sample++)
  98544. *buf1_++ = (FLAC__int16)signal[0][sample];
  98545. }
  98546. else
  98547. #endif
  98548. if(bytes_per_sample == 2) {
  98549. if(channels == 2) {
  98550. for(sample = 0; sample < samples; sample++) {
  98551. a_word = signal[0][sample];
  98552. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98553. *buf_++ = (FLAC__byte)a_word;
  98554. a_word = signal[1][sample];
  98555. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98556. *buf_++ = (FLAC__byte)a_word;
  98557. }
  98558. }
  98559. else if(channels == 1) {
  98560. for(sample = 0; sample < samples; sample++) {
  98561. a_word = signal[0][sample];
  98562. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98563. *buf_++ = (FLAC__byte)a_word;
  98564. }
  98565. }
  98566. else {
  98567. for(sample = 0; sample < samples; sample++) {
  98568. for(channel = 0; channel < channels; channel++) {
  98569. a_word = signal[channel][sample];
  98570. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98571. *buf_++ = (FLAC__byte)a_word;
  98572. }
  98573. }
  98574. }
  98575. }
  98576. else if(bytes_per_sample == 3) {
  98577. if(channels == 2) {
  98578. for(sample = 0; sample < samples; sample++) {
  98579. a_word = signal[0][sample];
  98580. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98581. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98582. *buf_++ = (FLAC__byte)a_word;
  98583. a_word = signal[1][sample];
  98584. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98585. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98586. *buf_++ = (FLAC__byte)a_word;
  98587. }
  98588. }
  98589. else if(channels == 1) {
  98590. for(sample = 0; sample < samples; sample++) {
  98591. a_word = signal[0][sample];
  98592. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98593. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98594. *buf_++ = (FLAC__byte)a_word;
  98595. }
  98596. }
  98597. else {
  98598. for(sample = 0; sample < samples; sample++) {
  98599. for(channel = 0; channel < channels; channel++) {
  98600. a_word = signal[channel][sample];
  98601. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98602. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98603. *buf_++ = (FLAC__byte)a_word;
  98604. }
  98605. }
  98606. }
  98607. }
  98608. else if(bytes_per_sample == 1) {
  98609. if(channels == 2) {
  98610. for(sample = 0; sample < samples; sample++) {
  98611. a_word = signal[0][sample];
  98612. *buf_++ = (FLAC__byte)a_word;
  98613. a_word = signal[1][sample];
  98614. *buf_++ = (FLAC__byte)a_word;
  98615. }
  98616. }
  98617. else if(channels == 1) {
  98618. for(sample = 0; sample < samples; sample++) {
  98619. a_word = signal[0][sample];
  98620. *buf_++ = (FLAC__byte)a_word;
  98621. }
  98622. }
  98623. else {
  98624. for(sample = 0; sample < samples; sample++) {
  98625. for(channel = 0; channel < channels; channel++) {
  98626. a_word = signal[channel][sample];
  98627. *buf_++ = (FLAC__byte)a_word;
  98628. }
  98629. }
  98630. }
  98631. }
  98632. else { /* bytes_per_sample == 4, maybe optimize more later */
  98633. for(sample = 0; sample < samples; sample++) {
  98634. for(channel = 0; channel < channels; channel++) {
  98635. a_word = signal[channel][sample];
  98636. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98637. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98638. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98639. *buf_++ = (FLAC__byte)a_word;
  98640. }
  98641. }
  98642. }
  98643. }
  98644. /*
  98645. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98646. */
  98647. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98648. {
  98649. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98650. /* overflow check */
  98651. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98652. return false;
  98653. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98654. return false;
  98655. if(ctx->capacity < bytes_needed) {
  98656. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98657. if(0 == tmp) {
  98658. free(ctx->internal_buf);
  98659. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98660. return false;
  98661. }
  98662. ctx->internal_buf = tmp;
  98663. ctx->capacity = bytes_needed;
  98664. }
  98665. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98666. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98667. return true;
  98668. }
  98669. #endif
  98670. /*** End of inlined file: md5.c ***/
  98671. /*** Start of inlined file: memory.c ***/
  98672. /*** Start of inlined file: juce_FlacHeader.h ***/
  98673. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98674. // tasks..
  98675. #define VERSION "1.2.1"
  98676. #define FLAC__NO_DLL 1
  98677. #if JUCE_MSVC
  98678. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98679. #endif
  98680. #if JUCE_MAC
  98681. #define FLAC__SYS_DARWIN 1
  98682. #endif
  98683. /*** End of inlined file: juce_FlacHeader.h ***/
  98684. #if JUCE_USE_FLAC
  98685. #if HAVE_CONFIG_H
  98686. # include <config.h>
  98687. #endif
  98688. /*** Start of inlined file: memory.h ***/
  98689. #ifndef FLAC__PRIVATE__MEMORY_H
  98690. #define FLAC__PRIVATE__MEMORY_H
  98691. #ifdef HAVE_CONFIG_H
  98692. #include <config.h>
  98693. #endif
  98694. #include <stdlib.h> /* for size_t */
  98695. /* Returns the unaligned address returned by malloc.
  98696. * Use free() on this address to deallocate.
  98697. */
  98698. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98699. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98700. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98701. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98702. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98703. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98704. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98705. #endif
  98706. #endif
  98707. /*** End of inlined file: memory.h ***/
  98708. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98709. {
  98710. void *x;
  98711. FLAC__ASSERT(0 != aligned_address);
  98712. #ifdef FLAC__ALIGN_MALLOC_DATA
  98713. /* align on 32-byte (256-bit) boundary */
  98714. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98715. #ifdef SIZEOF_VOIDP
  98716. #if SIZEOF_VOIDP == 4
  98717. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98718. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98719. #elif SIZEOF_VOIDP == 8
  98720. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98721. #else
  98722. # error Unsupported sizeof(void*)
  98723. #endif
  98724. #else
  98725. /* there's got to be a better way to do this right for all archs */
  98726. if(sizeof(void*) == sizeof(unsigned))
  98727. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98728. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98729. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98730. else
  98731. return 0;
  98732. #endif
  98733. #else
  98734. x = safe_malloc_(bytes);
  98735. *aligned_address = x;
  98736. #endif
  98737. return x;
  98738. }
  98739. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98740. {
  98741. FLAC__int32 *pu; /* unaligned pointer */
  98742. union { /* union needed to comply with C99 pointer aliasing rules */
  98743. FLAC__int32 *pa; /* aligned pointer */
  98744. void *pv; /* aligned pointer alias */
  98745. } u;
  98746. FLAC__ASSERT(elements > 0);
  98747. FLAC__ASSERT(0 != unaligned_pointer);
  98748. FLAC__ASSERT(0 != aligned_pointer);
  98749. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98750. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98751. if(0 == pu) {
  98752. return false;
  98753. }
  98754. else {
  98755. if(*unaligned_pointer != 0)
  98756. free(*unaligned_pointer);
  98757. *unaligned_pointer = pu;
  98758. *aligned_pointer = u.pa;
  98759. return true;
  98760. }
  98761. }
  98762. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98763. {
  98764. FLAC__uint32 *pu; /* unaligned pointer */
  98765. union { /* union needed to comply with C99 pointer aliasing rules */
  98766. FLAC__uint32 *pa; /* aligned pointer */
  98767. void *pv; /* aligned pointer alias */
  98768. } u;
  98769. FLAC__ASSERT(elements > 0);
  98770. FLAC__ASSERT(0 != unaligned_pointer);
  98771. FLAC__ASSERT(0 != aligned_pointer);
  98772. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98773. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98774. if(0 == pu) {
  98775. return false;
  98776. }
  98777. else {
  98778. if(*unaligned_pointer != 0)
  98779. free(*unaligned_pointer);
  98780. *unaligned_pointer = pu;
  98781. *aligned_pointer = u.pa;
  98782. return true;
  98783. }
  98784. }
  98785. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98786. {
  98787. FLAC__uint64 *pu; /* unaligned pointer */
  98788. union { /* union needed to comply with C99 pointer aliasing rules */
  98789. FLAC__uint64 *pa; /* aligned pointer */
  98790. void *pv; /* aligned pointer alias */
  98791. } u;
  98792. FLAC__ASSERT(elements > 0);
  98793. FLAC__ASSERT(0 != unaligned_pointer);
  98794. FLAC__ASSERT(0 != aligned_pointer);
  98795. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98796. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98797. if(0 == pu) {
  98798. return false;
  98799. }
  98800. else {
  98801. if(*unaligned_pointer != 0)
  98802. free(*unaligned_pointer);
  98803. *unaligned_pointer = pu;
  98804. *aligned_pointer = u.pa;
  98805. return true;
  98806. }
  98807. }
  98808. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98809. {
  98810. unsigned *pu; /* unaligned pointer */
  98811. union { /* union needed to comply with C99 pointer aliasing rules */
  98812. unsigned *pa; /* aligned pointer */
  98813. void *pv; /* aligned pointer alias */
  98814. } u;
  98815. FLAC__ASSERT(elements > 0);
  98816. FLAC__ASSERT(0 != unaligned_pointer);
  98817. FLAC__ASSERT(0 != aligned_pointer);
  98818. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98819. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98820. if(0 == pu) {
  98821. return false;
  98822. }
  98823. else {
  98824. if(*unaligned_pointer != 0)
  98825. free(*unaligned_pointer);
  98826. *unaligned_pointer = pu;
  98827. *aligned_pointer = u.pa;
  98828. return true;
  98829. }
  98830. }
  98831. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98832. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98833. {
  98834. FLAC__real *pu; /* unaligned pointer */
  98835. union { /* union needed to comply with C99 pointer aliasing rules */
  98836. FLAC__real *pa; /* aligned pointer */
  98837. void *pv; /* aligned pointer alias */
  98838. } u;
  98839. FLAC__ASSERT(elements > 0);
  98840. FLAC__ASSERT(0 != unaligned_pointer);
  98841. FLAC__ASSERT(0 != aligned_pointer);
  98842. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98843. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98844. if(0 == pu) {
  98845. return false;
  98846. }
  98847. else {
  98848. if(*unaligned_pointer != 0)
  98849. free(*unaligned_pointer);
  98850. *unaligned_pointer = pu;
  98851. *aligned_pointer = u.pa;
  98852. return true;
  98853. }
  98854. }
  98855. #endif
  98856. #endif
  98857. /*** End of inlined file: memory.c ***/
  98858. /*** Start of inlined file: stream_decoder.c ***/
  98859. /*** Start of inlined file: juce_FlacHeader.h ***/
  98860. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98861. // tasks..
  98862. #define VERSION "1.2.1"
  98863. #define FLAC__NO_DLL 1
  98864. #if JUCE_MSVC
  98865. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98866. #endif
  98867. #if JUCE_MAC
  98868. #define FLAC__SYS_DARWIN 1
  98869. #endif
  98870. /*** End of inlined file: juce_FlacHeader.h ***/
  98871. #if JUCE_USE_FLAC
  98872. #if HAVE_CONFIG_H
  98873. # include <config.h>
  98874. #endif
  98875. #if defined _MSC_VER || defined __MINGW32__
  98876. #include <io.h> /* for _setmode() */
  98877. #include <fcntl.h> /* for _O_BINARY */
  98878. #endif
  98879. #if defined __CYGWIN__ || defined __EMX__
  98880. #include <io.h> /* for setmode(), O_BINARY */
  98881. #include <fcntl.h> /* for _O_BINARY */
  98882. #endif
  98883. #include <stdio.h>
  98884. #include <stdlib.h> /* for malloc() */
  98885. #include <string.h> /* for memset/memcpy() */
  98886. #include <sys/stat.h> /* for stat() */
  98887. #include <sys/types.h> /* for off_t */
  98888. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98889. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98890. #define fseeko fseek
  98891. #define ftello ftell
  98892. #endif
  98893. #endif
  98894. /*** Start of inlined file: stream_decoder.h ***/
  98895. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98896. #define FLAC__PROTECTED__STREAM_DECODER_H
  98897. #if FLAC__HAS_OGG
  98898. #include "include/private/ogg_decoder_aspect.h"
  98899. #endif
  98900. typedef struct FLAC__StreamDecoderProtected {
  98901. FLAC__StreamDecoderState state;
  98902. unsigned channels;
  98903. FLAC__ChannelAssignment channel_assignment;
  98904. unsigned bits_per_sample;
  98905. unsigned sample_rate; /* in Hz */
  98906. unsigned blocksize; /* in samples (per channel) */
  98907. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98908. #if FLAC__HAS_OGG
  98909. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98910. #endif
  98911. } FLAC__StreamDecoderProtected;
  98912. /*
  98913. * return the number of input bytes consumed
  98914. */
  98915. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98916. #endif
  98917. /*** End of inlined file: stream_decoder.h ***/
  98918. #ifdef max
  98919. #undef max
  98920. #endif
  98921. #define max(a,b) ((a)>(b)?(a):(b))
  98922. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98923. #ifdef _MSC_VER
  98924. #define FLAC__U64L(x) x
  98925. #else
  98926. #define FLAC__U64L(x) x##LLU
  98927. #endif
  98928. /* technically this should be in an "export.c" but this is convenient enough */
  98929. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98930. #if FLAC__HAS_OGG
  98931. 1
  98932. #else
  98933. 0
  98934. #endif
  98935. ;
  98936. /***********************************************************************
  98937. *
  98938. * Private static data
  98939. *
  98940. ***********************************************************************/
  98941. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98942. /***********************************************************************
  98943. *
  98944. * Private class method prototypes
  98945. *
  98946. ***********************************************************************/
  98947. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98948. static FILE *get_binary_stdin_(void);
  98949. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98950. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98951. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98952. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98953. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98954. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98955. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98956. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98957. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98958. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98959. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98960. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98961. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98962. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98963. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98964. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98965. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98966. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98967. 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);
  98968. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98969. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98970. #if FLAC__HAS_OGG
  98971. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98972. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98973. #endif
  98974. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98975. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98976. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98977. #if FLAC__HAS_OGG
  98978. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98979. #endif
  98980. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98981. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98982. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98983. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98984. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98985. /***********************************************************************
  98986. *
  98987. * Private class data
  98988. *
  98989. ***********************************************************************/
  98990. typedef struct FLAC__StreamDecoderPrivate {
  98991. #if FLAC__HAS_OGG
  98992. FLAC__bool is_ogg;
  98993. #endif
  98994. FLAC__StreamDecoderReadCallback read_callback;
  98995. FLAC__StreamDecoderSeekCallback seek_callback;
  98996. FLAC__StreamDecoderTellCallback tell_callback;
  98997. FLAC__StreamDecoderLengthCallback length_callback;
  98998. FLAC__StreamDecoderEofCallback eof_callback;
  98999. FLAC__StreamDecoderWriteCallback write_callback;
  99000. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99001. FLAC__StreamDecoderErrorCallback error_callback;
  99002. /* generic 32-bit datapath: */
  99003. 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[]);
  99004. /* generic 64-bit datapath: */
  99005. 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[]);
  99006. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99007. 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[]);
  99008. /* 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: */
  99009. 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[]);
  99010. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99011. void *client_data;
  99012. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99013. FLAC__BitReader *input;
  99014. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99015. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99016. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99017. unsigned output_capacity, output_channels;
  99018. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99019. FLAC__uint64 samples_decoded;
  99020. FLAC__bool has_stream_info, has_seek_table;
  99021. FLAC__StreamMetadata stream_info;
  99022. FLAC__StreamMetadata seek_table;
  99023. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99024. FLAC__byte *metadata_filter_ids;
  99025. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99026. FLAC__Frame frame;
  99027. FLAC__bool cached; /* true if there is a byte in lookahead */
  99028. FLAC__CPUInfo cpuinfo;
  99029. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99030. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99031. /* unaligned (original) pointers to allocated data */
  99032. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99033. 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 */
  99034. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99035. FLAC__bool is_seeking;
  99036. FLAC__MD5Context md5context;
  99037. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99038. /* (the rest of these are only used for seeking) */
  99039. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99040. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99041. FLAC__uint64 target_sample;
  99042. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99043. #if FLAC__HAS_OGG
  99044. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99045. #endif
  99046. } FLAC__StreamDecoderPrivate;
  99047. /***********************************************************************
  99048. *
  99049. * Public static class data
  99050. *
  99051. ***********************************************************************/
  99052. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99053. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99054. "FLAC__STREAM_DECODER_READ_METADATA",
  99055. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99056. "FLAC__STREAM_DECODER_READ_FRAME",
  99057. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99058. "FLAC__STREAM_DECODER_OGG_ERROR",
  99059. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99060. "FLAC__STREAM_DECODER_ABORTED",
  99061. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99062. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99063. };
  99064. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99065. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99066. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99067. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99068. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99069. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99070. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99071. };
  99072. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99073. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99074. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99075. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99076. };
  99077. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99078. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99079. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99080. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99081. };
  99082. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99083. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99084. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99085. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99086. };
  99087. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99088. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99089. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99090. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99091. };
  99092. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99093. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99094. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99095. };
  99096. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99097. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99098. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99099. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99100. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99101. };
  99102. /***********************************************************************
  99103. *
  99104. * Class constructor/destructor
  99105. *
  99106. ***********************************************************************/
  99107. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99108. {
  99109. FLAC__StreamDecoder *decoder;
  99110. unsigned i;
  99111. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99112. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99113. if(decoder == 0) {
  99114. return 0;
  99115. }
  99116. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99117. if(decoder->protected_ == 0) {
  99118. free(decoder);
  99119. return 0;
  99120. }
  99121. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99122. if(decoder->private_ == 0) {
  99123. free(decoder->protected_);
  99124. free(decoder);
  99125. return 0;
  99126. }
  99127. decoder->private_->input = FLAC__bitreader_new();
  99128. if(decoder->private_->input == 0) {
  99129. free(decoder->private_);
  99130. free(decoder->protected_);
  99131. free(decoder);
  99132. return 0;
  99133. }
  99134. decoder->private_->metadata_filter_ids_capacity = 16;
  99135. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99136. FLAC__bitreader_delete(decoder->private_->input);
  99137. free(decoder->private_);
  99138. free(decoder->protected_);
  99139. free(decoder);
  99140. return 0;
  99141. }
  99142. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99143. decoder->private_->output[i] = 0;
  99144. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99145. }
  99146. decoder->private_->output_capacity = 0;
  99147. decoder->private_->output_channels = 0;
  99148. decoder->private_->has_seek_table = false;
  99149. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99150. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99151. decoder->private_->file = 0;
  99152. set_defaults_dec(decoder);
  99153. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99154. return decoder;
  99155. }
  99156. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99157. {
  99158. unsigned i;
  99159. FLAC__ASSERT(0 != decoder);
  99160. FLAC__ASSERT(0 != decoder->protected_);
  99161. FLAC__ASSERT(0 != decoder->private_);
  99162. FLAC__ASSERT(0 != decoder->private_->input);
  99163. (void)FLAC__stream_decoder_finish(decoder);
  99164. if(0 != decoder->private_->metadata_filter_ids)
  99165. free(decoder->private_->metadata_filter_ids);
  99166. FLAC__bitreader_delete(decoder->private_->input);
  99167. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99168. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99169. free(decoder->private_);
  99170. free(decoder->protected_);
  99171. free(decoder);
  99172. }
  99173. /***********************************************************************
  99174. *
  99175. * Public class methods
  99176. *
  99177. ***********************************************************************/
  99178. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99179. FLAC__StreamDecoder *decoder,
  99180. FLAC__StreamDecoderReadCallback read_callback,
  99181. FLAC__StreamDecoderSeekCallback seek_callback,
  99182. FLAC__StreamDecoderTellCallback tell_callback,
  99183. FLAC__StreamDecoderLengthCallback length_callback,
  99184. FLAC__StreamDecoderEofCallback eof_callback,
  99185. FLAC__StreamDecoderWriteCallback write_callback,
  99186. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99187. FLAC__StreamDecoderErrorCallback error_callback,
  99188. void *client_data,
  99189. FLAC__bool is_ogg
  99190. )
  99191. {
  99192. FLAC__ASSERT(0 != decoder);
  99193. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99194. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99195. #if !FLAC__HAS_OGG
  99196. if(is_ogg)
  99197. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99198. #endif
  99199. if(
  99200. 0 == read_callback ||
  99201. 0 == write_callback ||
  99202. 0 == error_callback ||
  99203. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99204. )
  99205. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99206. #if FLAC__HAS_OGG
  99207. decoder->private_->is_ogg = is_ogg;
  99208. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99209. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99210. #endif
  99211. /*
  99212. * get the CPU info and set the function pointers
  99213. */
  99214. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99215. /* first default to the non-asm routines */
  99216. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99217. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99218. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99219. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99220. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99221. /* now override with asm where appropriate */
  99222. #ifndef FLAC__NO_ASM
  99223. if(decoder->private_->cpuinfo.use_asm) {
  99224. #ifdef FLAC__CPU_IA32
  99225. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99226. #ifdef FLAC__HAS_NASM
  99227. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99228. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99229. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99230. #endif
  99231. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99232. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99233. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99234. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99235. }
  99236. else {
  99237. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99238. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99239. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99240. }
  99241. #endif
  99242. #elif defined FLAC__CPU_PPC
  99243. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99244. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99245. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99246. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99247. }
  99248. #endif
  99249. }
  99250. #endif
  99251. /* from here on, errors are fatal */
  99252. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99253. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99254. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99255. }
  99256. decoder->private_->read_callback = read_callback;
  99257. decoder->private_->seek_callback = seek_callback;
  99258. decoder->private_->tell_callback = tell_callback;
  99259. decoder->private_->length_callback = length_callback;
  99260. decoder->private_->eof_callback = eof_callback;
  99261. decoder->private_->write_callback = write_callback;
  99262. decoder->private_->metadata_callback = metadata_callback;
  99263. decoder->private_->error_callback = error_callback;
  99264. decoder->private_->client_data = client_data;
  99265. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99266. decoder->private_->samples_decoded = 0;
  99267. decoder->private_->has_stream_info = false;
  99268. decoder->private_->cached = false;
  99269. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99270. decoder->private_->is_seeking = false;
  99271. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99272. if(!FLAC__stream_decoder_reset(decoder)) {
  99273. /* above call sets the state for us */
  99274. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99275. }
  99276. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99277. }
  99278. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99279. FLAC__StreamDecoder *decoder,
  99280. FLAC__StreamDecoderReadCallback read_callback,
  99281. FLAC__StreamDecoderSeekCallback seek_callback,
  99282. FLAC__StreamDecoderTellCallback tell_callback,
  99283. FLAC__StreamDecoderLengthCallback length_callback,
  99284. FLAC__StreamDecoderEofCallback eof_callback,
  99285. FLAC__StreamDecoderWriteCallback write_callback,
  99286. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99287. FLAC__StreamDecoderErrorCallback error_callback,
  99288. void *client_data
  99289. )
  99290. {
  99291. return init_stream_internal_dec(
  99292. decoder,
  99293. read_callback,
  99294. seek_callback,
  99295. tell_callback,
  99296. length_callback,
  99297. eof_callback,
  99298. write_callback,
  99299. metadata_callback,
  99300. error_callback,
  99301. client_data,
  99302. /*is_ogg=*/false
  99303. );
  99304. }
  99305. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99306. FLAC__StreamDecoder *decoder,
  99307. FLAC__StreamDecoderReadCallback read_callback,
  99308. FLAC__StreamDecoderSeekCallback seek_callback,
  99309. FLAC__StreamDecoderTellCallback tell_callback,
  99310. FLAC__StreamDecoderLengthCallback length_callback,
  99311. FLAC__StreamDecoderEofCallback eof_callback,
  99312. FLAC__StreamDecoderWriteCallback write_callback,
  99313. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99314. FLAC__StreamDecoderErrorCallback error_callback,
  99315. void *client_data
  99316. )
  99317. {
  99318. return init_stream_internal_dec(
  99319. decoder,
  99320. read_callback,
  99321. seek_callback,
  99322. tell_callback,
  99323. length_callback,
  99324. eof_callback,
  99325. write_callback,
  99326. metadata_callback,
  99327. error_callback,
  99328. client_data,
  99329. /*is_ogg=*/true
  99330. );
  99331. }
  99332. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99333. FLAC__StreamDecoder *decoder,
  99334. FILE *file,
  99335. FLAC__StreamDecoderWriteCallback write_callback,
  99336. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99337. FLAC__StreamDecoderErrorCallback error_callback,
  99338. void *client_data,
  99339. FLAC__bool is_ogg
  99340. )
  99341. {
  99342. FLAC__ASSERT(0 != decoder);
  99343. FLAC__ASSERT(0 != file);
  99344. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99345. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99346. if(0 == write_callback || 0 == error_callback)
  99347. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99348. /*
  99349. * To make sure that our file does not go unclosed after an error, we
  99350. * must assign the FILE pointer before any further error can occur in
  99351. * this routine.
  99352. */
  99353. if(file == stdin)
  99354. file = get_binary_stdin_(); /* just to be safe */
  99355. decoder->private_->file = file;
  99356. return init_stream_internal_dec(
  99357. decoder,
  99358. file_read_callback_dec,
  99359. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99360. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99361. decoder->private_->file == stdin? 0: file_length_callback_,
  99362. file_eof_callback_,
  99363. write_callback,
  99364. metadata_callback,
  99365. error_callback,
  99366. client_data,
  99367. is_ogg
  99368. );
  99369. }
  99370. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99371. FLAC__StreamDecoder *decoder,
  99372. FILE *file,
  99373. FLAC__StreamDecoderWriteCallback write_callback,
  99374. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99375. FLAC__StreamDecoderErrorCallback error_callback,
  99376. void *client_data
  99377. )
  99378. {
  99379. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99380. }
  99381. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99382. FLAC__StreamDecoder *decoder,
  99383. FILE *file,
  99384. FLAC__StreamDecoderWriteCallback write_callback,
  99385. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99386. FLAC__StreamDecoderErrorCallback error_callback,
  99387. void *client_data
  99388. )
  99389. {
  99390. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99391. }
  99392. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99393. FLAC__StreamDecoder *decoder,
  99394. const char *filename,
  99395. FLAC__StreamDecoderWriteCallback write_callback,
  99396. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99397. FLAC__StreamDecoderErrorCallback error_callback,
  99398. void *client_data,
  99399. FLAC__bool is_ogg
  99400. )
  99401. {
  99402. FILE *file;
  99403. FLAC__ASSERT(0 != decoder);
  99404. /*
  99405. * To make sure that our file does not go unclosed after an error, we
  99406. * have to do the same entrance checks here that are later performed
  99407. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99408. */
  99409. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99410. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99411. if(0 == write_callback || 0 == error_callback)
  99412. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99413. file = filename? fopen(filename, "rb") : stdin;
  99414. if(0 == file)
  99415. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99416. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99417. }
  99418. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99419. FLAC__StreamDecoder *decoder,
  99420. const char *filename,
  99421. FLAC__StreamDecoderWriteCallback write_callback,
  99422. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99423. FLAC__StreamDecoderErrorCallback error_callback,
  99424. void *client_data
  99425. )
  99426. {
  99427. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99428. }
  99429. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99430. FLAC__StreamDecoder *decoder,
  99431. const char *filename,
  99432. FLAC__StreamDecoderWriteCallback write_callback,
  99433. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99434. FLAC__StreamDecoderErrorCallback error_callback,
  99435. void *client_data
  99436. )
  99437. {
  99438. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99439. }
  99440. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99441. {
  99442. FLAC__bool md5_failed = false;
  99443. unsigned i;
  99444. FLAC__ASSERT(0 != decoder);
  99445. FLAC__ASSERT(0 != decoder->private_);
  99446. FLAC__ASSERT(0 != decoder->protected_);
  99447. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99448. return true;
  99449. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99450. * always call FLAC__MD5Final()
  99451. */
  99452. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99453. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99454. free(decoder->private_->seek_table.data.seek_table.points);
  99455. decoder->private_->seek_table.data.seek_table.points = 0;
  99456. decoder->private_->has_seek_table = false;
  99457. }
  99458. FLAC__bitreader_free(decoder->private_->input);
  99459. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99460. /* WATCHOUT:
  99461. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99462. * output arrays have a buffer of up to 3 zeroes in front
  99463. * (at negative indices) for alignment purposes; we use 4
  99464. * to keep the data well-aligned.
  99465. */
  99466. if(0 != decoder->private_->output[i]) {
  99467. free(decoder->private_->output[i]-4);
  99468. decoder->private_->output[i] = 0;
  99469. }
  99470. if(0 != decoder->private_->residual_unaligned[i]) {
  99471. free(decoder->private_->residual_unaligned[i]);
  99472. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99473. }
  99474. }
  99475. decoder->private_->output_capacity = 0;
  99476. decoder->private_->output_channels = 0;
  99477. #if FLAC__HAS_OGG
  99478. if(decoder->private_->is_ogg)
  99479. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99480. #endif
  99481. if(0 != decoder->private_->file) {
  99482. if(decoder->private_->file != stdin)
  99483. fclose(decoder->private_->file);
  99484. decoder->private_->file = 0;
  99485. }
  99486. if(decoder->private_->do_md5_checking) {
  99487. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99488. md5_failed = true;
  99489. }
  99490. decoder->private_->is_seeking = false;
  99491. set_defaults_dec(decoder);
  99492. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99493. return !md5_failed;
  99494. }
  99495. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99496. {
  99497. FLAC__ASSERT(0 != decoder);
  99498. FLAC__ASSERT(0 != decoder->private_);
  99499. FLAC__ASSERT(0 != decoder->protected_);
  99500. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99501. return false;
  99502. #if FLAC__HAS_OGG
  99503. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99504. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99505. return true;
  99506. #else
  99507. (void)value;
  99508. return false;
  99509. #endif
  99510. }
  99511. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99512. {
  99513. FLAC__ASSERT(0 != decoder);
  99514. FLAC__ASSERT(0 != decoder->protected_);
  99515. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99516. return false;
  99517. decoder->protected_->md5_checking = value;
  99518. return true;
  99519. }
  99520. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99521. {
  99522. FLAC__ASSERT(0 != decoder);
  99523. FLAC__ASSERT(0 != decoder->private_);
  99524. FLAC__ASSERT(0 != decoder->protected_);
  99525. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99526. /* double protection */
  99527. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99528. return false;
  99529. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99530. return false;
  99531. decoder->private_->metadata_filter[type] = true;
  99532. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99533. decoder->private_->metadata_filter_ids_count = 0;
  99534. return true;
  99535. }
  99536. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99537. {
  99538. FLAC__ASSERT(0 != decoder);
  99539. FLAC__ASSERT(0 != decoder->private_);
  99540. FLAC__ASSERT(0 != decoder->protected_);
  99541. FLAC__ASSERT(0 != id);
  99542. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99543. return false;
  99544. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99545. return true;
  99546. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99547. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99548. 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))) {
  99549. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99550. return false;
  99551. }
  99552. decoder->private_->metadata_filter_ids_capacity *= 2;
  99553. }
  99554. 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));
  99555. decoder->private_->metadata_filter_ids_count++;
  99556. return true;
  99557. }
  99558. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99559. {
  99560. unsigned i;
  99561. FLAC__ASSERT(0 != decoder);
  99562. FLAC__ASSERT(0 != decoder->private_);
  99563. FLAC__ASSERT(0 != decoder->protected_);
  99564. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99565. return false;
  99566. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99567. decoder->private_->metadata_filter[i] = true;
  99568. decoder->private_->metadata_filter_ids_count = 0;
  99569. return true;
  99570. }
  99571. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99572. {
  99573. FLAC__ASSERT(0 != decoder);
  99574. FLAC__ASSERT(0 != decoder->private_);
  99575. FLAC__ASSERT(0 != decoder->protected_);
  99576. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99577. /* double protection */
  99578. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99579. return false;
  99580. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99581. return false;
  99582. decoder->private_->metadata_filter[type] = false;
  99583. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99584. decoder->private_->metadata_filter_ids_count = 0;
  99585. return true;
  99586. }
  99587. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99588. {
  99589. FLAC__ASSERT(0 != decoder);
  99590. FLAC__ASSERT(0 != decoder->private_);
  99591. FLAC__ASSERT(0 != decoder->protected_);
  99592. FLAC__ASSERT(0 != id);
  99593. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99594. return false;
  99595. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99596. return true;
  99597. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99598. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99599. 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))) {
  99600. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99601. return false;
  99602. }
  99603. decoder->private_->metadata_filter_ids_capacity *= 2;
  99604. }
  99605. 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));
  99606. decoder->private_->metadata_filter_ids_count++;
  99607. return true;
  99608. }
  99609. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99610. {
  99611. FLAC__ASSERT(0 != decoder);
  99612. FLAC__ASSERT(0 != decoder->private_);
  99613. FLAC__ASSERT(0 != decoder->protected_);
  99614. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99615. return false;
  99616. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99617. decoder->private_->metadata_filter_ids_count = 0;
  99618. return true;
  99619. }
  99620. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99621. {
  99622. FLAC__ASSERT(0 != decoder);
  99623. FLAC__ASSERT(0 != decoder->protected_);
  99624. return decoder->protected_->state;
  99625. }
  99626. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99627. {
  99628. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99629. }
  99630. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99631. {
  99632. FLAC__ASSERT(0 != decoder);
  99633. FLAC__ASSERT(0 != decoder->protected_);
  99634. return decoder->protected_->md5_checking;
  99635. }
  99636. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99637. {
  99638. FLAC__ASSERT(0 != decoder);
  99639. FLAC__ASSERT(0 != decoder->protected_);
  99640. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99641. }
  99642. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99643. {
  99644. FLAC__ASSERT(0 != decoder);
  99645. FLAC__ASSERT(0 != decoder->protected_);
  99646. return decoder->protected_->channels;
  99647. }
  99648. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99649. {
  99650. FLAC__ASSERT(0 != decoder);
  99651. FLAC__ASSERT(0 != decoder->protected_);
  99652. return decoder->protected_->channel_assignment;
  99653. }
  99654. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99655. {
  99656. FLAC__ASSERT(0 != decoder);
  99657. FLAC__ASSERT(0 != decoder->protected_);
  99658. return decoder->protected_->bits_per_sample;
  99659. }
  99660. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99661. {
  99662. FLAC__ASSERT(0 != decoder);
  99663. FLAC__ASSERT(0 != decoder->protected_);
  99664. return decoder->protected_->sample_rate;
  99665. }
  99666. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99667. {
  99668. FLAC__ASSERT(0 != decoder);
  99669. FLAC__ASSERT(0 != decoder->protected_);
  99670. return decoder->protected_->blocksize;
  99671. }
  99672. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99673. {
  99674. FLAC__ASSERT(0 != decoder);
  99675. FLAC__ASSERT(0 != decoder->private_);
  99676. FLAC__ASSERT(0 != position);
  99677. #if FLAC__HAS_OGG
  99678. if(decoder->private_->is_ogg)
  99679. return false;
  99680. #endif
  99681. if(0 == decoder->private_->tell_callback)
  99682. return false;
  99683. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99684. return false;
  99685. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99686. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99687. return false;
  99688. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99689. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99690. return true;
  99691. }
  99692. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99693. {
  99694. FLAC__ASSERT(0 != decoder);
  99695. FLAC__ASSERT(0 != decoder->private_);
  99696. FLAC__ASSERT(0 != decoder->protected_);
  99697. decoder->private_->samples_decoded = 0;
  99698. decoder->private_->do_md5_checking = false;
  99699. #if FLAC__HAS_OGG
  99700. if(decoder->private_->is_ogg)
  99701. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99702. #endif
  99703. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99704. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99705. return false;
  99706. }
  99707. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99708. return true;
  99709. }
  99710. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99711. {
  99712. FLAC__ASSERT(0 != decoder);
  99713. FLAC__ASSERT(0 != decoder->private_);
  99714. FLAC__ASSERT(0 != decoder->protected_);
  99715. if(!FLAC__stream_decoder_flush(decoder)) {
  99716. /* above call sets the state for us */
  99717. return false;
  99718. }
  99719. #if FLAC__HAS_OGG
  99720. /*@@@ could go in !internal_reset_hack block below */
  99721. if(decoder->private_->is_ogg)
  99722. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99723. #endif
  99724. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99725. * (internal_reset_hack) don't try to rewind since we are already at
  99726. * the beginning of the stream and don't want to fail if the input is
  99727. * not seekable.
  99728. */
  99729. if(!decoder->private_->internal_reset_hack) {
  99730. if(decoder->private_->file == stdin)
  99731. return false; /* can't rewind stdin, reset fails */
  99732. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99733. return false; /* seekable and seek fails, reset fails */
  99734. }
  99735. else
  99736. decoder->private_->internal_reset_hack = false;
  99737. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99738. decoder->private_->has_stream_info = false;
  99739. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99740. free(decoder->private_->seek_table.data.seek_table.points);
  99741. decoder->private_->seek_table.data.seek_table.points = 0;
  99742. decoder->private_->has_seek_table = false;
  99743. }
  99744. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99745. /*
  99746. * This goes in reset() and not flush() because according to the spec, a
  99747. * fixed-blocksize stream must stay that way through the whole stream.
  99748. */
  99749. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99750. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99751. * is because md5 checking may be turned on to start and then turned off if
  99752. * a seek occurs. So we init the context here and finalize it in
  99753. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99754. * properly.
  99755. */
  99756. FLAC__MD5Init(&decoder->private_->md5context);
  99757. decoder->private_->first_frame_offset = 0;
  99758. decoder->private_->unparseable_frame_count = 0;
  99759. return true;
  99760. }
  99761. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99762. {
  99763. FLAC__bool got_a_frame;
  99764. FLAC__ASSERT(0 != decoder);
  99765. FLAC__ASSERT(0 != decoder->protected_);
  99766. while(1) {
  99767. switch(decoder->protected_->state) {
  99768. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99769. if(!find_metadata_(decoder))
  99770. return false; /* above function sets the status for us */
  99771. break;
  99772. case FLAC__STREAM_DECODER_READ_METADATA:
  99773. if(!read_metadata_(decoder))
  99774. return false; /* above function sets the status for us */
  99775. else
  99776. return true;
  99777. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99778. if(!frame_sync_(decoder))
  99779. return true; /* above function sets the status for us */
  99780. break;
  99781. case FLAC__STREAM_DECODER_READ_FRAME:
  99782. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99783. return false; /* above function sets the status for us */
  99784. if(got_a_frame)
  99785. return true; /* above function sets the status for us */
  99786. break;
  99787. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99788. case FLAC__STREAM_DECODER_ABORTED:
  99789. return true;
  99790. default:
  99791. FLAC__ASSERT(0);
  99792. return false;
  99793. }
  99794. }
  99795. }
  99796. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99797. {
  99798. FLAC__ASSERT(0 != decoder);
  99799. FLAC__ASSERT(0 != decoder->protected_);
  99800. while(1) {
  99801. switch(decoder->protected_->state) {
  99802. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99803. if(!find_metadata_(decoder))
  99804. return false; /* above function sets the status for us */
  99805. break;
  99806. case FLAC__STREAM_DECODER_READ_METADATA:
  99807. if(!read_metadata_(decoder))
  99808. return false; /* above function sets the status for us */
  99809. break;
  99810. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99811. case FLAC__STREAM_DECODER_READ_FRAME:
  99812. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99813. case FLAC__STREAM_DECODER_ABORTED:
  99814. return true;
  99815. default:
  99816. FLAC__ASSERT(0);
  99817. return false;
  99818. }
  99819. }
  99820. }
  99821. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99822. {
  99823. FLAC__bool dummy;
  99824. FLAC__ASSERT(0 != decoder);
  99825. FLAC__ASSERT(0 != decoder->protected_);
  99826. while(1) {
  99827. switch(decoder->protected_->state) {
  99828. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99829. if(!find_metadata_(decoder))
  99830. return false; /* above function sets the status for us */
  99831. break;
  99832. case FLAC__STREAM_DECODER_READ_METADATA:
  99833. if(!read_metadata_(decoder))
  99834. return false; /* above function sets the status for us */
  99835. break;
  99836. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99837. if(!frame_sync_(decoder))
  99838. return true; /* above function sets the status for us */
  99839. break;
  99840. case FLAC__STREAM_DECODER_READ_FRAME:
  99841. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99842. return false; /* above function sets the status for us */
  99843. break;
  99844. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99845. case FLAC__STREAM_DECODER_ABORTED:
  99846. return true;
  99847. default:
  99848. FLAC__ASSERT(0);
  99849. return false;
  99850. }
  99851. }
  99852. }
  99853. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99854. {
  99855. FLAC__bool got_a_frame;
  99856. FLAC__ASSERT(0 != decoder);
  99857. FLAC__ASSERT(0 != decoder->protected_);
  99858. while(1) {
  99859. switch(decoder->protected_->state) {
  99860. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99861. case FLAC__STREAM_DECODER_READ_METADATA:
  99862. return false; /* above function sets the status for us */
  99863. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99864. if(!frame_sync_(decoder))
  99865. return true; /* above function sets the status for us */
  99866. break;
  99867. case FLAC__STREAM_DECODER_READ_FRAME:
  99868. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99869. return false; /* above function sets the status for us */
  99870. if(got_a_frame)
  99871. return true; /* above function sets the status for us */
  99872. break;
  99873. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99874. case FLAC__STREAM_DECODER_ABORTED:
  99875. return true;
  99876. default:
  99877. FLAC__ASSERT(0);
  99878. return false;
  99879. }
  99880. }
  99881. }
  99882. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99883. {
  99884. FLAC__uint64 length;
  99885. FLAC__ASSERT(0 != decoder);
  99886. if(
  99887. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99888. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99889. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99890. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99891. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99892. )
  99893. return false;
  99894. if(0 == decoder->private_->seek_callback)
  99895. return false;
  99896. FLAC__ASSERT(decoder->private_->seek_callback);
  99897. FLAC__ASSERT(decoder->private_->tell_callback);
  99898. FLAC__ASSERT(decoder->private_->length_callback);
  99899. FLAC__ASSERT(decoder->private_->eof_callback);
  99900. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99901. return false;
  99902. decoder->private_->is_seeking = true;
  99903. /* turn off md5 checking if a seek is attempted */
  99904. decoder->private_->do_md5_checking = false;
  99905. /* 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) */
  99906. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99907. decoder->private_->is_seeking = false;
  99908. return false;
  99909. }
  99910. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99911. if(
  99912. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99913. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99914. ) {
  99915. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99916. /* above call sets the state for us */
  99917. decoder->private_->is_seeking = false;
  99918. return false;
  99919. }
  99920. /* check this again in case we didn't know total_samples the first time */
  99921. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99922. decoder->private_->is_seeking = false;
  99923. return false;
  99924. }
  99925. }
  99926. {
  99927. const FLAC__bool ok =
  99928. #if FLAC__HAS_OGG
  99929. decoder->private_->is_ogg?
  99930. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99931. #endif
  99932. seek_to_absolute_sample_(decoder, length, sample)
  99933. ;
  99934. decoder->private_->is_seeking = false;
  99935. return ok;
  99936. }
  99937. }
  99938. /***********************************************************************
  99939. *
  99940. * Protected class methods
  99941. *
  99942. ***********************************************************************/
  99943. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99944. {
  99945. FLAC__ASSERT(0 != decoder);
  99946. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99947. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99948. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99949. }
  99950. /***********************************************************************
  99951. *
  99952. * Private class methods
  99953. *
  99954. ***********************************************************************/
  99955. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99956. {
  99957. #if FLAC__HAS_OGG
  99958. decoder->private_->is_ogg = false;
  99959. #endif
  99960. decoder->private_->read_callback = 0;
  99961. decoder->private_->seek_callback = 0;
  99962. decoder->private_->tell_callback = 0;
  99963. decoder->private_->length_callback = 0;
  99964. decoder->private_->eof_callback = 0;
  99965. decoder->private_->write_callback = 0;
  99966. decoder->private_->metadata_callback = 0;
  99967. decoder->private_->error_callback = 0;
  99968. decoder->private_->client_data = 0;
  99969. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99970. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99971. decoder->private_->metadata_filter_ids_count = 0;
  99972. decoder->protected_->md5_checking = false;
  99973. #if FLAC__HAS_OGG
  99974. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99975. #endif
  99976. }
  99977. /*
  99978. * This will forcibly set stdin to binary mode (for OSes that require it)
  99979. */
  99980. FILE *get_binary_stdin_(void)
  99981. {
  99982. /* if something breaks here it is probably due to the presence or
  99983. * absence of an underscore before the identifiers 'setmode',
  99984. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99985. */
  99986. #if defined _MSC_VER || defined __MINGW32__
  99987. _setmode(_fileno(stdin), _O_BINARY);
  99988. #elif defined __CYGWIN__
  99989. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99990. setmode(_fileno(stdin), _O_BINARY);
  99991. #elif defined __EMX__
  99992. setmode(fileno(stdin), O_BINARY);
  99993. #endif
  99994. return stdin;
  99995. }
  99996. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99997. {
  99998. unsigned i;
  99999. FLAC__int32 *tmp;
  100000. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100001. return true;
  100002. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100003. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100004. if(0 != decoder->private_->output[i]) {
  100005. free(decoder->private_->output[i]-4);
  100006. decoder->private_->output[i] = 0;
  100007. }
  100008. if(0 != decoder->private_->residual_unaligned[i]) {
  100009. free(decoder->private_->residual_unaligned[i]);
  100010. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100011. }
  100012. }
  100013. for(i = 0; i < channels; i++) {
  100014. /* WATCHOUT:
  100015. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100016. * output arrays have a buffer of up to 3 zeroes in front
  100017. * (at negative indices) for alignment purposes; we use 4
  100018. * to keep the data well-aligned.
  100019. */
  100020. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100021. if(tmp == 0) {
  100022. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100023. return false;
  100024. }
  100025. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100026. decoder->private_->output[i] = tmp + 4;
  100027. /* WATCHOUT:
  100028. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100029. */
  100030. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100031. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100032. return false;
  100033. }
  100034. }
  100035. decoder->private_->output_capacity = size;
  100036. decoder->private_->output_channels = channels;
  100037. return true;
  100038. }
  100039. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100040. {
  100041. size_t i;
  100042. FLAC__ASSERT(0 != decoder);
  100043. FLAC__ASSERT(0 != decoder->private_);
  100044. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100045. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100046. return true;
  100047. return false;
  100048. }
  100049. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100050. {
  100051. FLAC__uint32 x;
  100052. unsigned i, id_;
  100053. FLAC__bool first = true;
  100054. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100055. for(i = id_ = 0; i < 4; ) {
  100056. if(decoder->private_->cached) {
  100057. x = (FLAC__uint32)decoder->private_->lookahead;
  100058. decoder->private_->cached = false;
  100059. }
  100060. else {
  100061. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100062. return false; /* read_callback_ sets the state for us */
  100063. }
  100064. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100065. first = true;
  100066. i++;
  100067. id_ = 0;
  100068. continue;
  100069. }
  100070. if(x == ID3V2_TAG_[id_]) {
  100071. id_++;
  100072. i = 0;
  100073. if(id_ == 3) {
  100074. if(!skip_id3v2_tag_(decoder))
  100075. return false; /* skip_id3v2_tag_ sets the state for us */
  100076. }
  100077. continue;
  100078. }
  100079. id_ = 0;
  100080. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100081. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100082. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100083. return false; /* read_callback_ sets the state for us */
  100084. /* 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 */
  100085. /* else we have to check if the second byte is the end of a sync code */
  100086. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100087. decoder->private_->lookahead = (FLAC__byte)x;
  100088. decoder->private_->cached = true;
  100089. }
  100090. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100091. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100092. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100093. return true;
  100094. }
  100095. }
  100096. i = 0;
  100097. if(first) {
  100098. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100099. first = false;
  100100. }
  100101. }
  100102. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100103. return true;
  100104. }
  100105. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100106. {
  100107. FLAC__bool is_last;
  100108. FLAC__uint32 i, x, type, length;
  100109. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100110. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100111. return false; /* read_callback_ sets the state for us */
  100112. is_last = x? true : false;
  100113. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100114. return false; /* read_callback_ sets the state for us */
  100115. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100116. return false; /* read_callback_ sets the state for us */
  100117. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100118. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100119. return false;
  100120. decoder->private_->has_stream_info = true;
  100121. 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))
  100122. decoder->private_->do_md5_checking = false;
  100123. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100124. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100125. }
  100126. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100127. if(!read_metadata_seektable_(decoder, is_last, length))
  100128. return false;
  100129. decoder->private_->has_seek_table = true;
  100130. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100131. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100132. }
  100133. else {
  100134. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100135. unsigned real_length = length;
  100136. FLAC__StreamMetadata block;
  100137. block.is_last = is_last;
  100138. block.type = (FLAC__MetadataType)type;
  100139. block.length = length;
  100140. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100141. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100142. return false; /* read_callback_ sets the state for us */
  100143. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100144. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100145. return false;
  100146. }
  100147. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100148. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100149. skip_it = !skip_it;
  100150. }
  100151. if(skip_it) {
  100152. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100153. return false; /* read_callback_ sets the state for us */
  100154. }
  100155. else {
  100156. switch(type) {
  100157. case FLAC__METADATA_TYPE_PADDING:
  100158. /* skip the padding bytes */
  100159. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100160. return false; /* read_callback_ sets the state for us */
  100161. break;
  100162. case FLAC__METADATA_TYPE_APPLICATION:
  100163. /* remember, we read the ID already */
  100164. if(real_length > 0) {
  100165. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100166. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100167. return false;
  100168. }
  100169. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100170. return false; /* read_callback_ sets the state for us */
  100171. }
  100172. else
  100173. block.data.application.data = 0;
  100174. break;
  100175. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100176. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100177. return false;
  100178. break;
  100179. case FLAC__METADATA_TYPE_CUESHEET:
  100180. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100181. return false;
  100182. break;
  100183. case FLAC__METADATA_TYPE_PICTURE:
  100184. if(!read_metadata_picture_(decoder, &block.data.picture))
  100185. return false;
  100186. break;
  100187. case FLAC__METADATA_TYPE_STREAMINFO:
  100188. case FLAC__METADATA_TYPE_SEEKTABLE:
  100189. FLAC__ASSERT(0);
  100190. break;
  100191. default:
  100192. if(real_length > 0) {
  100193. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100194. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100195. return false;
  100196. }
  100197. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100198. return false; /* read_callback_ sets the state for us */
  100199. }
  100200. else
  100201. block.data.unknown.data = 0;
  100202. break;
  100203. }
  100204. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100205. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100206. /* now we have to free any malloc()ed data in the block */
  100207. switch(type) {
  100208. case FLAC__METADATA_TYPE_PADDING:
  100209. break;
  100210. case FLAC__METADATA_TYPE_APPLICATION:
  100211. if(0 != block.data.application.data)
  100212. free(block.data.application.data);
  100213. break;
  100214. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100215. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100216. free(block.data.vorbis_comment.vendor_string.entry);
  100217. if(block.data.vorbis_comment.num_comments > 0)
  100218. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100219. if(0 != block.data.vorbis_comment.comments[i].entry)
  100220. free(block.data.vorbis_comment.comments[i].entry);
  100221. if(0 != block.data.vorbis_comment.comments)
  100222. free(block.data.vorbis_comment.comments);
  100223. break;
  100224. case FLAC__METADATA_TYPE_CUESHEET:
  100225. if(block.data.cue_sheet.num_tracks > 0)
  100226. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100227. if(0 != block.data.cue_sheet.tracks[i].indices)
  100228. free(block.data.cue_sheet.tracks[i].indices);
  100229. if(0 != block.data.cue_sheet.tracks)
  100230. free(block.data.cue_sheet.tracks);
  100231. break;
  100232. case FLAC__METADATA_TYPE_PICTURE:
  100233. if(0 != block.data.picture.mime_type)
  100234. free(block.data.picture.mime_type);
  100235. if(0 != block.data.picture.description)
  100236. free(block.data.picture.description);
  100237. if(0 != block.data.picture.data)
  100238. free(block.data.picture.data);
  100239. break;
  100240. case FLAC__METADATA_TYPE_STREAMINFO:
  100241. case FLAC__METADATA_TYPE_SEEKTABLE:
  100242. FLAC__ASSERT(0);
  100243. default:
  100244. if(0 != block.data.unknown.data)
  100245. free(block.data.unknown.data);
  100246. break;
  100247. }
  100248. }
  100249. }
  100250. if(is_last) {
  100251. /* if this fails, it's OK, it's just a hint for the seek routine */
  100252. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100253. decoder->private_->first_frame_offset = 0;
  100254. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100255. }
  100256. return true;
  100257. }
  100258. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100259. {
  100260. FLAC__uint32 x;
  100261. unsigned bits, used_bits = 0;
  100262. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100263. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100264. decoder->private_->stream_info.is_last = is_last;
  100265. decoder->private_->stream_info.length = length;
  100266. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100267. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100268. return false; /* read_callback_ sets the state for us */
  100269. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100270. used_bits += bits;
  100271. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100272. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100273. return false; /* read_callback_ sets the state for us */
  100274. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100275. used_bits += bits;
  100276. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100277. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100278. return false; /* read_callback_ sets the state for us */
  100279. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100280. used_bits += bits;
  100281. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100282. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100283. return false; /* read_callback_ sets the state for us */
  100284. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100285. used_bits += bits;
  100286. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100287. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100288. return false; /* read_callback_ sets the state for us */
  100289. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100290. used_bits += bits;
  100291. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100292. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100293. return false; /* read_callback_ sets the state for us */
  100294. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100295. used_bits += bits;
  100296. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100297. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100298. return false; /* read_callback_ sets the state for us */
  100299. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100300. used_bits += bits;
  100301. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100302. 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))
  100303. return false; /* read_callback_ sets the state for us */
  100304. used_bits += bits;
  100305. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100306. return false; /* read_callback_ sets the state for us */
  100307. used_bits += 16*8;
  100308. /* skip the rest of the block */
  100309. FLAC__ASSERT(used_bits % 8 == 0);
  100310. length -= (used_bits / 8);
  100311. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100312. return false; /* read_callback_ sets the state for us */
  100313. return true;
  100314. }
  100315. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100316. {
  100317. FLAC__uint32 i, x;
  100318. FLAC__uint64 xx;
  100319. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100320. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100321. decoder->private_->seek_table.is_last = is_last;
  100322. decoder->private_->seek_table.length = length;
  100323. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100324. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100325. 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)))) {
  100326. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100327. return false;
  100328. }
  100329. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100330. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100331. return false; /* read_callback_ sets the state for us */
  100332. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100333. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100334. return false; /* read_callback_ sets the state for us */
  100335. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100336. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100337. return false; /* read_callback_ sets the state for us */
  100338. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100339. }
  100340. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100341. /* if there is a partial point left, skip over it */
  100342. if(length > 0) {
  100343. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100344. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100345. return false; /* read_callback_ sets the state for us */
  100346. }
  100347. return true;
  100348. }
  100349. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100350. {
  100351. FLAC__uint32 i;
  100352. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100353. /* read vendor string */
  100354. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100355. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100356. return false; /* read_callback_ sets the state for us */
  100357. if(obj->vendor_string.length > 0) {
  100358. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100359. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100360. return false;
  100361. }
  100362. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100363. return false; /* read_callback_ sets the state for us */
  100364. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100365. }
  100366. else
  100367. obj->vendor_string.entry = 0;
  100368. /* read num comments */
  100369. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100370. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100371. return false; /* read_callback_ sets the state for us */
  100372. /* read comments */
  100373. if(obj->num_comments > 0) {
  100374. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100375. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100376. return false;
  100377. }
  100378. for(i = 0; i < obj->num_comments; i++) {
  100379. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100380. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100381. return false; /* read_callback_ sets the state for us */
  100382. if(obj->comments[i].length > 0) {
  100383. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100384. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100385. return false;
  100386. }
  100387. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100388. return false; /* read_callback_ sets the state for us */
  100389. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100390. }
  100391. else
  100392. obj->comments[i].entry = 0;
  100393. }
  100394. }
  100395. else {
  100396. obj->comments = 0;
  100397. }
  100398. return true;
  100399. }
  100400. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100401. {
  100402. FLAC__uint32 i, j, x;
  100403. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100404. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100405. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100406. 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))
  100407. return false; /* read_callback_ sets the state for us */
  100408. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100409. return false; /* read_callback_ sets the state for us */
  100410. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100411. return false; /* read_callback_ sets the state for us */
  100412. obj->is_cd = x? true : false;
  100413. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100414. return false; /* read_callback_ sets the state for us */
  100415. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100416. return false; /* read_callback_ sets the state for us */
  100417. obj->num_tracks = x;
  100418. if(obj->num_tracks > 0) {
  100419. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100420. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100421. return false;
  100422. }
  100423. for(i = 0; i < obj->num_tracks; i++) {
  100424. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100425. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100426. return false; /* read_callback_ sets the state for us */
  100427. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100428. return false; /* read_callback_ sets the state for us */
  100429. track->number = (FLAC__byte)x;
  100430. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100431. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100432. return false; /* read_callback_ sets the state for us */
  100433. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100434. return false; /* read_callback_ sets the state for us */
  100435. track->type = x;
  100436. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100437. return false; /* read_callback_ sets the state for us */
  100438. track->pre_emphasis = x;
  100439. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100440. return false; /* read_callback_ sets the state for us */
  100441. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100442. return false; /* read_callback_ sets the state for us */
  100443. track->num_indices = (FLAC__byte)x;
  100444. if(track->num_indices > 0) {
  100445. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100446. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100447. return false;
  100448. }
  100449. for(j = 0; j < track->num_indices; j++) {
  100450. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100451. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100452. return false; /* read_callback_ sets the state for us */
  100453. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100454. return false; /* read_callback_ sets the state for us */
  100455. index->number = (FLAC__byte)x;
  100456. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100457. return false; /* read_callback_ sets the state for us */
  100458. }
  100459. }
  100460. }
  100461. }
  100462. return true;
  100463. }
  100464. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100465. {
  100466. FLAC__uint32 x;
  100467. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100468. /* read type */
  100469. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100470. return false; /* read_callback_ sets the state for us */
  100471. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100472. /* read MIME type */
  100473. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100474. return false; /* read_callback_ sets the state for us */
  100475. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100476. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100477. return false;
  100478. }
  100479. if(x > 0) {
  100480. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100481. return false; /* read_callback_ sets the state for us */
  100482. }
  100483. obj->mime_type[x] = '\0';
  100484. /* read description */
  100485. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100486. return false; /* read_callback_ sets the state for us */
  100487. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100488. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100489. return false;
  100490. }
  100491. if(x > 0) {
  100492. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100493. return false; /* read_callback_ sets the state for us */
  100494. }
  100495. obj->description[x] = '\0';
  100496. /* read width */
  100497. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100498. return false; /* read_callback_ sets the state for us */
  100499. /* read height */
  100500. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100501. return false; /* read_callback_ sets the state for us */
  100502. /* read depth */
  100503. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100504. return false; /* read_callback_ sets the state for us */
  100505. /* read colors */
  100506. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100507. return false; /* read_callback_ sets the state for us */
  100508. /* read data */
  100509. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100510. return false; /* read_callback_ sets the state for us */
  100511. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100512. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100513. return false;
  100514. }
  100515. if(obj->data_length > 0) {
  100516. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100517. return false; /* read_callback_ sets the state for us */
  100518. }
  100519. return true;
  100520. }
  100521. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100522. {
  100523. FLAC__uint32 x;
  100524. unsigned i, skip;
  100525. /* skip the version and flags bytes */
  100526. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100527. return false; /* read_callback_ sets the state for us */
  100528. /* get the size (in bytes) to skip */
  100529. skip = 0;
  100530. for(i = 0; i < 4; i++) {
  100531. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100532. return false; /* read_callback_ sets the state for us */
  100533. skip <<= 7;
  100534. skip |= (x & 0x7f);
  100535. }
  100536. /* skip the rest of the tag */
  100537. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100538. return false; /* read_callback_ sets the state for us */
  100539. return true;
  100540. }
  100541. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100542. {
  100543. FLAC__uint32 x;
  100544. FLAC__bool first = true;
  100545. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100546. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100547. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100548. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100549. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100550. return true;
  100551. }
  100552. }
  100553. /* make sure we're byte aligned */
  100554. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100555. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100556. return false; /* read_callback_ sets the state for us */
  100557. }
  100558. while(1) {
  100559. if(decoder->private_->cached) {
  100560. x = (FLAC__uint32)decoder->private_->lookahead;
  100561. decoder->private_->cached = false;
  100562. }
  100563. else {
  100564. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100565. return false; /* read_callback_ sets the state for us */
  100566. }
  100567. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100568. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100569. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100570. return false; /* read_callback_ sets the state for us */
  100571. /* 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 */
  100572. /* else we have to check if the second byte is the end of a sync code */
  100573. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100574. decoder->private_->lookahead = (FLAC__byte)x;
  100575. decoder->private_->cached = true;
  100576. }
  100577. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100578. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100579. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100580. return true;
  100581. }
  100582. }
  100583. if(first) {
  100584. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100585. first = false;
  100586. }
  100587. }
  100588. return true;
  100589. }
  100590. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100591. {
  100592. unsigned channel;
  100593. unsigned i;
  100594. FLAC__int32 mid, side;
  100595. unsigned frame_crc; /* the one we calculate from the input stream */
  100596. FLAC__uint32 x;
  100597. *got_a_frame = false;
  100598. /* init the CRC */
  100599. frame_crc = 0;
  100600. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100601. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100602. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100603. if(!read_frame_header_(decoder))
  100604. return false;
  100605. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100606. return true;
  100607. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100608. return false;
  100609. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100610. /*
  100611. * first figure the correct bits-per-sample of the subframe
  100612. */
  100613. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100614. switch(decoder->private_->frame.header.channel_assignment) {
  100615. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100616. /* no adjustment needed */
  100617. break;
  100618. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100619. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100620. if(channel == 1)
  100621. bps++;
  100622. break;
  100623. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100624. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100625. if(channel == 0)
  100626. bps++;
  100627. break;
  100628. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100629. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100630. if(channel == 1)
  100631. bps++;
  100632. break;
  100633. default:
  100634. FLAC__ASSERT(0);
  100635. }
  100636. /*
  100637. * now read it
  100638. */
  100639. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100640. return false;
  100641. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100642. return true;
  100643. }
  100644. if(!read_zero_padding_(decoder))
  100645. return false;
  100646. 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) */
  100647. return true;
  100648. /*
  100649. * Read the frame CRC-16 from the footer and check
  100650. */
  100651. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100652. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100653. return false; /* read_callback_ sets the state for us */
  100654. if(frame_crc == x) {
  100655. if(do_full_decode) {
  100656. /* Undo any special channel coding */
  100657. switch(decoder->private_->frame.header.channel_assignment) {
  100658. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100659. /* do nothing */
  100660. break;
  100661. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100662. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100663. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100664. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100665. break;
  100666. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100667. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100668. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100669. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100670. break;
  100671. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100672. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100673. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100674. #if 1
  100675. mid = decoder->private_->output[0][i];
  100676. side = decoder->private_->output[1][i];
  100677. mid <<= 1;
  100678. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100679. decoder->private_->output[0][i] = (mid + side) >> 1;
  100680. decoder->private_->output[1][i] = (mid - side) >> 1;
  100681. #else
  100682. /* OPT: without 'side' temp variable */
  100683. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100684. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100685. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100686. #endif
  100687. }
  100688. break;
  100689. default:
  100690. FLAC__ASSERT(0);
  100691. break;
  100692. }
  100693. }
  100694. }
  100695. else {
  100696. /* Bad frame, emit error and zero the output signal */
  100697. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100698. if(do_full_decode) {
  100699. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100700. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100701. }
  100702. }
  100703. }
  100704. *got_a_frame = true;
  100705. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100706. if(decoder->private_->next_fixed_block_size)
  100707. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100708. /* put the latest values into the public section of the decoder instance */
  100709. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100710. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100711. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100712. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100713. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100714. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100715. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100716. /* write it */
  100717. if(do_full_decode) {
  100718. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100719. return false;
  100720. }
  100721. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100722. return true;
  100723. }
  100724. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100725. {
  100726. FLAC__uint32 x;
  100727. FLAC__uint64 xx;
  100728. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100729. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100730. unsigned raw_header_len;
  100731. FLAC__bool is_unparseable = false;
  100732. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100733. /* init the raw header with the saved bits from synchronization */
  100734. raw_header[0] = decoder->private_->header_warmup[0];
  100735. raw_header[1] = decoder->private_->header_warmup[1];
  100736. raw_header_len = 2;
  100737. /* check to make sure that reserved bit is 0 */
  100738. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100739. is_unparseable = true;
  100740. /*
  100741. * Note that along the way as we read the header, we look for a sync
  100742. * code inside. If we find one it would indicate that our original
  100743. * sync was bad since there cannot be a sync code in a valid header.
  100744. *
  100745. * Three kinds of things can go wrong when reading the frame header:
  100746. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100747. * If we don't find a sync code, it can end up looking like we read
  100748. * a valid but unparseable header, until getting to the frame header
  100749. * CRC. Even then we could get a false positive on the CRC.
  100750. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100751. * future encoder).
  100752. * 3) We may be on a damaged frame which appears valid but unparseable.
  100753. *
  100754. * For all these reasons, we try and read a complete frame header as
  100755. * long as it seems valid, even if unparseable, up until the frame
  100756. * header CRC.
  100757. */
  100758. /*
  100759. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100760. */
  100761. for(i = 0; i < 2; i++) {
  100762. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100763. return false; /* read_callback_ sets the state for us */
  100764. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100765. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100766. decoder->private_->lookahead = (FLAC__byte)x;
  100767. decoder->private_->cached = true;
  100768. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100769. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100770. return true;
  100771. }
  100772. raw_header[raw_header_len++] = (FLAC__byte)x;
  100773. }
  100774. switch(x = raw_header[2] >> 4) {
  100775. case 0:
  100776. is_unparseable = true;
  100777. break;
  100778. case 1:
  100779. decoder->private_->frame.header.blocksize = 192;
  100780. break;
  100781. case 2:
  100782. case 3:
  100783. case 4:
  100784. case 5:
  100785. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100786. break;
  100787. case 6:
  100788. case 7:
  100789. blocksize_hint = x;
  100790. break;
  100791. case 8:
  100792. case 9:
  100793. case 10:
  100794. case 11:
  100795. case 12:
  100796. case 13:
  100797. case 14:
  100798. case 15:
  100799. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100800. break;
  100801. default:
  100802. FLAC__ASSERT(0);
  100803. break;
  100804. }
  100805. switch(x = raw_header[2] & 0x0f) {
  100806. case 0:
  100807. if(decoder->private_->has_stream_info)
  100808. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100809. else
  100810. is_unparseable = true;
  100811. break;
  100812. case 1:
  100813. decoder->private_->frame.header.sample_rate = 88200;
  100814. break;
  100815. case 2:
  100816. decoder->private_->frame.header.sample_rate = 176400;
  100817. break;
  100818. case 3:
  100819. decoder->private_->frame.header.sample_rate = 192000;
  100820. break;
  100821. case 4:
  100822. decoder->private_->frame.header.sample_rate = 8000;
  100823. break;
  100824. case 5:
  100825. decoder->private_->frame.header.sample_rate = 16000;
  100826. break;
  100827. case 6:
  100828. decoder->private_->frame.header.sample_rate = 22050;
  100829. break;
  100830. case 7:
  100831. decoder->private_->frame.header.sample_rate = 24000;
  100832. break;
  100833. case 8:
  100834. decoder->private_->frame.header.sample_rate = 32000;
  100835. break;
  100836. case 9:
  100837. decoder->private_->frame.header.sample_rate = 44100;
  100838. break;
  100839. case 10:
  100840. decoder->private_->frame.header.sample_rate = 48000;
  100841. break;
  100842. case 11:
  100843. decoder->private_->frame.header.sample_rate = 96000;
  100844. break;
  100845. case 12:
  100846. case 13:
  100847. case 14:
  100848. sample_rate_hint = x;
  100849. break;
  100850. case 15:
  100851. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100852. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100853. return true;
  100854. default:
  100855. FLAC__ASSERT(0);
  100856. }
  100857. x = (unsigned)(raw_header[3] >> 4);
  100858. if(x & 8) {
  100859. decoder->private_->frame.header.channels = 2;
  100860. switch(x & 7) {
  100861. case 0:
  100862. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100863. break;
  100864. case 1:
  100865. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100866. break;
  100867. case 2:
  100868. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100869. break;
  100870. default:
  100871. is_unparseable = true;
  100872. break;
  100873. }
  100874. }
  100875. else {
  100876. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100877. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100878. }
  100879. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100880. case 0:
  100881. if(decoder->private_->has_stream_info)
  100882. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100883. else
  100884. is_unparseable = true;
  100885. break;
  100886. case 1:
  100887. decoder->private_->frame.header.bits_per_sample = 8;
  100888. break;
  100889. case 2:
  100890. decoder->private_->frame.header.bits_per_sample = 12;
  100891. break;
  100892. case 4:
  100893. decoder->private_->frame.header.bits_per_sample = 16;
  100894. break;
  100895. case 5:
  100896. decoder->private_->frame.header.bits_per_sample = 20;
  100897. break;
  100898. case 6:
  100899. decoder->private_->frame.header.bits_per_sample = 24;
  100900. break;
  100901. case 3:
  100902. case 7:
  100903. is_unparseable = true;
  100904. break;
  100905. default:
  100906. FLAC__ASSERT(0);
  100907. break;
  100908. }
  100909. /* check to make sure that reserved bit is 0 */
  100910. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100911. is_unparseable = true;
  100912. /* read the frame's starting sample number (or frame number as the case may be) */
  100913. if(
  100914. raw_header[1] & 0x01 ||
  100915. /*@@@ 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 */
  100916. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100917. ) { /* variable blocksize */
  100918. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100919. return false; /* read_callback_ sets the state for us */
  100920. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100921. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100922. decoder->private_->cached = true;
  100923. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100924. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100925. return true;
  100926. }
  100927. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100928. decoder->private_->frame.header.number.sample_number = xx;
  100929. }
  100930. else { /* fixed blocksize */
  100931. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100932. return false; /* read_callback_ sets the state for us */
  100933. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100934. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100935. decoder->private_->cached = true;
  100936. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100937. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100938. return true;
  100939. }
  100940. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100941. decoder->private_->frame.header.number.frame_number = x;
  100942. }
  100943. if(blocksize_hint) {
  100944. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100945. return false; /* read_callback_ sets the state for us */
  100946. raw_header[raw_header_len++] = (FLAC__byte)x;
  100947. if(blocksize_hint == 7) {
  100948. FLAC__uint32 _x;
  100949. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100950. return false; /* read_callback_ sets the state for us */
  100951. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100952. x = (x << 8) | _x;
  100953. }
  100954. decoder->private_->frame.header.blocksize = x+1;
  100955. }
  100956. if(sample_rate_hint) {
  100957. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100958. return false; /* read_callback_ sets the state for us */
  100959. raw_header[raw_header_len++] = (FLAC__byte)x;
  100960. if(sample_rate_hint != 12) {
  100961. FLAC__uint32 _x;
  100962. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100963. return false; /* read_callback_ sets the state for us */
  100964. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100965. x = (x << 8) | _x;
  100966. }
  100967. if(sample_rate_hint == 12)
  100968. decoder->private_->frame.header.sample_rate = x*1000;
  100969. else if(sample_rate_hint == 13)
  100970. decoder->private_->frame.header.sample_rate = x;
  100971. else
  100972. decoder->private_->frame.header.sample_rate = x*10;
  100973. }
  100974. /* read the CRC-8 byte */
  100975. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100976. return false; /* read_callback_ sets the state for us */
  100977. crc8 = (FLAC__byte)x;
  100978. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100979. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100980. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100981. return true;
  100982. }
  100983. /* calculate the sample number from the frame number if needed */
  100984. decoder->private_->next_fixed_block_size = 0;
  100985. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100986. x = decoder->private_->frame.header.number.frame_number;
  100987. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100988. if(decoder->private_->fixed_block_size)
  100989. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100990. else if(decoder->private_->has_stream_info) {
  100991. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100992. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100993. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100994. }
  100995. else
  100996. is_unparseable = true;
  100997. }
  100998. else if(x == 0) {
  100999. decoder->private_->frame.header.number.sample_number = 0;
  101000. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101001. }
  101002. else {
  101003. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101004. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101005. }
  101006. }
  101007. if(is_unparseable) {
  101008. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101009. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101010. return true;
  101011. }
  101012. return true;
  101013. }
  101014. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101015. {
  101016. FLAC__uint32 x;
  101017. FLAC__bool wasted_bits;
  101018. unsigned i;
  101019. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101020. return false; /* read_callback_ sets the state for us */
  101021. wasted_bits = (x & 1);
  101022. x &= 0xfe;
  101023. if(wasted_bits) {
  101024. unsigned u;
  101025. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101026. return false; /* read_callback_ sets the state for us */
  101027. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101028. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101029. }
  101030. else
  101031. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101032. /*
  101033. * Lots of magic numbers here
  101034. */
  101035. if(x & 0x80) {
  101036. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101037. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101038. return true;
  101039. }
  101040. else if(x == 0) {
  101041. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101042. return false;
  101043. }
  101044. else if(x == 2) {
  101045. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101046. return false;
  101047. }
  101048. else if(x < 16) {
  101049. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101050. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101051. return true;
  101052. }
  101053. else if(x <= 24) {
  101054. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101055. return false;
  101056. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101057. return true;
  101058. }
  101059. else if(x < 64) {
  101060. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101061. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101062. return true;
  101063. }
  101064. else {
  101065. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101066. return false;
  101067. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101068. return true;
  101069. }
  101070. if(wasted_bits && do_full_decode) {
  101071. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101072. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101073. decoder->private_->output[channel][i] <<= x;
  101074. }
  101075. return true;
  101076. }
  101077. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101078. {
  101079. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101080. FLAC__int32 x;
  101081. unsigned i;
  101082. FLAC__int32 *output = decoder->private_->output[channel];
  101083. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101084. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101085. return false; /* read_callback_ sets the state for us */
  101086. subframe->value = x;
  101087. /* decode the subframe */
  101088. if(do_full_decode) {
  101089. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101090. output[i] = x;
  101091. }
  101092. return true;
  101093. }
  101094. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101095. {
  101096. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101097. FLAC__int32 i32;
  101098. FLAC__uint32 u32;
  101099. unsigned u;
  101100. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101101. subframe->residual = decoder->private_->residual[channel];
  101102. subframe->order = order;
  101103. /* read warm-up samples */
  101104. for(u = 0; u < order; u++) {
  101105. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101106. return false; /* read_callback_ sets the state for us */
  101107. subframe->warmup[u] = i32;
  101108. }
  101109. /* read entropy coding method info */
  101110. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101111. return false; /* read_callback_ sets the state for us */
  101112. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101113. switch(subframe->entropy_coding_method.type) {
  101114. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101115. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101116. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101117. return false; /* read_callback_ sets the state for us */
  101118. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101119. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101120. break;
  101121. default:
  101122. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101123. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101124. return true;
  101125. }
  101126. /* read residual */
  101127. switch(subframe->entropy_coding_method.type) {
  101128. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101129. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101130. 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))
  101131. return false;
  101132. break;
  101133. default:
  101134. FLAC__ASSERT(0);
  101135. }
  101136. /* decode the subframe */
  101137. if(do_full_decode) {
  101138. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101139. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101140. }
  101141. return true;
  101142. }
  101143. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101144. {
  101145. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101146. FLAC__int32 i32;
  101147. FLAC__uint32 u32;
  101148. unsigned u;
  101149. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101150. subframe->residual = decoder->private_->residual[channel];
  101151. subframe->order = order;
  101152. /* read warm-up samples */
  101153. for(u = 0; u < order; u++) {
  101154. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101155. return false; /* read_callback_ sets the state for us */
  101156. subframe->warmup[u] = i32;
  101157. }
  101158. /* read qlp coeff precision */
  101159. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101160. return false; /* read_callback_ sets the state for us */
  101161. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101162. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101163. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101164. return true;
  101165. }
  101166. subframe->qlp_coeff_precision = u32+1;
  101167. /* read qlp shift */
  101168. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101169. return false; /* read_callback_ sets the state for us */
  101170. subframe->quantization_level = i32;
  101171. /* read quantized lp coefficiencts */
  101172. for(u = 0; u < order; u++) {
  101173. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101174. return false; /* read_callback_ sets the state for us */
  101175. subframe->qlp_coeff[u] = i32;
  101176. }
  101177. /* read entropy coding method info */
  101178. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101179. return false; /* read_callback_ sets the state for us */
  101180. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101181. switch(subframe->entropy_coding_method.type) {
  101182. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101183. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101184. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101185. return false; /* read_callback_ sets the state for us */
  101186. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101187. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101188. break;
  101189. default:
  101190. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101191. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101192. return true;
  101193. }
  101194. /* read residual */
  101195. switch(subframe->entropy_coding_method.type) {
  101196. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101197. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101198. 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))
  101199. return false;
  101200. break;
  101201. default:
  101202. FLAC__ASSERT(0);
  101203. }
  101204. /* decode the subframe */
  101205. if(do_full_decode) {
  101206. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101207. /*@@@@@@ technically not pessimistic enough, should be more like
  101208. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101209. */
  101210. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101211. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101212. if(order <= 8)
  101213. 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);
  101214. else
  101215. 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);
  101216. }
  101217. else
  101218. 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);
  101219. else
  101220. 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);
  101221. }
  101222. return true;
  101223. }
  101224. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101225. {
  101226. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101227. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101228. unsigned i;
  101229. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101230. subframe->data = residual;
  101231. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101232. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101233. return false; /* read_callback_ sets the state for us */
  101234. residual[i] = x;
  101235. }
  101236. /* decode the subframe */
  101237. if(do_full_decode)
  101238. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101239. return true;
  101240. }
  101241. 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)
  101242. {
  101243. FLAC__uint32 rice_parameter;
  101244. int i;
  101245. unsigned partition, sample, u;
  101246. const unsigned partitions = 1u << partition_order;
  101247. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101248. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101249. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101250. /* sanity checks */
  101251. if(partition_order == 0) {
  101252. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101253. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101254. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101255. return true;
  101256. }
  101257. }
  101258. else {
  101259. if(partition_samples < predictor_order) {
  101260. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101261. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101262. return true;
  101263. }
  101264. }
  101265. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101266. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101267. return false;
  101268. }
  101269. sample = 0;
  101270. for(partition = 0; partition < partitions; partition++) {
  101271. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101272. return false; /* read_callback_ sets the state for us */
  101273. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101274. if(rice_parameter < pesc) {
  101275. partitioned_rice_contents->raw_bits[partition] = 0;
  101276. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101277. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101278. return false; /* read_callback_ sets the state for us */
  101279. sample += u;
  101280. }
  101281. else {
  101282. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101283. return false; /* read_callback_ sets the state for us */
  101284. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101285. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101286. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101287. return false; /* read_callback_ sets the state for us */
  101288. residual[sample] = i;
  101289. }
  101290. }
  101291. }
  101292. return true;
  101293. }
  101294. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101295. {
  101296. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101297. FLAC__uint32 zero = 0;
  101298. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101299. return false; /* read_callback_ sets the state for us */
  101300. if(zero != 0) {
  101301. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101302. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101303. }
  101304. }
  101305. return true;
  101306. }
  101307. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101308. {
  101309. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101310. if(
  101311. #if FLAC__HAS_OGG
  101312. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101313. !decoder->private_->is_ogg &&
  101314. #endif
  101315. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101316. ) {
  101317. *bytes = 0;
  101318. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101319. return false;
  101320. }
  101321. else if(*bytes > 0) {
  101322. /* While seeking, it is possible for our seek to land in the
  101323. * middle of audio data that looks exactly like a frame header
  101324. * from a future version of an encoder. When that happens, our
  101325. * error callback will get an
  101326. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101327. * unparseable_frame_count. But there is a remote possibility
  101328. * that it is properly synced at such a "future-codec frame",
  101329. * so to make sure, we wait to see many "unparseable" errors in
  101330. * a row before bailing out.
  101331. */
  101332. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101333. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101334. return false;
  101335. }
  101336. else {
  101337. const FLAC__StreamDecoderReadStatus status =
  101338. #if FLAC__HAS_OGG
  101339. decoder->private_->is_ogg?
  101340. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101341. #endif
  101342. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101343. ;
  101344. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101345. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101346. return false;
  101347. }
  101348. else if(*bytes == 0) {
  101349. if(
  101350. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101351. (
  101352. #if FLAC__HAS_OGG
  101353. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101354. !decoder->private_->is_ogg &&
  101355. #endif
  101356. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101357. )
  101358. ) {
  101359. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101360. return false;
  101361. }
  101362. else
  101363. return true;
  101364. }
  101365. else
  101366. return true;
  101367. }
  101368. }
  101369. else {
  101370. /* abort to avoid a deadlock */
  101371. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101372. return false;
  101373. }
  101374. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101375. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101376. * and at the same time hit the end of the stream (for example, seeking
  101377. * to a point that is after the beginning of the last Ogg page). There
  101378. * is no way to report an Ogg sync loss through the callbacks (see note
  101379. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101380. * So to keep the decoder from stopping at this point we gate the call
  101381. * to the eof_callback and let the Ogg decoder aspect set the
  101382. * end-of-stream state when it is needed.
  101383. */
  101384. }
  101385. #if FLAC__HAS_OGG
  101386. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101387. {
  101388. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101389. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101390. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101391. /* we don't really have a way to handle lost sync via read
  101392. * callback so we'll let it pass and let the underlying
  101393. * FLAC decoder catch the error
  101394. */
  101395. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101396. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101397. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101398. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101399. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101400. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101401. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101402. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101403. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101404. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101405. default:
  101406. FLAC__ASSERT(0);
  101407. /* double protection */
  101408. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101409. }
  101410. }
  101411. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101412. {
  101413. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101414. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101415. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101416. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101417. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101418. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101419. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101420. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101421. default:
  101422. /* double protection: */
  101423. FLAC__ASSERT(0);
  101424. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101425. }
  101426. }
  101427. #endif
  101428. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101429. {
  101430. if(decoder->private_->is_seeking) {
  101431. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101432. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101433. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101434. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101435. #if FLAC__HAS_OGG
  101436. decoder->private_->got_a_frame = true;
  101437. #endif
  101438. decoder->private_->last_frame = *frame; /* save the frame */
  101439. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101440. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101441. /* kick out of seek mode */
  101442. decoder->private_->is_seeking = false;
  101443. /* shift out the samples before target_sample */
  101444. if(delta > 0) {
  101445. unsigned channel;
  101446. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101447. for(channel = 0; channel < frame->header.channels; channel++)
  101448. newbuffer[channel] = buffer[channel] + delta;
  101449. decoder->private_->last_frame.header.blocksize -= delta;
  101450. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101451. /* write the relevant samples */
  101452. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101453. }
  101454. else {
  101455. /* write the relevant samples */
  101456. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101457. }
  101458. }
  101459. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101460. }
  101461. /*
  101462. * If we never got STREAMINFO, turn off MD5 checking to save
  101463. * cycles since we don't have a sum to compare to anyway
  101464. */
  101465. if(!decoder->private_->has_stream_info)
  101466. decoder->private_->do_md5_checking = false;
  101467. if(decoder->private_->do_md5_checking) {
  101468. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101469. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101470. }
  101471. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101472. }
  101473. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101474. {
  101475. if(!decoder->private_->is_seeking)
  101476. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101477. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101478. decoder->private_->unparseable_frame_count++;
  101479. }
  101480. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101481. {
  101482. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101483. FLAC__int64 pos = -1;
  101484. int i;
  101485. unsigned approx_bytes_per_frame;
  101486. FLAC__bool first_seek = true;
  101487. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101488. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101489. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101490. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101491. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101492. /* take these from the current frame in case they've changed mid-stream */
  101493. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101494. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101495. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101496. /* use values from stream info if we didn't decode a frame */
  101497. if(channels == 0)
  101498. channels = decoder->private_->stream_info.data.stream_info.channels;
  101499. if(bps == 0)
  101500. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101501. /* we are just guessing here */
  101502. if(max_framesize > 0)
  101503. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101504. /*
  101505. * Check if it's a known fixed-blocksize stream. Note that though
  101506. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101507. * never get a STREAMINFO block when decoding so the value of
  101508. * min_blocksize might be zero.
  101509. */
  101510. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101511. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101512. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101513. }
  101514. else
  101515. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101516. /*
  101517. * First, we set an upper and lower bound on where in the
  101518. * stream we will search. For now we assume the worst case
  101519. * scenario, which is our best guess at the beginning of
  101520. * the first frame and end of the stream.
  101521. */
  101522. lower_bound = first_frame_offset;
  101523. lower_bound_sample = 0;
  101524. upper_bound = stream_length;
  101525. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101526. /*
  101527. * Now we refine the bounds if we have a seektable with
  101528. * suitable points. Note that according to the spec they
  101529. * must be ordered by ascending sample number.
  101530. *
  101531. * Note: to protect against invalid seek tables we will ignore points
  101532. * that have frame_samples==0 or sample_number>=total_samples
  101533. */
  101534. if(seek_table) {
  101535. FLAC__uint64 new_lower_bound = lower_bound;
  101536. FLAC__uint64 new_upper_bound = upper_bound;
  101537. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101538. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101539. /* find the closest seek point <= target_sample, if it exists */
  101540. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101541. if(
  101542. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101543. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101544. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101545. seek_table->points[i].sample_number <= target_sample
  101546. )
  101547. break;
  101548. }
  101549. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101550. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101551. new_lower_bound_sample = seek_table->points[i].sample_number;
  101552. }
  101553. /* find the closest seek point > target_sample, if it exists */
  101554. for(i = 0; i < (int)seek_table->num_points; i++) {
  101555. if(
  101556. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101557. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101558. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101559. seek_table->points[i].sample_number > target_sample
  101560. )
  101561. break;
  101562. }
  101563. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101564. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101565. new_upper_bound_sample = seek_table->points[i].sample_number;
  101566. }
  101567. /* final protection against unsorted seek tables; keep original values if bogus */
  101568. if(new_upper_bound >= new_lower_bound) {
  101569. lower_bound = new_lower_bound;
  101570. upper_bound = new_upper_bound;
  101571. lower_bound_sample = new_lower_bound_sample;
  101572. upper_bound_sample = new_upper_bound_sample;
  101573. }
  101574. }
  101575. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101576. /* there are 2 insidious ways that the following equality occurs, which
  101577. * we need to fix:
  101578. * 1) total_samples is 0 (unknown) and target_sample is 0
  101579. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101580. * exactly equal to the last seek point in the seek table; this
  101581. * means there is no seek point above it, and upper_bound_samples
  101582. * remains equal to the estimate (of target_samples) we made above
  101583. * in either case it does not hurt to move upper_bound_sample up by 1
  101584. */
  101585. if(upper_bound_sample == lower_bound_sample)
  101586. upper_bound_sample++;
  101587. decoder->private_->target_sample = target_sample;
  101588. while(1) {
  101589. /* check if the bounds are still ok */
  101590. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101591. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101592. return false;
  101593. }
  101594. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101595. #if defined _MSC_VER || defined __MINGW32__
  101596. /* with VC++ you have to spoon feed it the casting */
  101597. 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;
  101598. #else
  101599. 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;
  101600. #endif
  101601. #else
  101602. /* a little less accurate: */
  101603. if(upper_bound - lower_bound < 0xffffffff)
  101604. 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;
  101605. else /* @@@ WATCHOUT, ~2TB limit */
  101606. 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;
  101607. #endif
  101608. if(pos >= (FLAC__int64)upper_bound)
  101609. pos = (FLAC__int64)upper_bound - 1;
  101610. if(pos < (FLAC__int64)lower_bound)
  101611. pos = (FLAC__int64)lower_bound;
  101612. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101613. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101614. return false;
  101615. }
  101616. if(!FLAC__stream_decoder_flush(decoder)) {
  101617. /* above call sets the state for us */
  101618. return false;
  101619. }
  101620. /* Now we need to get a frame. First we need to reset our
  101621. * unparseable_frame_count; if we get too many unparseable
  101622. * frames in a row, the read callback will return
  101623. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101624. * FLAC__stream_decoder_process_single() to return false.
  101625. */
  101626. decoder->private_->unparseable_frame_count = 0;
  101627. if(!FLAC__stream_decoder_process_single(decoder)) {
  101628. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101629. return false;
  101630. }
  101631. /* our write callback will change the state when it gets to the target frame */
  101632. /* 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 */
  101633. #if 0
  101634. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101635. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101636. break;
  101637. #endif
  101638. if(!decoder->private_->is_seeking)
  101639. break;
  101640. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101641. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101642. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101643. if (pos == (FLAC__int64)lower_bound) {
  101644. /* can't move back any more than the first frame, something is fatally wrong */
  101645. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101646. return false;
  101647. }
  101648. /* our last move backwards wasn't big enough, try again */
  101649. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101650. continue;
  101651. }
  101652. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101653. first_seek = false;
  101654. /* make sure we are not seeking in corrupted stream */
  101655. if (this_frame_sample < lower_bound_sample) {
  101656. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101657. return false;
  101658. }
  101659. /* we need to narrow the search */
  101660. if(target_sample < this_frame_sample) {
  101661. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101662. /*@@@@@@ what will decode position be if at end of stream? */
  101663. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101664. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101665. return false;
  101666. }
  101667. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101668. }
  101669. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101670. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101671. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101672. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101673. return false;
  101674. }
  101675. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101676. }
  101677. }
  101678. return true;
  101679. }
  101680. #if FLAC__HAS_OGG
  101681. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101682. {
  101683. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101684. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101685. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101686. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101687. FLAC__bool did_a_seek;
  101688. unsigned iteration = 0;
  101689. /* In the first iterations, we will calculate the target byte position
  101690. * by the distance from the target sample to left_sample and
  101691. * right_sample (let's call it "proportional search"). After that, we
  101692. * will switch to binary search.
  101693. */
  101694. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101695. /* We will switch to a linear search once our current sample is less
  101696. * than this number of samples ahead of the target sample
  101697. */
  101698. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101699. /* If the total number of samples is unknown, use a large value, and
  101700. * force binary search immediately.
  101701. */
  101702. if(right_sample == 0) {
  101703. right_sample = (FLAC__uint64)(-1);
  101704. BINARY_SEARCH_AFTER_ITERATION = 0;
  101705. }
  101706. decoder->private_->target_sample = target_sample;
  101707. for( ; ; iteration++) {
  101708. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101709. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101710. pos = (right_pos + left_pos) / 2;
  101711. }
  101712. else {
  101713. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101714. #if defined _MSC_VER || defined __MINGW32__
  101715. /* with MSVC you have to spoon feed it the casting */
  101716. 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));
  101717. #else
  101718. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101719. #endif
  101720. #else
  101721. /* a little less accurate: */
  101722. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101723. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101724. else /* @@@ WATCHOUT, ~2TB limit */
  101725. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101726. #endif
  101727. /* @@@ TODO: might want to limit pos to some distance
  101728. * before EOF, to make sure we land before the last frame,
  101729. * thereby getting a this_frame_sample and so having a better
  101730. * estimate.
  101731. */
  101732. }
  101733. /* physical seek */
  101734. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101735. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101736. return false;
  101737. }
  101738. if(!FLAC__stream_decoder_flush(decoder)) {
  101739. /* above call sets the state for us */
  101740. return false;
  101741. }
  101742. did_a_seek = true;
  101743. }
  101744. else
  101745. did_a_seek = false;
  101746. decoder->private_->got_a_frame = false;
  101747. if(!FLAC__stream_decoder_process_single(decoder)) {
  101748. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101749. return false;
  101750. }
  101751. if(!decoder->private_->got_a_frame) {
  101752. if(did_a_seek) {
  101753. /* this can happen if we seek to a point after the last frame; we drop
  101754. * to binary search right away in this case to avoid any wasted
  101755. * iterations of proportional search.
  101756. */
  101757. right_pos = pos;
  101758. BINARY_SEARCH_AFTER_ITERATION = 0;
  101759. }
  101760. else {
  101761. /* this can probably only happen if total_samples is unknown and the
  101762. * target_sample is past the end of the stream
  101763. */
  101764. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101765. return false;
  101766. }
  101767. }
  101768. /* our write callback will change the state when it gets to the target frame */
  101769. else if(!decoder->private_->is_seeking) {
  101770. break;
  101771. }
  101772. else {
  101773. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101774. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101775. if (did_a_seek) {
  101776. if (this_frame_sample <= target_sample) {
  101777. /* The 'equal' case should not happen, since
  101778. * FLAC__stream_decoder_process_single()
  101779. * should recognize that it has hit the
  101780. * target sample and we would exit through
  101781. * the 'break' above.
  101782. */
  101783. FLAC__ASSERT(this_frame_sample != target_sample);
  101784. left_sample = this_frame_sample;
  101785. /* sanity check to avoid infinite loop */
  101786. if (left_pos == pos) {
  101787. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101788. return false;
  101789. }
  101790. left_pos = pos;
  101791. }
  101792. else if(this_frame_sample > target_sample) {
  101793. right_sample = this_frame_sample;
  101794. /* sanity check to avoid infinite loop */
  101795. if (right_pos == pos) {
  101796. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101797. return false;
  101798. }
  101799. right_pos = pos;
  101800. }
  101801. }
  101802. }
  101803. }
  101804. return true;
  101805. }
  101806. #endif
  101807. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101808. {
  101809. (void)client_data;
  101810. if(*bytes > 0) {
  101811. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101812. if(ferror(decoder->private_->file))
  101813. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101814. else if(*bytes == 0)
  101815. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101816. else
  101817. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101818. }
  101819. else
  101820. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101821. }
  101822. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101823. {
  101824. (void)client_data;
  101825. if(decoder->private_->file == stdin)
  101826. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101827. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101828. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101829. else
  101830. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101831. }
  101832. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101833. {
  101834. off_t pos;
  101835. (void)client_data;
  101836. if(decoder->private_->file == stdin)
  101837. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101838. else if((pos = ftello(decoder->private_->file)) < 0)
  101839. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101840. else {
  101841. *absolute_byte_offset = (FLAC__uint64)pos;
  101842. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101843. }
  101844. }
  101845. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101846. {
  101847. struct stat filestats;
  101848. (void)client_data;
  101849. if(decoder->private_->file == stdin)
  101850. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101851. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101852. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101853. else {
  101854. *stream_length = (FLAC__uint64)filestats.st_size;
  101855. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101856. }
  101857. }
  101858. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101859. {
  101860. (void)client_data;
  101861. return feof(decoder->private_->file)? true : false;
  101862. }
  101863. #endif
  101864. /*** End of inlined file: stream_decoder.c ***/
  101865. /*** Start of inlined file: stream_encoder.c ***/
  101866. /*** Start of inlined file: juce_FlacHeader.h ***/
  101867. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101868. // tasks..
  101869. #define VERSION "1.2.1"
  101870. #define FLAC__NO_DLL 1
  101871. #if JUCE_MSVC
  101872. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101873. #endif
  101874. #if JUCE_MAC
  101875. #define FLAC__SYS_DARWIN 1
  101876. #endif
  101877. /*** End of inlined file: juce_FlacHeader.h ***/
  101878. #if JUCE_USE_FLAC
  101879. #if HAVE_CONFIG_H
  101880. # include <config.h>
  101881. #endif
  101882. #if defined _MSC_VER || defined __MINGW32__
  101883. #include <io.h> /* for _setmode() */
  101884. #include <fcntl.h> /* for _O_BINARY */
  101885. #endif
  101886. #if defined __CYGWIN__ || defined __EMX__
  101887. #include <io.h> /* for setmode(), O_BINARY */
  101888. #include <fcntl.h> /* for _O_BINARY */
  101889. #endif
  101890. #include <limits.h>
  101891. #include <stdio.h>
  101892. #include <stdlib.h> /* for malloc() */
  101893. #include <string.h> /* for memcpy() */
  101894. #include <sys/types.h> /* for off_t */
  101895. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101896. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101897. #define fseeko fseek
  101898. #define ftello ftell
  101899. #endif
  101900. #endif
  101901. /*** Start of inlined file: stream_encoder.h ***/
  101902. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101903. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101904. #if FLAC__HAS_OGG
  101905. #include "private/ogg_encoder_aspect.h"
  101906. #endif
  101907. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101908. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101909. typedef enum {
  101910. FLAC__APODIZATION_BARTLETT,
  101911. FLAC__APODIZATION_BARTLETT_HANN,
  101912. FLAC__APODIZATION_BLACKMAN,
  101913. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101914. FLAC__APODIZATION_CONNES,
  101915. FLAC__APODIZATION_FLATTOP,
  101916. FLAC__APODIZATION_GAUSS,
  101917. FLAC__APODIZATION_HAMMING,
  101918. FLAC__APODIZATION_HANN,
  101919. FLAC__APODIZATION_KAISER_BESSEL,
  101920. FLAC__APODIZATION_NUTTALL,
  101921. FLAC__APODIZATION_RECTANGLE,
  101922. FLAC__APODIZATION_TRIANGLE,
  101923. FLAC__APODIZATION_TUKEY,
  101924. FLAC__APODIZATION_WELCH
  101925. } FLAC__ApodizationFunction;
  101926. typedef struct {
  101927. FLAC__ApodizationFunction type;
  101928. union {
  101929. struct {
  101930. FLAC__real stddev;
  101931. } gauss;
  101932. struct {
  101933. FLAC__real p;
  101934. } tukey;
  101935. } parameters;
  101936. } FLAC__ApodizationSpecification;
  101937. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101938. typedef struct FLAC__StreamEncoderProtected {
  101939. FLAC__StreamEncoderState state;
  101940. FLAC__bool verify;
  101941. FLAC__bool streamable_subset;
  101942. FLAC__bool do_md5;
  101943. FLAC__bool do_mid_side_stereo;
  101944. FLAC__bool loose_mid_side_stereo;
  101945. unsigned channels;
  101946. unsigned bits_per_sample;
  101947. unsigned sample_rate;
  101948. unsigned blocksize;
  101949. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101950. unsigned num_apodizations;
  101951. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101952. #endif
  101953. unsigned max_lpc_order;
  101954. unsigned qlp_coeff_precision;
  101955. FLAC__bool do_qlp_coeff_prec_search;
  101956. FLAC__bool do_exhaustive_model_search;
  101957. FLAC__bool do_escape_coding;
  101958. unsigned min_residual_partition_order;
  101959. unsigned max_residual_partition_order;
  101960. unsigned rice_parameter_search_dist;
  101961. FLAC__uint64 total_samples_estimate;
  101962. FLAC__StreamMetadata **metadata;
  101963. unsigned num_metadata_blocks;
  101964. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101965. #if FLAC__HAS_OGG
  101966. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101967. #endif
  101968. } FLAC__StreamEncoderProtected;
  101969. #endif
  101970. /*** End of inlined file: stream_encoder.h ***/
  101971. #if FLAC__HAS_OGG
  101972. #include "include/private/ogg_helper.h"
  101973. #include "include/private/ogg_mapping.h"
  101974. #endif
  101975. /*** Start of inlined file: stream_encoder_framing.h ***/
  101976. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101977. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101978. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101979. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101980. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101981. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101982. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101983. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101984. #endif
  101985. /*** End of inlined file: stream_encoder_framing.h ***/
  101986. /*** Start of inlined file: window.h ***/
  101987. #ifndef FLAC__PRIVATE__WINDOW_H
  101988. #define FLAC__PRIVATE__WINDOW_H
  101989. #ifdef HAVE_CONFIG_H
  101990. #include <config.h>
  101991. #endif
  101992. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101993. /*
  101994. * FLAC__window_*()
  101995. * --------------------------------------------------------------------
  101996. * Calculates window coefficients according to different apodization
  101997. * functions.
  101998. *
  101999. * OUT window[0,L-1]
  102000. * IN L (number of points in window)
  102001. */
  102002. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102003. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102004. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102005. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102006. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102007. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102008. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102009. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102010. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102011. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102012. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102013. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102014. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102015. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102016. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102017. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102018. #endif
  102019. /*** End of inlined file: window.h ***/
  102020. #ifndef FLaC__INLINE
  102021. #define FLaC__INLINE
  102022. #endif
  102023. #ifdef min
  102024. #undef min
  102025. #endif
  102026. #define min(x,y) ((x)<(y)?(x):(y))
  102027. #ifdef max
  102028. #undef max
  102029. #endif
  102030. #define max(x,y) ((x)>(y)?(x):(y))
  102031. /* Exact Rice codeword length calculation is off by default. The simple
  102032. * (and fast) estimation (of how many bits a residual value will be
  102033. * encoded with) in this encoder is very good, almost always yielding
  102034. * compression within 0.1% of exact calculation.
  102035. */
  102036. #undef EXACT_RICE_BITS_CALCULATION
  102037. /* Rice parameter searching is off by default. The simple (and fast)
  102038. * parameter estimation in this encoder is very good, almost always
  102039. * yielding compression within 0.1% of the optimal parameters.
  102040. */
  102041. #undef ENABLE_RICE_PARAMETER_SEARCH
  102042. typedef struct {
  102043. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102044. unsigned size; /* of each data[] in samples */
  102045. unsigned tail;
  102046. } verify_input_fifo;
  102047. typedef struct {
  102048. const FLAC__byte *data;
  102049. unsigned capacity;
  102050. unsigned bytes;
  102051. } verify_output;
  102052. typedef enum {
  102053. ENCODER_IN_MAGIC = 0,
  102054. ENCODER_IN_METADATA = 1,
  102055. ENCODER_IN_AUDIO = 2
  102056. } EncoderStateHint;
  102057. static struct CompressionLevels {
  102058. FLAC__bool do_mid_side_stereo;
  102059. FLAC__bool loose_mid_side_stereo;
  102060. unsigned max_lpc_order;
  102061. unsigned qlp_coeff_precision;
  102062. FLAC__bool do_qlp_coeff_prec_search;
  102063. FLAC__bool do_escape_coding;
  102064. FLAC__bool do_exhaustive_model_search;
  102065. unsigned min_residual_partition_order;
  102066. unsigned max_residual_partition_order;
  102067. unsigned rice_parameter_search_dist;
  102068. } compression_levels_[] = {
  102069. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102070. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102071. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102072. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102073. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102074. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102075. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102076. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102077. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102078. };
  102079. /***********************************************************************
  102080. *
  102081. * Private class method prototypes
  102082. *
  102083. ***********************************************************************/
  102084. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102085. static void free_(FLAC__StreamEncoder *encoder);
  102086. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102087. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102088. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102089. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102090. #if FLAC__HAS_OGG
  102091. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102092. #endif
  102093. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102094. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102095. static FLAC__bool process_subframe_(
  102096. FLAC__StreamEncoder *encoder,
  102097. unsigned min_partition_order,
  102098. unsigned max_partition_order,
  102099. const FLAC__FrameHeader *frame_header,
  102100. unsigned subframe_bps,
  102101. const FLAC__int32 integer_signal[],
  102102. FLAC__Subframe *subframe[2],
  102103. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102104. FLAC__int32 *residual[2],
  102105. unsigned *best_subframe,
  102106. unsigned *best_bits
  102107. );
  102108. static FLAC__bool add_subframe_(
  102109. FLAC__StreamEncoder *encoder,
  102110. unsigned blocksize,
  102111. unsigned subframe_bps,
  102112. const FLAC__Subframe *subframe,
  102113. FLAC__BitWriter *frame
  102114. );
  102115. static unsigned evaluate_constant_subframe_(
  102116. FLAC__StreamEncoder *encoder,
  102117. const FLAC__int32 signal,
  102118. unsigned blocksize,
  102119. unsigned subframe_bps,
  102120. FLAC__Subframe *subframe
  102121. );
  102122. static unsigned evaluate_fixed_subframe_(
  102123. FLAC__StreamEncoder *encoder,
  102124. const FLAC__int32 signal[],
  102125. FLAC__int32 residual[],
  102126. FLAC__uint64 abs_residual_partition_sums[],
  102127. unsigned raw_bits_per_partition[],
  102128. unsigned blocksize,
  102129. unsigned subframe_bps,
  102130. unsigned order,
  102131. unsigned rice_parameter,
  102132. unsigned rice_parameter_limit,
  102133. unsigned min_partition_order,
  102134. unsigned max_partition_order,
  102135. FLAC__bool do_escape_coding,
  102136. unsigned rice_parameter_search_dist,
  102137. FLAC__Subframe *subframe,
  102138. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102139. );
  102140. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102141. static unsigned evaluate_lpc_subframe_(
  102142. FLAC__StreamEncoder *encoder,
  102143. const FLAC__int32 signal[],
  102144. FLAC__int32 residual[],
  102145. FLAC__uint64 abs_residual_partition_sums[],
  102146. unsigned raw_bits_per_partition[],
  102147. const FLAC__real lp_coeff[],
  102148. unsigned blocksize,
  102149. unsigned subframe_bps,
  102150. unsigned order,
  102151. unsigned qlp_coeff_precision,
  102152. unsigned rice_parameter,
  102153. unsigned rice_parameter_limit,
  102154. unsigned min_partition_order,
  102155. unsigned max_partition_order,
  102156. FLAC__bool do_escape_coding,
  102157. unsigned rice_parameter_search_dist,
  102158. FLAC__Subframe *subframe,
  102159. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102160. );
  102161. #endif
  102162. static unsigned evaluate_verbatim_subframe_(
  102163. FLAC__StreamEncoder *encoder,
  102164. const FLAC__int32 signal[],
  102165. unsigned blocksize,
  102166. unsigned subframe_bps,
  102167. FLAC__Subframe *subframe
  102168. );
  102169. static unsigned find_best_partition_order_(
  102170. struct FLAC__StreamEncoderPrivate *private_,
  102171. const FLAC__int32 residual[],
  102172. FLAC__uint64 abs_residual_partition_sums[],
  102173. unsigned raw_bits_per_partition[],
  102174. unsigned residual_samples,
  102175. unsigned predictor_order,
  102176. unsigned rice_parameter,
  102177. unsigned rice_parameter_limit,
  102178. unsigned min_partition_order,
  102179. unsigned max_partition_order,
  102180. unsigned bps,
  102181. FLAC__bool do_escape_coding,
  102182. unsigned rice_parameter_search_dist,
  102183. FLAC__EntropyCodingMethod *best_ecm
  102184. );
  102185. static void precompute_partition_info_sums_(
  102186. const FLAC__int32 residual[],
  102187. FLAC__uint64 abs_residual_partition_sums[],
  102188. unsigned residual_samples,
  102189. unsigned predictor_order,
  102190. unsigned min_partition_order,
  102191. unsigned max_partition_order,
  102192. unsigned bps
  102193. );
  102194. static void precompute_partition_info_escapes_(
  102195. const FLAC__int32 residual[],
  102196. unsigned raw_bits_per_partition[],
  102197. unsigned residual_samples,
  102198. unsigned predictor_order,
  102199. unsigned min_partition_order,
  102200. unsigned max_partition_order
  102201. );
  102202. static FLAC__bool set_partitioned_rice_(
  102203. #ifdef EXACT_RICE_BITS_CALCULATION
  102204. const FLAC__int32 residual[],
  102205. #endif
  102206. const FLAC__uint64 abs_residual_partition_sums[],
  102207. const unsigned raw_bits_per_partition[],
  102208. const unsigned residual_samples,
  102209. const unsigned predictor_order,
  102210. const unsigned suggested_rice_parameter,
  102211. const unsigned rice_parameter_limit,
  102212. const unsigned rice_parameter_search_dist,
  102213. const unsigned partition_order,
  102214. const FLAC__bool search_for_escapes,
  102215. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102216. unsigned *bits
  102217. );
  102218. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102219. /* verify-related routines: */
  102220. static void append_to_verify_fifo_(
  102221. verify_input_fifo *fifo,
  102222. const FLAC__int32 * const input[],
  102223. unsigned input_offset,
  102224. unsigned channels,
  102225. unsigned wide_samples
  102226. );
  102227. static void append_to_verify_fifo_interleaved_(
  102228. verify_input_fifo *fifo,
  102229. const FLAC__int32 input[],
  102230. unsigned input_offset,
  102231. unsigned channels,
  102232. unsigned wide_samples
  102233. );
  102234. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102235. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102236. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102237. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102238. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102239. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102240. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102241. 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);
  102242. static FILE *get_binary_stdout_(void);
  102243. /***********************************************************************
  102244. *
  102245. * Private class data
  102246. *
  102247. ***********************************************************************/
  102248. typedef struct FLAC__StreamEncoderPrivate {
  102249. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102250. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102251. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102252. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102253. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102254. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102255. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102256. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102257. #endif
  102258. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102259. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102260. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102261. FLAC__int32 *residual_workspace_mid_side[2][2];
  102262. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102263. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102264. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102265. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102266. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102267. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102268. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102269. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102270. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102271. unsigned best_subframe_mid_side[2];
  102272. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102273. unsigned best_subframe_bits_mid_side[2];
  102274. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102275. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102276. FLAC__BitWriter *frame; /* the current frame being worked on */
  102277. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102278. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102279. FLAC__ChannelAssignment last_channel_assignment;
  102280. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102281. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102282. unsigned current_sample_number;
  102283. unsigned current_frame_number;
  102284. FLAC__MD5Context md5context;
  102285. FLAC__CPUInfo cpuinfo;
  102286. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102287. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102288. #else
  102289. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102290. #endif
  102291. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102292. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102293. 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[]);
  102294. 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[]);
  102295. 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[]);
  102296. #endif
  102297. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102298. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102299. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102300. FLAC__bool disable_constant_subframes;
  102301. FLAC__bool disable_fixed_subframes;
  102302. FLAC__bool disable_verbatim_subframes;
  102303. #if FLAC__HAS_OGG
  102304. FLAC__bool is_ogg;
  102305. #endif
  102306. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102307. FLAC__StreamEncoderSeekCallback seek_callback;
  102308. FLAC__StreamEncoderTellCallback tell_callback;
  102309. FLAC__StreamEncoderWriteCallback write_callback;
  102310. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102311. FLAC__StreamEncoderProgressCallback progress_callback;
  102312. void *client_data;
  102313. unsigned first_seekpoint_to_check;
  102314. FILE *file; /* only used when encoding to a file */
  102315. FLAC__uint64 bytes_written;
  102316. FLAC__uint64 samples_written;
  102317. unsigned frames_written;
  102318. unsigned total_frames_estimate;
  102319. /* unaligned (original) pointers to allocated data */
  102320. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102321. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102322. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102323. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102324. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102325. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102326. FLAC__real *windowed_signal_unaligned;
  102327. #endif
  102328. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102329. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102330. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102331. unsigned *raw_bits_per_partition_unaligned;
  102332. /*
  102333. * These fields have been moved here from private function local
  102334. * declarations merely to save stack space during encoding.
  102335. */
  102336. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102337. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102338. #endif
  102339. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102340. /*
  102341. * The data for the verify section
  102342. */
  102343. struct {
  102344. FLAC__StreamDecoder *decoder;
  102345. EncoderStateHint state_hint;
  102346. FLAC__bool needs_magic_hack;
  102347. verify_input_fifo input_fifo;
  102348. verify_output output;
  102349. struct {
  102350. FLAC__uint64 absolute_sample;
  102351. unsigned frame_number;
  102352. unsigned channel;
  102353. unsigned sample;
  102354. FLAC__int32 expected;
  102355. FLAC__int32 got;
  102356. } error_stats;
  102357. } verify;
  102358. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102359. } FLAC__StreamEncoderPrivate;
  102360. /***********************************************************************
  102361. *
  102362. * Public static class data
  102363. *
  102364. ***********************************************************************/
  102365. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102366. "FLAC__STREAM_ENCODER_OK",
  102367. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102368. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102369. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102370. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102371. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102372. "FLAC__STREAM_ENCODER_IO_ERROR",
  102373. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102374. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102375. };
  102376. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102377. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102378. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102379. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102380. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102381. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102382. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102383. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102384. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102385. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102386. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102387. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102388. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102389. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102390. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102391. };
  102392. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102393. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102394. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102395. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102396. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102397. };
  102398. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102399. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102400. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102401. };
  102402. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102403. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102404. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102405. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102406. };
  102407. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102408. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102409. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102410. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102411. };
  102412. /* Number of samples that will be overread to watch for end of stream. By
  102413. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102414. * always try to read blocksize+1 samples before encoding a block, so that
  102415. * even if the stream has a total sample count that is an integral multiple
  102416. * of the blocksize, we will still notice when we are encoding the last
  102417. * block. This is needed, for example, to correctly set the end-of-stream
  102418. * marker in Ogg FLAC.
  102419. *
  102420. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102421. * not really any reason to change it.
  102422. */
  102423. static const unsigned OVERREAD_ = 1;
  102424. /***********************************************************************
  102425. *
  102426. * Class constructor/destructor
  102427. *
  102428. */
  102429. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102430. {
  102431. FLAC__StreamEncoder *encoder;
  102432. unsigned i;
  102433. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102434. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102435. if(encoder == 0) {
  102436. return 0;
  102437. }
  102438. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102439. if(encoder->protected_ == 0) {
  102440. free(encoder);
  102441. return 0;
  102442. }
  102443. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102444. if(encoder->private_ == 0) {
  102445. free(encoder->protected_);
  102446. free(encoder);
  102447. return 0;
  102448. }
  102449. encoder->private_->frame = FLAC__bitwriter_new();
  102450. if(encoder->private_->frame == 0) {
  102451. free(encoder->private_);
  102452. free(encoder->protected_);
  102453. free(encoder);
  102454. return 0;
  102455. }
  102456. encoder->private_->file = 0;
  102457. set_defaults_enc(encoder);
  102458. encoder->private_->is_being_deleted = false;
  102459. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102460. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102461. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102462. }
  102463. for(i = 0; i < 2; i++) {
  102464. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102465. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102466. }
  102467. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102468. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102469. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102470. }
  102471. for(i = 0; i < 2; i++) {
  102472. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102473. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102474. }
  102475. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102476. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102477. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102478. }
  102479. for(i = 0; i < 2; i++) {
  102480. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102481. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102482. }
  102483. for(i = 0; i < 2; i++)
  102484. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102485. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102486. return encoder;
  102487. }
  102488. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102489. {
  102490. unsigned i;
  102491. FLAC__ASSERT(0 != encoder);
  102492. FLAC__ASSERT(0 != encoder->protected_);
  102493. FLAC__ASSERT(0 != encoder->private_);
  102494. FLAC__ASSERT(0 != encoder->private_->frame);
  102495. encoder->private_->is_being_deleted = true;
  102496. (void)FLAC__stream_encoder_finish(encoder);
  102497. if(0 != encoder->private_->verify.decoder)
  102498. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102499. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102500. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102501. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102502. }
  102503. for(i = 0; i < 2; i++) {
  102504. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102505. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102506. }
  102507. for(i = 0; i < 2; i++)
  102508. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102509. FLAC__bitwriter_delete(encoder->private_->frame);
  102510. free(encoder->private_);
  102511. free(encoder->protected_);
  102512. free(encoder);
  102513. }
  102514. /***********************************************************************
  102515. *
  102516. * Public class methods
  102517. *
  102518. ***********************************************************************/
  102519. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102520. FLAC__StreamEncoder *encoder,
  102521. FLAC__StreamEncoderReadCallback read_callback,
  102522. FLAC__StreamEncoderWriteCallback write_callback,
  102523. FLAC__StreamEncoderSeekCallback seek_callback,
  102524. FLAC__StreamEncoderTellCallback tell_callback,
  102525. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102526. void *client_data,
  102527. FLAC__bool is_ogg
  102528. )
  102529. {
  102530. unsigned i;
  102531. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102532. FLAC__ASSERT(0 != encoder);
  102533. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102534. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102535. #if !FLAC__HAS_OGG
  102536. if(is_ogg)
  102537. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102538. #endif
  102539. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102540. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102541. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102542. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102543. if(encoder->protected_->channels != 2) {
  102544. encoder->protected_->do_mid_side_stereo = false;
  102545. encoder->protected_->loose_mid_side_stereo = false;
  102546. }
  102547. else if(!encoder->protected_->do_mid_side_stereo)
  102548. encoder->protected_->loose_mid_side_stereo = false;
  102549. if(encoder->protected_->bits_per_sample >= 32)
  102550. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102551. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102552. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102553. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102554. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102555. if(encoder->protected_->blocksize == 0) {
  102556. if(encoder->protected_->max_lpc_order == 0)
  102557. encoder->protected_->blocksize = 1152;
  102558. else
  102559. encoder->protected_->blocksize = 4096;
  102560. }
  102561. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102562. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102563. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102564. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102565. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102566. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102567. if(encoder->protected_->qlp_coeff_precision == 0) {
  102568. if(encoder->protected_->bits_per_sample < 16) {
  102569. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102570. /* @@@ until then we'll make a guess */
  102571. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102572. }
  102573. else if(encoder->protected_->bits_per_sample == 16) {
  102574. if(encoder->protected_->blocksize <= 192)
  102575. encoder->protected_->qlp_coeff_precision = 7;
  102576. else if(encoder->protected_->blocksize <= 384)
  102577. encoder->protected_->qlp_coeff_precision = 8;
  102578. else if(encoder->protected_->blocksize <= 576)
  102579. encoder->protected_->qlp_coeff_precision = 9;
  102580. else if(encoder->protected_->blocksize <= 1152)
  102581. encoder->protected_->qlp_coeff_precision = 10;
  102582. else if(encoder->protected_->blocksize <= 2304)
  102583. encoder->protected_->qlp_coeff_precision = 11;
  102584. else if(encoder->protected_->blocksize <= 4608)
  102585. encoder->protected_->qlp_coeff_precision = 12;
  102586. else
  102587. encoder->protected_->qlp_coeff_precision = 13;
  102588. }
  102589. else {
  102590. if(encoder->protected_->blocksize <= 384)
  102591. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102592. else if(encoder->protected_->blocksize <= 1152)
  102593. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102594. else
  102595. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102596. }
  102597. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102598. }
  102599. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102600. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102601. if(encoder->protected_->streamable_subset) {
  102602. if(
  102603. encoder->protected_->blocksize != 192 &&
  102604. encoder->protected_->blocksize != 576 &&
  102605. encoder->protected_->blocksize != 1152 &&
  102606. encoder->protected_->blocksize != 2304 &&
  102607. encoder->protected_->blocksize != 4608 &&
  102608. encoder->protected_->blocksize != 256 &&
  102609. encoder->protected_->blocksize != 512 &&
  102610. encoder->protected_->blocksize != 1024 &&
  102611. encoder->protected_->blocksize != 2048 &&
  102612. encoder->protected_->blocksize != 4096 &&
  102613. encoder->protected_->blocksize != 8192 &&
  102614. encoder->protected_->blocksize != 16384
  102615. )
  102616. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102617. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102618. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102619. if(
  102620. encoder->protected_->bits_per_sample != 8 &&
  102621. encoder->protected_->bits_per_sample != 12 &&
  102622. encoder->protected_->bits_per_sample != 16 &&
  102623. encoder->protected_->bits_per_sample != 20 &&
  102624. encoder->protected_->bits_per_sample != 24
  102625. )
  102626. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102627. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102628. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102629. if(
  102630. encoder->protected_->sample_rate <= 48000 &&
  102631. (
  102632. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102633. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102634. )
  102635. ) {
  102636. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102637. }
  102638. }
  102639. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102640. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102641. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102642. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102643. #if FLAC__HAS_OGG
  102644. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102645. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102646. unsigned i;
  102647. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102648. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102649. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102650. for( ; i > 0; i--)
  102651. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102652. encoder->protected_->metadata[0] = vc;
  102653. break;
  102654. }
  102655. }
  102656. }
  102657. #endif
  102658. /* keep track of any SEEKTABLE block */
  102659. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102660. unsigned i;
  102661. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102662. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102663. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102664. break; /* take only the first one */
  102665. }
  102666. }
  102667. }
  102668. /* validate metadata */
  102669. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102670. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102671. metadata_has_seektable = false;
  102672. metadata_has_vorbis_comment = false;
  102673. metadata_picture_has_type1 = false;
  102674. metadata_picture_has_type2 = false;
  102675. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102676. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102677. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102678. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102679. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102680. if(metadata_has_seektable) /* only one is allowed */
  102681. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102682. metadata_has_seektable = true;
  102683. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102684. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102685. }
  102686. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102687. if(metadata_has_vorbis_comment) /* only one is allowed */
  102688. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102689. metadata_has_vorbis_comment = true;
  102690. }
  102691. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102692. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102693. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102694. }
  102695. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102696. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102697. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102698. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102699. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102700. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102701. metadata_picture_has_type1 = true;
  102702. /* standard icon must be 32x32 pixel PNG */
  102703. if(
  102704. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102705. (
  102706. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102707. m->data.picture.width != 32 ||
  102708. m->data.picture.height != 32
  102709. )
  102710. )
  102711. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102712. }
  102713. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102714. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102715. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102716. metadata_picture_has_type2 = true;
  102717. }
  102718. }
  102719. }
  102720. encoder->private_->input_capacity = 0;
  102721. for(i = 0; i < encoder->protected_->channels; i++) {
  102722. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102723. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102724. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102725. #endif
  102726. }
  102727. for(i = 0; i < 2; i++) {
  102728. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102729. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102730. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102731. #endif
  102732. }
  102733. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102734. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102735. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102736. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102737. #endif
  102738. for(i = 0; i < encoder->protected_->channels; i++) {
  102739. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102740. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102741. encoder->private_->best_subframe[i] = 0;
  102742. }
  102743. for(i = 0; i < 2; i++) {
  102744. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102745. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102746. encoder->private_->best_subframe_mid_side[i] = 0;
  102747. }
  102748. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102749. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102750. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102751. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102752. #else
  102753. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102754. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102755. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102756. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102757. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102758. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102759. 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);
  102760. #endif
  102761. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102762. encoder->private_->loose_mid_side_stereo_frames = 1;
  102763. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102764. encoder->private_->current_sample_number = 0;
  102765. encoder->private_->current_frame_number = 0;
  102766. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102767. 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? */
  102768. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102769. /*
  102770. * get the CPU info and set the function pointers
  102771. */
  102772. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102773. /* first default to the non-asm routines */
  102774. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102775. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102776. #endif
  102777. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102778. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102779. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102780. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102781. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102782. #endif
  102783. /* now override with asm where appropriate */
  102784. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102785. # ifndef FLAC__NO_ASM
  102786. if(encoder->private_->cpuinfo.use_asm) {
  102787. # ifdef FLAC__CPU_IA32
  102788. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102789. # ifdef FLAC__HAS_NASM
  102790. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102791. if(encoder->protected_->max_lpc_order < 4)
  102792. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102793. else if(encoder->protected_->max_lpc_order < 8)
  102794. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102795. else if(encoder->protected_->max_lpc_order < 12)
  102796. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102797. else
  102798. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102799. }
  102800. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102801. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102802. else
  102803. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102804. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102805. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102806. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102807. }
  102808. else {
  102809. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102810. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102811. }
  102812. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102813. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102814. # endif /* FLAC__HAS_NASM */
  102815. # endif /* FLAC__CPU_IA32 */
  102816. }
  102817. # endif /* !FLAC__NO_ASM */
  102818. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102819. /* finally override based on wide-ness if necessary */
  102820. if(encoder->private_->use_wide_by_block) {
  102821. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102822. }
  102823. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102824. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102825. #if FLAC__HAS_OGG
  102826. encoder->private_->is_ogg = is_ogg;
  102827. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102828. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102829. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102830. }
  102831. #endif
  102832. encoder->private_->read_callback = read_callback;
  102833. encoder->private_->write_callback = write_callback;
  102834. encoder->private_->seek_callback = seek_callback;
  102835. encoder->private_->tell_callback = tell_callback;
  102836. encoder->private_->metadata_callback = metadata_callback;
  102837. encoder->private_->client_data = client_data;
  102838. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102839. /* the above function sets the state for us in case of an error */
  102840. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102841. }
  102842. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102843. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102844. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102845. }
  102846. /*
  102847. * Set up the verify stuff if necessary
  102848. */
  102849. if(encoder->protected_->verify) {
  102850. /*
  102851. * First, set up the fifo which will hold the
  102852. * original signal to compare against
  102853. */
  102854. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102855. for(i = 0; i < encoder->protected_->channels; i++) {
  102856. 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))) {
  102857. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102858. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102859. }
  102860. }
  102861. encoder->private_->verify.input_fifo.tail = 0;
  102862. /*
  102863. * Now set up a stream decoder for verification
  102864. */
  102865. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102866. if(0 == encoder->private_->verify.decoder) {
  102867. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102868. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102869. }
  102870. 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) {
  102871. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102872. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102873. }
  102874. }
  102875. encoder->private_->verify.error_stats.absolute_sample = 0;
  102876. encoder->private_->verify.error_stats.frame_number = 0;
  102877. encoder->private_->verify.error_stats.channel = 0;
  102878. encoder->private_->verify.error_stats.sample = 0;
  102879. encoder->private_->verify.error_stats.expected = 0;
  102880. encoder->private_->verify.error_stats.got = 0;
  102881. /*
  102882. * These must be done before we write any metadata, because that
  102883. * calls the write_callback, which uses these values.
  102884. */
  102885. encoder->private_->first_seekpoint_to_check = 0;
  102886. encoder->private_->samples_written = 0;
  102887. encoder->protected_->streaminfo_offset = 0;
  102888. encoder->protected_->seektable_offset = 0;
  102889. encoder->protected_->audio_offset = 0;
  102890. /*
  102891. * write the stream header
  102892. */
  102893. if(encoder->protected_->verify)
  102894. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102895. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102896. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102897. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102898. }
  102899. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102900. /* the above function sets the state for us in case of an error */
  102901. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102902. }
  102903. /*
  102904. * write the STREAMINFO metadata block
  102905. */
  102906. if(encoder->protected_->verify)
  102907. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102908. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102909. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102910. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102911. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102912. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102913. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102914. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102915. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102916. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102917. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102918. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102919. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102920. if(encoder->protected_->do_md5)
  102921. FLAC__MD5Init(&encoder->private_->md5context);
  102922. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102923. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102924. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102925. }
  102926. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102927. /* the above function sets the state for us in case of an error */
  102928. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102929. }
  102930. /*
  102931. * Now that the STREAMINFO block is written, we can init this to an
  102932. * absurdly-high value...
  102933. */
  102934. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102935. /* ... and clear this to 0 */
  102936. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102937. /*
  102938. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102939. * if not, we will write an empty one (FLAC__add_metadata_block()
  102940. * automatically supplies the vendor string).
  102941. *
  102942. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102943. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102944. * true it will have already insured that the metadata list is properly
  102945. * ordered.)
  102946. */
  102947. if(!metadata_has_vorbis_comment) {
  102948. FLAC__StreamMetadata vorbis_comment;
  102949. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102950. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102951. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102952. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102953. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102954. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102955. vorbis_comment.data.vorbis_comment.comments = 0;
  102956. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102957. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102958. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102959. }
  102960. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102961. /* the above function sets the state for us in case of an error */
  102962. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102963. }
  102964. }
  102965. /*
  102966. * write the user's metadata blocks
  102967. */
  102968. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102969. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102970. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102971. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102972. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102973. }
  102974. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102975. /* the above function sets the state for us in case of an error */
  102976. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102977. }
  102978. }
  102979. /* now that all the metadata is written, we save the stream offset */
  102980. 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 */
  102981. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102982. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102983. }
  102984. if(encoder->protected_->verify)
  102985. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102986. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102987. }
  102988. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102989. FLAC__StreamEncoder *encoder,
  102990. FLAC__StreamEncoderWriteCallback write_callback,
  102991. FLAC__StreamEncoderSeekCallback seek_callback,
  102992. FLAC__StreamEncoderTellCallback tell_callback,
  102993. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102994. void *client_data
  102995. )
  102996. {
  102997. return init_stream_internal_enc(
  102998. encoder,
  102999. /*read_callback=*/0,
  103000. write_callback,
  103001. seek_callback,
  103002. tell_callback,
  103003. metadata_callback,
  103004. client_data,
  103005. /*is_ogg=*/false
  103006. );
  103007. }
  103008. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103009. FLAC__StreamEncoder *encoder,
  103010. FLAC__StreamEncoderReadCallback read_callback,
  103011. FLAC__StreamEncoderWriteCallback write_callback,
  103012. FLAC__StreamEncoderSeekCallback seek_callback,
  103013. FLAC__StreamEncoderTellCallback tell_callback,
  103014. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103015. void *client_data
  103016. )
  103017. {
  103018. return init_stream_internal_enc(
  103019. encoder,
  103020. read_callback,
  103021. write_callback,
  103022. seek_callback,
  103023. tell_callback,
  103024. metadata_callback,
  103025. client_data,
  103026. /*is_ogg=*/true
  103027. );
  103028. }
  103029. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103030. FLAC__StreamEncoder *encoder,
  103031. FILE *file,
  103032. FLAC__StreamEncoderProgressCallback progress_callback,
  103033. void *client_data,
  103034. FLAC__bool is_ogg
  103035. )
  103036. {
  103037. FLAC__StreamEncoderInitStatus init_status;
  103038. FLAC__ASSERT(0 != encoder);
  103039. FLAC__ASSERT(0 != file);
  103040. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103041. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103042. /* double protection */
  103043. if(file == 0) {
  103044. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103045. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103046. }
  103047. /*
  103048. * To make sure that our file does not go unclosed after an error, we
  103049. * must assign the FILE pointer before any further error can occur in
  103050. * this routine.
  103051. */
  103052. if(file == stdout)
  103053. file = get_binary_stdout_(); /* just to be safe */
  103054. encoder->private_->file = file;
  103055. encoder->private_->progress_callback = progress_callback;
  103056. encoder->private_->bytes_written = 0;
  103057. encoder->private_->samples_written = 0;
  103058. encoder->private_->frames_written = 0;
  103059. init_status = init_stream_internal_enc(
  103060. encoder,
  103061. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103062. file_write_callback_,
  103063. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103064. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103065. /*metadata_callback=*/0,
  103066. client_data,
  103067. is_ogg
  103068. );
  103069. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103070. /* the above function sets the state for us in case of an error */
  103071. return init_status;
  103072. }
  103073. {
  103074. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103075. FLAC__ASSERT(blocksize != 0);
  103076. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103077. }
  103078. return init_status;
  103079. }
  103080. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103081. FLAC__StreamEncoder *encoder,
  103082. FILE *file,
  103083. FLAC__StreamEncoderProgressCallback progress_callback,
  103084. void *client_data
  103085. )
  103086. {
  103087. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103088. }
  103089. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103090. FLAC__StreamEncoder *encoder,
  103091. FILE *file,
  103092. FLAC__StreamEncoderProgressCallback progress_callback,
  103093. void *client_data
  103094. )
  103095. {
  103096. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103097. }
  103098. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103099. FLAC__StreamEncoder *encoder,
  103100. const char *filename,
  103101. FLAC__StreamEncoderProgressCallback progress_callback,
  103102. void *client_data,
  103103. FLAC__bool is_ogg
  103104. )
  103105. {
  103106. FILE *file;
  103107. FLAC__ASSERT(0 != encoder);
  103108. /*
  103109. * To make sure that our file does not go unclosed after an error, we
  103110. * have to do the same entrance checks here that are later performed
  103111. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103112. */
  103113. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103114. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103115. file = filename? fopen(filename, "w+b") : stdout;
  103116. if(file == 0) {
  103117. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103118. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103119. }
  103120. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103121. }
  103122. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103123. FLAC__StreamEncoder *encoder,
  103124. const char *filename,
  103125. FLAC__StreamEncoderProgressCallback progress_callback,
  103126. void *client_data
  103127. )
  103128. {
  103129. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103130. }
  103131. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103132. FLAC__StreamEncoder *encoder,
  103133. const char *filename,
  103134. FLAC__StreamEncoderProgressCallback progress_callback,
  103135. void *client_data
  103136. )
  103137. {
  103138. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103139. }
  103140. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103141. {
  103142. FLAC__bool error = false;
  103143. FLAC__ASSERT(0 != encoder);
  103144. FLAC__ASSERT(0 != encoder->private_);
  103145. FLAC__ASSERT(0 != encoder->protected_);
  103146. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103147. return true;
  103148. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103149. if(encoder->private_->current_sample_number != 0) {
  103150. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103151. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103152. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103153. error = true;
  103154. }
  103155. }
  103156. if(encoder->protected_->do_md5)
  103157. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103158. if(!encoder->private_->is_being_deleted) {
  103159. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103160. if(encoder->private_->seek_callback) {
  103161. #if FLAC__HAS_OGG
  103162. if(encoder->private_->is_ogg)
  103163. update_ogg_metadata_(encoder);
  103164. else
  103165. #endif
  103166. update_metadata_(encoder);
  103167. /* check if an error occurred while updating metadata */
  103168. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103169. error = true;
  103170. }
  103171. if(encoder->private_->metadata_callback)
  103172. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103173. }
  103174. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103175. if(!error)
  103176. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103177. error = true;
  103178. }
  103179. }
  103180. if(0 != encoder->private_->file) {
  103181. if(encoder->private_->file != stdout)
  103182. fclose(encoder->private_->file);
  103183. encoder->private_->file = 0;
  103184. }
  103185. #if FLAC__HAS_OGG
  103186. if(encoder->private_->is_ogg)
  103187. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103188. #endif
  103189. free_(encoder);
  103190. set_defaults_enc(encoder);
  103191. if(!error)
  103192. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103193. return !error;
  103194. }
  103195. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103196. {
  103197. FLAC__ASSERT(0 != encoder);
  103198. FLAC__ASSERT(0 != encoder->private_);
  103199. FLAC__ASSERT(0 != encoder->protected_);
  103200. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103201. return false;
  103202. #if FLAC__HAS_OGG
  103203. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103204. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103205. return true;
  103206. #else
  103207. (void)value;
  103208. return false;
  103209. #endif
  103210. }
  103211. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103212. {
  103213. FLAC__ASSERT(0 != encoder);
  103214. FLAC__ASSERT(0 != encoder->private_);
  103215. FLAC__ASSERT(0 != encoder->protected_);
  103216. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103217. return false;
  103218. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103219. encoder->protected_->verify = value;
  103220. #endif
  103221. return true;
  103222. }
  103223. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103224. {
  103225. FLAC__ASSERT(0 != encoder);
  103226. FLAC__ASSERT(0 != encoder->private_);
  103227. FLAC__ASSERT(0 != encoder->protected_);
  103228. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103229. return false;
  103230. encoder->protected_->streamable_subset = value;
  103231. return true;
  103232. }
  103233. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103234. {
  103235. FLAC__ASSERT(0 != encoder);
  103236. FLAC__ASSERT(0 != encoder->private_);
  103237. FLAC__ASSERT(0 != encoder->protected_);
  103238. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103239. return false;
  103240. encoder->protected_->do_md5 = value;
  103241. return true;
  103242. }
  103243. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103244. {
  103245. FLAC__ASSERT(0 != encoder);
  103246. FLAC__ASSERT(0 != encoder->private_);
  103247. FLAC__ASSERT(0 != encoder->protected_);
  103248. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103249. return false;
  103250. encoder->protected_->channels = value;
  103251. return true;
  103252. }
  103253. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103254. {
  103255. FLAC__ASSERT(0 != encoder);
  103256. FLAC__ASSERT(0 != encoder->private_);
  103257. FLAC__ASSERT(0 != encoder->protected_);
  103258. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103259. return false;
  103260. encoder->protected_->bits_per_sample = value;
  103261. return true;
  103262. }
  103263. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103264. {
  103265. FLAC__ASSERT(0 != encoder);
  103266. FLAC__ASSERT(0 != encoder->private_);
  103267. FLAC__ASSERT(0 != encoder->protected_);
  103268. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103269. return false;
  103270. encoder->protected_->sample_rate = value;
  103271. return true;
  103272. }
  103273. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103274. {
  103275. FLAC__bool ok = true;
  103276. FLAC__ASSERT(0 != encoder);
  103277. FLAC__ASSERT(0 != encoder->private_);
  103278. FLAC__ASSERT(0 != encoder->protected_);
  103279. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103280. return false;
  103281. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103282. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103283. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103284. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103285. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103286. #if 0
  103287. /* was: */
  103288. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103289. /* but it's too hard to specify the string in a locale-specific way */
  103290. #else
  103291. encoder->protected_->num_apodizations = 1;
  103292. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103293. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103294. #endif
  103295. #endif
  103296. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103297. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103298. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103299. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103300. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103301. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103302. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103303. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103304. return ok;
  103305. }
  103306. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103307. {
  103308. FLAC__ASSERT(0 != encoder);
  103309. FLAC__ASSERT(0 != encoder->private_);
  103310. FLAC__ASSERT(0 != encoder->protected_);
  103311. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103312. return false;
  103313. encoder->protected_->blocksize = value;
  103314. return true;
  103315. }
  103316. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103317. {
  103318. FLAC__ASSERT(0 != encoder);
  103319. FLAC__ASSERT(0 != encoder->private_);
  103320. FLAC__ASSERT(0 != encoder->protected_);
  103321. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103322. return false;
  103323. encoder->protected_->do_mid_side_stereo = value;
  103324. return true;
  103325. }
  103326. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103327. {
  103328. FLAC__ASSERT(0 != encoder);
  103329. FLAC__ASSERT(0 != encoder->private_);
  103330. FLAC__ASSERT(0 != encoder->protected_);
  103331. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103332. return false;
  103333. encoder->protected_->loose_mid_side_stereo = value;
  103334. return true;
  103335. }
  103336. /*@@@@add to tests*/
  103337. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103338. {
  103339. FLAC__ASSERT(0 != encoder);
  103340. FLAC__ASSERT(0 != encoder->private_);
  103341. FLAC__ASSERT(0 != encoder->protected_);
  103342. FLAC__ASSERT(0 != specification);
  103343. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103344. return false;
  103345. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103346. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103347. #else
  103348. encoder->protected_->num_apodizations = 0;
  103349. while(1) {
  103350. const char *s = strchr(specification, ';');
  103351. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103352. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103353. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103354. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103355. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103356. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103357. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103358. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103359. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103360. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103361. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103362. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103363. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103364. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103365. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103366. if (stddev > 0.0 && stddev <= 0.5) {
  103367. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103368. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103369. }
  103370. }
  103371. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103372. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103373. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103374. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103375. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103376. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103377. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103378. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103379. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103380. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103381. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103382. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103383. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103384. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103385. if (p >= 0.0 && p <= 1.0) {
  103386. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103387. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103388. }
  103389. }
  103390. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103391. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103392. if (encoder->protected_->num_apodizations == 32)
  103393. break;
  103394. if (s)
  103395. specification = s+1;
  103396. else
  103397. break;
  103398. }
  103399. if(encoder->protected_->num_apodizations == 0) {
  103400. encoder->protected_->num_apodizations = 1;
  103401. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103402. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103403. }
  103404. #endif
  103405. return true;
  103406. }
  103407. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103408. {
  103409. FLAC__ASSERT(0 != encoder);
  103410. FLAC__ASSERT(0 != encoder->private_);
  103411. FLAC__ASSERT(0 != encoder->protected_);
  103412. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103413. return false;
  103414. encoder->protected_->max_lpc_order = value;
  103415. return true;
  103416. }
  103417. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103418. {
  103419. FLAC__ASSERT(0 != encoder);
  103420. FLAC__ASSERT(0 != encoder->private_);
  103421. FLAC__ASSERT(0 != encoder->protected_);
  103422. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103423. return false;
  103424. encoder->protected_->qlp_coeff_precision = value;
  103425. return true;
  103426. }
  103427. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103428. {
  103429. FLAC__ASSERT(0 != encoder);
  103430. FLAC__ASSERT(0 != encoder->private_);
  103431. FLAC__ASSERT(0 != encoder->protected_);
  103432. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103433. return false;
  103434. encoder->protected_->do_qlp_coeff_prec_search = value;
  103435. return true;
  103436. }
  103437. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103438. {
  103439. FLAC__ASSERT(0 != encoder);
  103440. FLAC__ASSERT(0 != encoder->private_);
  103441. FLAC__ASSERT(0 != encoder->protected_);
  103442. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103443. return false;
  103444. #if 0
  103445. /*@@@ deprecated: */
  103446. encoder->protected_->do_escape_coding = value;
  103447. #else
  103448. (void)value;
  103449. #endif
  103450. return true;
  103451. }
  103452. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103453. {
  103454. FLAC__ASSERT(0 != encoder);
  103455. FLAC__ASSERT(0 != encoder->private_);
  103456. FLAC__ASSERT(0 != encoder->protected_);
  103457. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103458. return false;
  103459. encoder->protected_->do_exhaustive_model_search = value;
  103460. return true;
  103461. }
  103462. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103463. {
  103464. FLAC__ASSERT(0 != encoder);
  103465. FLAC__ASSERT(0 != encoder->private_);
  103466. FLAC__ASSERT(0 != encoder->protected_);
  103467. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103468. return false;
  103469. encoder->protected_->min_residual_partition_order = value;
  103470. return true;
  103471. }
  103472. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103473. {
  103474. FLAC__ASSERT(0 != encoder);
  103475. FLAC__ASSERT(0 != encoder->private_);
  103476. FLAC__ASSERT(0 != encoder->protected_);
  103477. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103478. return false;
  103479. encoder->protected_->max_residual_partition_order = value;
  103480. return true;
  103481. }
  103482. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103483. {
  103484. FLAC__ASSERT(0 != encoder);
  103485. FLAC__ASSERT(0 != encoder->private_);
  103486. FLAC__ASSERT(0 != encoder->protected_);
  103487. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103488. return false;
  103489. #if 0
  103490. /*@@@ deprecated: */
  103491. encoder->protected_->rice_parameter_search_dist = value;
  103492. #else
  103493. (void)value;
  103494. #endif
  103495. return true;
  103496. }
  103497. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103498. {
  103499. FLAC__ASSERT(0 != encoder);
  103500. FLAC__ASSERT(0 != encoder->private_);
  103501. FLAC__ASSERT(0 != encoder->protected_);
  103502. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103503. return false;
  103504. encoder->protected_->total_samples_estimate = value;
  103505. return true;
  103506. }
  103507. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103508. {
  103509. FLAC__ASSERT(0 != encoder);
  103510. FLAC__ASSERT(0 != encoder->private_);
  103511. FLAC__ASSERT(0 != encoder->protected_);
  103512. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103513. return false;
  103514. if(0 == metadata)
  103515. num_blocks = 0;
  103516. if(0 == num_blocks)
  103517. metadata = 0;
  103518. /* realloc() does not do exactly what we want so... */
  103519. if(encoder->protected_->metadata) {
  103520. free(encoder->protected_->metadata);
  103521. encoder->protected_->metadata = 0;
  103522. encoder->protected_->num_metadata_blocks = 0;
  103523. }
  103524. if(num_blocks) {
  103525. FLAC__StreamMetadata **m;
  103526. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103527. return false;
  103528. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103529. encoder->protected_->metadata = m;
  103530. encoder->protected_->num_metadata_blocks = num_blocks;
  103531. }
  103532. #if FLAC__HAS_OGG
  103533. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103534. return false;
  103535. #endif
  103536. return true;
  103537. }
  103538. /*
  103539. * These three functions are not static, but not publically exposed in
  103540. * include/FLAC/ either. They are used by the test suite.
  103541. */
  103542. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103543. {
  103544. FLAC__ASSERT(0 != encoder);
  103545. FLAC__ASSERT(0 != encoder->private_);
  103546. FLAC__ASSERT(0 != encoder->protected_);
  103547. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103548. return false;
  103549. encoder->private_->disable_constant_subframes = value;
  103550. return true;
  103551. }
  103552. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103553. {
  103554. FLAC__ASSERT(0 != encoder);
  103555. FLAC__ASSERT(0 != encoder->private_);
  103556. FLAC__ASSERT(0 != encoder->protected_);
  103557. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103558. return false;
  103559. encoder->private_->disable_fixed_subframes = value;
  103560. return true;
  103561. }
  103562. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103563. {
  103564. FLAC__ASSERT(0 != encoder);
  103565. FLAC__ASSERT(0 != encoder->private_);
  103566. FLAC__ASSERT(0 != encoder->protected_);
  103567. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103568. return false;
  103569. encoder->private_->disable_verbatim_subframes = value;
  103570. return true;
  103571. }
  103572. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103573. {
  103574. FLAC__ASSERT(0 != encoder);
  103575. FLAC__ASSERT(0 != encoder->private_);
  103576. FLAC__ASSERT(0 != encoder->protected_);
  103577. return encoder->protected_->state;
  103578. }
  103579. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103580. {
  103581. FLAC__ASSERT(0 != encoder);
  103582. FLAC__ASSERT(0 != encoder->private_);
  103583. FLAC__ASSERT(0 != encoder->protected_);
  103584. if(encoder->protected_->verify)
  103585. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103586. else
  103587. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103588. }
  103589. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  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_VERIFY_DECODER_ERROR)
  103595. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103596. else
  103597. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103598. }
  103599. 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)
  103600. {
  103601. FLAC__ASSERT(0 != encoder);
  103602. FLAC__ASSERT(0 != encoder->private_);
  103603. FLAC__ASSERT(0 != encoder->protected_);
  103604. if(0 != absolute_sample)
  103605. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103606. if(0 != frame_number)
  103607. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103608. if(0 != channel)
  103609. *channel = encoder->private_->verify.error_stats.channel;
  103610. if(0 != sample)
  103611. *sample = encoder->private_->verify.error_stats.sample;
  103612. if(0 != expected)
  103613. *expected = encoder->private_->verify.error_stats.expected;
  103614. if(0 != got)
  103615. *got = encoder->private_->verify.error_stats.got;
  103616. }
  103617. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103618. {
  103619. FLAC__ASSERT(0 != encoder);
  103620. FLAC__ASSERT(0 != encoder->private_);
  103621. FLAC__ASSERT(0 != encoder->protected_);
  103622. return encoder->protected_->verify;
  103623. }
  103624. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103625. {
  103626. FLAC__ASSERT(0 != encoder);
  103627. FLAC__ASSERT(0 != encoder->private_);
  103628. FLAC__ASSERT(0 != encoder->protected_);
  103629. return encoder->protected_->streamable_subset;
  103630. }
  103631. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103632. {
  103633. FLAC__ASSERT(0 != encoder);
  103634. FLAC__ASSERT(0 != encoder->private_);
  103635. FLAC__ASSERT(0 != encoder->protected_);
  103636. return encoder->protected_->do_md5;
  103637. }
  103638. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103639. {
  103640. FLAC__ASSERT(0 != encoder);
  103641. FLAC__ASSERT(0 != encoder->private_);
  103642. FLAC__ASSERT(0 != encoder->protected_);
  103643. return encoder->protected_->channels;
  103644. }
  103645. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103646. {
  103647. FLAC__ASSERT(0 != encoder);
  103648. FLAC__ASSERT(0 != encoder->private_);
  103649. FLAC__ASSERT(0 != encoder->protected_);
  103650. return encoder->protected_->bits_per_sample;
  103651. }
  103652. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103653. {
  103654. FLAC__ASSERT(0 != encoder);
  103655. FLAC__ASSERT(0 != encoder->private_);
  103656. FLAC__ASSERT(0 != encoder->protected_);
  103657. return encoder->protected_->sample_rate;
  103658. }
  103659. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103660. {
  103661. FLAC__ASSERT(0 != encoder);
  103662. FLAC__ASSERT(0 != encoder->private_);
  103663. FLAC__ASSERT(0 != encoder->protected_);
  103664. return encoder->protected_->blocksize;
  103665. }
  103666. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103667. {
  103668. FLAC__ASSERT(0 != encoder);
  103669. FLAC__ASSERT(0 != encoder->private_);
  103670. FLAC__ASSERT(0 != encoder->protected_);
  103671. return encoder->protected_->do_mid_side_stereo;
  103672. }
  103673. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103674. {
  103675. FLAC__ASSERT(0 != encoder);
  103676. FLAC__ASSERT(0 != encoder->private_);
  103677. FLAC__ASSERT(0 != encoder->protected_);
  103678. return encoder->protected_->loose_mid_side_stereo;
  103679. }
  103680. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103681. {
  103682. FLAC__ASSERT(0 != encoder);
  103683. FLAC__ASSERT(0 != encoder->private_);
  103684. FLAC__ASSERT(0 != encoder->protected_);
  103685. return encoder->protected_->max_lpc_order;
  103686. }
  103687. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103688. {
  103689. FLAC__ASSERT(0 != encoder);
  103690. FLAC__ASSERT(0 != encoder->private_);
  103691. FLAC__ASSERT(0 != encoder->protected_);
  103692. return encoder->protected_->qlp_coeff_precision;
  103693. }
  103694. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103695. {
  103696. FLAC__ASSERT(0 != encoder);
  103697. FLAC__ASSERT(0 != encoder->private_);
  103698. FLAC__ASSERT(0 != encoder->protected_);
  103699. return encoder->protected_->do_qlp_coeff_prec_search;
  103700. }
  103701. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103702. {
  103703. FLAC__ASSERT(0 != encoder);
  103704. FLAC__ASSERT(0 != encoder->private_);
  103705. FLAC__ASSERT(0 != encoder->protected_);
  103706. return encoder->protected_->do_escape_coding;
  103707. }
  103708. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103709. {
  103710. FLAC__ASSERT(0 != encoder);
  103711. FLAC__ASSERT(0 != encoder->private_);
  103712. FLAC__ASSERT(0 != encoder->protected_);
  103713. return encoder->protected_->do_exhaustive_model_search;
  103714. }
  103715. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103716. {
  103717. FLAC__ASSERT(0 != encoder);
  103718. FLAC__ASSERT(0 != encoder->private_);
  103719. FLAC__ASSERT(0 != encoder->protected_);
  103720. return encoder->protected_->min_residual_partition_order;
  103721. }
  103722. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103723. {
  103724. FLAC__ASSERT(0 != encoder);
  103725. FLAC__ASSERT(0 != encoder->private_);
  103726. FLAC__ASSERT(0 != encoder->protected_);
  103727. return encoder->protected_->max_residual_partition_order;
  103728. }
  103729. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103730. {
  103731. FLAC__ASSERT(0 != encoder);
  103732. FLAC__ASSERT(0 != encoder->private_);
  103733. FLAC__ASSERT(0 != encoder->protected_);
  103734. return encoder->protected_->rice_parameter_search_dist;
  103735. }
  103736. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103737. {
  103738. FLAC__ASSERT(0 != encoder);
  103739. FLAC__ASSERT(0 != encoder->private_);
  103740. FLAC__ASSERT(0 != encoder->protected_);
  103741. return encoder->protected_->total_samples_estimate;
  103742. }
  103743. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103744. {
  103745. unsigned i, j = 0, channel;
  103746. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103747. FLAC__ASSERT(0 != encoder);
  103748. FLAC__ASSERT(0 != encoder->private_);
  103749. FLAC__ASSERT(0 != encoder->protected_);
  103750. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103751. do {
  103752. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103753. if(encoder->protected_->verify)
  103754. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103755. for(channel = 0; channel < channels; channel++)
  103756. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103757. if(encoder->protected_->do_mid_side_stereo) {
  103758. FLAC__ASSERT(channels == 2);
  103759. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103760. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103761. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103762. 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' ! */
  103763. }
  103764. }
  103765. else
  103766. j += n;
  103767. encoder->private_->current_sample_number += n;
  103768. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103769. if(encoder->private_->current_sample_number > blocksize) {
  103770. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103771. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103772. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103773. return false;
  103774. /* move unprocessed overread samples to beginnings of arrays */
  103775. for(channel = 0; channel < channels; channel++)
  103776. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103777. if(encoder->protected_->do_mid_side_stereo) {
  103778. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103779. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103780. }
  103781. encoder->private_->current_sample_number = 1;
  103782. }
  103783. } while(j < samples);
  103784. return true;
  103785. }
  103786. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103787. {
  103788. unsigned i, j, k, channel;
  103789. FLAC__int32 x, mid, side;
  103790. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103791. FLAC__ASSERT(0 != encoder);
  103792. FLAC__ASSERT(0 != encoder->private_);
  103793. FLAC__ASSERT(0 != encoder->protected_);
  103794. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103795. j = k = 0;
  103796. /*
  103797. * we have several flavors of the same basic loop, optimized for
  103798. * different conditions:
  103799. */
  103800. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103801. /*
  103802. * stereo coding: unroll channel loop
  103803. */
  103804. do {
  103805. if(encoder->protected_->verify)
  103806. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103807. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103808. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103809. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103810. x = buffer[k++];
  103811. encoder->private_->integer_signal[1][i] = x;
  103812. mid += x;
  103813. side -= x;
  103814. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103815. encoder->private_->integer_signal_mid_side[1][i] = side;
  103816. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103817. }
  103818. encoder->private_->current_sample_number = i;
  103819. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103820. if(i > blocksize) {
  103821. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103822. return false;
  103823. /* move unprocessed overread samples to beginnings of arrays */
  103824. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103825. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103826. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103827. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103828. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103829. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103830. encoder->private_->current_sample_number = 1;
  103831. }
  103832. } while(j < samples);
  103833. }
  103834. else {
  103835. /*
  103836. * independent channel coding: buffer each channel in inner loop
  103837. */
  103838. do {
  103839. if(encoder->protected_->verify)
  103840. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103841. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103842. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103843. for(channel = 0; channel < channels; channel++)
  103844. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103845. }
  103846. encoder->private_->current_sample_number = i;
  103847. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103848. if(i > blocksize) {
  103849. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103850. return false;
  103851. /* move unprocessed overread samples to beginnings of arrays */
  103852. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103853. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103854. for(channel = 0; channel < channels; channel++)
  103855. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103856. encoder->private_->current_sample_number = 1;
  103857. }
  103858. } while(j < samples);
  103859. }
  103860. return true;
  103861. }
  103862. /***********************************************************************
  103863. *
  103864. * Private class methods
  103865. *
  103866. ***********************************************************************/
  103867. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103868. {
  103869. FLAC__ASSERT(0 != encoder);
  103870. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103871. encoder->protected_->verify = true;
  103872. #else
  103873. encoder->protected_->verify = false;
  103874. #endif
  103875. encoder->protected_->streamable_subset = true;
  103876. encoder->protected_->do_md5 = true;
  103877. encoder->protected_->do_mid_side_stereo = false;
  103878. encoder->protected_->loose_mid_side_stereo = false;
  103879. encoder->protected_->channels = 2;
  103880. encoder->protected_->bits_per_sample = 16;
  103881. encoder->protected_->sample_rate = 44100;
  103882. encoder->protected_->blocksize = 0;
  103883. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103884. encoder->protected_->num_apodizations = 1;
  103885. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103886. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103887. #endif
  103888. encoder->protected_->max_lpc_order = 0;
  103889. encoder->protected_->qlp_coeff_precision = 0;
  103890. encoder->protected_->do_qlp_coeff_prec_search = false;
  103891. encoder->protected_->do_exhaustive_model_search = false;
  103892. encoder->protected_->do_escape_coding = false;
  103893. encoder->protected_->min_residual_partition_order = 0;
  103894. encoder->protected_->max_residual_partition_order = 0;
  103895. encoder->protected_->rice_parameter_search_dist = 0;
  103896. encoder->protected_->total_samples_estimate = 0;
  103897. encoder->protected_->metadata = 0;
  103898. encoder->protected_->num_metadata_blocks = 0;
  103899. encoder->private_->seek_table = 0;
  103900. encoder->private_->disable_constant_subframes = false;
  103901. encoder->private_->disable_fixed_subframes = false;
  103902. encoder->private_->disable_verbatim_subframes = false;
  103903. #if FLAC__HAS_OGG
  103904. encoder->private_->is_ogg = false;
  103905. #endif
  103906. encoder->private_->read_callback = 0;
  103907. encoder->private_->write_callback = 0;
  103908. encoder->private_->seek_callback = 0;
  103909. encoder->private_->tell_callback = 0;
  103910. encoder->private_->metadata_callback = 0;
  103911. encoder->private_->progress_callback = 0;
  103912. encoder->private_->client_data = 0;
  103913. #if FLAC__HAS_OGG
  103914. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103915. #endif
  103916. }
  103917. void free_(FLAC__StreamEncoder *encoder)
  103918. {
  103919. unsigned i, channel;
  103920. FLAC__ASSERT(0 != encoder);
  103921. if(encoder->protected_->metadata) {
  103922. free(encoder->protected_->metadata);
  103923. encoder->protected_->metadata = 0;
  103924. encoder->protected_->num_metadata_blocks = 0;
  103925. }
  103926. for(i = 0; i < encoder->protected_->channels; i++) {
  103927. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103928. free(encoder->private_->integer_signal_unaligned[i]);
  103929. encoder->private_->integer_signal_unaligned[i] = 0;
  103930. }
  103931. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103932. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103933. free(encoder->private_->real_signal_unaligned[i]);
  103934. encoder->private_->real_signal_unaligned[i] = 0;
  103935. }
  103936. #endif
  103937. }
  103938. for(i = 0; i < 2; i++) {
  103939. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103940. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103941. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103942. }
  103943. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103944. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103945. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103946. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103947. }
  103948. #endif
  103949. }
  103950. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103951. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103952. if(0 != encoder->private_->window_unaligned[i]) {
  103953. free(encoder->private_->window_unaligned[i]);
  103954. encoder->private_->window_unaligned[i] = 0;
  103955. }
  103956. }
  103957. if(0 != encoder->private_->windowed_signal_unaligned) {
  103958. free(encoder->private_->windowed_signal_unaligned);
  103959. encoder->private_->windowed_signal_unaligned = 0;
  103960. }
  103961. #endif
  103962. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103963. for(i = 0; i < 2; i++) {
  103964. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103965. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103966. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103967. }
  103968. }
  103969. }
  103970. for(channel = 0; channel < 2; channel++) {
  103971. for(i = 0; i < 2; i++) {
  103972. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103973. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103974. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103975. }
  103976. }
  103977. }
  103978. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103979. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103980. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103981. }
  103982. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103983. free(encoder->private_->raw_bits_per_partition_unaligned);
  103984. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103985. }
  103986. if(encoder->protected_->verify) {
  103987. for(i = 0; i < encoder->protected_->channels; i++) {
  103988. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103989. free(encoder->private_->verify.input_fifo.data[i]);
  103990. encoder->private_->verify.input_fifo.data[i] = 0;
  103991. }
  103992. }
  103993. }
  103994. FLAC__bitwriter_free(encoder->private_->frame);
  103995. }
  103996. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103997. {
  103998. FLAC__bool ok;
  103999. unsigned i, channel;
  104000. FLAC__ASSERT(new_blocksize > 0);
  104001. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104002. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104003. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104004. if(new_blocksize <= encoder->private_->input_capacity)
  104005. return true;
  104006. ok = true;
  104007. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104008. * requires that the input arrays (in our case the integer signals)
  104009. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104010. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104011. */
  104012. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104013. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104014. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104015. encoder->private_->integer_signal[i] += 4;
  104016. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104017. #if 0 /* @@@ currently unused */
  104018. if(encoder->protected_->max_lpc_order > 0)
  104019. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104020. #endif
  104021. #endif
  104022. }
  104023. for(i = 0; ok && i < 2; i++) {
  104024. 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]);
  104025. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104026. encoder->private_->integer_signal_mid_side[i] += 4;
  104027. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104028. #if 0 /* @@@ currently unused */
  104029. if(encoder->protected_->max_lpc_order > 0)
  104030. 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]);
  104031. #endif
  104032. #endif
  104033. }
  104034. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104035. if(ok && encoder->protected_->max_lpc_order > 0) {
  104036. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104037. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104038. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104039. }
  104040. #endif
  104041. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104042. for(i = 0; ok && i < 2; i++) {
  104043. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104044. }
  104045. }
  104046. for(channel = 0; ok && channel < 2; channel++) {
  104047. for(i = 0; ok && i < 2; i++) {
  104048. 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]);
  104049. }
  104050. }
  104051. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104052. /*@@@ 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) */
  104053. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104054. if(encoder->protected_->do_escape_coding)
  104055. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104056. /* now adjust the windows if the blocksize has changed */
  104057. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104058. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104059. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104060. switch(encoder->protected_->apodizations[i].type) {
  104061. case FLAC__APODIZATION_BARTLETT:
  104062. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104063. break;
  104064. case FLAC__APODIZATION_BARTLETT_HANN:
  104065. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104066. break;
  104067. case FLAC__APODIZATION_BLACKMAN:
  104068. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104069. break;
  104070. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104071. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104072. break;
  104073. case FLAC__APODIZATION_CONNES:
  104074. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104075. break;
  104076. case FLAC__APODIZATION_FLATTOP:
  104077. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104078. break;
  104079. case FLAC__APODIZATION_GAUSS:
  104080. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104081. break;
  104082. case FLAC__APODIZATION_HAMMING:
  104083. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104084. break;
  104085. case FLAC__APODIZATION_HANN:
  104086. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104087. break;
  104088. case FLAC__APODIZATION_KAISER_BESSEL:
  104089. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104090. break;
  104091. case FLAC__APODIZATION_NUTTALL:
  104092. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104093. break;
  104094. case FLAC__APODIZATION_RECTANGLE:
  104095. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104096. break;
  104097. case FLAC__APODIZATION_TRIANGLE:
  104098. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104099. break;
  104100. case FLAC__APODIZATION_TUKEY:
  104101. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104102. break;
  104103. case FLAC__APODIZATION_WELCH:
  104104. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104105. break;
  104106. default:
  104107. FLAC__ASSERT(0);
  104108. /* double protection */
  104109. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104110. break;
  104111. }
  104112. }
  104113. }
  104114. #endif
  104115. if(ok)
  104116. encoder->private_->input_capacity = new_blocksize;
  104117. else
  104118. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104119. return ok;
  104120. }
  104121. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104122. {
  104123. const FLAC__byte *buffer;
  104124. size_t bytes;
  104125. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104126. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104127. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104128. return false;
  104129. }
  104130. if(encoder->protected_->verify) {
  104131. encoder->private_->verify.output.data = buffer;
  104132. encoder->private_->verify.output.bytes = bytes;
  104133. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104134. encoder->private_->verify.needs_magic_hack = true;
  104135. }
  104136. else {
  104137. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104138. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104139. FLAC__bitwriter_clear(encoder->private_->frame);
  104140. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104141. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104142. return false;
  104143. }
  104144. }
  104145. }
  104146. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104147. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104148. FLAC__bitwriter_clear(encoder->private_->frame);
  104149. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104150. return false;
  104151. }
  104152. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104153. FLAC__bitwriter_clear(encoder->private_->frame);
  104154. if(samples > 0) {
  104155. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104156. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104157. }
  104158. return true;
  104159. }
  104160. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104161. {
  104162. FLAC__StreamEncoderWriteStatus status;
  104163. FLAC__uint64 output_position = 0;
  104164. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104165. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104166. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104167. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104168. }
  104169. /*
  104170. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104171. */
  104172. if(samples == 0) {
  104173. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104174. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104175. encoder->protected_->streaminfo_offset = output_position;
  104176. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104177. encoder->protected_->seektable_offset = output_position;
  104178. }
  104179. /*
  104180. * Mark the current seek point if hit (if audio_offset == 0 that
  104181. * means we're still writing metadata and haven't hit the first
  104182. * frame yet)
  104183. */
  104184. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104185. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104186. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104187. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104188. FLAC__uint64 test_sample;
  104189. unsigned i;
  104190. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104191. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104192. if(test_sample > frame_last_sample) {
  104193. break;
  104194. }
  104195. else if(test_sample >= frame_first_sample) {
  104196. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104197. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104198. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104199. encoder->private_->first_seekpoint_to_check++;
  104200. /* DO NOT: "break;" and here's why:
  104201. * The seektable template may contain more than one target
  104202. * sample for any given frame; we will keep looping, generating
  104203. * duplicate seekpoints for them, and we'll clean it up later,
  104204. * just before writing the seektable back to the metadata.
  104205. */
  104206. }
  104207. else {
  104208. encoder->private_->first_seekpoint_to_check++;
  104209. }
  104210. }
  104211. }
  104212. #if FLAC__HAS_OGG
  104213. if(encoder->private_->is_ogg) {
  104214. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104215. &encoder->protected_->ogg_encoder_aspect,
  104216. buffer,
  104217. bytes,
  104218. samples,
  104219. encoder->private_->current_frame_number,
  104220. is_last_block,
  104221. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104222. encoder,
  104223. encoder->private_->client_data
  104224. );
  104225. }
  104226. else
  104227. #endif
  104228. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104229. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104230. encoder->private_->bytes_written += bytes;
  104231. encoder->private_->samples_written += samples;
  104232. /* we keep a high watermark on the number of frames written because
  104233. * when the encoder goes back to write metadata, 'current_frame'
  104234. * will drop back to 0.
  104235. */
  104236. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104237. }
  104238. else
  104239. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104240. return status;
  104241. }
  104242. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104243. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104244. {
  104245. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104246. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104247. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104248. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104249. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104250. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104251. FLAC__StreamEncoderSeekStatus seek_status;
  104252. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104253. /* All this is based on intimate knowledge of the stream header
  104254. * layout, but a change to the header format that would break this
  104255. * would also break all streams encoded in the previous format.
  104256. */
  104257. /*
  104258. * Write MD5 signature
  104259. */
  104260. {
  104261. const unsigned md5_offset =
  104262. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104263. (
  104264. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104265. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104266. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104267. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104268. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104269. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104270. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104271. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104272. ) / 8;
  104273. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104274. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104275. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104276. return;
  104277. }
  104278. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104279. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104280. return;
  104281. }
  104282. }
  104283. /*
  104284. * Write total samples
  104285. */
  104286. {
  104287. const unsigned total_samples_byte_offset =
  104288. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104289. (
  104290. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104291. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104292. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104293. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104294. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104295. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104296. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104297. - 4
  104298. ) / 8;
  104299. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104300. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104301. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104302. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104303. b[4] = (FLAC__byte)(samples & 0xFF);
  104304. 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) {
  104305. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104306. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104307. return;
  104308. }
  104309. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104310. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104311. return;
  104312. }
  104313. }
  104314. /*
  104315. * Write min/max framesize
  104316. */
  104317. {
  104318. const unsigned min_framesize_offset =
  104319. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104320. (
  104321. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104322. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104323. ) / 8;
  104324. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104325. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104326. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104327. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104328. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104329. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104330. 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) {
  104331. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104332. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104333. return;
  104334. }
  104335. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104336. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104337. return;
  104338. }
  104339. }
  104340. /*
  104341. * Write seektable
  104342. */
  104343. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104344. unsigned i;
  104345. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104346. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104347. 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) {
  104348. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104349. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104350. return;
  104351. }
  104352. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104353. FLAC__uint64 xx;
  104354. unsigned x;
  104355. xx = encoder->private_->seek_table->points[i].sample_number;
  104356. b[7] = (FLAC__byte)xx; xx >>= 8;
  104357. b[6] = (FLAC__byte)xx; xx >>= 8;
  104358. b[5] = (FLAC__byte)xx; xx >>= 8;
  104359. b[4] = (FLAC__byte)xx; xx >>= 8;
  104360. b[3] = (FLAC__byte)xx; xx >>= 8;
  104361. b[2] = (FLAC__byte)xx; xx >>= 8;
  104362. b[1] = (FLAC__byte)xx; xx >>= 8;
  104363. b[0] = (FLAC__byte)xx; xx >>= 8;
  104364. xx = encoder->private_->seek_table->points[i].stream_offset;
  104365. b[15] = (FLAC__byte)xx; xx >>= 8;
  104366. b[14] = (FLAC__byte)xx; xx >>= 8;
  104367. b[13] = (FLAC__byte)xx; xx >>= 8;
  104368. b[12] = (FLAC__byte)xx; xx >>= 8;
  104369. b[11] = (FLAC__byte)xx; xx >>= 8;
  104370. b[10] = (FLAC__byte)xx; xx >>= 8;
  104371. b[9] = (FLAC__byte)xx; xx >>= 8;
  104372. b[8] = (FLAC__byte)xx; xx >>= 8;
  104373. x = encoder->private_->seek_table->points[i].frame_samples;
  104374. b[17] = (FLAC__byte)x; x >>= 8;
  104375. b[16] = (FLAC__byte)x; x >>= 8;
  104376. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104377. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104378. return;
  104379. }
  104380. }
  104381. }
  104382. }
  104383. #if FLAC__HAS_OGG
  104384. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104385. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104386. {
  104387. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104388. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104389. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104390. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104391. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104392. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104393. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104394. FLAC__STREAM_SYNC_LENGTH
  104395. ;
  104396. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104397. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104398. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104399. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104400. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104401. ogg_page page;
  104402. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104403. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104404. /* Pre-check that client supports seeking, since we don't want the
  104405. * ogg_helper code to ever have to deal with this condition.
  104406. */
  104407. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104408. return;
  104409. /* All this is based on intimate knowledge of the stream header
  104410. * layout, but a change to the header format that would break this
  104411. * would also break all streams encoded in the previous format.
  104412. */
  104413. /**
  104414. ** Write STREAMINFO stats
  104415. **/
  104416. simple_ogg_page__init(&page);
  104417. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104418. simple_ogg_page__clear(&page);
  104419. return; /* state already set */
  104420. }
  104421. /*
  104422. * Write MD5 signature
  104423. */
  104424. {
  104425. const unsigned md5_offset =
  104426. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104427. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104428. (
  104429. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104430. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104431. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104432. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104433. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104434. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104435. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104436. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104437. ) / 8;
  104438. if(md5_offset + 16 > (unsigned)page.body_len) {
  104439. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104440. simple_ogg_page__clear(&page);
  104441. return;
  104442. }
  104443. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104444. }
  104445. /*
  104446. * Write total samples
  104447. */
  104448. {
  104449. const unsigned total_samples_byte_offset =
  104450. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104451. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104452. (
  104453. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104454. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104455. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104456. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104457. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104458. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104459. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104460. - 4
  104461. ) / 8;
  104462. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104463. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104464. simple_ogg_page__clear(&page);
  104465. return;
  104466. }
  104467. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104468. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104469. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104470. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104471. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104472. b[4] = (FLAC__byte)(samples & 0xFF);
  104473. memcpy(page.body + total_samples_byte_offset, b, 5);
  104474. }
  104475. /*
  104476. * Write min/max framesize
  104477. */
  104478. {
  104479. const unsigned min_framesize_offset =
  104480. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  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. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104487. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104488. simple_ogg_page__clear(&page);
  104489. return;
  104490. }
  104491. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104492. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104493. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104494. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104495. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104496. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104497. memcpy(page.body + min_framesize_offset, b, 6);
  104498. }
  104499. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104500. simple_ogg_page__clear(&page);
  104501. return; /* state already set */
  104502. }
  104503. simple_ogg_page__clear(&page);
  104504. /*
  104505. * Write seektable
  104506. */
  104507. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104508. unsigned i;
  104509. FLAC__byte *p;
  104510. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104511. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104512. simple_ogg_page__init(&page);
  104513. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104514. simple_ogg_page__clear(&page);
  104515. return; /* state already set */
  104516. }
  104517. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104518. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104519. simple_ogg_page__clear(&page);
  104520. return;
  104521. }
  104522. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104523. FLAC__uint64 xx;
  104524. unsigned x;
  104525. xx = encoder->private_->seek_table->points[i].sample_number;
  104526. b[7] = (FLAC__byte)xx; xx >>= 8;
  104527. b[6] = (FLAC__byte)xx; xx >>= 8;
  104528. b[5] = (FLAC__byte)xx; xx >>= 8;
  104529. b[4] = (FLAC__byte)xx; xx >>= 8;
  104530. b[3] = (FLAC__byte)xx; xx >>= 8;
  104531. b[2] = (FLAC__byte)xx; xx >>= 8;
  104532. b[1] = (FLAC__byte)xx; xx >>= 8;
  104533. b[0] = (FLAC__byte)xx; xx >>= 8;
  104534. xx = encoder->private_->seek_table->points[i].stream_offset;
  104535. b[15] = (FLAC__byte)xx; xx >>= 8;
  104536. b[14] = (FLAC__byte)xx; xx >>= 8;
  104537. b[13] = (FLAC__byte)xx; xx >>= 8;
  104538. b[12] = (FLAC__byte)xx; xx >>= 8;
  104539. b[11] = (FLAC__byte)xx; xx >>= 8;
  104540. b[10] = (FLAC__byte)xx; xx >>= 8;
  104541. b[9] = (FLAC__byte)xx; xx >>= 8;
  104542. b[8] = (FLAC__byte)xx; xx >>= 8;
  104543. x = encoder->private_->seek_table->points[i].frame_samples;
  104544. b[17] = (FLAC__byte)x; x >>= 8;
  104545. b[16] = (FLAC__byte)x; x >>= 8;
  104546. memcpy(p, b, 18);
  104547. }
  104548. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104549. simple_ogg_page__clear(&page);
  104550. return; /* state already set */
  104551. }
  104552. simple_ogg_page__clear(&page);
  104553. }
  104554. }
  104555. #endif
  104556. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104557. {
  104558. FLAC__uint16 crc;
  104559. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104560. /*
  104561. * Accumulate raw signal to the MD5 signature
  104562. */
  104563. 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)) {
  104564. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104565. return false;
  104566. }
  104567. /*
  104568. * Process the frame header and subframes into the frame bitbuffer
  104569. */
  104570. if(!process_subframes_(encoder, is_fractional_block)) {
  104571. /* the above function sets the state for us in case of an error */
  104572. return false;
  104573. }
  104574. /*
  104575. * Zero-pad the frame to a byte_boundary
  104576. */
  104577. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104578. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104579. return false;
  104580. }
  104581. /*
  104582. * CRC-16 the whole thing
  104583. */
  104584. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104585. if(
  104586. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104587. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104588. ) {
  104589. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104590. return false;
  104591. }
  104592. /*
  104593. * Write it
  104594. */
  104595. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104596. /* the above function sets the state for us in case of an error */
  104597. return false;
  104598. }
  104599. /*
  104600. * Get ready for the next frame
  104601. */
  104602. encoder->private_->current_sample_number = 0;
  104603. encoder->private_->current_frame_number++;
  104604. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104605. return true;
  104606. }
  104607. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104608. {
  104609. FLAC__FrameHeader frame_header;
  104610. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104611. FLAC__bool do_independent, do_mid_side;
  104612. /*
  104613. * Calculate the min,max Rice partition orders
  104614. */
  104615. if(is_fractional_block) {
  104616. max_partition_order = 0;
  104617. }
  104618. else {
  104619. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104620. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104621. }
  104622. min_partition_order = min(min_partition_order, max_partition_order);
  104623. /*
  104624. * Setup the frame
  104625. */
  104626. frame_header.blocksize = encoder->protected_->blocksize;
  104627. frame_header.sample_rate = encoder->protected_->sample_rate;
  104628. frame_header.channels = encoder->protected_->channels;
  104629. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104630. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104631. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104632. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104633. /*
  104634. * Figure out what channel assignments to try
  104635. */
  104636. if(encoder->protected_->do_mid_side_stereo) {
  104637. if(encoder->protected_->loose_mid_side_stereo) {
  104638. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104639. do_independent = true;
  104640. do_mid_side = true;
  104641. }
  104642. else {
  104643. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104644. do_mid_side = !do_independent;
  104645. }
  104646. }
  104647. else {
  104648. do_independent = true;
  104649. do_mid_side = true;
  104650. }
  104651. }
  104652. else {
  104653. do_independent = true;
  104654. do_mid_side = false;
  104655. }
  104656. FLAC__ASSERT(do_independent || do_mid_side);
  104657. /*
  104658. * Check for wasted bits; set effective bps for each subframe
  104659. */
  104660. if(do_independent) {
  104661. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104662. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104663. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104664. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104665. }
  104666. }
  104667. if(do_mid_side) {
  104668. FLAC__ASSERT(encoder->protected_->channels == 2);
  104669. for(channel = 0; channel < 2; channel++) {
  104670. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104671. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104672. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104673. }
  104674. }
  104675. /*
  104676. * First do a normal encoding pass of each independent channel
  104677. */
  104678. if(do_independent) {
  104679. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104680. if(!
  104681. process_subframe_(
  104682. encoder,
  104683. min_partition_order,
  104684. max_partition_order,
  104685. &frame_header,
  104686. encoder->private_->subframe_bps[channel],
  104687. encoder->private_->integer_signal[channel],
  104688. encoder->private_->subframe_workspace_ptr[channel],
  104689. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104690. encoder->private_->residual_workspace[channel],
  104691. encoder->private_->best_subframe+channel,
  104692. encoder->private_->best_subframe_bits+channel
  104693. )
  104694. )
  104695. return false;
  104696. }
  104697. }
  104698. /*
  104699. * Now do mid and side channels if requested
  104700. */
  104701. if(do_mid_side) {
  104702. FLAC__ASSERT(encoder->protected_->channels == 2);
  104703. for(channel = 0; channel < 2; channel++) {
  104704. if(!
  104705. process_subframe_(
  104706. encoder,
  104707. min_partition_order,
  104708. max_partition_order,
  104709. &frame_header,
  104710. encoder->private_->subframe_bps_mid_side[channel],
  104711. encoder->private_->integer_signal_mid_side[channel],
  104712. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104713. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104714. encoder->private_->residual_workspace_mid_side[channel],
  104715. encoder->private_->best_subframe_mid_side+channel,
  104716. encoder->private_->best_subframe_bits_mid_side+channel
  104717. )
  104718. )
  104719. return false;
  104720. }
  104721. }
  104722. /*
  104723. * Compose the frame bitbuffer
  104724. */
  104725. if(do_mid_side) {
  104726. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104727. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104728. FLAC__ChannelAssignment channel_assignment;
  104729. FLAC__ASSERT(encoder->protected_->channels == 2);
  104730. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104731. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104732. }
  104733. else {
  104734. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104735. unsigned min_bits;
  104736. int ca;
  104737. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104738. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104739. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104740. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104741. FLAC__ASSERT(do_independent && do_mid_side);
  104742. /* We have to figure out which channel assignent results in the smallest frame */
  104743. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104744. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104745. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104746. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104747. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104748. min_bits = bits[channel_assignment];
  104749. for(ca = 1; ca <= 3; ca++) {
  104750. if(bits[ca] < min_bits) {
  104751. min_bits = bits[ca];
  104752. channel_assignment = (FLAC__ChannelAssignment)ca;
  104753. }
  104754. }
  104755. }
  104756. frame_header.channel_assignment = channel_assignment;
  104757. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104758. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104759. return false;
  104760. }
  104761. switch(channel_assignment) {
  104762. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104763. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104764. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104765. break;
  104766. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104767. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104768. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104769. break;
  104770. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104771. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104772. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104773. break;
  104774. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104775. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104776. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104777. break;
  104778. default:
  104779. FLAC__ASSERT(0);
  104780. }
  104781. switch(channel_assignment) {
  104782. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104783. left_bps = encoder->private_->subframe_bps [0];
  104784. right_bps = encoder->private_->subframe_bps [1];
  104785. break;
  104786. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104787. left_bps = encoder->private_->subframe_bps [0];
  104788. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104789. break;
  104790. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104791. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104792. right_bps = encoder->private_->subframe_bps [1];
  104793. break;
  104794. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104795. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104796. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104797. break;
  104798. default:
  104799. FLAC__ASSERT(0);
  104800. }
  104801. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104802. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104803. return false;
  104804. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104805. return false;
  104806. }
  104807. else {
  104808. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104809. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104810. return false;
  104811. }
  104812. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104813. 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)) {
  104814. /* the above function sets the state for us in case of an error */
  104815. return false;
  104816. }
  104817. }
  104818. }
  104819. if(encoder->protected_->loose_mid_side_stereo) {
  104820. encoder->private_->loose_mid_side_stereo_frame_count++;
  104821. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104822. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104823. }
  104824. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104825. return true;
  104826. }
  104827. FLAC__bool process_subframe_(
  104828. FLAC__StreamEncoder *encoder,
  104829. unsigned min_partition_order,
  104830. unsigned max_partition_order,
  104831. const FLAC__FrameHeader *frame_header,
  104832. unsigned subframe_bps,
  104833. const FLAC__int32 integer_signal[],
  104834. FLAC__Subframe *subframe[2],
  104835. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104836. FLAC__int32 *residual[2],
  104837. unsigned *best_subframe,
  104838. unsigned *best_bits
  104839. )
  104840. {
  104841. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104842. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104843. #else
  104844. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104845. #endif
  104846. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104847. FLAC__double lpc_residual_bits_per_sample;
  104848. 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 */
  104849. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104850. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104851. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104852. #endif
  104853. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104854. unsigned rice_parameter;
  104855. unsigned _candidate_bits, _best_bits;
  104856. unsigned _best_subframe;
  104857. /* only use RICE2 partitions if stream bps > 16 */
  104858. 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;
  104859. FLAC__ASSERT(frame_header->blocksize > 0);
  104860. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104861. _best_subframe = 0;
  104862. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104863. _best_bits = UINT_MAX;
  104864. else
  104865. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104866. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104867. unsigned signal_is_constant = false;
  104868. 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);
  104869. /* check for constant subframe */
  104870. if(
  104871. !encoder->private_->disable_constant_subframes &&
  104872. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104873. fixed_residual_bits_per_sample[1] == 0.0
  104874. #else
  104875. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104876. #endif
  104877. ) {
  104878. /* the above means it's possible all samples are the same value; now double-check it: */
  104879. unsigned i;
  104880. signal_is_constant = true;
  104881. for(i = 1; i < frame_header->blocksize; i++) {
  104882. if(integer_signal[0] != integer_signal[i]) {
  104883. signal_is_constant = false;
  104884. break;
  104885. }
  104886. }
  104887. }
  104888. if(signal_is_constant) {
  104889. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104890. if(_candidate_bits < _best_bits) {
  104891. _best_subframe = !_best_subframe;
  104892. _best_bits = _candidate_bits;
  104893. }
  104894. }
  104895. else {
  104896. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104897. /* encode fixed */
  104898. if(encoder->protected_->do_exhaustive_model_search) {
  104899. min_fixed_order = 0;
  104900. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104901. }
  104902. else {
  104903. min_fixed_order = max_fixed_order = guess_fixed_order;
  104904. }
  104905. if(max_fixed_order >= frame_header->blocksize)
  104906. max_fixed_order = frame_header->blocksize - 1;
  104907. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104908. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104909. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104910. continue; /* don't even try */
  104911. 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 */
  104912. #else
  104913. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104914. continue; /* don't even try */
  104915. 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 */
  104916. #endif
  104917. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104918. if(rice_parameter >= rice_parameter_limit) {
  104919. #ifdef DEBUG_VERBOSE
  104920. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104921. #endif
  104922. rice_parameter = rice_parameter_limit - 1;
  104923. }
  104924. _candidate_bits =
  104925. evaluate_fixed_subframe_(
  104926. encoder,
  104927. integer_signal,
  104928. residual[!_best_subframe],
  104929. encoder->private_->abs_residual_partition_sums,
  104930. encoder->private_->raw_bits_per_partition,
  104931. frame_header->blocksize,
  104932. subframe_bps,
  104933. fixed_order,
  104934. rice_parameter,
  104935. rice_parameter_limit,
  104936. min_partition_order,
  104937. max_partition_order,
  104938. encoder->protected_->do_escape_coding,
  104939. encoder->protected_->rice_parameter_search_dist,
  104940. subframe[!_best_subframe],
  104941. partitioned_rice_contents[!_best_subframe]
  104942. );
  104943. if(_candidate_bits < _best_bits) {
  104944. _best_subframe = !_best_subframe;
  104945. _best_bits = _candidate_bits;
  104946. }
  104947. }
  104948. }
  104949. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104950. /* encode lpc */
  104951. if(encoder->protected_->max_lpc_order > 0) {
  104952. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104953. max_lpc_order = frame_header->blocksize-1;
  104954. else
  104955. max_lpc_order = encoder->protected_->max_lpc_order;
  104956. if(max_lpc_order > 0) {
  104957. unsigned a;
  104958. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104959. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104960. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104961. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104962. if(autoc[0] != 0.0) {
  104963. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104964. if(encoder->protected_->do_exhaustive_model_search) {
  104965. min_lpc_order = 1;
  104966. }
  104967. else {
  104968. const unsigned guess_lpc_order =
  104969. FLAC__lpc_compute_best_order(
  104970. lpc_error,
  104971. max_lpc_order,
  104972. frame_header->blocksize,
  104973. subframe_bps + (
  104974. encoder->protected_->do_qlp_coeff_prec_search?
  104975. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104976. encoder->protected_->qlp_coeff_precision
  104977. )
  104978. );
  104979. min_lpc_order = max_lpc_order = guess_lpc_order;
  104980. }
  104981. if(max_lpc_order >= frame_header->blocksize)
  104982. max_lpc_order = frame_header->blocksize - 1;
  104983. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104984. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104985. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104986. continue; /* don't even try */
  104987. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104988. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104989. if(rice_parameter >= rice_parameter_limit) {
  104990. #ifdef DEBUG_VERBOSE
  104991. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104992. #endif
  104993. rice_parameter = rice_parameter_limit - 1;
  104994. }
  104995. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104996. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104997. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104998. if(subframe_bps <= 17) {
  104999. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105000. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105001. }
  105002. else
  105003. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105004. }
  105005. else {
  105006. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105007. }
  105008. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105009. _candidate_bits =
  105010. evaluate_lpc_subframe_(
  105011. encoder,
  105012. integer_signal,
  105013. residual[!_best_subframe],
  105014. encoder->private_->abs_residual_partition_sums,
  105015. encoder->private_->raw_bits_per_partition,
  105016. encoder->private_->lp_coeff[lpc_order-1],
  105017. frame_header->blocksize,
  105018. subframe_bps,
  105019. lpc_order,
  105020. qlp_coeff_precision,
  105021. rice_parameter,
  105022. rice_parameter_limit,
  105023. min_partition_order,
  105024. max_partition_order,
  105025. encoder->protected_->do_escape_coding,
  105026. encoder->protected_->rice_parameter_search_dist,
  105027. subframe[!_best_subframe],
  105028. partitioned_rice_contents[!_best_subframe]
  105029. );
  105030. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105031. if(_candidate_bits < _best_bits) {
  105032. _best_subframe = !_best_subframe;
  105033. _best_bits = _candidate_bits;
  105034. }
  105035. }
  105036. }
  105037. }
  105038. }
  105039. }
  105040. }
  105041. }
  105042. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105043. }
  105044. }
  105045. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105046. if(_best_bits == UINT_MAX) {
  105047. FLAC__ASSERT(_best_subframe == 0);
  105048. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105049. }
  105050. *best_subframe = _best_subframe;
  105051. *best_bits = _best_bits;
  105052. return true;
  105053. }
  105054. FLAC__bool add_subframe_(
  105055. FLAC__StreamEncoder *encoder,
  105056. unsigned blocksize,
  105057. unsigned subframe_bps,
  105058. const FLAC__Subframe *subframe,
  105059. FLAC__BitWriter *frame
  105060. )
  105061. {
  105062. switch(subframe->type) {
  105063. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105064. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105065. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105066. return false;
  105067. }
  105068. break;
  105069. case FLAC__SUBFRAME_TYPE_FIXED:
  105070. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105071. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105072. return false;
  105073. }
  105074. break;
  105075. case FLAC__SUBFRAME_TYPE_LPC:
  105076. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105077. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105078. return false;
  105079. }
  105080. break;
  105081. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105082. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105083. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105084. return false;
  105085. }
  105086. break;
  105087. default:
  105088. FLAC__ASSERT(0);
  105089. }
  105090. return true;
  105091. }
  105092. #define SPOTCHECK_ESTIMATE 0
  105093. #if SPOTCHECK_ESTIMATE
  105094. static void spotcheck_subframe_estimate_(
  105095. FLAC__StreamEncoder *encoder,
  105096. unsigned blocksize,
  105097. unsigned subframe_bps,
  105098. const FLAC__Subframe *subframe,
  105099. unsigned estimate
  105100. )
  105101. {
  105102. FLAC__bool ret;
  105103. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105104. if(frame == 0) {
  105105. fprintf(stderr, "EST: can't allocate frame\n");
  105106. return;
  105107. }
  105108. if(!FLAC__bitwriter_init(frame)) {
  105109. fprintf(stderr, "EST: can't init frame\n");
  105110. return;
  105111. }
  105112. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105113. FLAC__ASSERT(ret);
  105114. {
  105115. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105116. if(estimate != actual)
  105117. 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);
  105118. }
  105119. FLAC__bitwriter_delete(frame);
  105120. }
  105121. #endif
  105122. unsigned evaluate_constant_subframe_(
  105123. FLAC__StreamEncoder *encoder,
  105124. const FLAC__int32 signal,
  105125. unsigned blocksize,
  105126. unsigned subframe_bps,
  105127. FLAC__Subframe *subframe
  105128. )
  105129. {
  105130. unsigned estimate;
  105131. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105132. subframe->data.constant.value = signal;
  105133. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105134. #if SPOTCHECK_ESTIMATE
  105135. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105136. #else
  105137. (void)encoder, (void)blocksize;
  105138. #endif
  105139. return estimate;
  105140. }
  105141. unsigned evaluate_fixed_subframe_(
  105142. FLAC__StreamEncoder *encoder,
  105143. const FLAC__int32 signal[],
  105144. FLAC__int32 residual[],
  105145. FLAC__uint64 abs_residual_partition_sums[],
  105146. unsigned raw_bits_per_partition[],
  105147. unsigned blocksize,
  105148. unsigned subframe_bps,
  105149. unsigned order,
  105150. unsigned rice_parameter,
  105151. unsigned rice_parameter_limit,
  105152. unsigned min_partition_order,
  105153. unsigned max_partition_order,
  105154. FLAC__bool do_escape_coding,
  105155. unsigned rice_parameter_search_dist,
  105156. FLAC__Subframe *subframe,
  105157. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105158. )
  105159. {
  105160. unsigned i, residual_bits, estimate;
  105161. const unsigned residual_samples = blocksize - order;
  105162. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105163. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105164. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105165. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105166. subframe->data.fixed.residual = residual;
  105167. residual_bits =
  105168. find_best_partition_order_(
  105169. encoder->private_,
  105170. residual,
  105171. abs_residual_partition_sums,
  105172. raw_bits_per_partition,
  105173. residual_samples,
  105174. order,
  105175. rice_parameter,
  105176. rice_parameter_limit,
  105177. min_partition_order,
  105178. max_partition_order,
  105179. subframe_bps,
  105180. do_escape_coding,
  105181. rice_parameter_search_dist,
  105182. &subframe->data.fixed.entropy_coding_method
  105183. );
  105184. subframe->data.fixed.order = order;
  105185. for(i = 0; i < order; i++)
  105186. subframe->data.fixed.warmup[i] = signal[i];
  105187. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105188. #if SPOTCHECK_ESTIMATE
  105189. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105190. #endif
  105191. return estimate;
  105192. }
  105193. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105194. unsigned evaluate_lpc_subframe_(
  105195. FLAC__StreamEncoder *encoder,
  105196. const FLAC__int32 signal[],
  105197. FLAC__int32 residual[],
  105198. FLAC__uint64 abs_residual_partition_sums[],
  105199. unsigned raw_bits_per_partition[],
  105200. const FLAC__real lp_coeff[],
  105201. unsigned blocksize,
  105202. unsigned subframe_bps,
  105203. unsigned order,
  105204. unsigned qlp_coeff_precision,
  105205. unsigned rice_parameter,
  105206. unsigned rice_parameter_limit,
  105207. unsigned min_partition_order,
  105208. unsigned max_partition_order,
  105209. FLAC__bool do_escape_coding,
  105210. unsigned rice_parameter_search_dist,
  105211. FLAC__Subframe *subframe,
  105212. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105213. )
  105214. {
  105215. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105216. unsigned i, residual_bits, estimate;
  105217. int quantization, ret;
  105218. const unsigned residual_samples = blocksize - order;
  105219. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105220. if(subframe_bps <= 16) {
  105221. FLAC__ASSERT(order > 0);
  105222. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105223. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105224. }
  105225. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105226. if(ret != 0)
  105227. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105228. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105229. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105230. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105231. else
  105232. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105233. else
  105234. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105235. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105236. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105237. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105238. subframe->data.lpc.residual = residual;
  105239. residual_bits =
  105240. find_best_partition_order_(
  105241. encoder->private_,
  105242. residual,
  105243. abs_residual_partition_sums,
  105244. raw_bits_per_partition,
  105245. residual_samples,
  105246. order,
  105247. rice_parameter,
  105248. rice_parameter_limit,
  105249. min_partition_order,
  105250. max_partition_order,
  105251. subframe_bps,
  105252. do_escape_coding,
  105253. rice_parameter_search_dist,
  105254. &subframe->data.lpc.entropy_coding_method
  105255. );
  105256. subframe->data.lpc.order = order;
  105257. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105258. subframe->data.lpc.quantization_level = quantization;
  105259. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105260. for(i = 0; i < order; i++)
  105261. subframe->data.lpc.warmup[i] = signal[i];
  105262. 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;
  105263. #if SPOTCHECK_ESTIMATE
  105264. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105265. #endif
  105266. return estimate;
  105267. }
  105268. #endif
  105269. unsigned evaluate_verbatim_subframe_(
  105270. FLAC__StreamEncoder *encoder,
  105271. const FLAC__int32 signal[],
  105272. unsigned blocksize,
  105273. unsigned subframe_bps,
  105274. FLAC__Subframe *subframe
  105275. )
  105276. {
  105277. unsigned estimate;
  105278. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105279. subframe->data.verbatim.data = signal;
  105280. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105281. #if SPOTCHECK_ESTIMATE
  105282. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105283. #else
  105284. (void)encoder;
  105285. #endif
  105286. return estimate;
  105287. }
  105288. unsigned find_best_partition_order_(
  105289. FLAC__StreamEncoderPrivate *private_,
  105290. const FLAC__int32 residual[],
  105291. FLAC__uint64 abs_residual_partition_sums[],
  105292. unsigned raw_bits_per_partition[],
  105293. unsigned residual_samples,
  105294. unsigned predictor_order,
  105295. unsigned rice_parameter,
  105296. unsigned rice_parameter_limit,
  105297. unsigned min_partition_order,
  105298. unsigned max_partition_order,
  105299. unsigned bps,
  105300. FLAC__bool do_escape_coding,
  105301. unsigned rice_parameter_search_dist,
  105302. FLAC__EntropyCodingMethod *best_ecm
  105303. )
  105304. {
  105305. unsigned residual_bits, best_residual_bits = 0;
  105306. unsigned best_parameters_index = 0;
  105307. unsigned best_partition_order = 0;
  105308. const unsigned blocksize = residual_samples + predictor_order;
  105309. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105310. min_partition_order = min(min_partition_order, max_partition_order);
  105311. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105312. if(do_escape_coding)
  105313. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105314. {
  105315. int partition_order;
  105316. unsigned sum;
  105317. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105318. if(!
  105319. set_partitioned_rice_(
  105320. #ifdef EXACT_RICE_BITS_CALCULATION
  105321. residual,
  105322. #endif
  105323. abs_residual_partition_sums+sum,
  105324. raw_bits_per_partition+sum,
  105325. residual_samples,
  105326. predictor_order,
  105327. rice_parameter,
  105328. rice_parameter_limit,
  105329. rice_parameter_search_dist,
  105330. (unsigned)partition_order,
  105331. do_escape_coding,
  105332. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105333. &residual_bits
  105334. )
  105335. )
  105336. {
  105337. FLAC__ASSERT(best_residual_bits != 0);
  105338. break;
  105339. }
  105340. sum += 1u << partition_order;
  105341. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105342. best_residual_bits = residual_bits;
  105343. best_parameters_index = !best_parameters_index;
  105344. best_partition_order = partition_order;
  105345. }
  105346. }
  105347. }
  105348. best_ecm->data.partitioned_rice.order = best_partition_order;
  105349. {
  105350. /*
  105351. * We are allowed to de-const the pointer based on our special
  105352. * knowledge; it is const to the outside world.
  105353. */
  105354. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105355. unsigned partition;
  105356. /* save best parameters and raw_bits */
  105357. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105358. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105359. if(do_escape_coding)
  105360. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105361. /*
  105362. * Now need to check if the type should be changed to
  105363. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105364. * size of the rice parameters.
  105365. */
  105366. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105367. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105368. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105369. break;
  105370. }
  105371. }
  105372. }
  105373. return best_residual_bits;
  105374. }
  105375. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105376. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105377. const FLAC__int32 residual[],
  105378. FLAC__uint64 abs_residual_partition_sums[],
  105379. unsigned blocksize,
  105380. unsigned predictor_order,
  105381. unsigned min_partition_order,
  105382. unsigned max_partition_order
  105383. );
  105384. #endif
  105385. void precompute_partition_info_sums_(
  105386. const FLAC__int32 residual[],
  105387. FLAC__uint64 abs_residual_partition_sums[],
  105388. unsigned residual_samples,
  105389. unsigned predictor_order,
  105390. unsigned min_partition_order,
  105391. unsigned max_partition_order,
  105392. unsigned bps
  105393. )
  105394. {
  105395. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105396. unsigned partitions = 1u << max_partition_order;
  105397. FLAC__ASSERT(default_partition_samples > predictor_order);
  105398. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105399. /* slightly pessimistic but still catches all common cases */
  105400. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105401. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105402. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105403. return;
  105404. }
  105405. #endif
  105406. /* first do max_partition_order */
  105407. {
  105408. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105409. /* slightly pessimistic but still catches all common cases */
  105410. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105411. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105412. FLAC__uint32 abs_residual_partition_sum;
  105413. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105414. end += default_partition_samples;
  105415. abs_residual_partition_sum = 0;
  105416. for( ; residual_sample < end; residual_sample++)
  105417. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105418. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105419. }
  105420. }
  105421. else { /* have to pessimistically use 64 bits for accumulator */
  105422. FLAC__uint64 abs_residual_partition_sum;
  105423. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105424. end += default_partition_samples;
  105425. abs_residual_partition_sum = 0;
  105426. for( ; residual_sample < end; residual_sample++)
  105427. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105428. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105429. }
  105430. }
  105431. }
  105432. /* now merge partitions for lower orders */
  105433. {
  105434. unsigned from_partition = 0, to_partition = partitions;
  105435. int partition_order;
  105436. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105437. unsigned i;
  105438. partitions >>= 1;
  105439. for(i = 0; i < partitions; i++) {
  105440. abs_residual_partition_sums[to_partition++] =
  105441. abs_residual_partition_sums[from_partition ] +
  105442. abs_residual_partition_sums[from_partition+1];
  105443. from_partition += 2;
  105444. }
  105445. }
  105446. }
  105447. }
  105448. void precompute_partition_info_escapes_(
  105449. const FLAC__int32 residual[],
  105450. unsigned raw_bits_per_partition[],
  105451. unsigned residual_samples,
  105452. unsigned predictor_order,
  105453. unsigned min_partition_order,
  105454. unsigned max_partition_order
  105455. )
  105456. {
  105457. int partition_order;
  105458. unsigned from_partition, to_partition = 0;
  105459. const unsigned blocksize = residual_samples + predictor_order;
  105460. /* first do max_partition_order */
  105461. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105462. FLAC__int32 r;
  105463. FLAC__uint32 rmax;
  105464. unsigned partition, partition_sample, partition_samples, residual_sample;
  105465. const unsigned partitions = 1u << partition_order;
  105466. const unsigned default_partition_samples = blocksize >> partition_order;
  105467. FLAC__ASSERT(default_partition_samples > predictor_order);
  105468. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105469. partition_samples = default_partition_samples;
  105470. if(partition == 0)
  105471. partition_samples -= predictor_order;
  105472. rmax = 0;
  105473. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105474. r = residual[residual_sample++];
  105475. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105476. if(r < 0)
  105477. rmax |= ~r;
  105478. else
  105479. rmax |= r;
  105480. }
  105481. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105482. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105483. }
  105484. to_partition = partitions;
  105485. break; /*@@@ yuck, should remove the 'for' loop instead */
  105486. }
  105487. /* now merge partitions for lower orders */
  105488. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105489. unsigned m;
  105490. unsigned i;
  105491. const unsigned partitions = 1u << partition_order;
  105492. for(i = 0; i < partitions; i++) {
  105493. m = raw_bits_per_partition[from_partition];
  105494. from_partition++;
  105495. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105496. from_partition++;
  105497. to_partition++;
  105498. }
  105499. }
  105500. }
  105501. #ifdef EXACT_RICE_BITS_CALCULATION
  105502. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105503. const unsigned rice_parameter,
  105504. const unsigned partition_samples,
  105505. const FLAC__int32 *residual
  105506. )
  105507. {
  105508. unsigned i, partition_bits =
  105509. 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 */
  105510. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105511. ;
  105512. for(i = 0; i < partition_samples; i++)
  105513. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105514. return partition_bits;
  105515. }
  105516. #else
  105517. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105518. const unsigned rice_parameter,
  105519. const unsigned partition_samples,
  105520. const FLAC__uint64 abs_residual_partition_sum
  105521. )
  105522. {
  105523. return
  105524. 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 */
  105525. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105526. (
  105527. rice_parameter?
  105528. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105529. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105530. )
  105531. - (partition_samples >> 1)
  105532. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105533. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105534. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105535. * So the subtraction term tries to guess how many extra bits were contributed.
  105536. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105537. */
  105538. ;
  105539. }
  105540. #endif
  105541. FLAC__bool set_partitioned_rice_(
  105542. #ifdef EXACT_RICE_BITS_CALCULATION
  105543. const FLAC__int32 residual[],
  105544. #endif
  105545. const FLAC__uint64 abs_residual_partition_sums[],
  105546. const unsigned raw_bits_per_partition[],
  105547. const unsigned residual_samples,
  105548. const unsigned predictor_order,
  105549. const unsigned suggested_rice_parameter,
  105550. const unsigned rice_parameter_limit,
  105551. const unsigned rice_parameter_search_dist,
  105552. const unsigned partition_order,
  105553. const FLAC__bool search_for_escapes,
  105554. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105555. unsigned *bits
  105556. )
  105557. {
  105558. unsigned rice_parameter, partition_bits;
  105559. unsigned best_partition_bits, best_rice_parameter = 0;
  105560. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105561. unsigned *parameters, *raw_bits;
  105562. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105563. unsigned min_rice_parameter, max_rice_parameter;
  105564. #else
  105565. (void)rice_parameter_search_dist;
  105566. #endif
  105567. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105568. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105569. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105570. parameters = partitioned_rice_contents->parameters;
  105571. raw_bits = partitioned_rice_contents->raw_bits;
  105572. if(partition_order == 0) {
  105573. best_partition_bits = (unsigned)(-1);
  105574. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105575. if(rice_parameter_search_dist) {
  105576. if(suggested_rice_parameter < rice_parameter_search_dist)
  105577. min_rice_parameter = 0;
  105578. else
  105579. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105580. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105581. if(max_rice_parameter >= rice_parameter_limit) {
  105582. #ifdef DEBUG_VERBOSE
  105583. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105584. #endif
  105585. max_rice_parameter = rice_parameter_limit - 1;
  105586. }
  105587. }
  105588. else
  105589. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105590. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105591. #else
  105592. rice_parameter = suggested_rice_parameter;
  105593. #endif
  105594. #ifdef EXACT_RICE_BITS_CALCULATION
  105595. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105596. #else
  105597. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105598. #endif
  105599. if(partition_bits < best_partition_bits) {
  105600. best_rice_parameter = rice_parameter;
  105601. best_partition_bits = partition_bits;
  105602. }
  105603. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105604. }
  105605. #endif
  105606. if(search_for_escapes) {
  105607. 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;
  105608. if(partition_bits <= best_partition_bits) {
  105609. raw_bits[0] = raw_bits_per_partition[0];
  105610. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105611. best_partition_bits = partition_bits;
  105612. }
  105613. else
  105614. raw_bits[0] = 0;
  105615. }
  105616. parameters[0] = best_rice_parameter;
  105617. bits_ += best_partition_bits;
  105618. }
  105619. else {
  105620. unsigned partition, residual_sample;
  105621. unsigned partition_samples;
  105622. FLAC__uint64 mean, k;
  105623. const unsigned partitions = 1u << partition_order;
  105624. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105625. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105626. if(partition == 0) {
  105627. if(partition_samples <= predictor_order)
  105628. return false;
  105629. else
  105630. partition_samples -= predictor_order;
  105631. }
  105632. mean = abs_residual_partition_sums[partition];
  105633. /* we are basically calculating the size in bits of the
  105634. * average residual magnitude in the partition:
  105635. * rice_parameter = floor(log2(mean/partition_samples))
  105636. * 'mean' is not a good name for the variable, it is
  105637. * actually the sum of magnitudes of all residual values
  105638. * in the partition, so the actual mean is
  105639. * mean/partition_samples
  105640. */
  105641. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105642. ;
  105643. if(rice_parameter >= rice_parameter_limit) {
  105644. #ifdef DEBUG_VERBOSE
  105645. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105646. #endif
  105647. rice_parameter = rice_parameter_limit - 1;
  105648. }
  105649. best_partition_bits = (unsigned)(-1);
  105650. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105651. if(rice_parameter_search_dist) {
  105652. if(rice_parameter < rice_parameter_search_dist)
  105653. min_rice_parameter = 0;
  105654. else
  105655. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105656. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105657. if(max_rice_parameter >= rice_parameter_limit) {
  105658. #ifdef DEBUG_VERBOSE
  105659. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105660. #endif
  105661. max_rice_parameter = rice_parameter_limit - 1;
  105662. }
  105663. }
  105664. else
  105665. min_rice_parameter = max_rice_parameter = rice_parameter;
  105666. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105667. #endif
  105668. #ifdef EXACT_RICE_BITS_CALCULATION
  105669. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105670. #else
  105671. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105672. #endif
  105673. if(partition_bits < best_partition_bits) {
  105674. best_rice_parameter = rice_parameter;
  105675. best_partition_bits = partition_bits;
  105676. }
  105677. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105678. }
  105679. #endif
  105680. if(search_for_escapes) {
  105681. 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;
  105682. if(partition_bits <= best_partition_bits) {
  105683. raw_bits[partition] = raw_bits_per_partition[partition];
  105684. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105685. best_partition_bits = partition_bits;
  105686. }
  105687. else
  105688. raw_bits[partition] = 0;
  105689. }
  105690. parameters[partition] = best_rice_parameter;
  105691. bits_ += best_partition_bits;
  105692. residual_sample += partition_samples;
  105693. }
  105694. }
  105695. *bits = bits_;
  105696. return true;
  105697. }
  105698. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105699. {
  105700. unsigned i, shift;
  105701. FLAC__int32 x = 0;
  105702. for(i = 0; i < samples && !(x&1); i++)
  105703. x |= signal[i];
  105704. if(x == 0) {
  105705. shift = 0;
  105706. }
  105707. else {
  105708. for(shift = 0; !(x&1); shift++)
  105709. x >>= 1;
  105710. }
  105711. if(shift > 0) {
  105712. for(i = 0; i < samples; i++)
  105713. signal[i] >>= shift;
  105714. }
  105715. return shift;
  105716. }
  105717. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105718. {
  105719. unsigned channel;
  105720. for(channel = 0; channel < channels; channel++)
  105721. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105722. fifo->tail += wide_samples;
  105723. FLAC__ASSERT(fifo->tail <= fifo->size);
  105724. }
  105725. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105726. {
  105727. unsigned channel;
  105728. unsigned sample, wide_sample;
  105729. unsigned tail = fifo->tail;
  105730. sample = input_offset * channels;
  105731. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105732. for(channel = 0; channel < channels; channel++)
  105733. fifo->data[channel][tail] = input[sample++];
  105734. tail++;
  105735. }
  105736. fifo->tail = tail;
  105737. FLAC__ASSERT(fifo->tail <= fifo->size);
  105738. }
  105739. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105740. {
  105741. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105742. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105743. (void)decoder;
  105744. if(encoder->private_->verify.needs_magic_hack) {
  105745. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105746. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105747. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105748. encoder->private_->verify.needs_magic_hack = false;
  105749. }
  105750. else {
  105751. if(encoded_bytes == 0) {
  105752. /*
  105753. * If we get here, a FIFO underflow has occurred,
  105754. * which means there is a bug somewhere.
  105755. */
  105756. FLAC__ASSERT(0);
  105757. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105758. }
  105759. else if(encoded_bytes < *bytes)
  105760. *bytes = encoded_bytes;
  105761. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105762. encoder->private_->verify.output.data += *bytes;
  105763. encoder->private_->verify.output.bytes -= *bytes;
  105764. }
  105765. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105766. }
  105767. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105768. {
  105769. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105770. unsigned channel;
  105771. const unsigned channels = frame->header.channels;
  105772. const unsigned blocksize = frame->header.blocksize;
  105773. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105774. (void)decoder;
  105775. for(channel = 0; channel < channels; channel++) {
  105776. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105777. unsigned i, sample = 0;
  105778. FLAC__int32 expect = 0, got = 0;
  105779. for(i = 0; i < blocksize; i++) {
  105780. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105781. sample = i;
  105782. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105783. got = (FLAC__int32)buffer[channel][i];
  105784. break;
  105785. }
  105786. }
  105787. FLAC__ASSERT(i < blocksize);
  105788. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105789. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105790. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105791. encoder->private_->verify.error_stats.channel = channel;
  105792. encoder->private_->verify.error_stats.sample = sample;
  105793. encoder->private_->verify.error_stats.expected = expect;
  105794. encoder->private_->verify.error_stats.got = got;
  105795. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105796. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105797. }
  105798. }
  105799. /* dequeue the frame from the fifo */
  105800. encoder->private_->verify.input_fifo.tail -= blocksize;
  105801. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105802. for(channel = 0; channel < channels; channel++)
  105803. 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]));
  105804. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105805. }
  105806. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105807. {
  105808. (void)decoder, (void)metadata, (void)client_data;
  105809. }
  105810. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105811. {
  105812. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105813. (void)decoder, (void)status;
  105814. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105815. }
  105816. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105817. {
  105818. (void)client_data;
  105819. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105820. if (*bytes == 0) {
  105821. if (feof(encoder->private_->file))
  105822. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105823. else if (ferror(encoder->private_->file))
  105824. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105825. }
  105826. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105827. }
  105828. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105829. {
  105830. (void)client_data;
  105831. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105832. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105833. else
  105834. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105835. }
  105836. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105837. {
  105838. off_t offset;
  105839. (void)client_data;
  105840. offset = ftello(encoder->private_->file);
  105841. if(offset < 0) {
  105842. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105843. }
  105844. else {
  105845. *absolute_byte_offset = (FLAC__uint64)offset;
  105846. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105847. }
  105848. }
  105849. #ifdef FLAC__VALGRIND_TESTING
  105850. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105851. {
  105852. size_t ret = fwrite(ptr, size, nmemb, stream);
  105853. if(!ferror(stream))
  105854. fflush(stream);
  105855. return ret;
  105856. }
  105857. #else
  105858. #define local__fwrite fwrite
  105859. #endif
  105860. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105861. {
  105862. (void)client_data, (void)current_frame;
  105863. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105864. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105865. #if FLAC__HAS_OGG
  105866. /* We would like to be able to use 'samples > 0' in the
  105867. * clause here but currently because of the nature of our
  105868. * Ogg writing implementation, 'samples' is always 0 (see
  105869. * ogg_encoder_aspect.c). The downside is extra progress
  105870. * callbacks.
  105871. */
  105872. encoder->private_->is_ogg? true :
  105873. #endif
  105874. samples > 0
  105875. );
  105876. if(call_it) {
  105877. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105878. * because at this point in the callback chain, the stats
  105879. * have not been updated. Only after we return and control
  105880. * gets back to write_frame_() are the stats updated
  105881. */
  105882. 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);
  105883. }
  105884. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105885. }
  105886. else
  105887. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105888. }
  105889. /*
  105890. * This will forcibly set stdout to binary mode (for OSes that require it)
  105891. */
  105892. FILE *get_binary_stdout_(void)
  105893. {
  105894. /* if something breaks here it is probably due to the presence or
  105895. * absence of an underscore before the identifiers 'setmode',
  105896. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105897. */
  105898. #if defined _MSC_VER || defined __MINGW32__
  105899. _setmode(_fileno(stdout), _O_BINARY);
  105900. #elif defined __CYGWIN__
  105901. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105902. setmode(_fileno(stdout), _O_BINARY);
  105903. #elif defined __EMX__
  105904. setmode(fileno(stdout), O_BINARY);
  105905. #endif
  105906. return stdout;
  105907. }
  105908. #endif
  105909. /*** End of inlined file: stream_encoder.c ***/
  105910. /*** Start of inlined file: stream_encoder_framing.c ***/
  105911. /*** Start of inlined file: juce_FlacHeader.h ***/
  105912. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105913. // tasks..
  105914. #define VERSION "1.2.1"
  105915. #define FLAC__NO_DLL 1
  105916. #if JUCE_MSVC
  105917. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105918. #endif
  105919. #if JUCE_MAC
  105920. #define FLAC__SYS_DARWIN 1
  105921. #endif
  105922. /*** End of inlined file: juce_FlacHeader.h ***/
  105923. #if JUCE_USE_FLAC
  105924. #if HAVE_CONFIG_H
  105925. # include <config.h>
  105926. #endif
  105927. #include <stdio.h>
  105928. #include <string.h> /* for strlen() */
  105929. #ifdef max
  105930. #undef max
  105931. #endif
  105932. #define max(x,y) ((x)>(y)?(x):(y))
  105933. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105934. 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);
  105935. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105936. {
  105937. unsigned i, j;
  105938. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105939. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105940. return false;
  105941. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105942. return false;
  105943. /*
  105944. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105945. */
  105946. i = metadata->length;
  105947. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105948. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105949. i -= metadata->data.vorbis_comment.vendor_string.length;
  105950. i += vendor_string_length;
  105951. }
  105952. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105953. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105954. return false;
  105955. switch(metadata->type) {
  105956. case FLAC__METADATA_TYPE_STREAMINFO:
  105957. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105958. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105959. return false;
  105960. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105961. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105962. return false;
  105963. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105964. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105965. return false;
  105966. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105967. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105968. return false;
  105969. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105970. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105971. return false;
  105972. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105973. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105974. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105975. return false;
  105976. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105977. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105978. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105979. return false;
  105980. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105981. return false;
  105982. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105983. return false;
  105984. break;
  105985. case FLAC__METADATA_TYPE_PADDING:
  105986. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105987. return false;
  105988. break;
  105989. case FLAC__METADATA_TYPE_APPLICATION:
  105990. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105991. return false;
  105992. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105993. return false;
  105994. break;
  105995. case FLAC__METADATA_TYPE_SEEKTABLE:
  105996. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105997. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105998. return false;
  105999. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106000. return false;
  106001. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106002. return false;
  106003. }
  106004. break;
  106005. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106006. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106007. return false;
  106008. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106009. return false;
  106010. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106011. return false;
  106012. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106013. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106014. return false;
  106015. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106016. return false;
  106017. }
  106018. break;
  106019. case FLAC__METADATA_TYPE_CUESHEET:
  106020. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106021. 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))
  106022. return false;
  106023. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106024. return false;
  106025. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106026. return false;
  106027. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106028. return false;
  106029. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106030. return false;
  106031. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106032. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106033. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106034. return false;
  106035. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106036. return false;
  106037. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106038. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106039. return false;
  106040. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106041. return false;
  106042. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106043. return false;
  106044. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106045. return false;
  106046. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106047. return false;
  106048. for(j = 0; j < track->num_indices; j++) {
  106049. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106050. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106051. return false;
  106052. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106053. return false;
  106054. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106055. return false;
  106056. }
  106057. }
  106058. break;
  106059. case FLAC__METADATA_TYPE_PICTURE:
  106060. {
  106061. size_t len;
  106062. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106063. return false;
  106064. len = strlen(metadata->data.picture.mime_type);
  106065. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106066. return false;
  106067. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106068. return false;
  106069. len = strlen((const char *)metadata->data.picture.description);
  106070. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106071. return false;
  106072. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106073. return false;
  106074. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106075. return false;
  106076. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106077. return false;
  106078. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106079. return false;
  106080. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106081. return false;
  106082. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106083. return false;
  106084. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106085. return false;
  106086. }
  106087. break;
  106088. default:
  106089. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106090. return false;
  106091. break;
  106092. }
  106093. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106094. return true;
  106095. }
  106096. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106097. {
  106098. unsigned u, blocksize_hint, sample_rate_hint;
  106099. FLAC__byte crc;
  106100. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106101. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106102. return false;
  106103. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106104. return false;
  106105. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106106. return false;
  106107. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106108. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106109. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106110. blocksize_hint = 0;
  106111. switch(header->blocksize) {
  106112. case 192: u = 1; break;
  106113. case 576: u = 2; break;
  106114. case 1152: u = 3; break;
  106115. case 2304: u = 4; break;
  106116. case 4608: u = 5; break;
  106117. case 256: u = 8; break;
  106118. case 512: u = 9; break;
  106119. case 1024: u = 10; break;
  106120. case 2048: u = 11; break;
  106121. case 4096: u = 12; break;
  106122. case 8192: u = 13; break;
  106123. case 16384: u = 14; break;
  106124. case 32768: u = 15; break;
  106125. default:
  106126. if(header->blocksize <= 0x100)
  106127. blocksize_hint = u = 6;
  106128. else
  106129. blocksize_hint = u = 7;
  106130. break;
  106131. }
  106132. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106133. return false;
  106134. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106135. sample_rate_hint = 0;
  106136. switch(header->sample_rate) {
  106137. case 88200: u = 1; break;
  106138. case 176400: u = 2; break;
  106139. case 192000: u = 3; break;
  106140. case 8000: u = 4; break;
  106141. case 16000: u = 5; break;
  106142. case 22050: u = 6; break;
  106143. case 24000: u = 7; break;
  106144. case 32000: u = 8; break;
  106145. case 44100: u = 9; break;
  106146. case 48000: u = 10; break;
  106147. case 96000: u = 11; break;
  106148. default:
  106149. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106150. sample_rate_hint = u = 12;
  106151. else if(header->sample_rate % 10 == 0)
  106152. sample_rate_hint = u = 14;
  106153. else if(header->sample_rate <= 0xffff)
  106154. sample_rate_hint = u = 13;
  106155. else
  106156. u = 0;
  106157. break;
  106158. }
  106159. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106160. return false;
  106161. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106162. switch(header->channel_assignment) {
  106163. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106164. u = header->channels - 1;
  106165. break;
  106166. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106167. FLAC__ASSERT(header->channels == 2);
  106168. u = 8;
  106169. break;
  106170. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106171. FLAC__ASSERT(header->channels == 2);
  106172. u = 9;
  106173. break;
  106174. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106175. FLAC__ASSERT(header->channels == 2);
  106176. u = 10;
  106177. break;
  106178. default:
  106179. FLAC__ASSERT(0);
  106180. }
  106181. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106182. return false;
  106183. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106184. switch(header->bits_per_sample) {
  106185. case 8 : u = 1; break;
  106186. case 12: u = 2; break;
  106187. case 16: u = 4; break;
  106188. case 20: u = 5; break;
  106189. case 24: u = 6; break;
  106190. default: u = 0; break;
  106191. }
  106192. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106193. return false;
  106194. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106195. return false;
  106196. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106197. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106198. return false;
  106199. }
  106200. else {
  106201. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106202. return false;
  106203. }
  106204. if(blocksize_hint)
  106205. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106206. return false;
  106207. switch(sample_rate_hint) {
  106208. case 12:
  106209. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106210. return false;
  106211. break;
  106212. case 13:
  106213. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106214. return false;
  106215. break;
  106216. case 14:
  106217. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106218. return false;
  106219. break;
  106220. }
  106221. /* write the CRC */
  106222. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106223. return false;
  106224. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106225. return false;
  106226. return true;
  106227. }
  106228. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106229. {
  106230. FLAC__bool ok;
  106231. ok =
  106232. 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) &&
  106233. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106234. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106235. ;
  106236. return ok;
  106237. }
  106238. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106239. {
  106240. unsigned i;
  106241. 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))
  106242. return false;
  106243. if(wasted_bits)
  106244. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106245. return false;
  106246. for(i = 0; i < subframe->order; i++)
  106247. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106248. return false;
  106249. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106250. return false;
  106251. switch(subframe->entropy_coding_method.type) {
  106252. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106253. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106254. if(!add_residual_partitioned_rice_(
  106255. bw,
  106256. subframe->residual,
  106257. residual_samples,
  106258. subframe->order,
  106259. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106260. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106261. subframe->entropy_coding_method.data.partitioned_rice.order,
  106262. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106263. ))
  106264. return false;
  106265. break;
  106266. default:
  106267. FLAC__ASSERT(0);
  106268. }
  106269. return true;
  106270. }
  106271. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106272. {
  106273. unsigned i;
  106274. 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))
  106275. return false;
  106276. if(wasted_bits)
  106277. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106278. return false;
  106279. for(i = 0; i < subframe->order; i++)
  106280. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106281. return false;
  106282. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106283. return false;
  106284. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106285. return false;
  106286. for(i = 0; i < subframe->order; i++)
  106287. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106288. return false;
  106289. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106290. return false;
  106291. switch(subframe->entropy_coding_method.type) {
  106292. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106293. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106294. if(!add_residual_partitioned_rice_(
  106295. bw,
  106296. subframe->residual,
  106297. residual_samples,
  106298. subframe->order,
  106299. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106300. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106301. subframe->entropy_coding_method.data.partitioned_rice.order,
  106302. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106303. ))
  106304. return false;
  106305. break;
  106306. default:
  106307. FLAC__ASSERT(0);
  106308. }
  106309. return true;
  106310. }
  106311. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106312. {
  106313. unsigned i;
  106314. const FLAC__int32 *signal = subframe->data;
  106315. 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))
  106316. return false;
  106317. if(wasted_bits)
  106318. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106319. return false;
  106320. for(i = 0; i < samples; i++)
  106321. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106322. return false;
  106323. return true;
  106324. }
  106325. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106326. {
  106327. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106328. return false;
  106329. switch(method->type) {
  106330. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106331. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106332. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106333. return false;
  106334. break;
  106335. default:
  106336. FLAC__ASSERT(0);
  106337. }
  106338. return true;
  106339. }
  106340. 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)
  106341. {
  106342. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106343. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106344. if(partition_order == 0) {
  106345. unsigned i;
  106346. if(raw_bits[0] == 0) {
  106347. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106348. return false;
  106349. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106350. return false;
  106351. }
  106352. else {
  106353. FLAC__ASSERT(rice_parameters[0] == 0);
  106354. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106355. return false;
  106356. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106357. return false;
  106358. for(i = 0; i < residual_samples; i++) {
  106359. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106360. return false;
  106361. }
  106362. }
  106363. return true;
  106364. }
  106365. else {
  106366. unsigned i, j, k = 0, k_last = 0;
  106367. unsigned partition_samples;
  106368. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106369. for(i = 0; i < (1u<<partition_order); i++) {
  106370. partition_samples = default_partition_samples;
  106371. if(i == 0)
  106372. partition_samples -= predictor_order;
  106373. k += partition_samples;
  106374. if(raw_bits[i] == 0) {
  106375. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106376. return false;
  106377. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106378. return false;
  106379. }
  106380. else {
  106381. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106382. return false;
  106383. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106384. return false;
  106385. for(j = k_last; j < k; j++) {
  106386. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106387. return false;
  106388. }
  106389. }
  106390. k_last = k;
  106391. }
  106392. return true;
  106393. }
  106394. }
  106395. #endif
  106396. /*** End of inlined file: stream_encoder_framing.c ***/
  106397. /*** Start of inlined file: window_flac.c ***/
  106398. /*** Start of inlined file: juce_FlacHeader.h ***/
  106399. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106400. // tasks..
  106401. #define VERSION "1.2.1"
  106402. #define FLAC__NO_DLL 1
  106403. #if JUCE_MSVC
  106404. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106405. #endif
  106406. #if JUCE_MAC
  106407. #define FLAC__SYS_DARWIN 1
  106408. #endif
  106409. /*** End of inlined file: juce_FlacHeader.h ***/
  106410. #if JUCE_USE_FLAC
  106411. #if HAVE_CONFIG_H
  106412. # include <config.h>
  106413. #endif
  106414. #include <math.h>
  106415. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106416. #ifndef M_PI
  106417. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106418. #define M_PI 3.14159265358979323846
  106419. #endif
  106420. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106421. {
  106422. const FLAC__int32 N = L - 1;
  106423. FLAC__int32 n;
  106424. if (L & 1) {
  106425. for (n = 0; n <= N/2; n++)
  106426. window[n] = 2.0f * n / (float)N;
  106427. for (; n <= N; n++)
  106428. window[n] = 2.0f - 2.0f * n / (float)N;
  106429. }
  106430. else {
  106431. for (n = 0; n <= L/2-1; n++)
  106432. window[n] = 2.0f * n / (float)N;
  106433. for (; n <= N; n++)
  106434. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106435. }
  106436. }
  106437. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106438. {
  106439. const FLAC__int32 N = L - 1;
  106440. FLAC__int32 n;
  106441. for (n = 0; n < L; n++)
  106442. 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)));
  106443. }
  106444. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106445. {
  106446. const FLAC__int32 N = L - 1;
  106447. FLAC__int32 n;
  106448. for (n = 0; n < L; n++)
  106449. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106450. }
  106451. /* 4-term -92dB side-lobe */
  106452. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106453. {
  106454. const FLAC__int32 N = L - 1;
  106455. FLAC__int32 n;
  106456. for (n = 0; n <= N; n++)
  106457. 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));
  106458. }
  106459. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106460. {
  106461. const FLAC__int32 N = L - 1;
  106462. const double N2 = (double)N / 2.;
  106463. FLAC__int32 n;
  106464. for (n = 0; n <= N; n++) {
  106465. double k = ((double)n - N2) / N2;
  106466. k = 1.0f - k * k;
  106467. window[n] = (FLAC__real)(k * k);
  106468. }
  106469. }
  106470. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106471. {
  106472. const FLAC__int32 N = L - 1;
  106473. FLAC__int32 n;
  106474. for (n = 0; n < L; n++)
  106475. 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));
  106476. }
  106477. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106478. {
  106479. const FLAC__int32 N = L - 1;
  106480. const double N2 = (double)N / 2.;
  106481. FLAC__int32 n;
  106482. for (n = 0; n <= N; n++) {
  106483. const double k = ((double)n - N2) / (stddev * N2);
  106484. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106485. }
  106486. }
  106487. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106488. {
  106489. const FLAC__int32 N = L - 1;
  106490. FLAC__int32 n;
  106491. for (n = 0; n < L; n++)
  106492. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106493. }
  106494. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106495. {
  106496. const FLAC__int32 N = L - 1;
  106497. FLAC__int32 n;
  106498. for (n = 0; n < L; n++)
  106499. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106500. }
  106501. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106502. {
  106503. const FLAC__int32 N = L - 1;
  106504. FLAC__int32 n;
  106505. for (n = 0; n < L; n++)
  106506. 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));
  106507. }
  106508. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106509. {
  106510. const FLAC__int32 N = L - 1;
  106511. FLAC__int32 n;
  106512. for (n = 0; n < L; n++)
  106513. 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));
  106514. }
  106515. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106516. {
  106517. FLAC__int32 n;
  106518. for (n = 0; n < L; n++)
  106519. window[n] = 1.0f;
  106520. }
  106521. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106522. {
  106523. FLAC__int32 n;
  106524. if (L & 1) {
  106525. for (n = 1; n <= L+1/2; n++)
  106526. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106527. for (; n <= L; n++)
  106528. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106529. }
  106530. else {
  106531. for (n = 1; n <= L/2; n++)
  106532. window[n-1] = 2.0f * n / (float)L;
  106533. for (; n <= L; n++)
  106534. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106535. }
  106536. }
  106537. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106538. {
  106539. if (p <= 0.0)
  106540. FLAC__window_rectangle(window, L);
  106541. else if (p >= 1.0)
  106542. FLAC__window_hann(window, L);
  106543. else {
  106544. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106545. FLAC__int32 n;
  106546. /* start with rectangle... */
  106547. FLAC__window_rectangle(window, L);
  106548. /* ...replace ends with hann */
  106549. if (Np > 0) {
  106550. for (n = 0; n <= Np; n++) {
  106551. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106552. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106553. }
  106554. }
  106555. }
  106556. }
  106557. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106558. {
  106559. const FLAC__int32 N = L - 1;
  106560. const double N2 = (double)N / 2.;
  106561. FLAC__int32 n;
  106562. for (n = 0; n <= N; n++) {
  106563. const double k = ((double)n - N2) / N2;
  106564. window[n] = (FLAC__real)(1.0f - k * k);
  106565. }
  106566. }
  106567. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106568. #endif
  106569. /*** End of inlined file: window_flac.c ***/
  106570. #else
  106571. #include <FLAC/all.h>
  106572. #endif
  106573. }
  106574. #undef max
  106575. #undef min
  106576. BEGIN_JUCE_NAMESPACE
  106577. static const char* const flacFormatName = "FLAC file";
  106578. static const char* const flacExtensions[] = { ".flac", 0 };
  106579. class FlacReader : public AudioFormatReader
  106580. {
  106581. public:
  106582. FlacReader (InputStream* const in)
  106583. : AudioFormatReader (in, TRANS (flacFormatName)),
  106584. reservoir (2, 0),
  106585. reservoirStart (0),
  106586. samplesInReservoir (0),
  106587. scanningForLength (false)
  106588. {
  106589. using namespace FlacNamespace;
  106590. lengthInSamples = 0;
  106591. decoder = FLAC__stream_decoder_new();
  106592. ok = FLAC__stream_decoder_init_stream (decoder,
  106593. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106594. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106595. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106596. if (ok)
  106597. {
  106598. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106599. if (lengthInSamples == 0 && sampleRate > 0)
  106600. {
  106601. // the length hasn't been stored in the metadata, so we'll need to
  106602. // work it out the length the hard way, by scanning the whole file..
  106603. scanningForLength = true;
  106604. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106605. scanningForLength = false;
  106606. const int64 tempLength = lengthInSamples;
  106607. FLAC__stream_decoder_reset (decoder);
  106608. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106609. lengthInSamples = tempLength;
  106610. }
  106611. }
  106612. }
  106613. ~FlacReader()
  106614. {
  106615. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106616. }
  106617. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106618. {
  106619. sampleRate = info.sample_rate;
  106620. bitsPerSample = info.bits_per_sample;
  106621. lengthInSamples = (unsigned int) info.total_samples;
  106622. numChannels = info.channels;
  106623. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106624. }
  106625. // returns the number of samples read
  106626. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106627. int64 startSampleInFile, int numSamples)
  106628. {
  106629. using namespace FlacNamespace;
  106630. if (! ok)
  106631. return false;
  106632. while (numSamples > 0)
  106633. {
  106634. if (startSampleInFile >= reservoirStart
  106635. && startSampleInFile < reservoirStart + samplesInReservoir)
  106636. {
  106637. const int num = (int) jmin ((int64) numSamples,
  106638. reservoirStart + samplesInReservoir - startSampleInFile);
  106639. jassert (num > 0);
  106640. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106641. if (destSamples[i] != 0)
  106642. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106643. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106644. sizeof (int) * num);
  106645. startOffsetInDestBuffer += num;
  106646. startSampleInFile += num;
  106647. numSamples -= num;
  106648. }
  106649. else
  106650. {
  106651. if (startSampleInFile >= (int) lengthInSamples)
  106652. {
  106653. samplesInReservoir = 0;
  106654. }
  106655. else if (startSampleInFile < reservoirStart
  106656. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106657. {
  106658. // had some problems with flac crashing if the read pos is aligned more
  106659. // accurately than this. Probably fixed in newer versions of the library, though.
  106660. reservoirStart = (int) (startSampleInFile & ~511);
  106661. samplesInReservoir = 0;
  106662. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106663. }
  106664. else
  106665. {
  106666. reservoirStart += samplesInReservoir;
  106667. samplesInReservoir = 0;
  106668. FLAC__stream_decoder_process_single (decoder);
  106669. }
  106670. if (samplesInReservoir == 0)
  106671. break;
  106672. }
  106673. }
  106674. if (numSamples > 0)
  106675. {
  106676. for (int i = numDestChannels; --i >= 0;)
  106677. if (destSamples[i] != 0)
  106678. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106679. sizeof (int) * numSamples);
  106680. }
  106681. return true;
  106682. }
  106683. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106684. {
  106685. if (scanningForLength)
  106686. {
  106687. lengthInSamples += numSamples;
  106688. }
  106689. else
  106690. {
  106691. if (numSamples > reservoir.getNumSamples())
  106692. reservoir.setSize (numChannels, numSamples, false, false, true);
  106693. const int bitsToShift = 32 - bitsPerSample;
  106694. for (int i = 0; i < (int) numChannels; ++i)
  106695. {
  106696. const FlacNamespace::FLAC__int32* src = buffer[i];
  106697. int n = i;
  106698. while (src == 0 && n > 0)
  106699. src = buffer [--n];
  106700. if (src != 0)
  106701. {
  106702. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106703. for (int j = 0; j < numSamples; ++j)
  106704. dest[j] = src[j] << bitsToShift;
  106705. }
  106706. }
  106707. samplesInReservoir = numSamples;
  106708. }
  106709. }
  106710. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106711. {
  106712. using namespace FlacNamespace;
  106713. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106714. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106715. }
  106716. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106717. {
  106718. using namespace FlacNamespace;
  106719. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106720. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106721. }
  106722. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106723. {
  106724. using namespace FlacNamespace;
  106725. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106726. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106727. }
  106728. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106729. {
  106730. using namespace FlacNamespace;
  106731. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106732. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106733. }
  106734. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106735. {
  106736. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106737. }
  106738. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106739. const FlacNamespace::FLAC__Frame* frame,
  106740. const FlacNamespace::FLAC__int32* const buffer[],
  106741. void* client_data)
  106742. {
  106743. using namespace FlacNamespace;
  106744. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106745. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106746. }
  106747. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106748. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106749. void* client_data)
  106750. {
  106751. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106752. }
  106753. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106754. {
  106755. }
  106756. private:
  106757. FlacNamespace::FLAC__StreamDecoder* decoder;
  106758. AudioSampleBuffer reservoir;
  106759. int reservoirStart, samplesInReservoir;
  106760. bool ok, scanningForLength;
  106761. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  106762. };
  106763. class FlacWriter : public AudioFormatWriter
  106764. {
  106765. public:
  106766. FlacWriter (OutputStream* const out, double sampleRate_,
  106767. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106768. : AudioFormatWriter (out, TRANS (flacFormatName),
  106769. sampleRate_, numChannels_, bitsPerSample_)
  106770. {
  106771. using namespace FlacNamespace;
  106772. encoder = FLAC__stream_encoder_new();
  106773. if (qualityOptionIndex > 0)
  106774. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106775. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106776. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106777. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106778. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106779. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106780. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106781. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106782. ok = FLAC__stream_encoder_init_stream (encoder,
  106783. encodeWriteCallback, encodeSeekCallback,
  106784. encodeTellCallback, encodeMetadataCallback,
  106785. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106786. }
  106787. ~FlacWriter()
  106788. {
  106789. if (ok)
  106790. {
  106791. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106792. output->flush();
  106793. }
  106794. else
  106795. {
  106796. output = 0; // to stop the base class deleting this, as it needs to be returned
  106797. // to the caller of createWriter()
  106798. }
  106799. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106800. }
  106801. bool write (const int** samplesToWrite, int numSamples)
  106802. {
  106803. using namespace FlacNamespace;
  106804. if (! ok)
  106805. return false;
  106806. int* buf[3];
  106807. HeapBlock<int> temp;
  106808. const int bitsToShift = 32 - bitsPerSample;
  106809. if (bitsToShift > 0)
  106810. {
  106811. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106812. temp.malloc (numSamples * numChannelsToWrite);
  106813. buf[0] = temp.getData();
  106814. buf[1] = temp.getData() + numSamples;
  106815. buf[2] = 0;
  106816. for (int i = numChannelsToWrite; --i >= 0;)
  106817. if (samplesToWrite[i] != 0)
  106818. for (int j = 0; j < numSamples; ++j)
  106819. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106820. samplesToWrite = const_cast<const int**> (buf);
  106821. }
  106822. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  106823. }
  106824. bool writeData (const void* const data, const int size) const
  106825. {
  106826. return output->write (data, size);
  106827. }
  106828. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106829. {
  106830. using namespace FlacNamespace;
  106831. b += bytes;
  106832. for (int i = 0; i < bytes; ++i)
  106833. {
  106834. *(--b) = (FLAC__byte) (val & 0xff);
  106835. val >>= 8;
  106836. }
  106837. }
  106838. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106839. {
  106840. using namespace FlacNamespace;
  106841. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106842. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106843. const unsigned int channelsMinus1 = info.channels - 1;
  106844. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106845. packUint32 (info.min_blocksize, buffer, 2);
  106846. packUint32 (info.max_blocksize, buffer + 2, 2);
  106847. packUint32 (info.min_framesize, buffer + 4, 3);
  106848. packUint32 (info.max_framesize, buffer + 7, 3);
  106849. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106850. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106851. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106852. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106853. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106854. memcpy (buffer + 18, info.md5sum, 16);
  106855. const bool seekOk = output->setPosition (4);
  106856. (void) seekOk;
  106857. // if this fails, you've given it an output stream that can't seek! It needs
  106858. // to be able to seek back to write the header
  106859. jassert (seekOk);
  106860. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106861. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106862. }
  106863. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106864. const FlacNamespace::FLAC__byte buffer[],
  106865. size_t bytes,
  106866. unsigned int /*samples*/,
  106867. unsigned int /*current_frame*/,
  106868. void* client_data)
  106869. {
  106870. using namespace FlacNamespace;
  106871. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106872. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106873. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106874. }
  106875. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106876. {
  106877. using namespace FlacNamespace;
  106878. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106879. }
  106880. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106881. {
  106882. using namespace FlacNamespace;
  106883. if (client_data == 0)
  106884. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106885. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106886. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106887. }
  106888. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106889. {
  106890. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106891. }
  106892. bool ok;
  106893. private:
  106894. FlacNamespace::FLAC__StreamEncoder* encoder;
  106895. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  106896. };
  106897. FlacAudioFormat::FlacAudioFormat()
  106898. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106899. {
  106900. }
  106901. FlacAudioFormat::~FlacAudioFormat()
  106902. {
  106903. }
  106904. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106905. {
  106906. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106907. return Array <int> (rates);
  106908. }
  106909. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106910. {
  106911. const int depths[] = { 16, 24, 0 };
  106912. return Array <int> (depths);
  106913. }
  106914. bool FlacAudioFormat::canDoStereo() { return true; }
  106915. bool FlacAudioFormat::canDoMono() { return true; }
  106916. bool FlacAudioFormat::isCompressed() { return true; }
  106917. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106918. const bool deleteStreamIfOpeningFails)
  106919. {
  106920. ScopedPointer<FlacReader> r (new FlacReader (in));
  106921. if (r->sampleRate != 0)
  106922. return r.release();
  106923. if (! deleteStreamIfOpeningFails)
  106924. r->input = 0;
  106925. return 0;
  106926. }
  106927. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106928. double sampleRate,
  106929. unsigned int numberOfChannels,
  106930. int bitsPerSample,
  106931. const StringPairArray& /*metadataValues*/,
  106932. int qualityOptionIndex)
  106933. {
  106934. if (getPossibleBitDepths().contains (bitsPerSample))
  106935. {
  106936. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  106937. if (w->ok)
  106938. return w.release();
  106939. }
  106940. return 0;
  106941. }
  106942. END_JUCE_NAMESPACE
  106943. #endif
  106944. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106945. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106946. #if JUCE_USE_OGGVORBIS
  106947. #if JUCE_MAC
  106948. #define __MACOSX__ 1
  106949. #endif
  106950. namespace OggVorbisNamespace
  106951. {
  106952. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106953. /*** Start of inlined file: vorbisenc.h ***/
  106954. #ifndef _OV_ENC_H_
  106955. #define _OV_ENC_H_
  106956. #ifdef __cplusplus
  106957. extern "C"
  106958. {
  106959. #endif /* __cplusplus */
  106960. /*** Start of inlined file: codec.h ***/
  106961. #ifndef _vorbis_codec_h_
  106962. #define _vorbis_codec_h_
  106963. #ifdef __cplusplus
  106964. extern "C"
  106965. {
  106966. #endif /* __cplusplus */
  106967. /*** Start of inlined file: ogg.h ***/
  106968. #ifndef _OGG_H
  106969. #define _OGG_H
  106970. #ifdef __cplusplus
  106971. extern "C" {
  106972. #endif
  106973. /*** Start of inlined file: os_types.h ***/
  106974. #ifndef _OS_TYPES_H
  106975. #define _OS_TYPES_H
  106976. /* make it easy on the folks that want to compile the libs with a
  106977. different malloc than stdlib */
  106978. #define _ogg_malloc malloc
  106979. #define _ogg_calloc calloc
  106980. #define _ogg_realloc realloc
  106981. #define _ogg_free free
  106982. #if defined(_WIN32)
  106983. # if defined(__CYGWIN__)
  106984. # include <_G_config.h>
  106985. typedef _G_int64_t ogg_int64_t;
  106986. typedef _G_int32_t ogg_int32_t;
  106987. typedef _G_uint32_t ogg_uint32_t;
  106988. typedef _G_int16_t ogg_int16_t;
  106989. typedef _G_uint16_t ogg_uint16_t;
  106990. # elif defined(__MINGW32__)
  106991. typedef short ogg_int16_t;
  106992. typedef unsigned short ogg_uint16_t;
  106993. typedef int ogg_int32_t;
  106994. typedef unsigned int ogg_uint32_t;
  106995. typedef long long ogg_int64_t;
  106996. typedef unsigned long long ogg_uint64_t;
  106997. # elif defined(__MWERKS__)
  106998. typedef long long ogg_int64_t;
  106999. typedef int ogg_int32_t;
  107000. typedef unsigned int ogg_uint32_t;
  107001. typedef short ogg_int16_t;
  107002. typedef unsigned short ogg_uint16_t;
  107003. # else
  107004. /* MSVC/Borland */
  107005. typedef __int64 ogg_int64_t;
  107006. typedef __int32 ogg_int32_t;
  107007. typedef unsigned __int32 ogg_uint32_t;
  107008. typedef __int16 ogg_int16_t;
  107009. typedef unsigned __int16 ogg_uint16_t;
  107010. # endif
  107011. #elif defined(__MACOS__)
  107012. # include <sys/types.h>
  107013. typedef SInt16 ogg_int16_t;
  107014. typedef UInt16 ogg_uint16_t;
  107015. typedef SInt32 ogg_int32_t;
  107016. typedef UInt32 ogg_uint32_t;
  107017. typedef SInt64 ogg_int64_t;
  107018. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107019. # include <sys/types.h>
  107020. typedef int16_t ogg_int16_t;
  107021. typedef u_int16_t ogg_uint16_t;
  107022. typedef int32_t ogg_int32_t;
  107023. typedef u_int32_t ogg_uint32_t;
  107024. typedef int64_t ogg_int64_t;
  107025. #elif defined(__BEOS__)
  107026. /* Be */
  107027. # include <inttypes.h>
  107028. typedef int16_t ogg_int16_t;
  107029. typedef u_int16_t ogg_uint16_t;
  107030. typedef int32_t ogg_int32_t;
  107031. typedef u_int32_t ogg_uint32_t;
  107032. typedef int64_t ogg_int64_t;
  107033. #elif defined (__EMX__)
  107034. /* OS/2 GCC */
  107035. typedef short ogg_int16_t;
  107036. typedef unsigned short ogg_uint16_t;
  107037. typedef int ogg_int32_t;
  107038. typedef unsigned int ogg_uint32_t;
  107039. typedef long long ogg_int64_t;
  107040. #elif defined (DJGPP)
  107041. /* DJGPP */
  107042. typedef short ogg_int16_t;
  107043. typedef int ogg_int32_t;
  107044. typedef unsigned int ogg_uint32_t;
  107045. typedef long long ogg_int64_t;
  107046. #elif defined(R5900)
  107047. /* PS2 EE */
  107048. typedef long ogg_int64_t;
  107049. typedef int ogg_int32_t;
  107050. typedef unsigned ogg_uint32_t;
  107051. typedef short ogg_int16_t;
  107052. #elif defined(__SYMBIAN32__)
  107053. /* Symbian GCC */
  107054. typedef signed short ogg_int16_t;
  107055. typedef unsigned short ogg_uint16_t;
  107056. typedef signed int ogg_int32_t;
  107057. typedef unsigned int ogg_uint32_t;
  107058. typedef long long int ogg_int64_t;
  107059. #else
  107060. # include <sys/types.h>
  107061. /*** Start of inlined file: config_types.h ***/
  107062. #ifndef __CONFIG_TYPES_H__
  107063. #define __CONFIG_TYPES_H__
  107064. typedef int16_t ogg_int16_t;
  107065. typedef unsigned short ogg_uint16_t;
  107066. typedef int32_t ogg_int32_t;
  107067. typedef unsigned int ogg_uint32_t;
  107068. typedef int64_t ogg_int64_t;
  107069. #endif
  107070. /*** End of inlined file: config_types.h ***/
  107071. #endif
  107072. #endif /* _OS_TYPES_H */
  107073. /*** End of inlined file: os_types.h ***/
  107074. typedef struct {
  107075. long endbyte;
  107076. int endbit;
  107077. unsigned char *buffer;
  107078. unsigned char *ptr;
  107079. long storage;
  107080. } oggpack_buffer;
  107081. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107082. typedef struct {
  107083. unsigned char *header;
  107084. long header_len;
  107085. unsigned char *body;
  107086. long body_len;
  107087. } ogg_page;
  107088. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107089. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107090. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107091. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107092. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107093. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107094. }
  107095. /* ogg_stream_state contains the current encode/decode state of a logical
  107096. Ogg bitstream **********************************************************/
  107097. typedef struct {
  107098. unsigned char *body_data; /* bytes from packet bodies */
  107099. long body_storage; /* storage elements allocated */
  107100. long body_fill; /* elements stored; fill mark */
  107101. long body_returned; /* elements of fill returned */
  107102. int *lacing_vals; /* The values that will go to the segment table */
  107103. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107104. this way, but it is simple coupled to the
  107105. lacing fifo */
  107106. long lacing_storage;
  107107. long lacing_fill;
  107108. long lacing_packet;
  107109. long lacing_returned;
  107110. unsigned char header[282]; /* working space for header encode */
  107111. int header_fill;
  107112. int e_o_s; /* set when we have buffered the last packet in the
  107113. logical bitstream */
  107114. int b_o_s; /* set after we've written the initial page
  107115. of a logical bitstream */
  107116. long serialno;
  107117. long pageno;
  107118. ogg_int64_t packetno; /* sequence number for decode; the framing
  107119. knows where there's a hole in the data,
  107120. but we need coupling so that the codec
  107121. (which is in a seperate abstraction
  107122. layer) also knows about the gap */
  107123. ogg_int64_t granulepos;
  107124. } ogg_stream_state;
  107125. /* ogg_packet is used to encapsulate the data and metadata belonging
  107126. to a single raw Ogg/Vorbis packet *************************************/
  107127. typedef struct {
  107128. unsigned char *packet;
  107129. long bytes;
  107130. long b_o_s;
  107131. long e_o_s;
  107132. ogg_int64_t granulepos;
  107133. ogg_int64_t packetno; /* sequence number for decode; the framing
  107134. knows where there's a hole in the data,
  107135. but we need coupling so that the codec
  107136. (which is in a seperate abstraction
  107137. layer) also knows about the gap */
  107138. } ogg_packet;
  107139. typedef struct {
  107140. unsigned char *data;
  107141. int storage;
  107142. int fill;
  107143. int returned;
  107144. int unsynced;
  107145. int headerbytes;
  107146. int bodybytes;
  107147. } ogg_sync_state;
  107148. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107149. extern void oggpack_writeinit(oggpack_buffer *b);
  107150. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107151. extern void oggpack_writealign(oggpack_buffer *b);
  107152. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107153. extern void oggpack_reset(oggpack_buffer *b);
  107154. extern void oggpack_writeclear(oggpack_buffer *b);
  107155. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107156. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107157. extern long oggpack_look(oggpack_buffer *b,int bits);
  107158. extern long oggpack_look1(oggpack_buffer *b);
  107159. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107160. extern void oggpack_adv1(oggpack_buffer *b);
  107161. extern long oggpack_read(oggpack_buffer *b,int bits);
  107162. extern long oggpack_read1(oggpack_buffer *b);
  107163. extern long oggpack_bytes(oggpack_buffer *b);
  107164. extern long oggpack_bits(oggpack_buffer *b);
  107165. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107166. extern void oggpackB_writeinit(oggpack_buffer *b);
  107167. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107168. extern void oggpackB_writealign(oggpack_buffer *b);
  107169. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107170. extern void oggpackB_reset(oggpack_buffer *b);
  107171. extern void oggpackB_writeclear(oggpack_buffer *b);
  107172. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107173. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107174. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107175. extern long oggpackB_look1(oggpack_buffer *b);
  107176. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107177. extern void oggpackB_adv1(oggpack_buffer *b);
  107178. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107179. extern long oggpackB_read1(oggpack_buffer *b);
  107180. extern long oggpackB_bytes(oggpack_buffer *b);
  107181. extern long oggpackB_bits(oggpack_buffer *b);
  107182. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107183. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107184. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107185. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107186. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107187. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107188. extern int ogg_sync_init(ogg_sync_state *oy);
  107189. extern int ogg_sync_clear(ogg_sync_state *oy);
  107190. extern int ogg_sync_reset(ogg_sync_state *oy);
  107191. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107192. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107193. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107194. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107195. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107196. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107197. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107198. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107199. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107200. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107201. extern int ogg_stream_clear(ogg_stream_state *os);
  107202. extern int ogg_stream_reset(ogg_stream_state *os);
  107203. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107204. extern int ogg_stream_destroy(ogg_stream_state *os);
  107205. extern int ogg_stream_eos(ogg_stream_state *os);
  107206. extern void ogg_page_checksum_set(ogg_page *og);
  107207. extern int ogg_page_version(ogg_page *og);
  107208. extern int ogg_page_continued(ogg_page *og);
  107209. extern int ogg_page_bos(ogg_page *og);
  107210. extern int ogg_page_eos(ogg_page *og);
  107211. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107212. extern int ogg_page_serialno(ogg_page *og);
  107213. extern long ogg_page_pageno(ogg_page *og);
  107214. extern int ogg_page_packets(ogg_page *og);
  107215. extern void ogg_packet_clear(ogg_packet *op);
  107216. #ifdef __cplusplus
  107217. }
  107218. #endif
  107219. #endif /* _OGG_H */
  107220. /*** End of inlined file: ogg.h ***/
  107221. typedef struct vorbis_info{
  107222. int version;
  107223. int channels;
  107224. long rate;
  107225. /* The below bitrate declarations are *hints*.
  107226. Combinations of the three values carry the following implications:
  107227. all three set to the same value:
  107228. implies a fixed rate bitstream
  107229. only nominal set:
  107230. implies a VBR stream that averages the nominal bitrate. No hard
  107231. upper/lower limit
  107232. upper and or lower set:
  107233. implies a VBR bitstream that obeys the bitrate limits. nominal
  107234. may also be set to give a nominal rate.
  107235. none set:
  107236. the coder does not care to speculate.
  107237. */
  107238. long bitrate_upper;
  107239. long bitrate_nominal;
  107240. long bitrate_lower;
  107241. long bitrate_window;
  107242. void *codec_setup;
  107243. } vorbis_info;
  107244. /* vorbis_dsp_state buffers the current vorbis audio
  107245. analysis/synthesis state. The DSP state belongs to a specific
  107246. logical bitstream ****************************************************/
  107247. typedef struct vorbis_dsp_state{
  107248. int analysisp;
  107249. vorbis_info *vi;
  107250. float **pcm;
  107251. float **pcmret;
  107252. int pcm_storage;
  107253. int pcm_current;
  107254. int pcm_returned;
  107255. int preextrapolate;
  107256. int eofflag;
  107257. long lW;
  107258. long W;
  107259. long nW;
  107260. long centerW;
  107261. ogg_int64_t granulepos;
  107262. ogg_int64_t sequence;
  107263. ogg_int64_t glue_bits;
  107264. ogg_int64_t time_bits;
  107265. ogg_int64_t floor_bits;
  107266. ogg_int64_t res_bits;
  107267. void *backend_state;
  107268. } vorbis_dsp_state;
  107269. typedef struct vorbis_block{
  107270. /* necessary stream state for linking to the framing abstraction */
  107271. float **pcm; /* this is a pointer into local storage */
  107272. oggpack_buffer opb;
  107273. long lW;
  107274. long W;
  107275. long nW;
  107276. int pcmend;
  107277. int mode;
  107278. int eofflag;
  107279. ogg_int64_t granulepos;
  107280. ogg_int64_t sequence;
  107281. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107282. /* local storage to avoid remallocing; it's up to the mapping to
  107283. structure it */
  107284. void *localstore;
  107285. long localtop;
  107286. long localalloc;
  107287. long totaluse;
  107288. struct alloc_chain *reap;
  107289. /* bitmetrics for the frame */
  107290. long glue_bits;
  107291. long time_bits;
  107292. long floor_bits;
  107293. long res_bits;
  107294. void *internal;
  107295. } vorbis_block;
  107296. /* vorbis_block is a single block of data to be processed as part of
  107297. the analysis/synthesis stream; it belongs to a specific logical
  107298. bitstream, but is independant from other vorbis_blocks belonging to
  107299. that logical bitstream. *************************************************/
  107300. struct alloc_chain{
  107301. void *ptr;
  107302. struct alloc_chain *next;
  107303. };
  107304. /* vorbis_info contains all the setup information specific to the
  107305. specific compression/decompression mode in progress (eg,
  107306. psychoacoustic settings, channel setup, options, codebook
  107307. etc). vorbis_info and substructures are in backends.h.
  107308. *********************************************************************/
  107309. /* the comments are not part of vorbis_info so that vorbis_info can be
  107310. static storage */
  107311. typedef struct vorbis_comment{
  107312. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107313. whatever vendor is set to in encode */
  107314. char **user_comments;
  107315. int *comment_lengths;
  107316. int comments;
  107317. char *vendor;
  107318. } vorbis_comment;
  107319. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107320. and produce a packet (see docs/analysis.txt). The packet is then
  107321. coded into a framed OggSquish bitstream by the second layer (see
  107322. docs/framing.txt). Decode is the reverse process; we sync/frame
  107323. the bitstream and extract individual packets, then decode the
  107324. packet back into PCM audio.
  107325. The extra framing/packetizing is used in streaming formats, such as
  107326. files. Over the net (such as with UDP), the framing and
  107327. packetization aren't necessary as they're provided by the transport
  107328. and the streaming layer is not used */
  107329. /* Vorbis PRIMITIVES: general ***************************************/
  107330. extern void vorbis_info_init(vorbis_info *vi);
  107331. extern void vorbis_info_clear(vorbis_info *vi);
  107332. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107333. extern void vorbis_comment_init(vorbis_comment *vc);
  107334. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107335. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107336. const char *tag, char *contents);
  107337. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107338. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107339. extern void vorbis_comment_clear(vorbis_comment *vc);
  107340. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107341. extern int vorbis_block_clear(vorbis_block *vb);
  107342. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107343. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107344. ogg_int64_t granulepos);
  107345. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107346. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107347. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107348. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107349. vorbis_comment *vc,
  107350. ogg_packet *op,
  107351. ogg_packet *op_comm,
  107352. ogg_packet *op_code);
  107353. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107354. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107355. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107356. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107357. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107358. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107359. ogg_packet *op);
  107360. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107361. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107362. ogg_packet *op);
  107363. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107364. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107365. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107366. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107367. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107368. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107369. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107370. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107371. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107372. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107373. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107374. /* Vorbis ERRORS and return codes ***********************************/
  107375. #define OV_FALSE -1
  107376. #define OV_EOF -2
  107377. #define OV_HOLE -3
  107378. #define OV_EREAD -128
  107379. #define OV_EFAULT -129
  107380. #define OV_EIMPL -130
  107381. #define OV_EINVAL -131
  107382. #define OV_ENOTVORBIS -132
  107383. #define OV_EBADHEADER -133
  107384. #define OV_EVERSION -134
  107385. #define OV_ENOTAUDIO -135
  107386. #define OV_EBADPACKET -136
  107387. #define OV_EBADLINK -137
  107388. #define OV_ENOSEEK -138
  107389. #ifdef __cplusplus
  107390. }
  107391. #endif /* __cplusplus */
  107392. #endif
  107393. /*** End of inlined file: codec.h ***/
  107394. extern int vorbis_encode_init(vorbis_info *vi,
  107395. long channels,
  107396. long rate,
  107397. long max_bitrate,
  107398. long nominal_bitrate,
  107399. long min_bitrate);
  107400. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107401. long channels,
  107402. long rate,
  107403. long max_bitrate,
  107404. long nominal_bitrate,
  107405. long min_bitrate);
  107406. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107407. long channels,
  107408. long rate,
  107409. float quality /* quality level from 0. (lo) to 1. (hi) */
  107410. );
  107411. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107412. long channels,
  107413. long rate,
  107414. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107415. );
  107416. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107417. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107418. /* deprecated rate management supported only for compatability */
  107419. #define OV_ECTL_RATEMANAGE_GET 0x10
  107420. #define OV_ECTL_RATEMANAGE_SET 0x11
  107421. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107422. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107423. struct ovectl_ratemanage_arg {
  107424. int management_active;
  107425. long bitrate_hard_min;
  107426. long bitrate_hard_max;
  107427. double bitrate_hard_window;
  107428. long bitrate_av_lo;
  107429. long bitrate_av_hi;
  107430. double bitrate_av_window;
  107431. double bitrate_av_window_center;
  107432. };
  107433. /* new rate setup */
  107434. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107435. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107436. struct ovectl_ratemanage2_arg {
  107437. int management_active;
  107438. long bitrate_limit_min_kbps;
  107439. long bitrate_limit_max_kbps;
  107440. long bitrate_limit_reservoir_bits;
  107441. double bitrate_limit_reservoir_bias;
  107442. long bitrate_average_kbps;
  107443. double bitrate_average_damping;
  107444. };
  107445. #define OV_ECTL_LOWPASS_GET 0x20
  107446. #define OV_ECTL_LOWPASS_SET 0x21
  107447. #define OV_ECTL_IBLOCK_GET 0x30
  107448. #define OV_ECTL_IBLOCK_SET 0x31
  107449. #ifdef __cplusplus
  107450. }
  107451. #endif /* __cplusplus */
  107452. #endif
  107453. /*** End of inlined file: vorbisenc.h ***/
  107454. /*** Start of inlined file: vorbisfile.h ***/
  107455. #ifndef _OV_FILE_H_
  107456. #define _OV_FILE_H_
  107457. #ifdef __cplusplus
  107458. extern "C"
  107459. {
  107460. #endif /* __cplusplus */
  107461. #include <stdio.h>
  107462. /* The function prototypes for the callbacks are basically the same as for
  107463. * the stdio functions fread, fseek, fclose, ftell.
  107464. * The one difference is that the FILE * arguments have been replaced with
  107465. * a void * - this is to be used as a pointer to whatever internal data these
  107466. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107467. *
  107468. * If you use other functions, check the docs for these functions and return
  107469. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107470. * unseekable
  107471. */
  107472. typedef struct {
  107473. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107474. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107475. int (*close_func) (void *datasource);
  107476. long (*tell_func) (void *datasource);
  107477. } ov_callbacks;
  107478. #define NOTOPEN 0
  107479. #define PARTOPEN 1
  107480. #define OPENED 2
  107481. #define STREAMSET 3
  107482. #define INITSET 4
  107483. typedef struct OggVorbis_File {
  107484. void *datasource; /* Pointer to a FILE *, etc. */
  107485. int seekable;
  107486. ogg_int64_t offset;
  107487. ogg_int64_t end;
  107488. ogg_sync_state oy;
  107489. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107490. stream appears */
  107491. int links;
  107492. ogg_int64_t *offsets;
  107493. ogg_int64_t *dataoffsets;
  107494. long *serialnos;
  107495. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107496. compatability; x2 size, stores both
  107497. beginning and end values */
  107498. vorbis_info *vi;
  107499. vorbis_comment *vc;
  107500. /* Decoding working state local storage */
  107501. ogg_int64_t pcm_offset;
  107502. int ready_state;
  107503. long current_serialno;
  107504. int current_link;
  107505. double bittrack;
  107506. double samptrack;
  107507. ogg_stream_state os; /* take physical pages, weld into a logical
  107508. stream of packets */
  107509. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107510. vorbis_block vb; /* local working space for packet->PCM decode */
  107511. ov_callbacks callbacks;
  107512. } OggVorbis_File;
  107513. extern int ov_clear(OggVorbis_File *vf);
  107514. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107515. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107516. char *initial, long ibytes, ov_callbacks callbacks);
  107517. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107518. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107519. char *initial, long ibytes, ov_callbacks callbacks);
  107520. extern int ov_test_open(OggVorbis_File *vf);
  107521. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107522. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107523. extern long ov_streams(OggVorbis_File *vf);
  107524. extern long ov_seekable(OggVorbis_File *vf);
  107525. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107526. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107527. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107528. extern double ov_time_total(OggVorbis_File *vf,int i);
  107529. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107530. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107531. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107532. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107533. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107534. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107535. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107536. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107537. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107538. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107539. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107540. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107541. extern double ov_time_tell(OggVorbis_File *vf);
  107542. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107543. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107544. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107545. int *bitstream);
  107546. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107547. int bigendianp,int word,int sgned,int *bitstream);
  107548. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107549. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107550. extern int ov_halfrate_p(OggVorbis_File *vf);
  107551. #ifdef __cplusplus
  107552. }
  107553. #endif /* __cplusplus */
  107554. #endif
  107555. /*** End of inlined file: vorbisfile.h ***/
  107556. /*** Start of inlined file: bitwise.c ***/
  107557. /* We're 'LSb' endian; if we write a word but read individual bits,
  107558. then we'll read the lsb first */
  107559. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107560. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107561. // tasks..
  107562. #if JUCE_MSVC
  107563. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107564. #endif
  107565. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107566. #if JUCE_USE_OGGVORBIS
  107567. #include <string.h>
  107568. #include <stdlib.h>
  107569. #define BUFFER_INCREMENT 256
  107570. static const unsigned long mask[]=
  107571. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107572. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107573. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107574. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107575. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107576. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107577. 0x3fffffff,0x7fffffff,0xffffffff };
  107578. static const unsigned int mask8B[]=
  107579. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107580. void oggpack_writeinit(oggpack_buffer *b){
  107581. memset(b,0,sizeof(*b));
  107582. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107583. b->buffer[0]='\0';
  107584. b->storage=BUFFER_INCREMENT;
  107585. }
  107586. void oggpackB_writeinit(oggpack_buffer *b){
  107587. oggpack_writeinit(b);
  107588. }
  107589. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107590. long bytes=bits>>3;
  107591. bits-=bytes*8;
  107592. b->ptr=b->buffer+bytes;
  107593. b->endbit=bits;
  107594. b->endbyte=bytes;
  107595. *b->ptr&=mask[bits];
  107596. }
  107597. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107598. long bytes=bits>>3;
  107599. bits-=bytes*8;
  107600. b->ptr=b->buffer+bytes;
  107601. b->endbit=bits;
  107602. b->endbyte=bytes;
  107603. *b->ptr&=mask8B[bits];
  107604. }
  107605. /* Takes only up to 32 bits. */
  107606. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107607. if(b->endbyte+4>=b->storage){
  107608. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107609. b->storage+=BUFFER_INCREMENT;
  107610. b->ptr=b->buffer+b->endbyte;
  107611. }
  107612. value&=mask[bits];
  107613. bits+=b->endbit;
  107614. b->ptr[0]|=value<<b->endbit;
  107615. if(bits>=8){
  107616. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107617. if(bits>=16){
  107618. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107619. if(bits>=24){
  107620. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107621. if(bits>=32){
  107622. if(b->endbit)
  107623. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107624. else
  107625. b->ptr[4]=0;
  107626. }
  107627. }
  107628. }
  107629. }
  107630. b->endbyte+=bits/8;
  107631. b->ptr+=bits/8;
  107632. b->endbit=bits&7;
  107633. }
  107634. /* Takes only up to 32 bits. */
  107635. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107636. if(b->endbyte+4>=b->storage){
  107637. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107638. b->storage+=BUFFER_INCREMENT;
  107639. b->ptr=b->buffer+b->endbyte;
  107640. }
  107641. value=(value&mask[bits])<<(32-bits);
  107642. bits+=b->endbit;
  107643. b->ptr[0]|=value>>(24+b->endbit);
  107644. if(bits>=8){
  107645. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107646. if(bits>=16){
  107647. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107648. if(bits>=24){
  107649. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107650. if(bits>=32){
  107651. if(b->endbit)
  107652. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107653. else
  107654. b->ptr[4]=0;
  107655. }
  107656. }
  107657. }
  107658. }
  107659. b->endbyte+=bits/8;
  107660. b->ptr+=bits/8;
  107661. b->endbit=bits&7;
  107662. }
  107663. void oggpack_writealign(oggpack_buffer *b){
  107664. int bits=8-b->endbit;
  107665. if(bits<8)
  107666. oggpack_write(b,0,bits);
  107667. }
  107668. void oggpackB_writealign(oggpack_buffer *b){
  107669. int bits=8-b->endbit;
  107670. if(bits<8)
  107671. oggpackB_write(b,0,bits);
  107672. }
  107673. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107674. void *source,
  107675. long bits,
  107676. void (*w)(oggpack_buffer *,
  107677. unsigned long,
  107678. int),
  107679. int msb){
  107680. unsigned char *ptr=(unsigned char *)source;
  107681. long bytes=bits/8;
  107682. bits-=bytes*8;
  107683. if(b->endbit){
  107684. int i;
  107685. /* unaligned copy. Do it the hard way. */
  107686. for(i=0;i<bytes;i++)
  107687. w(b,(unsigned long)(ptr[i]),8);
  107688. }else{
  107689. /* aligned block copy */
  107690. if(b->endbyte+bytes+1>=b->storage){
  107691. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107692. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107693. b->ptr=b->buffer+b->endbyte;
  107694. }
  107695. memmove(b->ptr,source,bytes);
  107696. b->ptr+=bytes;
  107697. b->endbyte+=bytes;
  107698. *b->ptr=0;
  107699. }
  107700. if(bits){
  107701. if(msb)
  107702. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107703. else
  107704. w(b,(unsigned long)(ptr[bytes]),bits);
  107705. }
  107706. }
  107707. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107708. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107709. }
  107710. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107711. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107712. }
  107713. void oggpack_reset(oggpack_buffer *b){
  107714. b->ptr=b->buffer;
  107715. b->buffer[0]=0;
  107716. b->endbit=b->endbyte=0;
  107717. }
  107718. void oggpackB_reset(oggpack_buffer *b){
  107719. oggpack_reset(b);
  107720. }
  107721. void oggpack_writeclear(oggpack_buffer *b){
  107722. _ogg_free(b->buffer);
  107723. memset(b,0,sizeof(*b));
  107724. }
  107725. void oggpackB_writeclear(oggpack_buffer *b){
  107726. oggpack_writeclear(b);
  107727. }
  107728. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107729. memset(b,0,sizeof(*b));
  107730. b->buffer=b->ptr=buf;
  107731. b->storage=bytes;
  107732. }
  107733. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107734. oggpack_readinit(b,buf,bytes);
  107735. }
  107736. /* Read in bits without advancing the bitptr; bits <= 32 */
  107737. long oggpack_look(oggpack_buffer *b,int bits){
  107738. unsigned long ret;
  107739. unsigned long m=mask[bits];
  107740. bits+=b->endbit;
  107741. if(b->endbyte+4>=b->storage){
  107742. /* not the main path */
  107743. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107744. }
  107745. ret=b->ptr[0]>>b->endbit;
  107746. if(bits>8){
  107747. ret|=b->ptr[1]<<(8-b->endbit);
  107748. if(bits>16){
  107749. ret|=b->ptr[2]<<(16-b->endbit);
  107750. if(bits>24){
  107751. ret|=b->ptr[3]<<(24-b->endbit);
  107752. if(bits>32 && b->endbit)
  107753. ret|=b->ptr[4]<<(32-b->endbit);
  107754. }
  107755. }
  107756. }
  107757. return(m&ret);
  107758. }
  107759. /* Read in bits without advancing the bitptr; bits <= 32 */
  107760. long oggpackB_look(oggpack_buffer *b,int bits){
  107761. unsigned long ret;
  107762. int m=32-bits;
  107763. bits+=b->endbit;
  107764. if(b->endbyte+4>=b->storage){
  107765. /* not the main path */
  107766. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107767. }
  107768. ret=b->ptr[0]<<(24+b->endbit);
  107769. if(bits>8){
  107770. ret|=b->ptr[1]<<(16+b->endbit);
  107771. if(bits>16){
  107772. ret|=b->ptr[2]<<(8+b->endbit);
  107773. if(bits>24){
  107774. ret|=b->ptr[3]<<(b->endbit);
  107775. if(bits>32 && b->endbit)
  107776. ret|=b->ptr[4]>>(8-b->endbit);
  107777. }
  107778. }
  107779. }
  107780. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107781. }
  107782. long oggpack_look1(oggpack_buffer *b){
  107783. if(b->endbyte>=b->storage)return(-1);
  107784. return((b->ptr[0]>>b->endbit)&1);
  107785. }
  107786. long oggpackB_look1(oggpack_buffer *b){
  107787. if(b->endbyte>=b->storage)return(-1);
  107788. return((b->ptr[0]>>(7-b->endbit))&1);
  107789. }
  107790. void oggpack_adv(oggpack_buffer *b,int bits){
  107791. bits+=b->endbit;
  107792. b->ptr+=bits/8;
  107793. b->endbyte+=bits/8;
  107794. b->endbit=bits&7;
  107795. }
  107796. void oggpackB_adv(oggpack_buffer *b,int bits){
  107797. oggpack_adv(b,bits);
  107798. }
  107799. void oggpack_adv1(oggpack_buffer *b){
  107800. if(++(b->endbit)>7){
  107801. b->endbit=0;
  107802. b->ptr++;
  107803. b->endbyte++;
  107804. }
  107805. }
  107806. void oggpackB_adv1(oggpack_buffer *b){
  107807. oggpack_adv1(b);
  107808. }
  107809. /* bits <= 32 */
  107810. long oggpack_read(oggpack_buffer *b,int bits){
  107811. long ret;
  107812. unsigned long m=mask[bits];
  107813. bits+=b->endbit;
  107814. if(b->endbyte+4>=b->storage){
  107815. /* not the main path */
  107816. ret=-1L;
  107817. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107818. }
  107819. ret=b->ptr[0]>>b->endbit;
  107820. if(bits>8){
  107821. ret|=b->ptr[1]<<(8-b->endbit);
  107822. if(bits>16){
  107823. ret|=b->ptr[2]<<(16-b->endbit);
  107824. if(bits>24){
  107825. ret|=b->ptr[3]<<(24-b->endbit);
  107826. if(bits>32 && b->endbit){
  107827. ret|=b->ptr[4]<<(32-b->endbit);
  107828. }
  107829. }
  107830. }
  107831. }
  107832. ret&=m;
  107833. overflow:
  107834. b->ptr+=bits/8;
  107835. b->endbyte+=bits/8;
  107836. b->endbit=bits&7;
  107837. return(ret);
  107838. }
  107839. /* bits <= 32 */
  107840. long oggpackB_read(oggpack_buffer *b,int bits){
  107841. long ret;
  107842. long m=32-bits;
  107843. bits+=b->endbit;
  107844. if(b->endbyte+4>=b->storage){
  107845. /* not the main path */
  107846. ret=-1L;
  107847. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107848. }
  107849. ret=b->ptr[0]<<(24+b->endbit);
  107850. if(bits>8){
  107851. ret|=b->ptr[1]<<(16+b->endbit);
  107852. if(bits>16){
  107853. ret|=b->ptr[2]<<(8+b->endbit);
  107854. if(bits>24){
  107855. ret|=b->ptr[3]<<(b->endbit);
  107856. if(bits>32 && b->endbit)
  107857. ret|=b->ptr[4]>>(8-b->endbit);
  107858. }
  107859. }
  107860. }
  107861. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107862. overflow:
  107863. b->ptr+=bits/8;
  107864. b->endbyte+=bits/8;
  107865. b->endbit=bits&7;
  107866. return(ret);
  107867. }
  107868. long oggpack_read1(oggpack_buffer *b){
  107869. long ret;
  107870. if(b->endbyte>=b->storage){
  107871. /* not the main path */
  107872. ret=-1L;
  107873. goto overflow;
  107874. }
  107875. ret=(b->ptr[0]>>b->endbit)&1;
  107876. overflow:
  107877. b->endbit++;
  107878. if(b->endbit>7){
  107879. b->endbit=0;
  107880. b->ptr++;
  107881. b->endbyte++;
  107882. }
  107883. return(ret);
  107884. }
  107885. long oggpackB_read1(oggpack_buffer *b){
  107886. long ret;
  107887. if(b->endbyte>=b->storage){
  107888. /* not the main path */
  107889. ret=-1L;
  107890. goto overflow;
  107891. }
  107892. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107893. overflow:
  107894. b->endbit++;
  107895. if(b->endbit>7){
  107896. b->endbit=0;
  107897. b->ptr++;
  107898. b->endbyte++;
  107899. }
  107900. return(ret);
  107901. }
  107902. long oggpack_bytes(oggpack_buffer *b){
  107903. return(b->endbyte+(b->endbit+7)/8);
  107904. }
  107905. long oggpack_bits(oggpack_buffer *b){
  107906. return(b->endbyte*8+b->endbit);
  107907. }
  107908. long oggpackB_bytes(oggpack_buffer *b){
  107909. return oggpack_bytes(b);
  107910. }
  107911. long oggpackB_bits(oggpack_buffer *b){
  107912. return oggpack_bits(b);
  107913. }
  107914. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107915. return(b->buffer);
  107916. }
  107917. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107918. return oggpack_get_buffer(b);
  107919. }
  107920. /* Self test of the bitwise routines; everything else is based on
  107921. them, so they damned well better be solid. */
  107922. #ifdef _V_SELFTEST
  107923. #include <stdio.h>
  107924. static int ilog(unsigned int v){
  107925. int ret=0;
  107926. while(v){
  107927. ret++;
  107928. v>>=1;
  107929. }
  107930. return(ret);
  107931. }
  107932. oggpack_buffer o;
  107933. oggpack_buffer r;
  107934. void report(char *in){
  107935. fprintf(stderr,"%s",in);
  107936. exit(1);
  107937. }
  107938. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107939. long bytes,i;
  107940. unsigned char *buffer;
  107941. oggpack_reset(&o);
  107942. for(i=0;i<vals;i++)
  107943. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107944. buffer=oggpack_get_buffer(&o);
  107945. bytes=oggpack_bytes(&o);
  107946. if(bytes!=compsize)report("wrong number of bytes!\n");
  107947. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107948. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107949. report("wrote incorrect value!\n");
  107950. }
  107951. oggpack_readinit(&r,buffer,bytes);
  107952. for(i=0;i<vals;i++){
  107953. int tbit=bits?bits:ilog(b[i]);
  107954. if(oggpack_look(&r,tbit)==-1)
  107955. report("out of data!\n");
  107956. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107957. report("looked at incorrect value!\n");
  107958. if(tbit==1)
  107959. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107960. report("looked at single bit incorrect value!\n");
  107961. if(tbit==1){
  107962. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107963. report("read incorrect single bit value!\n");
  107964. }else{
  107965. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107966. report("read incorrect value!\n");
  107967. }
  107968. }
  107969. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107970. }
  107971. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107972. long bytes,i;
  107973. unsigned char *buffer;
  107974. oggpackB_reset(&o);
  107975. for(i=0;i<vals;i++)
  107976. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107977. buffer=oggpackB_get_buffer(&o);
  107978. bytes=oggpackB_bytes(&o);
  107979. if(bytes!=compsize)report("wrong number of bytes!\n");
  107980. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107981. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107982. report("wrote incorrect value!\n");
  107983. }
  107984. oggpackB_readinit(&r,buffer,bytes);
  107985. for(i=0;i<vals;i++){
  107986. int tbit=bits?bits:ilog(b[i]);
  107987. if(oggpackB_look(&r,tbit)==-1)
  107988. report("out of data!\n");
  107989. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107990. report("looked at incorrect value!\n");
  107991. if(tbit==1)
  107992. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107993. report("looked at single bit incorrect value!\n");
  107994. if(tbit==1){
  107995. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107996. report("read incorrect single bit value!\n");
  107997. }else{
  107998. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107999. report("read incorrect value!\n");
  108000. }
  108001. }
  108002. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108003. }
  108004. int main(void){
  108005. unsigned char *buffer;
  108006. long bytes,i;
  108007. static unsigned long testbuffer1[]=
  108008. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108009. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108010. int test1size=43;
  108011. static unsigned long testbuffer2[]=
  108012. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108013. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108014. 85525151,0,12321,1,349528352};
  108015. int test2size=21;
  108016. static unsigned long testbuffer3[]=
  108017. {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,
  108018. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108019. int test3size=56;
  108020. static unsigned long large[]=
  108021. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108022. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108023. 85525151,0,12321,1,2146528352};
  108024. int onesize=33;
  108025. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108026. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108027. 223,4};
  108028. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108029. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108030. 245,251,128};
  108031. int twosize=6;
  108032. static int two[6]={61,255,255,251,231,29};
  108033. static int twoB[6]={247,63,255,253,249,120};
  108034. int threesize=54;
  108035. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108036. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108037. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108038. 100,52,4,14,18,86,77,1};
  108039. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108040. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108041. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108042. 200,20,254,4,58,106,176,144,0};
  108043. int foursize=38;
  108044. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108045. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108046. 28,2,133,0,1};
  108047. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108048. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108049. 129,10,4,32};
  108050. int fivesize=45;
  108051. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108052. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108053. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108054. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108055. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108056. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108057. int sixsize=7;
  108058. static int six[7]={17,177,170,242,169,19,148};
  108059. static int sixB[7]={136,141,85,79,149,200,41};
  108060. /* Test read/write together */
  108061. /* Later we test against pregenerated bitstreams */
  108062. oggpack_writeinit(&o);
  108063. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108064. cliptest(testbuffer1,test1size,0,one,onesize);
  108065. fprintf(stderr,"ok.");
  108066. fprintf(stderr,"\nNull bit call (LSb): ");
  108067. cliptest(testbuffer3,test3size,0,two,twosize);
  108068. fprintf(stderr,"ok.");
  108069. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108070. cliptest(testbuffer2,test2size,0,three,threesize);
  108071. fprintf(stderr,"ok.");
  108072. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108073. oggpack_reset(&o);
  108074. for(i=0;i<test2size;i++)
  108075. oggpack_write(&o,large[i],32);
  108076. buffer=oggpack_get_buffer(&o);
  108077. bytes=oggpack_bytes(&o);
  108078. oggpack_readinit(&r,buffer,bytes);
  108079. for(i=0;i<test2size;i++){
  108080. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108081. if(oggpack_look(&r,32)!=large[i]){
  108082. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108083. oggpack_look(&r,32),large[i]);
  108084. report("read incorrect value!\n");
  108085. }
  108086. oggpack_adv(&r,32);
  108087. }
  108088. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108089. fprintf(stderr,"ok.");
  108090. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108091. cliptest(testbuffer1,test1size,7,four,foursize);
  108092. fprintf(stderr,"ok.");
  108093. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108094. cliptest(testbuffer2,test2size,17,five,fivesize);
  108095. fprintf(stderr,"ok.");
  108096. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108097. cliptest(testbuffer3,test3size,1,six,sixsize);
  108098. fprintf(stderr,"ok.");
  108099. fprintf(stderr,"\nTesting read past end (LSb): ");
  108100. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108101. for(i=0;i<64;i++){
  108102. if(oggpack_read(&r,1)!=0){
  108103. fprintf(stderr,"failed; got -1 prematurely.\n");
  108104. exit(1);
  108105. }
  108106. }
  108107. if(oggpack_look(&r,1)!=-1 ||
  108108. oggpack_read(&r,1)!=-1){
  108109. fprintf(stderr,"failed; read past end without -1.\n");
  108110. exit(1);
  108111. }
  108112. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108113. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108114. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108115. exit(1);
  108116. }
  108117. if(oggpack_look(&r,18)!=0 ||
  108118. oggpack_look(&r,18)!=0){
  108119. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108120. exit(1);
  108121. }
  108122. if(oggpack_look(&r,19)!=-1 ||
  108123. oggpack_look(&r,19)!=-1){
  108124. fprintf(stderr,"failed; read past end without -1.\n");
  108125. exit(1);
  108126. }
  108127. if(oggpack_look(&r,32)!=-1 ||
  108128. oggpack_look(&r,32)!=-1){
  108129. fprintf(stderr,"failed; read past end without -1.\n");
  108130. exit(1);
  108131. }
  108132. oggpack_writeclear(&o);
  108133. fprintf(stderr,"ok.\n");
  108134. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108135. /* Test read/write together */
  108136. /* Later we test against pregenerated bitstreams */
  108137. oggpackB_writeinit(&o);
  108138. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108139. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108140. fprintf(stderr,"ok.");
  108141. fprintf(stderr,"\nNull bit call (MSb): ");
  108142. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108143. fprintf(stderr,"ok.");
  108144. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108145. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108146. fprintf(stderr,"ok.");
  108147. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108148. oggpackB_reset(&o);
  108149. for(i=0;i<test2size;i++)
  108150. oggpackB_write(&o,large[i],32);
  108151. buffer=oggpackB_get_buffer(&o);
  108152. bytes=oggpackB_bytes(&o);
  108153. oggpackB_readinit(&r,buffer,bytes);
  108154. for(i=0;i<test2size;i++){
  108155. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108156. if(oggpackB_look(&r,32)!=large[i]){
  108157. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108158. oggpackB_look(&r,32),large[i]);
  108159. report("read incorrect value!\n");
  108160. }
  108161. oggpackB_adv(&r,32);
  108162. }
  108163. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108164. fprintf(stderr,"ok.");
  108165. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108166. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108167. fprintf(stderr,"ok.");
  108168. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108169. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108170. fprintf(stderr,"ok.");
  108171. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108172. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108173. fprintf(stderr,"ok.");
  108174. fprintf(stderr,"\nTesting read past end (MSb): ");
  108175. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108176. for(i=0;i<64;i++){
  108177. if(oggpackB_read(&r,1)!=0){
  108178. fprintf(stderr,"failed; got -1 prematurely.\n");
  108179. exit(1);
  108180. }
  108181. }
  108182. if(oggpackB_look(&r,1)!=-1 ||
  108183. oggpackB_read(&r,1)!=-1){
  108184. fprintf(stderr,"failed; read past end without -1.\n");
  108185. exit(1);
  108186. }
  108187. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108188. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108189. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108190. exit(1);
  108191. }
  108192. if(oggpackB_look(&r,18)!=0 ||
  108193. oggpackB_look(&r,18)!=0){
  108194. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108195. exit(1);
  108196. }
  108197. if(oggpackB_look(&r,19)!=-1 ||
  108198. oggpackB_look(&r,19)!=-1){
  108199. fprintf(stderr,"failed; read past end without -1.\n");
  108200. exit(1);
  108201. }
  108202. if(oggpackB_look(&r,32)!=-1 ||
  108203. oggpackB_look(&r,32)!=-1){
  108204. fprintf(stderr,"failed; read past end without -1.\n");
  108205. exit(1);
  108206. }
  108207. oggpackB_writeclear(&o);
  108208. fprintf(stderr,"ok.\n\n");
  108209. return(0);
  108210. }
  108211. #endif /* _V_SELFTEST */
  108212. #undef BUFFER_INCREMENT
  108213. #endif
  108214. /*** End of inlined file: bitwise.c ***/
  108215. /*** Start of inlined file: framing.c ***/
  108216. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108217. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108218. // tasks..
  108219. #if JUCE_MSVC
  108220. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108221. #endif
  108222. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108223. #if JUCE_USE_OGGVORBIS
  108224. #include <stdlib.h>
  108225. #include <string.h>
  108226. /* A complete description of Ogg framing exists in docs/framing.html */
  108227. int ogg_page_version(ogg_page *og){
  108228. return((int)(og->header[4]));
  108229. }
  108230. int ogg_page_continued(ogg_page *og){
  108231. return((int)(og->header[5]&0x01));
  108232. }
  108233. int ogg_page_bos(ogg_page *og){
  108234. return((int)(og->header[5]&0x02));
  108235. }
  108236. int ogg_page_eos(ogg_page *og){
  108237. return((int)(og->header[5]&0x04));
  108238. }
  108239. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108240. unsigned char *page=og->header;
  108241. ogg_int64_t granulepos=page[13]&(0xff);
  108242. granulepos= (granulepos<<8)|(page[12]&0xff);
  108243. granulepos= (granulepos<<8)|(page[11]&0xff);
  108244. granulepos= (granulepos<<8)|(page[10]&0xff);
  108245. granulepos= (granulepos<<8)|(page[9]&0xff);
  108246. granulepos= (granulepos<<8)|(page[8]&0xff);
  108247. granulepos= (granulepos<<8)|(page[7]&0xff);
  108248. granulepos= (granulepos<<8)|(page[6]&0xff);
  108249. return(granulepos);
  108250. }
  108251. int ogg_page_serialno(ogg_page *og){
  108252. return(og->header[14] |
  108253. (og->header[15]<<8) |
  108254. (og->header[16]<<16) |
  108255. (og->header[17]<<24));
  108256. }
  108257. long ogg_page_pageno(ogg_page *og){
  108258. return(og->header[18] |
  108259. (og->header[19]<<8) |
  108260. (og->header[20]<<16) |
  108261. (og->header[21]<<24));
  108262. }
  108263. /* returns the number of packets that are completed on this page (if
  108264. the leading packet is begun on a previous page, but ends on this
  108265. page, it's counted */
  108266. /* NOTE:
  108267. If a page consists of a packet begun on a previous page, and a new
  108268. packet begun (but not completed) on this page, the return will be:
  108269. ogg_page_packets(page) ==1,
  108270. ogg_page_continued(page) !=0
  108271. If a page happens to be a single packet that was begun on a
  108272. previous page, and spans to the next page (in the case of a three or
  108273. more page packet), the return will be:
  108274. ogg_page_packets(page) ==0,
  108275. ogg_page_continued(page) !=0
  108276. */
  108277. int ogg_page_packets(ogg_page *og){
  108278. int i,n=og->header[26],count=0;
  108279. for(i=0;i<n;i++)
  108280. if(og->header[27+i]<255)count++;
  108281. return(count);
  108282. }
  108283. #if 0
  108284. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108285. use the static init below) */
  108286. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108287. int i;
  108288. unsigned long r;
  108289. r = index << 24;
  108290. for (i=0; i<8; i++)
  108291. if (r & 0x80000000UL)
  108292. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108293. polynomial, although we use an
  108294. unreflected alg and an init/final
  108295. of 0, not 0xffffffff */
  108296. else
  108297. r<<=1;
  108298. return (r & 0xffffffffUL);
  108299. }
  108300. #endif
  108301. static const ogg_uint32_t crc_lookup[256]={
  108302. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108303. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108304. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108305. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108306. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108307. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108308. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108309. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108310. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108311. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108312. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108313. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108314. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108315. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108316. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108317. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108318. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108319. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108320. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108321. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108322. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108323. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108324. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108325. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108326. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108327. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108328. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108329. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108330. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108331. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108332. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108333. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108334. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108335. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108336. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108337. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108338. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108339. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108340. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108341. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108342. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108343. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108344. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108345. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108346. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108347. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108348. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108349. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108350. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108351. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108352. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108353. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108354. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108355. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108356. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108357. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108358. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108359. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108360. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108361. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108362. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108363. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108364. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108365. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108366. /* init the encode/decode logical stream state */
  108367. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108368. if(os){
  108369. memset(os,0,sizeof(*os));
  108370. os->body_storage=16*1024;
  108371. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108372. os->lacing_storage=1024;
  108373. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108374. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108375. os->serialno=serialno;
  108376. return(0);
  108377. }
  108378. return(-1);
  108379. }
  108380. /* _clear does not free os, only the non-flat storage within */
  108381. int ogg_stream_clear(ogg_stream_state *os){
  108382. if(os){
  108383. if(os->body_data)_ogg_free(os->body_data);
  108384. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108385. if(os->granule_vals)_ogg_free(os->granule_vals);
  108386. memset(os,0,sizeof(*os));
  108387. }
  108388. return(0);
  108389. }
  108390. int ogg_stream_destroy(ogg_stream_state *os){
  108391. if(os){
  108392. ogg_stream_clear(os);
  108393. _ogg_free(os);
  108394. }
  108395. return(0);
  108396. }
  108397. /* Helpers for ogg_stream_encode; this keeps the structure and
  108398. what's happening fairly clear */
  108399. static void _os_body_expand(ogg_stream_state *os,int needed){
  108400. if(os->body_storage<=os->body_fill+needed){
  108401. os->body_storage+=(needed+1024);
  108402. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108403. }
  108404. }
  108405. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108406. if(os->lacing_storage<=os->lacing_fill+needed){
  108407. os->lacing_storage+=(needed+32);
  108408. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108409. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108410. }
  108411. }
  108412. /* checksum the page */
  108413. /* Direct table CRC; note that this will be faster in the future if we
  108414. perform the checksum silmultaneously with other copies */
  108415. void ogg_page_checksum_set(ogg_page *og){
  108416. if(og){
  108417. ogg_uint32_t crc_reg=0;
  108418. int i;
  108419. /* safety; needed for API behavior, but not framing code */
  108420. og->header[22]=0;
  108421. og->header[23]=0;
  108422. og->header[24]=0;
  108423. og->header[25]=0;
  108424. for(i=0;i<og->header_len;i++)
  108425. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108426. for(i=0;i<og->body_len;i++)
  108427. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108428. og->header[22]=(unsigned char)(crc_reg&0xff);
  108429. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108430. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108431. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108432. }
  108433. }
  108434. /* submit data to the internal buffer of the framing engine */
  108435. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108436. int lacing_vals=op->bytes/255+1,i;
  108437. if(os->body_returned){
  108438. /* advance packet data according to the body_returned pointer. We
  108439. had to keep it around to return a pointer into the buffer last
  108440. call */
  108441. os->body_fill-=os->body_returned;
  108442. if(os->body_fill)
  108443. memmove(os->body_data,os->body_data+os->body_returned,
  108444. os->body_fill);
  108445. os->body_returned=0;
  108446. }
  108447. /* make sure we have the buffer storage */
  108448. _os_body_expand(os,op->bytes);
  108449. _os_lacing_expand(os,lacing_vals);
  108450. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108451. the liability of overly clean abstraction for the time being. It
  108452. will actually be fairly easy to eliminate the extra copy in the
  108453. future */
  108454. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108455. os->body_fill+=op->bytes;
  108456. /* Store lacing vals for this packet */
  108457. for(i=0;i<lacing_vals-1;i++){
  108458. os->lacing_vals[os->lacing_fill+i]=255;
  108459. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108460. }
  108461. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108462. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108463. /* flag the first segment as the beginning of the packet */
  108464. os->lacing_vals[os->lacing_fill]|= 0x100;
  108465. os->lacing_fill+=lacing_vals;
  108466. /* for the sake of completeness */
  108467. os->packetno++;
  108468. if(op->e_o_s)os->e_o_s=1;
  108469. return(0);
  108470. }
  108471. /* This will flush remaining packets into a page (returning nonzero),
  108472. even if there is not enough data to trigger a flush normally
  108473. (undersized page). If there are no packets or partial packets to
  108474. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108475. try to flush a normal sized page like ogg_stream_pageout; a call to
  108476. ogg_stream_flush does not guarantee that all packets have flushed.
  108477. Only a return value of 0 from ogg_stream_flush indicates all packet
  108478. data is flushed into pages.
  108479. since ogg_stream_flush will flush the last page in a stream even if
  108480. it's undersized, you almost certainly want to use ogg_stream_pageout
  108481. (and *not* ogg_stream_flush) unless you specifically need to flush
  108482. an page regardless of size in the middle of a stream. */
  108483. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108484. int i;
  108485. int vals=0;
  108486. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108487. int bytes=0;
  108488. long acc=0;
  108489. ogg_int64_t granule_pos=-1;
  108490. if(maxvals==0)return(0);
  108491. /* construct a page */
  108492. /* decide how many segments to include */
  108493. /* If this is the initial header case, the first page must only include
  108494. the initial header packet */
  108495. if(os->b_o_s==0){ /* 'initial header page' case */
  108496. granule_pos=0;
  108497. for(vals=0;vals<maxvals;vals++){
  108498. if((os->lacing_vals[vals]&0x0ff)<255){
  108499. vals++;
  108500. break;
  108501. }
  108502. }
  108503. }else{
  108504. for(vals=0;vals<maxvals;vals++){
  108505. if(acc>4096)break;
  108506. acc+=os->lacing_vals[vals]&0x0ff;
  108507. if((os->lacing_vals[vals]&0xff)<255)
  108508. granule_pos=os->granule_vals[vals];
  108509. }
  108510. }
  108511. /* construct the header in temp storage */
  108512. memcpy(os->header,"OggS",4);
  108513. /* stream structure version */
  108514. os->header[4]=0x00;
  108515. /* continued packet flag? */
  108516. os->header[5]=0x00;
  108517. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108518. /* first page flag? */
  108519. if(os->b_o_s==0)os->header[5]|=0x02;
  108520. /* last page flag? */
  108521. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108522. os->b_o_s=1;
  108523. /* 64 bits of PCM position */
  108524. for(i=6;i<14;i++){
  108525. os->header[i]=(unsigned char)(granule_pos&0xff);
  108526. granule_pos>>=8;
  108527. }
  108528. /* 32 bits of stream serial number */
  108529. {
  108530. long serialno=os->serialno;
  108531. for(i=14;i<18;i++){
  108532. os->header[i]=(unsigned char)(serialno&0xff);
  108533. serialno>>=8;
  108534. }
  108535. }
  108536. /* 32 bits of page counter (we have both counter and page header
  108537. because this val can roll over) */
  108538. if(os->pageno==-1)os->pageno=0; /* because someone called
  108539. stream_reset; this would be a
  108540. strange thing to do in an
  108541. encode stream, but it has
  108542. plausible uses */
  108543. {
  108544. long pageno=os->pageno++;
  108545. for(i=18;i<22;i++){
  108546. os->header[i]=(unsigned char)(pageno&0xff);
  108547. pageno>>=8;
  108548. }
  108549. }
  108550. /* zero for computation; filled in later */
  108551. os->header[22]=0;
  108552. os->header[23]=0;
  108553. os->header[24]=0;
  108554. os->header[25]=0;
  108555. /* segment table */
  108556. os->header[26]=(unsigned char)(vals&0xff);
  108557. for(i=0;i<vals;i++)
  108558. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108559. /* set pointers in the ogg_page struct */
  108560. og->header=os->header;
  108561. og->header_len=os->header_fill=vals+27;
  108562. og->body=os->body_data+os->body_returned;
  108563. og->body_len=bytes;
  108564. /* advance the lacing data and set the body_returned pointer */
  108565. os->lacing_fill-=vals;
  108566. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108567. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108568. os->body_returned+=bytes;
  108569. /* calculate the checksum */
  108570. ogg_page_checksum_set(og);
  108571. /* done */
  108572. return(1);
  108573. }
  108574. /* This constructs pages from buffered packet segments. The pointers
  108575. returned are to static buffers; do not free. The returned buffers are
  108576. good only until the next call (using the same ogg_stream_state) */
  108577. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108578. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108579. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108580. os->lacing_fill>=255 || /* 'segment table full' case */
  108581. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108582. return(ogg_stream_flush(os,og));
  108583. }
  108584. /* not enough data to construct a page and not end of stream */
  108585. return(0);
  108586. }
  108587. int ogg_stream_eos(ogg_stream_state *os){
  108588. return os->e_o_s;
  108589. }
  108590. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108591. /* This has two layers to place more of the multi-serialno and paging
  108592. control in the application's hands. First, we expose a data buffer
  108593. using ogg_sync_buffer(). The app either copies into the
  108594. buffer, or passes it directly to read(), etc. We then call
  108595. ogg_sync_wrote() to tell how many bytes we just added.
  108596. Pages are returned (pointers into the buffer in ogg_sync_state)
  108597. by ogg_sync_pageout(). The page is then submitted to
  108598. ogg_stream_pagein() along with the appropriate
  108599. ogg_stream_state* (ie, matching serialno). We then get raw
  108600. packets out calling ogg_stream_packetout() with a
  108601. ogg_stream_state. */
  108602. /* initialize the struct to a known state */
  108603. int ogg_sync_init(ogg_sync_state *oy){
  108604. if(oy){
  108605. memset(oy,0,sizeof(*oy));
  108606. }
  108607. return(0);
  108608. }
  108609. /* clear non-flat storage within */
  108610. int ogg_sync_clear(ogg_sync_state *oy){
  108611. if(oy){
  108612. if(oy->data)_ogg_free(oy->data);
  108613. ogg_sync_init(oy);
  108614. }
  108615. return(0);
  108616. }
  108617. int ogg_sync_destroy(ogg_sync_state *oy){
  108618. if(oy){
  108619. ogg_sync_clear(oy);
  108620. _ogg_free(oy);
  108621. }
  108622. return(0);
  108623. }
  108624. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108625. /* first, clear out any space that has been previously returned */
  108626. if(oy->returned){
  108627. oy->fill-=oy->returned;
  108628. if(oy->fill>0)
  108629. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108630. oy->returned=0;
  108631. }
  108632. if(size>oy->storage-oy->fill){
  108633. /* We need to extend the internal buffer */
  108634. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108635. if(oy->data)
  108636. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108637. else
  108638. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108639. oy->storage=newsize;
  108640. }
  108641. /* expose a segment at least as large as requested at the fill mark */
  108642. return((char *)oy->data+oy->fill);
  108643. }
  108644. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108645. if(oy->fill+bytes>oy->storage)return(-1);
  108646. oy->fill+=bytes;
  108647. return(0);
  108648. }
  108649. /* sync the stream. This is meant to be useful for finding page
  108650. boundaries.
  108651. return values for this:
  108652. -n) skipped n bytes
  108653. 0) page not ready; more data (no bytes skipped)
  108654. n) page synced at current location; page length n bytes
  108655. */
  108656. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108657. unsigned char *page=oy->data+oy->returned;
  108658. unsigned char *next;
  108659. long bytes=oy->fill-oy->returned;
  108660. if(oy->headerbytes==0){
  108661. int headerbytes,i;
  108662. if(bytes<27)return(0); /* not enough for a header */
  108663. /* verify capture pattern */
  108664. if(memcmp(page,"OggS",4))goto sync_fail;
  108665. headerbytes=page[26]+27;
  108666. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108667. /* count up body length in the segment table */
  108668. for(i=0;i<page[26];i++)
  108669. oy->bodybytes+=page[27+i];
  108670. oy->headerbytes=headerbytes;
  108671. }
  108672. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108673. /* The whole test page is buffered. Verify the checksum */
  108674. {
  108675. /* Grab the checksum bytes, set the header field to zero */
  108676. char chksum[4];
  108677. ogg_page log;
  108678. memcpy(chksum,page+22,4);
  108679. memset(page+22,0,4);
  108680. /* set up a temp page struct and recompute the checksum */
  108681. log.header=page;
  108682. log.header_len=oy->headerbytes;
  108683. log.body=page+oy->headerbytes;
  108684. log.body_len=oy->bodybytes;
  108685. ogg_page_checksum_set(&log);
  108686. /* Compare */
  108687. if(memcmp(chksum,page+22,4)){
  108688. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108689. at all) */
  108690. /* replace the computed checksum with the one actually read in */
  108691. memcpy(page+22,chksum,4);
  108692. /* Bad checksum. Lose sync */
  108693. goto sync_fail;
  108694. }
  108695. }
  108696. /* yes, have a whole page all ready to go */
  108697. {
  108698. unsigned char *page=oy->data+oy->returned;
  108699. long bytes;
  108700. if(og){
  108701. og->header=page;
  108702. og->header_len=oy->headerbytes;
  108703. og->body=page+oy->headerbytes;
  108704. og->body_len=oy->bodybytes;
  108705. }
  108706. oy->unsynced=0;
  108707. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108708. oy->headerbytes=0;
  108709. oy->bodybytes=0;
  108710. return(bytes);
  108711. }
  108712. sync_fail:
  108713. oy->headerbytes=0;
  108714. oy->bodybytes=0;
  108715. /* search for possible capture */
  108716. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108717. if(!next)
  108718. next=oy->data+oy->fill;
  108719. oy->returned=next-oy->data;
  108720. return(-(next-page));
  108721. }
  108722. /* sync the stream and get a page. Keep trying until we find a page.
  108723. Supress 'sync errors' after reporting the first.
  108724. return values:
  108725. -1) recapture (hole in data)
  108726. 0) need more data
  108727. 1) page returned
  108728. Returns pointers into buffered data; invalidated by next call to
  108729. _stream, _clear, _init, or _buffer */
  108730. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108731. /* all we need to do is verify a page at the head of the stream
  108732. buffer. If it doesn't verify, we look for the next potential
  108733. frame */
  108734. for(;;){
  108735. long ret=ogg_sync_pageseek(oy,og);
  108736. if(ret>0){
  108737. /* have a page */
  108738. return(1);
  108739. }
  108740. if(ret==0){
  108741. /* need more data */
  108742. return(0);
  108743. }
  108744. /* head did not start a synced page... skipped some bytes */
  108745. if(!oy->unsynced){
  108746. oy->unsynced=1;
  108747. return(-1);
  108748. }
  108749. /* loop. keep looking */
  108750. }
  108751. }
  108752. /* add the incoming page to the stream state; we decompose the page
  108753. into packet segments here as well. */
  108754. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108755. unsigned char *header=og->header;
  108756. unsigned char *body=og->body;
  108757. long bodysize=og->body_len;
  108758. int segptr=0;
  108759. int version=ogg_page_version(og);
  108760. int continued=ogg_page_continued(og);
  108761. int bos=ogg_page_bos(og);
  108762. int eos=ogg_page_eos(og);
  108763. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108764. int serialno=ogg_page_serialno(og);
  108765. long pageno=ogg_page_pageno(og);
  108766. int segments=header[26];
  108767. /* clean up 'returned data' */
  108768. {
  108769. long lr=os->lacing_returned;
  108770. long br=os->body_returned;
  108771. /* body data */
  108772. if(br){
  108773. os->body_fill-=br;
  108774. if(os->body_fill)
  108775. memmove(os->body_data,os->body_data+br,os->body_fill);
  108776. os->body_returned=0;
  108777. }
  108778. if(lr){
  108779. /* segment table */
  108780. if(os->lacing_fill-lr){
  108781. memmove(os->lacing_vals,os->lacing_vals+lr,
  108782. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108783. memmove(os->granule_vals,os->granule_vals+lr,
  108784. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108785. }
  108786. os->lacing_fill-=lr;
  108787. os->lacing_packet-=lr;
  108788. os->lacing_returned=0;
  108789. }
  108790. }
  108791. /* check the serial number */
  108792. if(serialno!=os->serialno)return(-1);
  108793. if(version>0)return(-1);
  108794. _os_lacing_expand(os,segments+1);
  108795. /* are we in sequence? */
  108796. if(pageno!=os->pageno){
  108797. int i;
  108798. /* unroll previous partial packet (if any) */
  108799. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108800. os->body_fill-=os->lacing_vals[i]&0xff;
  108801. os->lacing_fill=os->lacing_packet;
  108802. /* make a note of dropped data in segment table */
  108803. if(os->pageno!=-1){
  108804. os->lacing_vals[os->lacing_fill++]=0x400;
  108805. os->lacing_packet++;
  108806. }
  108807. }
  108808. /* are we a 'continued packet' page? If so, we may need to skip
  108809. some segments */
  108810. if(continued){
  108811. if(os->lacing_fill<1 ||
  108812. os->lacing_vals[os->lacing_fill-1]==0x400){
  108813. bos=0;
  108814. for(;segptr<segments;segptr++){
  108815. int val=header[27+segptr];
  108816. body+=val;
  108817. bodysize-=val;
  108818. if(val<255){
  108819. segptr++;
  108820. break;
  108821. }
  108822. }
  108823. }
  108824. }
  108825. if(bodysize){
  108826. _os_body_expand(os,bodysize);
  108827. memcpy(os->body_data+os->body_fill,body,bodysize);
  108828. os->body_fill+=bodysize;
  108829. }
  108830. {
  108831. int saved=-1;
  108832. while(segptr<segments){
  108833. int val=header[27+segptr];
  108834. os->lacing_vals[os->lacing_fill]=val;
  108835. os->granule_vals[os->lacing_fill]=-1;
  108836. if(bos){
  108837. os->lacing_vals[os->lacing_fill]|=0x100;
  108838. bos=0;
  108839. }
  108840. if(val<255)saved=os->lacing_fill;
  108841. os->lacing_fill++;
  108842. segptr++;
  108843. if(val<255)os->lacing_packet=os->lacing_fill;
  108844. }
  108845. /* set the granulepos on the last granuleval of the last full packet */
  108846. if(saved!=-1){
  108847. os->granule_vals[saved]=granulepos;
  108848. }
  108849. }
  108850. if(eos){
  108851. os->e_o_s=1;
  108852. if(os->lacing_fill>0)
  108853. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108854. }
  108855. os->pageno=pageno+1;
  108856. return(0);
  108857. }
  108858. /* clear things to an initial state. Good to call, eg, before seeking */
  108859. int ogg_sync_reset(ogg_sync_state *oy){
  108860. oy->fill=0;
  108861. oy->returned=0;
  108862. oy->unsynced=0;
  108863. oy->headerbytes=0;
  108864. oy->bodybytes=0;
  108865. return(0);
  108866. }
  108867. int ogg_stream_reset(ogg_stream_state *os){
  108868. os->body_fill=0;
  108869. os->body_returned=0;
  108870. os->lacing_fill=0;
  108871. os->lacing_packet=0;
  108872. os->lacing_returned=0;
  108873. os->header_fill=0;
  108874. os->e_o_s=0;
  108875. os->b_o_s=0;
  108876. os->pageno=-1;
  108877. os->packetno=0;
  108878. os->granulepos=0;
  108879. return(0);
  108880. }
  108881. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108882. ogg_stream_reset(os);
  108883. os->serialno=serialno;
  108884. return(0);
  108885. }
  108886. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108887. /* The last part of decode. We have the stream broken into packet
  108888. segments. Now we need to group them into packets (or return the
  108889. out of sync markers) */
  108890. int ptr=os->lacing_returned;
  108891. if(os->lacing_packet<=ptr)return(0);
  108892. if(os->lacing_vals[ptr]&0x400){
  108893. /* we need to tell the codec there's a gap; it might need to
  108894. handle previous packet dependencies. */
  108895. os->lacing_returned++;
  108896. os->packetno++;
  108897. return(-1);
  108898. }
  108899. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108900. to ask if there's a whole packet
  108901. waiting */
  108902. /* Gather the whole packet. We'll have no holes or a partial packet */
  108903. {
  108904. int size=os->lacing_vals[ptr]&0xff;
  108905. int bytes=size;
  108906. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108907. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108908. while(size==255){
  108909. int val=os->lacing_vals[++ptr];
  108910. size=val&0xff;
  108911. if(val&0x200)eos=0x200;
  108912. bytes+=size;
  108913. }
  108914. if(op){
  108915. op->e_o_s=eos;
  108916. op->b_o_s=bos;
  108917. op->packet=os->body_data+os->body_returned;
  108918. op->packetno=os->packetno;
  108919. op->granulepos=os->granule_vals[ptr];
  108920. op->bytes=bytes;
  108921. }
  108922. if(adv){
  108923. os->body_returned+=bytes;
  108924. os->lacing_returned=ptr+1;
  108925. os->packetno++;
  108926. }
  108927. }
  108928. return(1);
  108929. }
  108930. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108931. return _packetout(os,op,1);
  108932. }
  108933. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108934. return _packetout(os,op,0);
  108935. }
  108936. void ogg_packet_clear(ogg_packet *op) {
  108937. _ogg_free(op->packet);
  108938. memset(op, 0, sizeof(*op));
  108939. }
  108940. #ifdef _V_SELFTEST
  108941. #include <stdio.h>
  108942. ogg_stream_state os_en, os_de;
  108943. ogg_sync_state oy;
  108944. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108945. long j;
  108946. static int sequence=0;
  108947. static int lastno=0;
  108948. if(op->bytes!=len){
  108949. fprintf(stderr,"incorrect packet length!\n");
  108950. exit(1);
  108951. }
  108952. if(op->granulepos!=pos){
  108953. fprintf(stderr,"incorrect packet position!\n");
  108954. exit(1);
  108955. }
  108956. /* packet number just follows sequence/gap; adjust the input number
  108957. for that */
  108958. if(no==0){
  108959. sequence=0;
  108960. }else{
  108961. sequence++;
  108962. if(no>lastno+1)
  108963. sequence++;
  108964. }
  108965. lastno=no;
  108966. if(op->packetno!=sequence){
  108967. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108968. (long)(op->packetno),sequence);
  108969. exit(1);
  108970. }
  108971. /* Test data */
  108972. for(j=0;j<op->bytes;j++)
  108973. if(op->packet[j]!=((j+no)&0xff)){
  108974. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108975. j,op->packet[j],(j+no)&0xff);
  108976. exit(1);
  108977. }
  108978. }
  108979. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108980. long j;
  108981. /* Test data */
  108982. for(j=0;j<og->body_len;j++)
  108983. if(og->body[j]!=data[j]){
  108984. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108985. j,data[j],og->body[j]);
  108986. exit(1);
  108987. }
  108988. /* Test header */
  108989. for(j=0;j<og->header_len;j++){
  108990. if(og->header[j]!=header[j]){
  108991. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108992. for(j=0;j<header[26]+27;j++)
  108993. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108994. fprintf(stderr,"\n");
  108995. exit(1);
  108996. }
  108997. }
  108998. if(og->header_len!=header[26]+27){
  108999. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109000. og->header_len,header[26]+27);
  109001. exit(1);
  109002. }
  109003. }
  109004. void print_header(ogg_page *og){
  109005. int j;
  109006. fprintf(stderr,"\nHEADER:\n");
  109007. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109008. og->header[0],og->header[1],og->header[2],og->header[3],
  109009. (int)og->header[4],(int)og->header[5]);
  109010. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109011. (og->header[9]<<24)|(og->header[8]<<16)|
  109012. (og->header[7]<<8)|og->header[6],
  109013. (og->header[17]<<24)|(og->header[16]<<16)|
  109014. (og->header[15]<<8)|og->header[14],
  109015. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109016. (og->header[19]<<8)|og->header[18]);
  109017. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109018. (int)og->header[22],(int)og->header[23],
  109019. (int)og->header[24],(int)og->header[25],
  109020. (int)og->header[26]);
  109021. for(j=27;j<og->header_len;j++)
  109022. fprintf(stderr,"%d ",(int)og->header[j]);
  109023. fprintf(stderr,")\n\n");
  109024. }
  109025. void copy_page(ogg_page *og){
  109026. unsigned char *temp=_ogg_malloc(og->header_len);
  109027. memcpy(temp,og->header,og->header_len);
  109028. og->header=temp;
  109029. temp=_ogg_malloc(og->body_len);
  109030. memcpy(temp,og->body,og->body_len);
  109031. og->body=temp;
  109032. }
  109033. void free_page(ogg_page *og){
  109034. _ogg_free (og->header);
  109035. _ogg_free (og->body);
  109036. }
  109037. void error(void){
  109038. fprintf(stderr,"error!\n");
  109039. exit(1);
  109040. }
  109041. /* 17 only */
  109042. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109043. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109044. 0x01,0x02,0x03,0x04,0,0,0,0,
  109045. 0x15,0xed,0xec,0x91,
  109046. 1,
  109047. 17};
  109048. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109049. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109050. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109051. 0x01,0x02,0x03,0x04,0,0,0,0,
  109052. 0x59,0x10,0x6c,0x2c,
  109053. 1,
  109054. 17};
  109055. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109056. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109057. 0x01,0x02,0x03,0x04,1,0,0,0,
  109058. 0x89,0x33,0x85,0xce,
  109059. 13,
  109060. 254,255,0,255,1,255,245,255,255,0,
  109061. 255,255,90};
  109062. /* nil packets; beginning,middle,end */
  109063. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109064. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109065. 0x01,0x02,0x03,0x04,0,0,0,0,
  109066. 0xff,0x7b,0x23,0x17,
  109067. 1,
  109068. 0};
  109069. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109070. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109071. 0x01,0x02,0x03,0x04,1,0,0,0,
  109072. 0x5c,0x3f,0x66,0xcb,
  109073. 17,
  109074. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109075. 255,255,90,0};
  109076. /* large initial packet */
  109077. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109078. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109079. 0x01,0x02,0x03,0x04,0,0,0,0,
  109080. 0x01,0x27,0x31,0xaa,
  109081. 18,
  109082. 255,255,255,255,255,255,255,255,
  109083. 255,255,255,255,255,255,255,255,255,10};
  109084. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109085. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109086. 0x01,0x02,0x03,0x04,1,0,0,0,
  109087. 0x7f,0x4e,0x8a,0xd2,
  109088. 4,
  109089. 255,4,255,0};
  109090. /* continuing packet test */
  109091. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109092. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109093. 0x01,0x02,0x03,0x04,0,0,0,0,
  109094. 0xff,0x7b,0x23,0x17,
  109095. 1,
  109096. 0};
  109097. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109098. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109099. 0x01,0x02,0x03,0x04,1,0,0,0,
  109100. 0x54,0x05,0x51,0xc8,
  109101. 17,
  109102. 255,255,255,255,255,255,255,255,
  109103. 255,255,255,255,255,255,255,255,255};
  109104. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109105. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109106. 0x01,0x02,0x03,0x04,2,0,0,0,
  109107. 0xc8,0xc3,0xcb,0xed,
  109108. 5,
  109109. 10,255,4,255,0};
  109110. /* page with the 255 segment limit */
  109111. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109112. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109113. 0x01,0x02,0x03,0x04,0,0,0,0,
  109114. 0xff,0x7b,0x23,0x17,
  109115. 1,
  109116. 0};
  109117. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109118. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109119. 0x01,0x02,0x03,0x04,1,0,0,0,
  109120. 0xed,0x2a,0x2e,0xa7,
  109121. 255,
  109122. 10,10,10,10,10,10,10,10,
  109123. 10,10,10,10,10,10,10,10,
  109124. 10,10,10,10,10,10,10,10,
  109125. 10,10,10,10,10,10,10,10,
  109126. 10,10,10,10,10,10,10,10,
  109127. 10,10,10,10,10,10,10,10,
  109128. 10,10,10,10,10,10,10,10,
  109129. 10,10,10,10,10,10,10,10,
  109130. 10,10,10,10,10,10,10,10,
  109131. 10,10,10,10,10,10,10,10,
  109132. 10,10,10,10,10,10,10,10,
  109133. 10,10,10,10,10,10,10,10,
  109134. 10,10,10,10,10,10,10,10,
  109135. 10,10,10,10,10,10,10,10,
  109136. 10,10,10,10,10,10,10,10,
  109137. 10,10,10,10,10,10,10,10,
  109138. 10,10,10,10,10,10,10,10,
  109139. 10,10,10,10,10,10,10,10,
  109140. 10,10,10,10,10,10,10,10,
  109141. 10,10,10,10,10,10,10,10,
  109142. 10,10,10,10,10,10,10,10,
  109143. 10,10,10,10,10,10,10,10,
  109144. 10,10,10,10,10,10,10,10,
  109145. 10,10,10,10,10,10,10,10,
  109146. 10,10,10,10,10,10,10,10,
  109147. 10,10,10,10,10,10,10,10,
  109148. 10,10,10,10,10,10,10,10,
  109149. 10,10,10,10,10,10,10,10,
  109150. 10,10,10,10,10,10,10,10,
  109151. 10,10,10,10,10,10,10,10,
  109152. 10,10,10,10,10,10,10,10,
  109153. 10,10,10,10,10,10,10};
  109154. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109155. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109156. 0x01,0x02,0x03,0x04,2,0,0,0,
  109157. 0x6c,0x3b,0x82,0x3d,
  109158. 1,
  109159. 50};
  109160. /* packet that overspans over an entire page */
  109161. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109162. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109163. 0x01,0x02,0x03,0x04,0,0,0,0,
  109164. 0xff,0x7b,0x23,0x17,
  109165. 1,
  109166. 0};
  109167. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109168. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109169. 0x01,0x02,0x03,0x04,1,0,0,0,
  109170. 0x3c,0xd9,0x4d,0x3f,
  109171. 17,
  109172. 100,255,255,255,255,255,255,255,255,
  109173. 255,255,255,255,255,255,255,255};
  109174. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109175. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109176. 0x01,0x02,0x03,0x04,2,0,0,0,
  109177. 0x01,0xd2,0xe5,0xe5,
  109178. 17,
  109179. 255,255,255,255,255,255,255,255,
  109180. 255,255,255,255,255,255,255,255,255};
  109181. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109182. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109183. 0x01,0x02,0x03,0x04,3,0,0,0,
  109184. 0xef,0xdd,0x88,0xde,
  109185. 7,
  109186. 255,255,75,255,4,255,0};
  109187. /* packet that overspans over an entire page */
  109188. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109189. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109190. 0x01,0x02,0x03,0x04,0,0,0,0,
  109191. 0xff,0x7b,0x23,0x17,
  109192. 1,
  109193. 0};
  109194. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109195. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109196. 0x01,0x02,0x03,0x04,1,0,0,0,
  109197. 0x3c,0xd9,0x4d,0x3f,
  109198. 17,
  109199. 100,255,255,255,255,255,255,255,255,
  109200. 255,255,255,255,255,255,255,255};
  109201. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109202. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109203. 0x01,0x02,0x03,0x04,2,0,0,0,
  109204. 0xd4,0xe0,0x60,0xe5,
  109205. 1,0};
  109206. void test_pack(const int *pl, const int **headers, int byteskip,
  109207. int pageskip, int packetskip){
  109208. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109209. long inptr=0;
  109210. long outptr=0;
  109211. long deptr=0;
  109212. long depacket=0;
  109213. long granule_pos=7,pageno=0;
  109214. int i,j,packets,pageout=pageskip;
  109215. int eosflag=0;
  109216. int bosflag=0;
  109217. int byteskipcount=0;
  109218. ogg_stream_reset(&os_en);
  109219. ogg_stream_reset(&os_de);
  109220. ogg_sync_reset(&oy);
  109221. for(packets=0;packets<packetskip;packets++)
  109222. depacket+=pl[packets];
  109223. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109224. for(i=0;i<packets;i++){
  109225. /* construct a test packet */
  109226. ogg_packet op;
  109227. int len=pl[i];
  109228. op.packet=data+inptr;
  109229. op.bytes=len;
  109230. op.e_o_s=(pl[i+1]<0?1:0);
  109231. op.granulepos=granule_pos;
  109232. granule_pos+=1024;
  109233. for(j=0;j<len;j++)data[inptr++]=i+j;
  109234. /* submit the test packet */
  109235. ogg_stream_packetin(&os_en,&op);
  109236. /* retrieve any finished pages */
  109237. {
  109238. ogg_page og;
  109239. while(ogg_stream_pageout(&os_en,&og)){
  109240. /* We have a page. Check it carefully */
  109241. fprintf(stderr,"%ld, ",pageno);
  109242. if(headers[pageno]==NULL){
  109243. fprintf(stderr,"coded too many pages!\n");
  109244. exit(1);
  109245. }
  109246. check_page(data+outptr,headers[pageno],&og);
  109247. outptr+=og.body_len;
  109248. pageno++;
  109249. if(pageskip){
  109250. bosflag=1;
  109251. pageskip--;
  109252. deptr+=og.body_len;
  109253. }
  109254. /* have a complete page; submit it to sync/decode */
  109255. {
  109256. ogg_page og_de;
  109257. ogg_packet op_de,op_de2;
  109258. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109259. char *next=buf;
  109260. byteskipcount+=og.header_len;
  109261. if(byteskipcount>byteskip){
  109262. memcpy(next,og.header,byteskipcount-byteskip);
  109263. next+=byteskipcount-byteskip;
  109264. byteskipcount=byteskip;
  109265. }
  109266. byteskipcount+=og.body_len;
  109267. if(byteskipcount>byteskip){
  109268. memcpy(next,og.body,byteskipcount-byteskip);
  109269. next+=byteskipcount-byteskip;
  109270. byteskipcount=byteskip;
  109271. }
  109272. ogg_sync_wrote(&oy,next-buf);
  109273. while(1){
  109274. int ret=ogg_sync_pageout(&oy,&og_de);
  109275. if(ret==0)break;
  109276. if(ret<0)continue;
  109277. /* got a page. Happy happy. Verify that it's good. */
  109278. fprintf(stderr,"(%ld), ",pageout);
  109279. check_page(data+deptr,headers[pageout],&og_de);
  109280. deptr+=og_de.body_len;
  109281. pageout++;
  109282. /* submit it to deconstitution */
  109283. ogg_stream_pagein(&os_de,&og_de);
  109284. /* packets out? */
  109285. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109286. ogg_stream_packetpeek(&os_de,NULL);
  109287. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109288. /* verify peek and out match */
  109289. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109290. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109291. depacket);
  109292. exit(1);
  109293. }
  109294. /* verify the packet! */
  109295. /* check data */
  109296. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109297. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109298. depacket);
  109299. exit(1);
  109300. }
  109301. /* check bos flag */
  109302. if(bosflag==0 && op_de.b_o_s==0){
  109303. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109304. exit(1);
  109305. }
  109306. if(bosflag && op_de.b_o_s){
  109307. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109308. exit(1);
  109309. }
  109310. bosflag=1;
  109311. depacket+=op_de.bytes;
  109312. /* check eos flag */
  109313. if(eosflag){
  109314. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109315. exit(1);
  109316. }
  109317. if(op_de.e_o_s)eosflag=1;
  109318. /* check granulepos flag */
  109319. if(op_de.granulepos!=-1){
  109320. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109321. }
  109322. }
  109323. }
  109324. }
  109325. }
  109326. }
  109327. }
  109328. _ogg_free(data);
  109329. if(headers[pageno]!=NULL){
  109330. fprintf(stderr,"did not write last page!\n");
  109331. exit(1);
  109332. }
  109333. if(headers[pageout]!=NULL){
  109334. fprintf(stderr,"did not decode last page!\n");
  109335. exit(1);
  109336. }
  109337. if(inptr!=outptr){
  109338. fprintf(stderr,"encoded page data incomplete!\n");
  109339. exit(1);
  109340. }
  109341. if(inptr!=deptr){
  109342. fprintf(stderr,"decoded page data incomplete!\n");
  109343. exit(1);
  109344. }
  109345. if(inptr!=depacket){
  109346. fprintf(stderr,"decoded packet data incomplete!\n");
  109347. exit(1);
  109348. }
  109349. if(!eosflag){
  109350. fprintf(stderr,"Never got a packet with EOS set!\n");
  109351. exit(1);
  109352. }
  109353. fprintf(stderr,"ok.\n");
  109354. }
  109355. int main(void){
  109356. ogg_stream_init(&os_en,0x04030201);
  109357. ogg_stream_init(&os_de,0x04030201);
  109358. ogg_sync_init(&oy);
  109359. /* Exercise each code path in the framing code. Also verify that
  109360. the checksums are working. */
  109361. {
  109362. /* 17 only */
  109363. const int packets[]={17, -1};
  109364. const int *headret[]={head1_0,NULL};
  109365. fprintf(stderr,"testing single page encoding... ");
  109366. test_pack(packets,headret,0,0,0);
  109367. }
  109368. {
  109369. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109370. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109371. const int *headret[]={head1_1,head2_1,NULL};
  109372. fprintf(stderr,"testing basic page encoding... ");
  109373. test_pack(packets,headret,0,0,0);
  109374. }
  109375. {
  109376. /* nil packets; beginning,middle,end */
  109377. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109378. const int *headret[]={head1_2,head2_2,NULL};
  109379. fprintf(stderr,"testing basic nil packets... ");
  109380. test_pack(packets,headret,0,0,0);
  109381. }
  109382. {
  109383. /* large initial packet */
  109384. const int packets[]={4345,259,255,-1};
  109385. const int *headret[]={head1_3,head2_3,NULL};
  109386. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109387. test_pack(packets,headret,0,0,0);
  109388. }
  109389. {
  109390. /* continuing packet test */
  109391. const int packets[]={0,4345,259,255,-1};
  109392. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109393. fprintf(stderr,"testing single packet page span... ");
  109394. test_pack(packets,headret,0,0,0);
  109395. }
  109396. /* page with the 255 segment limit */
  109397. {
  109398. const int packets[]={0,10,10,10,10,10,10,10,10,
  109399. 10,10,10,10,10,10,10,10,
  109400. 10,10,10,10,10,10,10,10,
  109401. 10,10,10,10,10,10,10,10,
  109402. 10,10,10,10,10,10,10,10,
  109403. 10,10,10,10,10,10,10,10,
  109404. 10,10,10,10,10,10,10,10,
  109405. 10,10,10,10,10,10,10,10,
  109406. 10,10,10,10,10,10,10,10,
  109407. 10,10,10,10,10,10,10,10,
  109408. 10,10,10,10,10,10,10,10,
  109409. 10,10,10,10,10,10,10,10,
  109410. 10,10,10,10,10,10,10,10,
  109411. 10,10,10,10,10,10,10,10,
  109412. 10,10,10,10,10,10,10,10,
  109413. 10,10,10,10,10,10,10,10,
  109414. 10,10,10,10,10,10,10,10,
  109415. 10,10,10,10,10,10,10,10,
  109416. 10,10,10,10,10,10,10,10,
  109417. 10,10,10,10,10,10,10,10,
  109418. 10,10,10,10,10,10,10,10,
  109419. 10,10,10,10,10,10,10,10,
  109420. 10,10,10,10,10,10,10,10,
  109421. 10,10,10,10,10,10,10,10,
  109422. 10,10,10,10,10,10,10,10,
  109423. 10,10,10,10,10,10,10,10,
  109424. 10,10,10,10,10,10,10,10,
  109425. 10,10,10,10,10,10,10,10,
  109426. 10,10,10,10,10,10,10,10,
  109427. 10,10,10,10,10,10,10,10,
  109428. 10,10,10,10,10,10,10,10,
  109429. 10,10,10,10,10,10,10,50,-1};
  109430. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109431. fprintf(stderr,"testing max packet segments... ");
  109432. test_pack(packets,headret,0,0,0);
  109433. }
  109434. {
  109435. /* packet that overspans over an entire page */
  109436. const int packets[]={0,100,9000,259,255,-1};
  109437. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109438. fprintf(stderr,"testing very large packets... ");
  109439. test_pack(packets,headret,0,0,0);
  109440. }
  109441. {
  109442. /* test for the libogg 1.1.1 resync in large continuation bug
  109443. found by Josh Coalson) */
  109444. const int packets[]={0,100,9000,259,255,-1};
  109445. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109446. fprintf(stderr,"testing continuation resync in very large packets... ");
  109447. test_pack(packets,headret,100,2,3);
  109448. }
  109449. {
  109450. /* term only page. why not? */
  109451. const int packets[]={0,100,4080,-1};
  109452. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109453. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109454. test_pack(packets,headret,0,0,0);
  109455. }
  109456. {
  109457. /* build a bunch of pages for testing */
  109458. unsigned char *data=_ogg_malloc(1024*1024);
  109459. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109460. int inptr=0,i,j;
  109461. ogg_page og[5];
  109462. ogg_stream_reset(&os_en);
  109463. for(i=0;pl[i]!=-1;i++){
  109464. ogg_packet op;
  109465. int len=pl[i];
  109466. op.packet=data+inptr;
  109467. op.bytes=len;
  109468. op.e_o_s=(pl[i+1]<0?1:0);
  109469. op.granulepos=(i+1)*1000;
  109470. for(j=0;j<len;j++)data[inptr++]=i+j;
  109471. ogg_stream_packetin(&os_en,&op);
  109472. }
  109473. _ogg_free(data);
  109474. /* retrieve finished pages */
  109475. for(i=0;i<5;i++){
  109476. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109477. fprintf(stderr,"Too few pages output building sync tests!\n");
  109478. exit(1);
  109479. }
  109480. copy_page(&og[i]);
  109481. }
  109482. /* Test lost pages on pagein/packetout: no rollback */
  109483. {
  109484. ogg_page temp;
  109485. ogg_packet test;
  109486. fprintf(stderr,"Testing loss of pages... ");
  109487. ogg_sync_reset(&oy);
  109488. ogg_stream_reset(&os_de);
  109489. for(i=0;i<5;i++){
  109490. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109491. og[i].header_len);
  109492. ogg_sync_wrote(&oy,og[i].header_len);
  109493. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109494. ogg_sync_wrote(&oy,og[i].body_len);
  109495. }
  109496. ogg_sync_pageout(&oy,&temp);
  109497. ogg_stream_pagein(&os_de,&temp);
  109498. ogg_sync_pageout(&oy,&temp);
  109499. ogg_stream_pagein(&os_de,&temp);
  109500. ogg_sync_pageout(&oy,&temp);
  109501. /* skip */
  109502. ogg_sync_pageout(&oy,&temp);
  109503. ogg_stream_pagein(&os_de,&temp);
  109504. /* do we get the expected results/packets? */
  109505. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109506. checkpacket(&test,0,0,0);
  109507. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109508. checkpacket(&test,100,1,-1);
  109509. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109510. checkpacket(&test,4079,2,3000);
  109511. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109512. fprintf(stderr,"Error: loss of page did not return error\n");
  109513. exit(1);
  109514. }
  109515. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109516. checkpacket(&test,76,5,-1);
  109517. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109518. checkpacket(&test,34,6,-1);
  109519. fprintf(stderr,"ok.\n");
  109520. }
  109521. /* Test lost pages on pagein/packetout: rollback with continuation */
  109522. {
  109523. ogg_page temp;
  109524. ogg_packet test;
  109525. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109526. ogg_sync_reset(&oy);
  109527. ogg_stream_reset(&os_de);
  109528. for(i=0;i<5;i++){
  109529. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109530. og[i].header_len);
  109531. ogg_sync_wrote(&oy,og[i].header_len);
  109532. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109533. ogg_sync_wrote(&oy,og[i].body_len);
  109534. }
  109535. ogg_sync_pageout(&oy,&temp);
  109536. ogg_stream_pagein(&os_de,&temp);
  109537. ogg_sync_pageout(&oy,&temp);
  109538. ogg_stream_pagein(&os_de,&temp);
  109539. ogg_sync_pageout(&oy,&temp);
  109540. ogg_stream_pagein(&os_de,&temp);
  109541. ogg_sync_pageout(&oy,&temp);
  109542. /* skip */
  109543. ogg_sync_pageout(&oy,&temp);
  109544. ogg_stream_pagein(&os_de,&temp);
  109545. /* do we get the expected results/packets? */
  109546. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109547. checkpacket(&test,0,0,0);
  109548. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109549. checkpacket(&test,100,1,-1);
  109550. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109551. checkpacket(&test,4079,2,3000);
  109552. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109553. checkpacket(&test,2956,3,4000);
  109554. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109555. fprintf(stderr,"Error: loss of page did not return error\n");
  109556. exit(1);
  109557. }
  109558. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109559. checkpacket(&test,300,13,14000);
  109560. fprintf(stderr,"ok.\n");
  109561. }
  109562. /* the rest only test sync */
  109563. {
  109564. ogg_page og_de;
  109565. /* Test fractional page inputs: incomplete capture */
  109566. fprintf(stderr,"Testing sync on partial inputs... ");
  109567. ogg_sync_reset(&oy);
  109568. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109569. 3);
  109570. ogg_sync_wrote(&oy,3);
  109571. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109572. /* Test fractional page inputs: incomplete fixed header */
  109573. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109574. 20);
  109575. ogg_sync_wrote(&oy,20);
  109576. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109577. /* Test fractional page inputs: incomplete header */
  109578. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109579. 5);
  109580. ogg_sync_wrote(&oy,5);
  109581. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109582. /* Test fractional page inputs: incomplete body */
  109583. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109584. og[1].header_len-28);
  109585. ogg_sync_wrote(&oy,og[1].header_len-28);
  109586. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109587. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109588. ogg_sync_wrote(&oy,1000);
  109589. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109590. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109591. og[1].body_len-1000);
  109592. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109593. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109594. fprintf(stderr,"ok.\n");
  109595. }
  109596. /* Test fractional page inputs: page + incomplete capture */
  109597. {
  109598. ogg_page og_de;
  109599. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109600. ogg_sync_reset(&oy);
  109601. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109602. og[1].header_len);
  109603. ogg_sync_wrote(&oy,og[1].header_len);
  109604. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109605. og[1].body_len);
  109606. ogg_sync_wrote(&oy,og[1].body_len);
  109607. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109608. 20);
  109609. ogg_sync_wrote(&oy,20);
  109610. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109611. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109612. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109613. og[1].header_len-20);
  109614. ogg_sync_wrote(&oy,og[1].header_len-20);
  109615. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109616. og[1].body_len);
  109617. ogg_sync_wrote(&oy,og[1].body_len);
  109618. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109619. fprintf(stderr,"ok.\n");
  109620. }
  109621. /* Test recapture: garbage + page */
  109622. {
  109623. ogg_page og_de;
  109624. fprintf(stderr,"Testing search for capture... ");
  109625. ogg_sync_reset(&oy);
  109626. /* 'garbage' */
  109627. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109628. og[1].body_len);
  109629. ogg_sync_wrote(&oy,og[1].body_len);
  109630. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109631. og[1].header_len);
  109632. ogg_sync_wrote(&oy,og[1].header_len);
  109633. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109634. og[1].body_len);
  109635. ogg_sync_wrote(&oy,og[1].body_len);
  109636. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109637. 20);
  109638. ogg_sync_wrote(&oy,20);
  109639. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109640. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109641. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109642. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109643. og[2].header_len-20);
  109644. ogg_sync_wrote(&oy,og[2].header_len-20);
  109645. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109646. og[2].body_len);
  109647. ogg_sync_wrote(&oy,og[2].body_len);
  109648. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109649. fprintf(stderr,"ok.\n");
  109650. }
  109651. /* Test recapture: page + garbage + page */
  109652. {
  109653. ogg_page og_de;
  109654. fprintf(stderr,"Testing recapture... ");
  109655. ogg_sync_reset(&oy);
  109656. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109657. og[1].header_len);
  109658. ogg_sync_wrote(&oy,og[1].header_len);
  109659. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109660. og[1].body_len);
  109661. ogg_sync_wrote(&oy,og[1].body_len);
  109662. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109663. og[2].header_len);
  109664. ogg_sync_wrote(&oy,og[2].header_len);
  109665. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109666. og[2].header_len);
  109667. ogg_sync_wrote(&oy,og[2].header_len);
  109668. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109669. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109670. og[2].body_len-5);
  109671. ogg_sync_wrote(&oy,og[2].body_len-5);
  109672. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109673. og[3].header_len);
  109674. ogg_sync_wrote(&oy,og[3].header_len);
  109675. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109676. og[3].body_len);
  109677. ogg_sync_wrote(&oy,og[3].body_len);
  109678. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109679. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109680. fprintf(stderr,"ok.\n");
  109681. }
  109682. /* Free page data that was previously copied */
  109683. {
  109684. for(i=0;i<5;i++){
  109685. free_page(&og[i]);
  109686. }
  109687. }
  109688. }
  109689. return(0);
  109690. }
  109691. #endif
  109692. #endif
  109693. /*** End of inlined file: framing.c ***/
  109694. /*** Start of inlined file: analysis.c ***/
  109695. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109696. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109697. // tasks..
  109698. #if JUCE_MSVC
  109699. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109700. #endif
  109701. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109702. #if JUCE_USE_OGGVORBIS
  109703. #include <stdio.h>
  109704. #include <string.h>
  109705. #include <math.h>
  109706. /*** Start of inlined file: codec_internal.h ***/
  109707. #ifndef _V_CODECI_H_
  109708. #define _V_CODECI_H_
  109709. /*** Start of inlined file: envelope.h ***/
  109710. #ifndef _V_ENVELOPE_
  109711. #define _V_ENVELOPE_
  109712. /*** Start of inlined file: mdct.h ***/
  109713. #ifndef _OGG_mdct_H_
  109714. #define _OGG_mdct_H_
  109715. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109716. #ifdef MDCT_INTEGERIZED
  109717. #define DATA_TYPE int
  109718. #define REG_TYPE register int
  109719. #define TRIGBITS 14
  109720. #define cPI3_8 6270
  109721. #define cPI2_8 11585
  109722. #define cPI1_8 15137
  109723. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109724. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109725. #define HALVE(x) ((x)>>1)
  109726. #else
  109727. #define DATA_TYPE float
  109728. #define REG_TYPE float
  109729. #define cPI3_8 .38268343236508977175F
  109730. #define cPI2_8 .70710678118654752441F
  109731. #define cPI1_8 .92387953251128675613F
  109732. #define FLOAT_CONV(x) (x)
  109733. #define MULT_NORM(x) (x)
  109734. #define HALVE(x) ((x)*.5f)
  109735. #endif
  109736. typedef struct {
  109737. int n;
  109738. int log2n;
  109739. DATA_TYPE *trig;
  109740. int *bitrev;
  109741. DATA_TYPE scale;
  109742. } mdct_lookup;
  109743. extern void mdct_init(mdct_lookup *lookup,int n);
  109744. extern void mdct_clear(mdct_lookup *l);
  109745. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109746. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109747. #endif
  109748. /*** End of inlined file: mdct.h ***/
  109749. #define VE_PRE 16
  109750. #define VE_WIN 4
  109751. #define VE_POST 2
  109752. #define VE_AMP (VE_PRE+VE_POST-1)
  109753. #define VE_BANDS 7
  109754. #define VE_NEARDC 15
  109755. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109756. #define VE_MAXSTRETCH 12 /* one-third full block */
  109757. typedef struct {
  109758. float ampbuf[VE_AMP];
  109759. int ampptr;
  109760. float nearDC[VE_NEARDC];
  109761. float nearDC_acc;
  109762. float nearDC_partialacc;
  109763. int nearptr;
  109764. } envelope_filter_state;
  109765. typedef struct {
  109766. int begin;
  109767. int end;
  109768. float *window;
  109769. float total;
  109770. } envelope_band;
  109771. typedef struct {
  109772. int ch;
  109773. int winlength;
  109774. int searchstep;
  109775. float minenergy;
  109776. mdct_lookup mdct;
  109777. float *mdct_win;
  109778. envelope_band band[VE_BANDS];
  109779. envelope_filter_state *filter;
  109780. int stretch;
  109781. int *mark;
  109782. long storage;
  109783. long current;
  109784. long curmark;
  109785. long cursor;
  109786. } envelope_lookup;
  109787. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109788. extern void _ve_envelope_clear(envelope_lookup *e);
  109789. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109790. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109791. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109792. #endif
  109793. /*** End of inlined file: envelope.h ***/
  109794. /*** Start of inlined file: codebook.h ***/
  109795. #ifndef _V_CODEBOOK_H_
  109796. #define _V_CODEBOOK_H_
  109797. /* This structure encapsulates huffman and VQ style encoding books; it
  109798. doesn't do anything specific to either.
  109799. valuelist/quantlist are nonNULL (and q_* significant) only if
  109800. there's entry->value mapping to be done.
  109801. If encode-side mapping must be done (and thus the entry needs to be
  109802. hunted), the auxiliary encode pointer will point to a decision
  109803. tree. This is true of both VQ and huffman, but is mostly useful
  109804. with VQ.
  109805. */
  109806. typedef struct static_codebook{
  109807. long dim; /* codebook dimensions (elements per vector) */
  109808. long entries; /* codebook entries */
  109809. long *lengthlist; /* codeword lengths in bits */
  109810. /* mapping ***************************************************************/
  109811. int maptype; /* 0=none
  109812. 1=implicitly populated values from map column
  109813. 2=listed arbitrary values */
  109814. /* The below does a linear, single monotonic sequence mapping. */
  109815. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109816. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109817. int q_quant; /* bits: 0 < quant <= 16 */
  109818. int q_sequencep; /* bitflag */
  109819. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109820. map == 2: list of dim*entries quantized entry vals
  109821. */
  109822. /* encode helpers ********************************************************/
  109823. struct encode_aux_nearestmatch *nearest_tree;
  109824. struct encode_aux_threshmatch *thresh_tree;
  109825. struct encode_aux_pigeonhole *pigeon_tree;
  109826. int allocedp;
  109827. } static_codebook;
  109828. /* this structures an arbitrary trained book to quickly find the
  109829. nearest cell match */
  109830. typedef struct encode_aux_nearestmatch{
  109831. /* pre-calculated partitioning tree */
  109832. long *ptr0;
  109833. long *ptr1;
  109834. long *p; /* decision points (each is an entry) */
  109835. long *q; /* decision points (each is an entry) */
  109836. long aux; /* number of tree entries */
  109837. long alloc;
  109838. } encode_aux_nearestmatch;
  109839. /* assumes a maptype of 1; encode side only, so that's OK */
  109840. typedef struct encode_aux_threshmatch{
  109841. float *quantthresh;
  109842. long *quantmap;
  109843. int quantvals;
  109844. int threshvals;
  109845. } encode_aux_threshmatch;
  109846. typedef struct encode_aux_pigeonhole{
  109847. float min;
  109848. float del;
  109849. int mapentries;
  109850. int quantvals;
  109851. long *pigeonmap;
  109852. long fittotal;
  109853. long *fitlist;
  109854. long *fitmap;
  109855. long *fitlength;
  109856. } encode_aux_pigeonhole;
  109857. typedef struct codebook{
  109858. long dim; /* codebook dimensions (elements per vector) */
  109859. long entries; /* codebook entries */
  109860. long used_entries; /* populated codebook entries */
  109861. const static_codebook *c;
  109862. /* for encode, the below are entry-ordered, fully populated */
  109863. /* for decode, the below are ordered by bitreversed codeword and only
  109864. used entries are populated */
  109865. float *valuelist; /* list of dim*entries actual entry values */
  109866. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109867. int *dec_index; /* only used if sparseness collapsed */
  109868. char *dec_codelengths;
  109869. ogg_uint32_t *dec_firsttable;
  109870. int dec_firsttablen;
  109871. int dec_maxlength;
  109872. } codebook;
  109873. extern void vorbis_staticbook_clear(static_codebook *b);
  109874. extern void vorbis_staticbook_destroy(static_codebook *b);
  109875. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109876. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109877. extern void vorbis_book_clear(codebook *b);
  109878. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109879. extern float *_book_logdist(const static_codebook *b,float *vals);
  109880. extern float _float32_unpack(long val);
  109881. extern long _float32_pack(float val);
  109882. extern int _best(codebook *book, float *a, int step);
  109883. extern int _ilog(unsigned int v);
  109884. extern long _book_maptype1_quantvals(const static_codebook *b);
  109885. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109886. extern long vorbis_book_codeword(codebook *book,int entry);
  109887. extern long vorbis_book_codelen(codebook *book,int entry);
  109888. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109889. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109890. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109891. extern int vorbis_book_errorv(codebook *book, float *a);
  109892. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109893. oggpack_buffer *b);
  109894. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109895. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109896. oggpack_buffer *b,int n);
  109897. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109898. oggpack_buffer *b,int n);
  109899. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109900. oggpack_buffer *b,int n);
  109901. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109902. long off,int ch,
  109903. oggpack_buffer *b,int n);
  109904. #endif
  109905. /*** End of inlined file: codebook.h ***/
  109906. #define BLOCKTYPE_IMPULSE 0
  109907. #define BLOCKTYPE_PADDING 1
  109908. #define BLOCKTYPE_TRANSITION 0
  109909. #define BLOCKTYPE_LONG 1
  109910. #define PACKETBLOBS 15
  109911. typedef struct vorbis_block_internal{
  109912. float **pcmdelay; /* this is a pointer into local storage */
  109913. float ampmax;
  109914. int blocktype;
  109915. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109916. blob [PACKETBLOBS/2] points to
  109917. the oggpack_buffer in the
  109918. main vorbis_block */
  109919. } vorbis_block_internal;
  109920. typedef void vorbis_look_floor;
  109921. typedef void vorbis_look_residue;
  109922. typedef void vorbis_look_transform;
  109923. /* mode ************************************************************/
  109924. typedef struct {
  109925. int blockflag;
  109926. int windowtype;
  109927. int transformtype;
  109928. int mapping;
  109929. } vorbis_info_mode;
  109930. typedef void vorbis_info_floor;
  109931. typedef void vorbis_info_residue;
  109932. typedef void vorbis_info_mapping;
  109933. /*** Start of inlined file: psy.h ***/
  109934. #ifndef _V_PSY_H_
  109935. #define _V_PSY_H_
  109936. /*** Start of inlined file: smallft.h ***/
  109937. #ifndef _V_SMFT_H_
  109938. #define _V_SMFT_H_
  109939. typedef struct {
  109940. int n;
  109941. float *trigcache;
  109942. int *splitcache;
  109943. } drft_lookup;
  109944. extern void drft_forward(drft_lookup *l,float *data);
  109945. extern void drft_backward(drft_lookup *l,float *data);
  109946. extern void drft_init(drft_lookup *l,int n);
  109947. extern void drft_clear(drft_lookup *l);
  109948. #endif
  109949. /*** End of inlined file: smallft.h ***/
  109950. /*** Start of inlined file: backends.h ***/
  109951. /* this is exposed up here because we need it for static modes.
  109952. Lookups for each backend aren't exposed because there's no reason
  109953. to do so */
  109954. #ifndef _vorbis_backend_h_
  109955. #define _vorbis_backend_h_
  109956. /* this would all be simpler/shorter with templates, but.... */
  109957. /* Floor backend generic *****************************************/
  109958. typedef struct{
  109959. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109960. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109961. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109962. void (*free_info) (vorbis_info_floor *);
  109963. void (*free_look) (vorbis_look_floor *);
  109964. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109965. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109966. void *buffer,float *);
  109967. } vorbis_func_floor;
  109968. typedef struct{
  109969. int order;
  109970. long rate;
  109971. long barkmap;
  109972. int ampbits;
  109973. int ampdB;
  109974. int numbooks; /* <= 16 */
  109975. int books[16];
  109976. float lessthan; /* encode-only config setting hacks for libvorbis */
  109977. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109978. } vorbis_info_floor0;
  109979. #define VIF_POSIT 63
  109980. #define VIF_CLASS 16
  109981. #define VIF_PARTS 31
  109982. typedef struct{
  109983. int partitions; /* 0 to 31 */
  109984. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109985. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109986. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109987. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109988. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109989. int mult; /* 1 2 3 or 4 */
  109990. int postlist[VIF_POSIT+2]; /* first two implicit */
  109991. /* encode side analysis parameters */
  109992. float maxover;
  109993. float maxunder;
  109994. float maxerr;
  109995. float twofitweight;
  109996. float twofitatten;
  109997. int n;
  109998. } vorbis_info_floor1;
  109999. /* Residue backend generic *****************************************/
  110000. typedef struct{
  110001. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110002. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110003. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110004. vorbis_info_residue *);
  110005. void (*free_info) (vorbis_info_residue *);
  110006. void (*free_look) (vorbis_look_residue *);
  110007. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110008. float **,int *,int);
  110009. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110010. vorbis_look_residue *,
  110011. float **,float **,int *,int,long **);
  110012. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110013. float **,int *,int);
  110014. } vorbis_func_residue;
  110015. typedef struct vorbis_info_residue0{
  110016. /* block-partitioned VQ coded straight residue */
  110017. long begin;
  110018. long end;
  110019. /* first stage (lossless partitioning) */
  110020. int grouping; /* group n vectors per partition */
  110021. int partitions; /* possible codebooks for a partition */
  110022. int groupbook; /* huffbook for partitioning */
  110023. int secondstages[64]; /* expanded out to pointers in lookup */
  110024. int booklist[256]; /* list of second stage books */
  110025. float classmetric1[64];
  110026. float classmetric2[64];
  110027. } vorbis_info_residue0;
  110028. /* Mapping backend generic *****************************************/
  110029. typedef struct{
  110030. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110031. oggpack_buffer *);
  110032. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110033. void (*free_info) (vorbis_info_mapping *);
  110034. int (*forward) (struct vorbis_block *vb);
  110035. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110036. } vorbis_func_mapping;
  110037. typedef struct vorbis_info_mapping0{
  110038. int submaps; /* <= 16 */
  110039. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110040. int floorsubmap[16]; /* [mux] submap to floors */
  110041. int residuesubmap[16]; /* [mux] submap to residue */
  110042. int coupling_steps;
  110043. int coupling_mag[256];
  110044. int coupling_ang[256];
  110045. } vorbis_info_mapping0;
  110046. #endif
  110047. /*** End of inlined file: backends.h ***/
  110048. #ifndef EHMER_MAX
  110049. #define EHMER_MAX 56
  110050. #endif
  110051. /* psychoacoustic setup ********************************************/
  110052. #define P_BANDS 17 /* 62Hz to 16kHz */
  110053. #define P_LEVELS 8 /* 30dB to 100dB */
  110054. #define P_LEVEL_0 30. /* 30 dB */
  110055. #define P_NOISECURVES 3
  110056. #define NOISE_COMPAND_LEVELS 40
  110057. typedef struct vorbis_info_psy{
  110058. int blockflag;
  110059. float ath_adjatt;
  110060. float ath_maxatt;
  110061. float tone_masteratt[P_NOISECURVES];
  110062. float tone_centerboost;
  110063. float tone_decay;
  110064. float tone_abs_limit;
  110065. float toneatt[P_BANDS];
  110066. int noisemaskp;
  110067. float noisemaxsupp;
  110068. float noisewindowlo;
  110069. float noisewindowhi;
  110070. int noisewindowlomin;
  110071. int noisewindowhimin;
  110072. int noisewindowfixed;
  110073. float noiseoff[P_NOISECURVES][P_BANDS];
  110074. float noisecompand[NOISE_COMPAND_LEVELS];
  110075. float max_curve_dB;
  110076. int normal_channel_p;
  110077. int normal_point_p;
  110078. int normal_start;
  110079. int normal_partition;
  110080. double normal_thresh;
  110081. } vorbis_info_psy;
  110082. typedef struct{
  110083. int eighth_octave_lines;
  110084. /* for block long/short tuning; encode only */
  110085. float preecho_thresh[VE_BANDS];
  110086. float postecho_thresh[VE_BANDS];
  110087. float stretch_penalty;
  110088. float preecho_minenergy;
  110089. float ampmax_att_per_sec;
  110090. /* channel coupling config */
  110091. int coupling_pkHz[PACKETBLOBS];
  110092. int coupling_pointlimit[2][PACKETBLOBS];
  110093. int coupling_prepointamp[PACKETBLOBS];
  110094. int coupling_postpointamp[PACKETBLOBS];
  110095. int sliding_lowpass[2][PACKETBLOBS];
  110096. } vorbis_info_psy_global;
  110097. typedef struct {
  110098. float ampmax;
  110099. int channels;
  110100. vorbis_info_psy_global *gi;
  110101. int coupling_pointlimit[2][P_NOISECURVES];
  110102. } vorbis_look_psy_global;
  110103. typedef struct {
  110104. int n;
  110105. struct vorbis_info_psy *vi;
  110106. float ***tonecurves;
  110107. float **noiseoffset;
  110108. float *ath;
  110109. long *octave; /* in n.ocshift format */
  110110. long *bark;
  110111. long firstoc;
  110112. long shiftoc;
  110113. int eighth_octave_lines; /* power of two, please */
  110114. int total_octave_lines;
  110115. long rate; /* cache it */
  110116. float m_val; /* Masking compensation value */
  110117. } vorbis_look_psy;
  110118. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110119. vorbis_info_psy_global *gi,int n,long rate);
  110120. extern void _vp_psy_clear(vorbis_look_psy *p);
  110121. extern void *_vi_psy_dup(void *source);
  110122. extern void _vi_psy_free(vorbis_info_psy *i);
  110123. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110124. extern void _vp_remove_floor(vorbis_look_psy *p,
  110125. float *mdct,
  110126. int *icodedflr,
  110127. float *residue,
  110128. int sliding_lowpass);
  110129. extern void _vp_noisemask(vorbis_look_psy *p,
  110130. float *logmdct,
  110131. float *logmask);
  110132. extern void _vp_tonemask(vorbis_look_psy *p,
  110133. float *logfft,
  110134. float *logmask,
  110135. float global_specmax,
  110136. float local_specmax);
  110137. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110138. float *noise,
  110139. float *tone,
  110140. int offset_select,
  110141. float *logmask,
  110142. float *mdct,
  110143. float *logmdct);
  110144. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110145. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110146. vorbis_info_psy_global *g,
  110147. vorbis_look_psy *p,
  110148. vorbis_info_mapping0 *vi,
  110149. float **mdct);
  110150. extern void _vp_couple(int blobno,
  110151. vorbis_info_psy_global *g,
  110152. vorbis_look_psy *p,
  110153. vorbis_info_mapping0 *vi,
  110154. float **res,
  110155. float **mag_memo,
  110156. int **mag_sort,
  110157. int **ifloor,
  110158. int *nonzero,
  110159. int sliding_lowpass);
  110160. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110161. float *in,float *out,int *sortedindex);
  110162. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110163. float *magnitudes,int *sortedindex);
  110164. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110165. vorbis_look_psy *p,
  110166. vorbis_info_mapping0 *vi,
  110167. float **mags);
  110168. extern void hf_reduction(vorbis_info_psy_global *g,
  110169. vorbis_look_psy *p,
  110170. vorbis_info_mapping0 *vi,
  110171. float **mdct);
  110172. #endif
  110173. /*** End of inlined file: psy.h ***/
  110174. /*** Start of inlined file: bitrate.h ***/
  110175. #ifndef _V_BITRATE_H_
  110176. #define _V_BITRATE_H_
  110177. /*** Start of inlined file: os.h ***/
  110178. #ifndef _OS_H
  110179. #define _OS_H
  110180. /********************************************************************
  110181. * *
  110182. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110183. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110184. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110185. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110186. * *
  110187. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110188. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110189. * *
  110190. ********************************************************************
  110191. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110192. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110193. ********************************************************************/
  110194. #ifdef HAVE_CONFIG_H
  110195. #include "config.h"
  110196. #endif
  110197. #include <math.h>
  110198. /*** Start of inlined file: misc.h ***/
  110199. #ifndef _V_RANDOM_H_
  110200. #define _V_RANDOM_H_
  110201. extern int analysis_noisy;
  110202. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110203. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110204. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110205. ogg_int64_t off);
  110206. #ifdef DEBUG_MALLOC
  110207. #define _VDBG_GRAPHFILE "malloc.m"
  110208. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110209. extern void _VDBG_free(void *ptr,char *file,long line);
  110210. #ifndef MISC_C
  110211. #undef _ogg_malloc
  110212. #undef _ogg_calloc
  110213. #undef _ogg_realloc
  110214. #undef _ogg_free
  110215. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110216. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110217. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110218. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110219. #endif
  110220. #endif
  110221. #endif
  110222. /*** End of inlined file: misc.h ***/
  110223. #ifndef _V_IFDEFJAIL_H_
  110224. # define _V_IFDEFJAIL_H_
  110225. # ifdef __GNUC__
  110226. # define STIN static __inline__
  110227. # elif _WIN32
  110228. # define STIN static __inline
  110229. # else
  110230. # define STIN static
  110231. # endif
  110232. #ifdef DJGPP
  110233. # define rint(x) (floor((x)+0.5f))
  110234. #endif
  110235. #ifndef M_PI
  110236. # define M_PI (3.1415926536f)
  110237. #endif
  110238. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110239. # include <malloc.h>
  110240. # define rint(x) (floor((x)+0.5f))
  110241. # define NO_FLOAT_MATH_LIB
  110242. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110243. #endif
  110244. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110245. void *_alloca(size_t size);
  110246. # define alloca _alloca
  110247. #endif
  110248. #ifndef FAST_HYPOT
  110249. # define FAST_HYPOT hypot
  110250. #endif
  110251. #endif
  110252. #ifdef HAVE_ALLOCA_H
  110253. # include <alloca.h>
  110254. #endif
  110255. #ifdef USE_MEMORY_H
  110256. # include <memory.h>
  110257. #endif
  110258. #ifndef min
  110259. # define min(x,y) ((x)>(y)?(y):(x))
  110260. #endif
  110261. #ifndef max
  110262. # define max(x,y) ((x)<(y)?(y):(x))
  110263. #endif
  110264. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110265. # define VORBIS_FPU_CONTROL
  110266. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110267. Because of encapsulation constraints (GCC can't see inside the asm
  110268. block and so we end up doing stupid things like a store/load that
  110269. is collectively a noop), we do it this way */
  110270. /* we must set up the fpu before this works!! */
  110271. typedef ogg_int16_t vorbis_fpu_control;
  110272. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110273. ogg_int16_t ret;
  110274. ogg_int16_t temp;
  110275. __asm__ __volatile__("fnstcw %0\n\t"
  110276. "movw %0,%%dx\n\t"
  110277. "orw $62463,%%dx\n\t"
  110278. "movw %%dx,%1\n\t"
  110279. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110280. *fpu=ret;
  110281. }
  110282. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110283. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110284. }
  110285. /* assumes the FPU is in round mode! */
  110286. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110287. we get extra fst/fld to
  110288. truncate precision */
  110289. int i;
  110290. __asm__("fistl %0": "=m"(i) : "t"(f));
  110291. return(i);
  110292. }
  110293. #endif
  110294. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110295. # define VORBIS_FPU_CONTROL
  110296. typedef ogg_int16_t vorbis_fpu_control;
  110297. static __inline int vorbis_ftoi(double f){
  110298. int i;
  110299. __asm{
  110300. fld f
  110301. fistp i
  110302. }
  110303. return i;
  110304. }
  110305. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110306. }
  110307. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110308. }
  110309. #endif
  110310. #ifndef VORBIS_FPU_CONTROL
  110311. typedef int vorbis_fpu_control;
  110312. static int vorbis_ftoi(double f){
  110313. return (int)(f+.5);
  110314. }
  110315. /* We don't have special code for this compiler/arch, so do it the slow way */
  110316. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110317. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110318. #endif
  110319. #endif /* _OS_H */
  110320. /*** End of inlined file: os.h ***/
  110321. /* encode side bitrate tracking */
  110322. typedef struct bitrate_manager_state {
  110323. int managed;
  110324. long avg_reservoir;
  110325. long minmax_reservoir;
  110326. long avg_bitsper;
  110327. long min_bitsper;
  110328. long max_bitsper;
  110329. long short_per_long;
  110330. double avgfloat;
  110331. vorbis_block *vb;
  110332. int choice;
  110333. } bitrate_manager_state;
  110334. typedef struct bitrate_manager_info{
  110335. long avg_rate;
  110336. long min_rate;
  110337. long max_rate;
  110338. long reservoir_bits;
  110339. double reservoir_bias;
  110340. double slew_damp;
  110341. } bitrate_manager_info;
  110342. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110343. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110344. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110345. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110346. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110347. #endif
  110348. /*** End of inlined file: bitrate.h ***/
  110349. static int ilog(unsigned int v){
  110350. int ret=0;
  110351. while(v){
  110352. ret++;
  110353. v>>=1;
  110354. }
  110355. return(ret);
  110356. }
  110357. static int ilog2(unsigned int v){
  110358. int ret=0;
  110359. if(v)--v;
  110360. while(v){
  110361. ret++;
  110362. v>>=1;
  110363. }
  110364. return(ret);
  110365. }
  110366. typedef struct private_state {
  110367. /* local lookup storage */
  110368. envelope_lookup *ve; /* envelope lookup */
  110369. int window[2];
  110370. vorbis_look_transform **transform[2]; /* block, type */
  110371. drft_lookup fft_look[2];
  110372. int modebits;
  110373. vorbis_look_floor **flr;
  110374. vorbis_look_residue **residue;
  110375. vorbis_look_psy *psy;
  110376. vorbis_look_psy_global *psy_g_look;
  110377. /* local storage, only used on the encoding side. This way the
  110378. application does not need to worry about freeing some packets'
  110379. memory and not others'; packet storage is always tracked.
  110380. Cleared next call to a _dsp_ function */
  110381. unsigned char *header;
  110382. unsigned char *header1;
  110383. unsigned char *header2;
  110384. bitrate_manager_state bms;
  110385. ogg_int64_t sample_count;
  110386. } private_state;
  110387. /* codec_setup_info contains all the setup information specific to the
  110388. specific compression/decompression mode in progress (eg,
  110389. psychoacoustic settings, channel setup, options, codebook
  110390. etc).
  110391. *********************************************************************/
  110392. /*** Start of inlined file: highlevel.h ***/
  110393. typedef struct highlevel_byblocktype {
  110394. double tone_mask_setting;
  110395. double tone_peaklimit_setting;
  110396. double noise_bias_setting;
  110397. double noise_compand_setting;
  110398. } highlevel_byblocktype;
  110399. typedef struct highlevel_encode_setup {
  110400. void *setup;
  110401. int set_in_stone;
  110402. double base_setting;
  110403. double long_setting;
  110404. double short_setting;
  110405. double impulse_noisetune;
  110406. int managed;
  110407. long bitrate_min;
  110408. long bitrate_av;
  110409. double bitrate_av_damp;
  110410. long bitrate_max;
  110411. long bitrate_reservoir;
  110412. double bitrate_reservoir_bias;
  110413. int impulse_block_p;
  110414. int noise_normalize_p;
  110415. double stereo_point_setting;
  110416. double lowpass_kHz;
  110417. double ath_floating_dB;
  110418. double ath_absolute_dB;
  110419. double amplitude_track_dBpersec;
  110420. double trigger_setting;
  110421. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110422. } highlevel_encode_setup;
  110423. /*** End of inlined file: highlevel.h ***/
  110424. typedef struct codec_setup_info {
  110425. /* Vorbis supports only short and long blocks, but allows the
  110426. encoder to choose the sizes */
  110427. long blocksizes[2];
  110428. /* modes are the primary means of supporting on-the-fly different
  110429. blocksizes, different channel mappings (LR or M/A),
  110430. different residue backends, etc. Each mode consists of a
  110431. blocksize flag and a mapping (along with the mapping setup */
  110432. int modes;
  110433. int maps;
  110434. int floors;
  110435. int residues;
  110436. int books;
  110437. int psys; /* encode only */
  110438. vorbis_info_mode *mode_param[64];
  110439. int map_type[64];
  110440. vorbis_info_mapping *map_param[64];
  110441. int floor_type[64];
  110442. vorbis_info_floor *floor_param[64];
  110443. int residue_type[64];
  110444. vorbis_info_residue *residue_param[64];
  110445. static_codebook *book_param[256];
  110446. codebook *fullbooks;
  110447. vorbis_info_psy *psy_param[4]; /* encode only */
  110448. vorbis_info_psy_global psy_g_param;
  110449. bitrate_manager_info bi;
  110450. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110451. highly redundant structure, but
  110452. improves clarity of program flow. */
  110453. int halfrate_flag; /* painless downsample for decode */
  110454. } codec_setup_info;
  110455. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110456. extern void _vp_global_free(vorbis_look_psy_global *look);
  110457. #endif
  110458. /*** End of inlined file: codec_internal.h ***/
  110459. /*** Start of inlined file: registry.h ***/
  110460. #ifndef _V_REG_H_
  110461. #define _V_REG_H_
  110462. #define VI_TRANSFORMB 1
  110463. #define VI_WINDOWB 1
  110464. #define VI_TIMEB 1
  110465. #define VI_FLOORB 2
  110466. #define VI_RESB 3
  110467. #define VI_MAPB 1
  110468. extern vorbis_func_floor *_floor_P[];
  110469. extern vorbis_func_residue *_residue_P[];
  110470. extern vorbis_func_mapping *_mapping_P[];
  110471. #endif
  110472. /*** End of inlined file: registry.h ***/
  110473. /*** Start of inlined file: scales.h ***/
  110474. #ifndef _V_SCALES_H_
  110475. #define _V_SCALES_H_
  110476. #include <math.h>
  110477. /* 20log10(x) */
  110478. #define VORBIS_IEEE_FLOAT32 1
  110479. #ifdef VORBIS_IEEE_FLOAT32
  110480. static float unitnorm(float x){
  110481. union {
  110482. ogg_uint32_t i;
  110483. float f;
  110484. } ix;
  110485. ix.f = x;
  110486. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110487. return ix.f;
  110488. }
  110489. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110490. static float todB(const float *x){
  110491. union {
  110492. ogg_uint32_t i;
  110493. float f;
  110494. } ix;
  110495. ix.f = *x;
  110496. ix.i = ix.i&0x7fffffff;
  110497. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110498. }
  110499. #define todB_nn(x) todB(x)
  110500. #else
  110501. static float unitnorm(float x){
  110502. if(x<0)return(-1.f);
  110503. return(1.f);
  110504. }
  110505. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110506. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110507. #endif
  110508. #define fromdB(x) (exp((x)*.11512925f))
  110509. /* The bark scale equations are approximations, since the original
  110510. table was somewhat hand rolled. The below are chosen to have the
  110511. best possible fit to the rolled tables, thus their somewhat odd
  110512. appearance (these are more accurate and over a longer range than
  110513. the oft-quoted bark equations found in the texts I have). The
  110514. approximations are valid from 0 - 30kHz (nyquist) or so.
  110515. all f in Hz, z in Bark */
  110516. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110517. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110518. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110519. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110520. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110521. 0.0 */
  110522. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110523. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110524. #endif
  110525. /*** End of inlined file: scales.h ***/
  110526. int analysis_noisy=1;
  110527. /* decides between modes, dispatches to the appropriate mapping. */
  110528. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110529. int ret,i;
  110530. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110531. vb->glue_bits=0;
  110532. vb->time_bits=0;
  110533. vb->floor_bits=0;
  110534. vb->res_bits=0;
  110535. /* first things first. Make sure encode is ready */
  110536. for(i=0;i<PACKETBLOBS;i++)
  110537. oggpack_reset(vbi->packetblob[i]);
  110538. /* we only have one mapping type (0), and we let the mapping code
  110539. itself figure out what soft mode to use. This allows easier
  110540. bitrate management */
  110541. if((ret=_mapping_P[0]->forward(vb)))
  110542. return(ret);
  110543. if(op){
  110544. if(vorbis_bitrate_managed(vb))
  110545. /* The app is using a bitmanaged mode... but not using the
  110546. bitrate management interface. */
  110547. return(OV_EINVAL);
  110548. op->packet=oggpack_get_buffer(&vb->opb);
  110549. op->bytes=oggpack_bytes(&vb->opb);
  110550. op->b_o_s=0;
  110551. op->e_o_s=vb->eofflag;
  110552. op->granulepos=vb->granulepos;
  110553. op->packetno=vb->sequence; /* for sake of completeness */
  110554. }
  110555. return(0);
  110556. }
  110557. /* there was no great place to put this.... */
  110558. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110559. int j;
  110560. FILE *of;
  110561. char buffer[80];
  110562. /* if(i==5870){*/
  110563. sprintf(buffer,"%s_%d.m",base,i);
  110564. of=fopen(buffer,"w");
  110565. if(!of)perror("failed to open data dump file");
  110566. for(j=0;j<n;j++){
  110567. if(bark){
  110568. float b=toBARK((4000.f*j/n)+.25);
  110569. fprintf(of,"%f ",b);
  110570. }else
  110571. if(off!=0)
  110572. fprintf(of,"%f ",(double)(j+off)/8000.);
  110573. else
  110574. fprintf(of,"%f ",(double)j);
  110575. if(dB){
  110576. float val;
  110577. if(v[j]==0.)
  110578. val=-140.;
  110579. else
  110580. val=todB(v+j);
  110581. fprintf(of,"%f\n",val);
  110582. }else{
  110583. fprintf(of,"%f\n",v[j]);
  110584. }
  110585. }
  110586. fclose(of);
  110587. /* } */
  110588. }
  110589. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110590. ogg_int64_t off){
  110591. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110592. }
  110593. #endif
  110594. /*** End of inlined file: analysis.c ***/
  110595. /*** Start of inlined file: bitrate.c ***/
  110596. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110597. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110598. // tasks..
  110599. #if JUCE_MSVC
  110600. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110601. #endif
  110602. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110603. #if JUCE_USE_OGGVORBIS
  110604. #include <stdlib.h>
  110605. #include <string.h>
  110606. #include <math.h>
  110607. /* compute bitrate tracking setup */
  110608. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110609. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110610. bitrate_manager_info *bi=&ci->bi;
  110611. memset(bm,0,sizeof(*bm));
  110612. if(bi && (bi->reservoir_bits>0)){
  110613. long ratesamples=vi->rate;
  110614. int halfsamples=ci->blocksizes[0]>>1;
  110615. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110616. bm->managed=1;
  110617. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110618. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110619. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110620. bm->avgfloat=PACKETBLOBS/2;
  110621. /* not a necessary fix, but one that leads to a more balanced
  110622. typical initialization */
  110623. {
  110624. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110625. bm->minmax_reservoir=desired_fill;
  110626. bm->avg_reservoir=desired_fill;
  110627. }
  110628. }
  110629. }
  110630. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110631. memset(bm,0,sizeof(*bm));
  110632. return;
  110633. }
  110634. int vorbis_bitrate_managed(vorbis_block *vb){
  110635. vorbis_dsp_state *vd=vb->vd;
  110636. private_state *b=(private_state*)vd->backend_state;
  110637. bitrate_manager_state *bm=&b->bms;
  110638. if(bm && bm->managed)return(1);
  110639. return(0);
  110640. }
  110641. /* finish taking in the block we just processed */
  110642. int vorbis_bitrate_addblock(vorbis_block *vb){
  110643. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110644. vorbis_dsp_state *vd=vb->vd;
  110645. private_state *b=(private_state*)vd->backend_state;
  110646. bitrate_manager_state *bm=&b->bms;
  110647. vorbis_info *vi=vd->vi;
  110648. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110649. bitrate_manager_info *bi=&ci->bi;
  110650. int choice=rint(bm->avgfloat);
  110651. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110652. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110653. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110654. int samples=ci->blocksizes[vb->W]>>1;
  110655. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110656. if(!bm->managed){
  110657. /* not a bitrate managed stream, but for API simplicity, we'll
  110658. buffer the packet to keep the code path clean */
  110659. if(bm->vb)return(-1); /* one has been submitted without
  110660. being claimed */
  110661. bm->vb=vb;
  110662. return(0);
  110663. }
  110664. bm->vb=vb;
  110665. /* look ahead for avg floater */
  110666. if(bm->avg_bitsper>0){
  110667. double slew=0.;
  110668. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110669. double slewlimit= 15./bi->slew_damp;
  110670. /* choosing a new floater:
  110671. if we're over target, we slew down
  110672. if we're under target, we slew up
  110673. choose slew as follows: look through packetblobs of this frame
  110674. and set slew as the first in the appropriate direction that
  110675. gives us the slew we want. This may mean no slew if delta is
  110676. already favorable.
  110677. Then limit slew to slew max */
  110678. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110679. while(choice>0 && this_bits>avg_target_bits &&
  110680. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110681. choice--;
  110682. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110683. }
  110684. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110685. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110686. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110687. choice++;
  110688. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110689. }
  110690. }
  110691. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110692. if(slew<-slewlimit)slew=-slewlimit;
  110693. if(slew>slewlimit)slew=slewlimit;
  110694. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110695. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110696. }
  110697. /* enforce min(if used) on the current floater (if used) */
  110698. if(bm->min_bitsper>0){
  110699. /* do we need to force the bitrate up? */
  110700. if(this_bits<min_target_bits){
  110701. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110702. choice++;
  110703. if(choice>=PACKETBLOBS)break;
  110704. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110705. }
  110706. }
  110707. }
  110708. /* enforce max (if used) on the current floater (if used) */
  110709. if(bm->max_bitsper>0){
  110710. /* do we need to force the bitrate down? */
  110711. if(this_bits>max_target_bits){
  110712. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110713. choice--;
  110714. if(choice<0)break;
  110715. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110716. }
  110717. }
  110718. }
  110719. /* Choice of packetblobs now made based on floater, and min/max
  110720. requirements. Now boundary check extreme choices */
  110721. if(choice<0){
  110722. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110723. frame will need to be truncated */
  110724. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110725. bm->choice=choice=0;
  110726. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110727. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110728. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110729. }
  110730. }else{
  110731. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110732. if(choice>=PACKETBLOBS)
  110733. choice=PACKETBLOBS-1;
  110734. bm->choice=choice;
  110735. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110736. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110737. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110738. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110739. }
  110740. /* now we have the final packet and the final packet size. Update statistics */
  110741. /* min and max reservoir */
  110742. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110743. if(max_target_bits>0 && this_bits>max_target_bits){
  110744. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110745. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110746. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110747. }else{
  110748. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110749. if(bm->minmax_reservoir>desired_fill){
  110750. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110751. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110752. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110753. }else{
  110754. bm->minmax_reservoir=desired_fill;
  110755. }
  110756. }else{
  110757. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110758. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110759. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110760. }else{
  110761. bm->minmax_reservoir=desired_fill;
  110762. }
  110763. }
  110764. }
  110765. }
  110766. /* avg reservoir */
  110767. if(bm->avg_bitsper>0){
  110768. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110769. bm->avg_reservoir+=this_bits-avg_target_bits;
  110770. }
  110771. return(0);
  110772. }
  110773. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110774. private_state *b=(private_state*)vd->backend_state;
  110775. bitrate_manager_state *bm=&b->bms;
  110776. vorbis_block *vb=bm->vb;
  110777. int choice=PACKETBLOBS/2;
  110778. if(!vb)return 0;
  110779. if(op){
  110780. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110781. if(vorbis_bitrate_managed(vb))
  110782. choice=bm->choice;
  110783. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110784. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110785. op->b_o_s=0;
  110786. op->e_o_s=vb->eofflag;
  110787. op->granulepos=vb->granulepos;
  110788. op->packetno=vb->sequence; /* for sake of completeness */
  110789. }
  110790. bm->vb=0;
  110791. return(1);
  110792. }
  110793. #endif
  110794. /*** End of inlined file: bitrate.c ***/
  110795. /*** Start of inlined file: block.c ***/
  110796. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110797. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110798. // tasks..
  110799. #if JUCE_MSVC
  110800. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110801. #endif
  110802. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110803. #if JUCE_USE_OGGVORBIS
  110804. #include <stdio.h>
  110805. #include <stdlib.h>
  110806. #include <string.h>
  110807. /*** Start of inlined file: window.h ***/
  110808. #ifndef _V_WINDOW_
  110809. #define _V_WINDOW_
  110810. extern float *_vorbis_window_get(int n);
  110811. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110812. int lW,int W,int nW);
  110813. #endif
  110814. /*** End of inlined file: window.h ***/
  110815. /*** Start of inlined file: lpc.h ***/
  110816. #ifndef _V_LPC_H_
  110817. #define _V_LPC_H_
  110818. /* simple linear scale LPC code */
  110819. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110820. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110821. float *data,long n);
  110822. #endif
  110823. /*** End of inlined file: lpc.h ***/
  110824. /* pcm accumulator examples (not exhaustive):
  110825. <-------------- lW ---------------->
  110826. <--------------- W ---------------->
  110827. : .....|..... _______________ |
  110828. : .''' | '''_--- | |\ |
  110829. :.....''' |_____--- '''......| | \_______|
  110830. :.................|__________________|_______|__|______|
  110831. |<------ Sl ------>| > Sr < |endW
  110832. |beginSl |endSl | |endSr
  110833. |beginW |endlW |beginSr
  110834. |< lW >|
  110835. <--------------- W ---------------->
  110836. | | .. ______________ |
  110837. | | ' `/ | ---_ |
  110838. |___.'___/`. | ---_____|
  110839. |_______|__|_______|_________________|
  110840. | >|Sl|< |<------ Sr ----->|endW
  110841. | | |endSl |beginSr |endSr
  110842. |beginW | |endlW
  110843. mult[0] |beginSl mult[n]
  110844. <-------------- lW ----------------->
  110845. |<--W-->|
  110846. : .............. ___ | |
  110847. : .''' |`/ \ | |
  110848. :.....''' |/`....\|...|
  110849. :.........................|___|___|___|
  110850. |Sl |Sr |endW
  110851. | | |endSr
  110852. | |beginSr
  110853. | |endSl
  110854. |beginSl
  110855. |beginW
  110856. */
  110857. /* block abstraction setup *********************************************/
  110858. #ifndef WORD_ALIGN
  110859. #define WORD_ALIGN 8
  110860. #endif
  110861. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110862. int i;
  110863. memset(vb,0,sizeof(*vb));
  110864. vb->vd=v;
  110865. vb->localalloc=0;
  110866. vb->localstore=NULL;
  110867. if(v->analysisp){
  110868. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110869. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110870. vbi->ampmax=-9999;
  110871. for(i=0;i<PACKETBLOBS;i++){
  110872. if(i==PACKETBLOBS/2){
  110873. vbi->packetblob[i]=&vb->opb;
  110874. }else{
  110875. vbi->packetblob[i]=
  110876. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110877. }
  110878. oggpack_writeinit(vbi->packetblob[i]);
  110879. }
  110880. }
  110881. return(0);
  110882. }
  110883. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110884. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110885. if(bytes+vb->localtop>vb->localalloc){
  110886. /* can't just _ogg_realloc... there are outstanding pointers */
  110887. if(vb->localstore){
  110888. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110889. vb->totaluse+=vb->localtop;
  110890. link->next=vb->reap;
  110891. link->ptr=vb->localstore;
  110892. vb->reap=link;
  110893. }
  110894. /* highly conservative */
  110895. vb->localalloc=bytes;
  110896. vb->localstore=_ogg_malloc(vb->localalloc);
  110897. vb->localtop=0;
  110898. }
  110899. {
  110900. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110901. vb->localtop+=bytes;
  110902. return ret;
  110903. }
  110904. }
  110905. /* reap the chain, pull the ripcord */
  110906. void _vorbis_block_ripcord(vorbis_block *vb){
  110907. /* reap the chain */
  110908. struct alloc_chain *reap=vb->reap;
  110909. while(reap){
  110910. struct alloc_chain *next=reap->next;
  110911. _ogg_free(reap->ptr);
  110912. memset(reap,0,sizeof(*reap));
  110913. _ogg_free(reap);
  110914. reap=next;
  110915. }
  110916. /* consolidate storage */
  110917. if(vb->totaluse){
  110918. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110919. vb->localalloc+=vb->totaluse;
  110920. vb->totaluse=0;
  110921. }
  110922. /* pull the ripcord */
  110923. vb->localtop=0;
  110924. vb->reap=NULL;
  110925. }
  110926. int vorbis_block_clear(vorbis_block *vb){
  110927. int i;
  110928. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110929. _vorbis_block_ripcord(vb);
  110930. if(vb->localstore)_ogg_free(vb->localstore);
  110931. if(vbi){
  110932. for(i=0;i<PACKETBLOBS;i++){
  110933. oggpack_writeclear(vbi->packetblob[i]);
  110934. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110935. }
  110936. _ogg_free(vbi);
  110937. }
  110938. memset(vb,0,sizeof(*vb));
  110939. return(0);
  110940. }
  110941. /* Analysis side code, but directly related to blocking. Thus it's
  110942. here and not in analysis.c (which is for analysis transforms only).
  110943. The init is here because some of it is shared */
  110944. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110945. int i;
  110946. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110947. private_state *b=NULL;
  110948. int hs;
  110949. if(ci==NULL) return 1;
  110950. hs=ci->halfrate_flag;
  110951. memset(v,0,sizeof(*v));
  110952. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110953. v->vi=vi;
  110954. b->modebits=ilog2(ci->modes);
  110955. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110956. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110957. /* MDCT is tranform 0 */
  110958. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110959. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110960. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110961. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110962. /* Vorbis I uses only window type 0 */
  110963. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110964. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110965. if(encp){ /* encode/decode differ here */
  110966. /* analysis always needs an fft */
  110967. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110968. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110969. /* finish the codebooks */
  110970. if(!ci->fullbooks){
  110971. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110972. for(i=0;i<ci->books;i++)
  110973. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110974. }
  110975. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110976. for(i=0;i<ci->psys;i++){
  110977. _vp_psy_init(b->psy+i,
  110978. ci->psy_param[i],
  110979. &ci->psy_g_param,
  110980. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110981. vi->rate);
  110982. }
  110983. v->analysisp=1;
  110984. }else{
  110985. /* finish the codebooks */
  110986. if(!ci->fullbooks){
  110987. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110988. for(i=0;i<ci->books;i++){
  110989. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110990. /* decode codebooks are now standalone after init */
  110991. vorbis_staticbook_destroy(ci->book_param[i]);
  110992. ci->book_param[i]=NULL;
  110993. }
  110994. }
  110995. }
  110996. /* initialize the storage vectors. blocksize[1] is small for encode,
  110997. but the correct size for decode */
  110998. v->pcm_storage=ci->blocksizes[1];
  110999. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111000. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111001. {
  111002. int i;
  111003. for(i=0;i<vi->channels;i++)
  111004. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111005. }
  111006. /* all 1 (large block) or 0 (small block) */
  111007. /* explicitly set for the sake of clarity */
  111008. v->lW=0; /* previous window size */
  111009. v->W=0; /* current window size */
  111010. /* all vector indexes */
  111011. v->centerW=ci->blocksizes[1]/2;
  111012. v->pcm_current=v->centerW;
  111013. /* initialize all the backend lookups */
  111014. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111015. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111016. for(i=0;i<ci->floors;i++)
  111017. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111018. look(v,ci->floor_param[i]);
  111019. for(i=0;i<ci->residues;i++)
  111020. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111021. look(v,ci->residue_param[i]);
  111022. return 0;
  111023. }
  111024. /* arbitrary settings and spec-mandated numbers get filled in here */
  111025. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111026. private_state *b=NULL;
  111027. if(_vds_shared_init(v,vi,1))return 1;
  111028. b=(private_state*)v->backend_state;
  111029. b->psy_g_look=_vp_global_look(vi);
  111030. /* Initialize the envelope state storage */
  111031. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111032. _ve_envelope_init(b->ve,vi);
  111033. vorbis_bitrate_init(vi,&b->bms);
  111034. /* compressed audio packets start after the headers
  111035. with sequence number 3 */
  111036. v->sequence=3;
  111037. return(0);
  111038. }
  111039. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111040. int i;
  111041. if(v){
  111042. vorbis_info *vi=v->vi;
  111043. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111044. private_state *b=(private_state*)v->backend_state;
  111045. if(b){
  111046. if(b->ve){
  111047. _ve_envelope_clear(b->ve);
  111048. _ogg_free(b->ve);
  111049. }
  111050. if(b->transform[0]){
  111051. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111052. _ogg_free(b->transform[0][0]);
  111053. _ogg_free(b->transform[0]);
  111054. }
  111055. if(b->transform[1]){
  111056. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111057. _ogg_free(b->transform[1][0]);
  111058. _ogg_free(b->transform[1]);
  111059. }
  111060. if(b->flr){
  111061. for(i=0;i<ci->floors;i++)
  111062. _floor_P[ci->floor_type[i]]->
  111063. free_look(b->flr[i]);
  111064. _ogg_free(b->flr);
  111065. }
  111066. if(b->residue){
  111067. for(i=0;i<ci->residues;i++)
  111068. _residue_P[ci->residue_type[i]]->
  111069. free_look(b->residue[i]);
  111070. _ogg_free(b->residue);
  111071. }
  111072. if(b->psy){
  111073. for(i=0;i<ci->psys;i++)
  111074. _vp_psy_clear(b->psy+i);
  111075. _ogg_free(b->psy);
  111076. }
  111077. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111078. vorbis_bitrate_clear(&b->bms);
  111079. drft_clear(&b->fft_look[0]);
  111080. drft_clear(&b->fft_look[1]);
  111081. }
  111082. if(v->pcm){
  111083. for(i=0;i<vi->channels;i++)
  111084. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111085. _ogg_free(v->pcm);
  111086. if(v->pcmret)_ogg_free(v->pcmret);
  111087. }
  111088. if(b){
  111089. /* free header, header1, header2 */
  111090. if(b->header)_ogg_free(b->header);
  111091. if(b->header1)_ogg_free(b->header1);
  111092. if(b->header2)_ogg_free(b->header2);
  111093. _ogg_free(b);
  111094. }
  111095. memset(v,0,sizeof(*v));
  111096. }
  111097. }
  111098. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111099. int i;
  111100. vorbis_info *vi=v->vi;
  111101. private_state *b=(private_state*)v->backend_state;
  111102. /* free header, header1, header2 */
  111103. if(b->header)_ogg_free(b->header);b->header=NULL;
  111104. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111105. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111106. /* Do we have enough storage space for the requested buffer? If not,
  111107. expand the PCM (and envelope) storage */
  111108. if(v->pcm_current+vals>=v->pcm_storage){
  111109. v->pcm_storage=v->pcm_current+vals*2;
  111110. for(i=0;i<vi->channels;i++){
  111111. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111112. }
  111113. }
  111114. for(i=0;i<vi->channels;i++)
  111115. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111116. return(v->pcmret);
  111117. }
  111118. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111119. int i;
  111120. int order=32;
  111121. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111122. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111123. long j;
  111124. v->preextrapolate=1;
  111125. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111126. for(i=0;i<v->vi->channels;i++){
  111127. /* need to run the extrapolation in reverse! */
  111128. for(j=0;j<v->pcm_current;j++)
  111129. work[j]=v->pcm[i][v->pcm_current-j-1];
  111130. /* prime as above */
  111131. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111132. /* run the predictor filter */
  111133. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111134. order,
  111135. work+v->pcm_current-v->centerW,
  111136. v->centerW);
  111137. for(j=0;j<v->pcm_current;j++)
  111138. v->pcm[i][v->pcm_current-j-1]=work[j];
  111139. }
  111140. }
  111141. }
  111142. /* call with val<=0 to set eof */
  111143. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111144. vorbis_info *vi=v->vi;
  111145. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111146. if(vals<=0){
  111147. int order=32;
  111148. int i;
  111149. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111150. /* if it wasn't done earlier (very short sample) */
  111151. if(!v->preextrapolate)
  111152. _preextrapolate_helper(v);
  111153. /* We're encoding the end of the stream. Just make sure we have
  111154. [at least] a few full blocks of zeroes at the end. */
  111155. /* actually, we don't want zeroes; that could drop a large
  111156. amplitude off a cliff, creating spread spectrum noise that will
  111157. suck to encode. Extrapolate for the sake of cleanliness. */
  111158. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111159. v->eofflag=v->pcm_current;
  111160. v->pcm_current+=ci->blocksizes[1]*3;
  111161. for(i=0;i<vi->channels;i++){
  111162. if(v->eofflag>order*2){
  111163. /* extrapolate with LPC to fill in */
  111164. long n;
  111165. /* make a predictor filter */
  111166. n=v->eofflag;
  111167. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111168. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111169. /* run the predictor filter */
  111170. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111171. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111172. }else{
  111173. /* not enough data to extrapolate (unlikely to happen due to
  111174. guarding the overlap, but bulletproof in case that
  111175. assumtion goes away). zeroes will do. */
  111176. memset(v->pcm[i]+v->eofflag,0,
  111177. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111178. }
  111179. }
  111180. }else{
  111181. if(v->pcm_current+vals>v->pcm_storage)
  111182. return(OV_EINVAL);
  111183. v->pcm_current+=vals;
  111184. /* we may want to reverse extrapolate the beginning of a stream
  111185. too... in case we're beginning on a cliff! */
  111186. /* clumsy, but simple. It only runs once, so simple is good. */
  111187. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111188. _preextrapolate_helper(v);
  111189. }
  111190. return(0);
  111191. }
  111192. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111193. the next block on which to continue analysis */
  111194. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111195. int i;
  111196. vorbis_info *vi=v->vi;
  111197. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111198. private_state *b=(private_state*)v->backend_state;
  111199. vorbis_look_psy_global *g=b->psy_g_look;
  111200. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111201. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111202. /* check to see if we're started... */
  111203. if(!v->preextrapolate)return(0);
  111204. /* check to see if we're done... */
  111205. if(v->eofflag==-1)return(0);
  111206. /* By our invariant, we have lW, W and centerW set. Search for
  111207. the next boundary so we can determine nW (the next window size)
  111208. which lets us compute the shape of the current block's window */
  111209. /* we do an envelope search even on a single blocksize; we may still
  111210. be throwing more bits at impulses, and envelope search handles
  111211. marking impulses too. */
  111212. {
  111213. long bp=_ve_envelope_search(v);
  111214. if(bp==-1){
  111215. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111216. full long block */
  111217. v->nW=0;
  111218. }else{
  111219. if(ci->blocksizes[0]==ci->blocksizes[1])
  111220. v->nW=0;
  111221. else
  111222. v->nW=bp;
  111223. }
  111224. }
  111225. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111226. {
  111227. /* center of next block + next block maximum right side. */
  111228. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111229. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111230. although this check is
  111231. less strict that the
  111232. _ve_envelope_search,
  111233. the search is not run
  111234. if we only use one
  111235. block size */
  111236. }
  111237. /* fill in the block. Note that for a short window, lW and nW are *short*
  111238. regardless of actual settings in the stream */
  111239. _vorbis_block_ripcord(vb);
  111240. vb->lW=v->lW;
  111241. vb->W=v->W;
  111242. vb->nW=v->nW;
  111243. if(v->W){
  111244. if(!v->lW || !v->nW){
  111245. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111246. /*fprintf(stderr,"-");*/
  111247. }else{
  111248. vbi->blocktype=BLOCKTYPE_LONG;
  111249. /*fprintf(stderr,"_");*/
  111250. }
  111251. }else{
  111252. if(_ve_envelope_mark(v)){
  111253. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111254. /*fprintf(stderr,"|");*/
  111255. }else{
  111256. vbi->blocktype=BLOCKTYPE_PADDING;
  111257. /*fprintf(stderr,".");*/
  111258. }
  111259. }
  111260. vb->vd=v;
  111261. vb->sequence=v->sequence++;
  111262. vb->granulepos=v->granulepos;
  111263. vb->pcmend=ci->blocksizes[v->W];
  111264. /* copy the vectors; this uses the local storage in vb */
  111265. /* this tracks 'strongest peak' for later psychoacoustics */
  111266. /* moved to the global psy state; clean this mess up */
  111267. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111268. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111269. vbi->ampmax=g->ampmax;
  111270. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111271. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111272. for(i=0;i<vi->channels;i++){
  111273. vbi->pcmdelay[i]=
  111274. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111275. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111276. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111277. /* before we added the delay
  111278. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111279. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111280. */
  111281. }
  111282. /* handle eof detection: eof==0 means that we've not yet received EOF
  111283. eof>0 marks the last 'real' sample in pcm[]
  111284. eof<0 'no more to do'; doesn't get here */
  111285. if(v->eofflag){
  111286. if(v->centerW>=v->eofflag){
  111287. v->eofflag=-1;
  111288. vb->eofflag=1;
  111289. return(1);
  111290. }
  111291. }
  111292. /* advance storage vectors and clean up */
  111293. {
  111294. int new_centerNext=ci->blocksizes[1]/2;
  111295. int movementW=centerNext-new_centerNext;
  111296. if(movementW>0){
  111297. _ve_envelope_shift(b->ve,movementW);
  111298. v->pcm_current-=movementW;
  111299. for(i=0;i<vi->channels;i++)
  111300. memmove(v->pcm[i],v->pcm[i]+movementW,
  111301. v->pcm_current*sizeof(*v->pcm[i]));
  111302. v->lW=v->W;
  111303. v->W=v->nW;
  111304. v->centerW=new_centerNext;
  111305. if(v->eofflag){
  111306. v->eofflag-=movementW;
  111307. if(v->eofflag<=0)v->eofflag=-1;
  111308. /* do not add padding to end of stream! */
  111309. if(v->centerW>=v->eofflag){
  111310. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111311. }else{
  111312. v->granulepos+=movementW;
  111313. }
  111314. }else{
  111315. v->granulepos+=movementW;
  111316. }
  111317. }
  111318. }
  111319. /* done */
  111320. return(1);
  111321. }
  111322. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111323. vorbis_info *vi=v->vi;
  111324. codec_setup_info *ci;
  111325. int hs;
  111326. if(!v->backend_state)return -1;
  111327. if(!vi)return -1;
  111328. ci=(codec_setup_info*) vi->codec_setup;
  111329. if(!ci)return -1;
  111330. hs=ci->halfrate_flag;
  111331. v->centerW=ci->blocksizes[1]>>(hs+1);
  111332. v->pcm_current=v->centerW>>hs;
  111333. v->pcm_returned=-1;
  111334. v->granulepos=-1;
  111335. v->sequence=-1;
  111336. v->eofflag=0;
  111337. ((private_state *)(v->backend_state))->sample_count=-1;
  111338. return(0);
  111339. }
  111340. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111341. if(_vds_shared_init(v,vi,0)) return 1;
  111342. vorbis_synthesis_restart(v);
  111343. return 0;
  111344. }
  111345. /* Unlike in analysis, the window is only partially applied for each
  111346. block. The time domain envelope is not yet handled at the point of
  111347. calling (as it relies on the previous block). */
  111348. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111349. vorbis_info *vi=v->vi;
  111350. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111351. private_state *b=(private_state*)v->backend_state;
  111352. int hs=ci->halfrate_flag;
  111353. int i,j;
  111354. if(!vb)return(OV_EINVAL);
  111355. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111356. v->lW=v->W;
  111357. v->W=vb->W;
  111358. v->nW=-1;
  111359. if((v->sequence==-1)||
  111360. (v->sequence+1 != vb->sequence)){
  111361. v->granulepos=-1; /* out of sequence; lose count */
  111362. b->sample_count=-1;
  111363. }
  111364. v->sequence=vb->sequence;
  111365. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111366. was called on block */
  111367. int n=ci->blocksizes[v->W]>>(hs+1);
  111368. int n0=ci->blocksizes[0]>>(hs+1);
  111369. int n1=ci->blocksizes[1]>>(hs+1);
  111370. int thisCenter;
  111371. int prevCenter;
  111372. v->glue_bits+=vb->glue_bits;
  111373. v->time_bits+=vb->time_bits;
  111374. v->floor_bits+=vb->floor_bits;
  111375. v->res_bits+=vb->res_bits;
  111376. if(v->centerW){
  111377. thisCenter=n1;
  111378. prevCenter=0;
  111379. }else{
  111380. thisCenter=0;
  111381. prevCenter=n1;
  111382. }
  111383. /* v->pcm is now used like a two-stage double buffer. We don't want
  111384. to have to constantly shift *or* adjust memory usage. Don't
  111385. accept a new block until the old is shifted out */
  111386. for(j=0;j<vi->channels;j++){
  111387. /* the overlap/add section */
  111388. if(v->lW){
  111389. if(v->W){
  111390. /* large/large */
  111391. float *w=_vorbis_window_get(b->window[1]-hs);
  111392. float *pcm=v->pcm[j]+prevCenter;
  111393. float *p=vb->pcm[j];
  111394. for(i=0;i<n1;i++)
  111395. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111396. }else{
  111397. /* large/small */
  111398. float *w=_vorbis_window_get(b->window[0]-hs);
  111399. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111400. float *p=vb->pcm[j];
  111401. for(i=0;i<n0;i++)
  111402. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111403. }
  111404. }else{
  111405. if(v->W){
  111406. /* small/large */
  111407. float *w=_vorbis_window_get(b->window[0]-hs);
  111408. float *pcm=v->pcm[j]+prevCenter;
  111409. float *p=vb->pcm[j]+n1/2-n0/2;
  111410. for(i=0;i<n0;i++)
  111411. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111412. for(;i<n1/2+n0/2;i++)
  111413. pcm[i]=p[i];
  111414. }else{
  111415. /* small/small */
  111416. float *w=_vorbis_window_get(b->window[0]-hs);
  111417. float *pcm=v->pcm[j]+prevCenter;
  111418. float *p=vb->pcm[j];
  111419. for(i=0;i<n0;i++)
  111420. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111421. }
  111422. }
  111423. /* the copy section */
  111424. {
  111425. float *pcm=v->pcm[j]+thisCenter;
  111426. float *p=vb->pcm[j]+n;
  111427. for(i=0;i<n;i++)
  111428. pcm[i]=p[i];
  111429. }
  111430. }
  111431. if(v->centerW)
  111432. v->centerW=0;
  111433. else
  111434. v->centerW=n1;
  111435. /* deal with initial packet state; we do this using the explicit
  111436. pcm_returned==-1 flag otherwise we're sensitive to first block
  111437. being short or long */
  111438. if(v->pcm_returned==-1){
  111439. v->pcm_returned=thisCenter;
  111440. v->pcm_current=thisCenter;
  111441. }else{
  111442. v->pcm_returned=prevCenter;
  111443. v->pcm_current=prevCenter+
  111444. ((ci->blocksizes[v->lW]/4+
  111445. ci->blocksizes[v->W]/4)>>hs);
  111446. }
  111447. }
  111448. /* track the frame number... This is for convenience, but also
  111449. making sure our last packet doesn't end with added padding. If
  111450. the last packet is partial, the number of samples we'll have to
  111451. return will be past the vb->granulepos.
  111452. This is not foolproof! It will be confused if we begin
  111453. decoding at the last page after a seek or hole. In that case,
  111454. we don't have a starting point to judge where the last frame
  111455. is. For this reason, vorbisfile will always try to make sure
  111456. it reads the last two marked pages in proper sequence */
  111457. if(b->sample_count==-1){
  111458. b->sample_count=0;
  111459. }else{
  111460. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111461. }
  111462. if(v->granulepos==-1){
  111463. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111464. v->granulepos=vb->granulepos;
  111465. /* is this a short page? */
  111466. if(b->sample_count>v->granulepos){
  111467. /* corner case; if this is both the first and last audio page,
  111468. then spec says the end is cut, not beginning */
  111469. if(vb->eofflag){
  111470. /* trim the end */
  111471. /* no preceeding granulepos; assume we started at zero (we'd
  111472. have to in a short single-page stream) */
  111473. /* granulepos could be -1 due to a seek, but that would result
  111474. in a long count, not short count */
  111475. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111476. }else{
  111477. /* trim the beginning */
  111478. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111479. if(v->pcm_returned>v->pcm_current)
  111480. v->pcm_returned=v->pcm_current;
  111481. }
  111482. }
  111483. }
  111484. }else{
  111485. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111486. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111487. if(v->granulepos>vb->granulepos){
  111488. long extra=v->granulepos-vb->granulepos;
  111489. if(extra)
  111490. if(vb->eofflag){
  111491. /* partial last frame. Strip the extra samples off */
  111492. v->pcm_current-=extra>>hs;
  111493. } /* else {Shouldn't happen *unless* the bitstream is out of
  111494. spec. Either way, believe the bitstream } */
  111495. } /* else {Shouldn't happen *unless* the bitstream is out of
  111496. spec. Either way, believe the bitstream } */
  111497. v->granulepos=vb->granulepos;
  111498. }
  111499. }
  111500. /* Update, cleanup */
  111501. if(vb->eofflag)v->eofflag=1;
  111502. return(0);
  111503. }
  111504. /* pcm==NULL indicates we just want the pending samples, no more */
  111505. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111506. vorbis_info *vi=v->vi;
  111507. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111508. if(pcm){
  111509. int i;
  111510. for(i=0;i<vi->channels;i++)
  111511. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111512. *pcm=v->pcmret;
  111513. }
  111514. return(v->pcm_current-v->pcm_returned);
  111515. }
  111516. return(0);
  111517. }
  111518. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111519. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111520. v->pcm_returned+=n;
  111521. return(0);
  111522. }
  111523. /* intended for use with a specific vorbisfile feature; we want access
  111524. to the [usually synthetic/postextrapolated] buffer and lapping at
  111525. the end of a decode cycle, specifically, a half-short-block worth.
  111526. This funtion works like pcmout above, except it will also expose
  111527. this implicit buffer data not normally decoded. */
  111528. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111529. vorbis_info *vi=v->vi;
  111530. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111531. int hs=ci->halfrate_flag;
  111532. int n=ci->blocksizes[v->W]>>(hs+1);
  111533. int n0=ci->blocksizes[0]>>(hs+1);
  111534. int n1=ci->blocksizes[1]>>(hs+1);
  111535. int i,j;
  111536. if(v->pcm_returned<0)return 0;
  111537. /* our returned data ends at pcm_returned; because the synthesis pcm
  111538. buffer is a two-fragment ring, that means our data block may be
  111539. fragmented by buffering, wrapping or a short block not filling
  111540. out a buffer. To simplify things, we unfragment if it's at all
  111541. possibly needed. Otherwise, we'd need to call lapout more than
  111542. once as well as hold additional dsp state. Opt for
  111543. simplicity. */
  111544. /* centerW was advanced by blockin; it would be the center of the
  111545. *next* block */
  111546. if(v->centerW==n1){
  111547. /* the data buffer wraps; swap the halves */
  111548. /* slow, sure, small */
  111549. for(j=0;j<vi->channels;j++){
  111550. float *p=v->pcm[j];
  111551. for(i=0;i<n1;i++){
  111552. float temp=p[i];
  111553. p[i]=p[i+n1];
  111554. p[i+n1]=temp;
  111555. }
  111556. }
  111557. v->pcm_current-=n1;
  111558. v->pcm_returned-=n1;
  111559. v->centerW=0;
  111560. }
  111561. /* solidify buffer into contiguous space */
  111562. if((v->lW^v->W)==1){
  111563. /* long/short or short/long */
  111564. for(j=0;j<vi->channels;j++){
  111565. float *s=v->pcm[j];
  111566. float *d=v->pcm[j]+(n1-n0)/2;
  111567. for(i=(n1+n0)/2-1;i>=0;--i)
  111568. d[i]=s[i];
  111569. }
  111570. v->pcm_returned+=(n1-n0)/2;
  111571. v->pcm_current+=(n1-n0)/2;
  111572. }else{
  111573. if(v->lW==0){
  111574. /* short/short */
  111575. for(j=0;j<vi->channels;j++){
  111576. float *s=v->pcm[j];
  111577. float *d=v->pcm[j]+n1-n0;
  111578. for(i=n0-1;i>=0;--i)
  111579. d[i]=s[i];
  111580. }
  111581. v->pcm_returned+=n1-n0;
  111582. v->pcm_current+=n1-n0;
  111583. }
  111584. }
  111585. if(pcm){
  111586. int i;
  111587. for(i=0;i<vi->channels;i++)
  111588. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111589. *pcm=v->pcmret;
  111590. }
  111591. return(n1+n-v->pcm_returned);
  111592. }
  111593. float *vorbis_window(vorbis_dsp_state *v,int W){
  111594. vorbis_info *vi=v->vi;
  111595. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111596. int hs=ci->halfrate_flag;
  111597. private_state *b=(private_state*)v->backend_state;
  111598. if(b->window[W]-1<0)return NULL;
  111599. return _vorbis_window_get(b->window[W]-hs);
  111600. }
  111601. #endif
  111602. /*** End of inlined file: block.c ***/
  111603. /*** Start of inlined file: codebook.c ***/
  111604. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111605. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111606. // tasks..
  111607. #if JUCE_MSVC
  111608. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111609. #endif
  111610. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111611. #if JUCE_USE_OGGVORBIS
  111612. #include <stdlib.h>
  111613. #include <string.h>
  111614. #include <math.h>
  111615. /* packs the given codebook into the bitstream **************************/
  111616. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111617. long i,j;
  111618. int ordered=0;
  111619. /* first the basic parameters */
  111620. oggpack_write(opb,0x564342,24);
  111621. oggpack_write(opb,c->dim,16);
  111622. oggpack_write(opb,c->entries,24);
  111623. /* pack the codewords. There are two packings; length ordered and
  111624. length random. Decide between the two now. */
  111625. for(i=1;i<c->entries;i++)
  111626. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111627. if(i==c->entries)ordered=1;
  111628. if(ordered){
  111629. /* length ordered. We only need to say how many codewords of
  111630. each length. The actual codewords are generated
  111631. deterministically */
  111632. long count=0;
  111633. oggpack_write(opb,1,1); /* ordered */
  111634. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111635. for(i=1;i<c->entries;i++){
  111636. long thisx=c->lengthlist[i];
  111637. long last=c->lengthlist[i-1];
  111638. if(thisx>last){
  111639. for(j=last;j<thisx;j++){
  111640. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111641. count=i;
  111642. }
  111643. }
  111644. }
  111645. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111646. }else{
  111647. /* length random. Again, we don't code the codeword itself, just
  111648. the length. This time, though, we have to encode each length */
  111649. oggpack_write(opb,0,1); /* unordered */
  111650. /* algortihmic mapping has use for 'unused entries', which we tag
  111651. here. The algorithmic mapping happens as usual, but the unused
  111652. entry has no codeword. */
  111653. for(i=0;i<c->entries;i++)
  111654. if(c->lengthlist[i]==0)break;
  111655. if(i==c->entries){
  111656. oggpack_write(opb,0,1); /* no unused entries */
  111657. for(i=0;i<c->entries;i++)
  111658. oggpack_write(opb,c->lengthlist[i]-1,5);
  111659. }else{
  111660. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111661. for(i=0;i<c->entries;i++){
  111662. if(c->lengthlist[i]==0){
  111663. oggpack_write(opb,0,1);
  111664. }else{
  111665. oggpack_write(opb,1,1);
  111666. oggpack_write(opb,c->lengthlist[i]-1,5);
  111667. }
  111668. }
  111669. }
  111670. }
  111671. /* is the entry number the desired return value, or do we have a
  111672. mapping? If we have a mapping, what type? */
  111673. oggpack_write(opb,c->maptype,4);
  111674. switch(c->maptype){
  111675. case 0:
  111676. /* no mapping */
  111677. break;
  111678. case 1:case 2:
  111679. /* implicitly populated value mapping */
  111680. /* explicitly populated value mapping */
  111681. if(!c->quantlist){
  111682. /* no quantlist? error */
  111683. return(-1);
  111684. }
  111685. /* values that define the dequantization */
  111686. oggpack_write(opb,c->q_min,32);
  111687. oggpack_write(opb,c->q_delta,32);
  111688. oggpack_write(opb,c->q_quant-1,4);
  111689. oggpack_write(opb,c->q_sequencep,1);
  111690. {
  111691. int quantvals;
  111692. switch(c->maptype){
  111693. case 1:
  111694. /* a single column of (c->entries/c->dim) quantized values for
  111695. building a full value list algorithmically (square lattice) */
  111696. quantvals=_book_maptype1_quantvals(c);
  111697. break;
  111698. case 2:
  111699. /* every value (c->entries*c->dim total) specified explicitly */
  111700. quantvals=c->entries*c->dim;
  111701. break;
  111702. default: /* NOT_REACHABLE */
  111703. quantvals=-1;
  111704. }
  111705. /* quantized values */
  111706. for(i=0;i<quantvals;i++)
  111707. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111708. }
  111709. break;
  111710. default:
  111711. /* error case; we don't have any other map types now */
  111712. return(-1);
  111713. }
  111714. return(0);
  111715. }
  111716. /* unpacks a codebook from the packet buffer into the codebook struct,
  111717. readies the codebook auxiliary structures for decode *************/
  111718. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111719. long i,j;
  111720. memset(s,0,sizeof(*s));
  111721. s->allocedp=1;
  111722. /* make sure alignment is correct */
  111723. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111724. /* first the basic parameters */
  111725. s->dim=oggpack_read(opb,16);
  111726. s->entries=oggpack_read(opb,24);
  111727. if(s->entries==-1)goto _eofout;
  111728. /* codeword ordering.... length ordered or unordered? */
  111729. switch((int)oggpack_read(opb,1)){
  111730. case 0:
  111731. /* unordered */
  111732. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111733. /* allocated but unused entries? */
  111734. if(oggpack_read(opb,1)){
  111735. /* yes, unused entries */
  111736. for(i=0;i<s->entries;i++){
  111737. if(oggpack_read(opb,1)){
  111738. long num=oggpack_read(opb,5);
  111739. if(num==-1)goto _eofout;
  111740. s->lengthlist[i]=num+1;
  111741. }else
  111742. s->lengthlist[i]=0;
  111743. }
  111744. }else{
  111745. /* all entries used; no tagging */
  111746. for(i=0;i<s->entries;i++){
  111747. long num=oggpack_read(opb,5);
  111748. if(num==-1)goto _eofout;
  111749. s->lengthlist[i]=num+1;
  111750. }
  111751. }
  111752. break;
  111753. case 1:
  111754. /* ordered */
  111755. {
  111756. long length=oggpack_read(opb,5)+1;
  111757. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111758. for(i=0;i<s->entries;){
  111759. long num=oggpack_read(opb,_ilog(s->entries-i));
  111760. if(num==-1)goto _eofout;
  111761. for(j=0;j<num && i<s->entries;j++,i++)
  111762. s->lengthlist[i]=length;
  111763. length++;
  111764. }
  111765. }
  111766. break;
  111767. default:
  111768. /* EOF */
  111769. return(-1);
  111770. }
  111771. /* Do we have a mapping to unpack? */
  111772. switch((s->maptype=oggpack_read(opb,4))){
  111773. case 0:
  111774. /* no mapping */
  111775. break;
  111776. case 1: case 2:
  111777. /* implicitly populated value mapping */
  111778. /* explicitly populated value mapping */
  111779. s->q_min=oggpack_read(opb,32);
  111780. s->q_delta=oggpack_read(opb,32);
  111781. s->q_quant=oggpack_read(opb,4)+1;
  111782. s->q_sequencep=oggpack_read(opb,1);
  111783. {
  111784. int quantvals=0;
  111785. switch(s->maptype){
  111786. case 1:
  111787. quantvals=_book_maptype1_quantvals(s);
  111788. break;
  111789. case 2:
  111790. quantvals=s->entries*s->dim;
  111791. break;
  111792. }
  111793. /* quantized values */
  111794. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111795. for(i=0;i<quantvals;i++)
  111796. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111797. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111798. }
  111799. break;
  111800. default:
  111801. goto _errout;
  111802. }
  111803. /* all set */
  111804. return(0);
  111805. _errout:
  111806. _eofout:
  111807. vorbis_staticbook_clear(s);
  111808. return(-1);
  111809. }
  111810. /* returns the number of bits ************************************************/
  111811. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111812. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111813. return(book->c->lengthlist[a]);
  111814. }
  111815. /* One the encode side, our vector writers are each designed for a
  111816. specific purpose, and the encoder is not flexible without modification:
  111817. The LSP vector coder uses a single stage nearest-match with no
  111818. interleave, so no step and no error return. This is specced by floor0
  111819. and doesn't change.
  111820. Residue0 encoding interleaves, uses multiple stages, and each stage
  111821. peels of a specific amount of resolution from a lattice (thus we want
  111822. to match by threshold, not nearest match). Residue doesn't *have* to
  111823. be encoded that way, but to change it, one will need to add more
  111824. infrastructure on the encode side (decode side is specced and simpler) */
  111825. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111826. /* returns entry number and *modifies a* to the quantization value *****/
  111827. int vorbis_book_errorv(codebook *book,float *a){
  111828. int dim=book->dim,k;
  111829. int best=_best(book,a,1);
  111830. for(k=0;k<dim;k++)
  111831. a[k]=(book->valuelist+best*dim)[k];
  111832. return(best);
  111833. }
  111834. /* returns the number of bits and *modifies a* to the quantization value *****/
  111835. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111836. int k,dim=book->dim;
  111837. for(k=0;k<dim;k++)
  111838. a[k]=(book->valuelist+best*dim)[k];
  111839. return(vorbis_book_encode(book,best,b));
  111840. }
  111841. /* the 'eliminate the decode tree' optimization actually requires the
  111842. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111843. (and one of the first places where carefully thought out design
  111844. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111845. to an MSb bitpacker), but not actually the huge hit it appears to
  111846. be. The first-stage decode table catches most words so that
  111847. bitreverse is not in the main execution path. */
  111848. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111849. int read=book->dec_maxlength;
  111850. long lo,hi;
  111851. long lok = oggpack_look(b,book->dec_firsttablen);
  111852. if (lok >= 0) {
  111853. long entry = book->dec_firsttable[lok];
  111854. if(entry&0x80000000UL){
  111855. lo=(entry>>15)&0x7fff;
  111856. hi=book->used_entries-(entry&0x7fff);
  111857. }else{
  111858. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111859. return(entry-1);
  111860. }
  111861. }else{
  111862. lo=0;
  111863. hi=book->used_entries;
  111864. }
  111865. lok = oggpack_look(b, read);
  111866. while(lok<0 && read>1)
  111867. lok = oggpack_look(b, --read);
  111868. if(lok<0)return -1;
  111869. /* bisect search for the codeword in the ordered list */
  111870. {
  111871. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111872. while(hi-lo>1){
  111873. long p=(hi-lo)>>1;
  111874. long test=book->codelist[lo+p]>testword;
  111875. lo+=p&(test-1);
  111876. hi-=p&(-test);
  111877. }
  111878. if(book->dec_codelengths[lo]<=read){
  111879. oggpack_adv(b, book->dec_codelengths[lo]);
  111880. return(lo);
  111881. }
  111882. }
  111883. oggpack_adv(b, read);
  111884. return(-1);
  111885. }
  111886. /* Decode side is specced and easier, because we don't need to find
  111887. matches using different criteria; we simply read and map. There are
  111888. two things we need to do 'depending':
  111889. We may need to support interleave. We don't really, but it's
  111890. convenient to do it here rather than rebuild the vector later.
  111891. Cascades may be additive or multiplicitive; this is not inherent in
  111892. the codebook, but set in the code using the codebook. Like
  111893. interleaving, it's easiest to do it here.
  111894. addmul==0 -> declarative (set the value)
  111895. addmul==1 -> additive
  111896. addmul==2 -> multiplicitive */
  111897. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111898. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111899. long packed_entry=decode_packed_entry_number(book,b);
  111900. if(packed_entry>=0)
  111901. return(book->dec_index[packed_entry]);
  111902. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111903. return(packed_entry);
  111904. }
  111905. /* returns 0 on OK or -1 on eof *************************************/
  111906. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111907. int step=n/book->dim;
  111908. long *entry = (long*)alloca(sizeof(*entry)*step);
  111909. float **t = (float**)alloca(sizeof(*t)*step);
  111910. int i,j,o;
  111911. for (i = 0; i < step; i++) {
  111912. entry[i]=decode_packed_entry_number(book,b);
  111913. if(entry[i]==-1)return(-1);
  111914. t[i] = book->valuelist+entry[i]*book->dim;
  111915. }
  111916. for(i=0,o=0;i<book->dim;i++,o+=step)
  111917. for (j=0;j<step;j++)
  111918. a[o+j]+=t[j][i];
  111919. return(0);
  111920. }
  111921. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111922. int i,j,entry;
  111923. float *t;
  111924. if(book->dim>8){
  111925. for(i=0;i<n;){
  111926. entry = decode_packed_entry_number(book,b);
  111927. if(entry==-1)return(-1);
  111928. t = book->valuelist+entry*book->dim;
  111929. for (j=0;j<book->dim;)
  111930. a[i++]+=t[j++];
  111931. }
  111932. }else{
  111933. for(i=0;i<n;){
  111934. entry = decode_packed_entry_number(book,b);
  111935. if(entry==-1)return(-1);
  111936. t = book->valuelist+entry*book->dim;
  111937. j=0;
  111938. switch((int)book->dim){
  111939. case 8:
  111940. a[i++]+=t[j++];
  111941. case 7:
  111942. a[i++]+=t[j++];
  111943. case 6:
  111944. a[i++]+=t[j++];
  111945. case 5:
  111946. a[i++]+=t[j++];
  111947. case 4:
  111948. a[i++]+=t[j++];
  111949. case 3:
  111950. a[i++]+=t[j++];
  111951. case 2:
  111952. a[i++]+=t[j++];
  111953. case 1:
  111954. a[i++]+=t[j++];
  111955. case 0:
  111956. break;
  111957. }
  111958. }
  111959. }
  111960. return(0);
  111961. }
  111962. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111963. int i,j,entry;
  111964. float *t;
  111965. for(i=0;i<n;){
  111966. entry = decode_packed_entry_number(book,b);
  111967. if(entry==-1)return(-1);
  111968. t = book->valuelist+entry*book->dim;
  111969. for (j=0;j<book->dim;)
  111970. a[i++]=t[j++];
  111971. }
  111972. return(0);
  111973. }
  111974. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111975. oggpack_buffer *b,int n){
  111976. long i,j,entry;
  111977. int chptr=0;
  111978. for(i=offset/ch;i<(offset+n)/ch;){
  111979. entry = decode_packed_entry_number(book,b);
  111980. if(entry==-1)return(-1);
  111981. {
  111982. const float *t = book->valuelist+entry*book->dim;
  111983. for (j=0;j<book->dim;j++){
  111984. a[chptr++][i]+=t[j];
  111985. if(chptr==ch){
  111986. chptr=0;
  111987. i++;
  111988. }
  111989. }
  111990. }
  111991. }
  111992. return(0);
  111993. }
  111994. #ifdef _V_SELFTEST
  111995. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111996. number of vectors through (keeping track of the quantized values),
  111997. and decode using the unpacked book. quantized version of in should
  111998. exactly equal out */
  111999. #include <stdio.h>
  112000. #include "vorbis/book/lsp20_0.vqh"
  112001. #include "vorbis/book/res0a_13.vqh"
  112002. #define TESTSIZE 40
  112003. float test1[TESTSIZE]={
  112004. 0.105939f,
  112005. 0.215373f,
  112006. 0.429117f,
  112007. 0.587974f,
  112008. 0.181173f,
  112009. 0.296583f,
  112010. 0.515707f,
  112011. 0.715261f,
  112012. 0.162327f,
  112013. 0.263834f,
  112014. 0.342876f,
  112015. 0.406025f,
  112016. 0.103571f,
  112017. 0.223561f,
  112018. 0.368513f,
  112019. 0.540313f,
  112020. 0.136672f,
  112021. 0.395882f,
  112022. 0.587183f,
  112023. 0.652476f,
  112024. 0.114338f,
  112025. 0.417300f,
  112026. 0.525486f,
  112027. 0.698679f,
  112028. 0.147492f,
  112029. 0.324481f,
  112030. 0.643089f,
  112031. 0.757582f,
  112032. 0.139556f,
  112033. 0.215795f,
  112034. 0.324559f,
  112035. 0.399387f,
  112036. 0.120236f,
  112037. 0.267420f,
  112038. 0.446940f,
  112039. 0.608760f,
  112040. 0.115587f,
  112041. 0.287234f,
  112042. 0.571081f,
  112043. 0.708603f,
  112044. };
  112045. float test3[TESTSIZE]={
  112046. 0,1,-2,3,4,-5,6,7,8,9,
  112047. 8,-2,7,-1,4,6,8,3,1,-9,
  112048. 10,11,12,13,14,15,26,17,18,19,
  112049. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112050. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112051. &_vq_book_res0a_13,NULL};
  112052. float *testvec[]={test1,test3};
  112053. int main(){
  112054. oggpack_buffer write;
  112055. oggpack_buffer read;
  112056. long ptr=0,i;
  112057. oggpack_writeinit(&write);
  112058. fprintf(stderr,"Testing codebook abstraction...:\n");
  112059. while(testlist[ptr]){
  112060. codebook c;
  112061. static_codebook s;
  112062. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112063. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112064. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112065. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112066. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112067. /* pack the codebook, write the testvector */
  112068. oggpack_reset(&write);
  112069. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112070. we can write */
  112071. vorbis_staticbook_pack(testlist[ptr],&write);
  112072. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112073. for(i=0;i<TESTSIZE;i+=c.dim){
  112074. int best=_best(&c,qv+i,1);
  112075. vorbis_book_encodev(&c,best,qv+i,&write);
  112076. }
  112077. vorbis_book_clear(&c);
  112078. fprintf(stderr,"OK.\n");
  112079. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112080. /* transfer the write data to a read buffer and unpack/read */
  112081. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112082. if(vorbis_staticbook_unpack(&read,&s)){
  112083. fprintf(stderr,"Error unpacking codebook.\n");
  112084. exit(1);
  112085. }
  112086. if(vorbis_book_init_decode(&c,&s)){
  112087. fprintf(stderr,"Error initializing codebook.\n");
  112088. exit(1);
  112089. }
  112090. for(i=0;i<TESTSIZE;i+=c.dim)
  112091. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112092. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112093. exit(1);
  112094. }
  112095. for(i=0;i<TESTSIZE;i++)
  112096. if(fabs(qv[i]-iv[i])>.000001){
  112097. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112098. iv[i],qv[i],i);
  112099. exit(1);
  112100. }
  112101. fprintf(stderr,"OK\n");
  112102. ptr++;
  112103. }
  112104. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112105. exit(0);
  112106. }
  112107. #endif
  112108. #endif
  112109. /*** End of inlined file: codebook.c ***/
  112110. /*** Start of inlined file: envelope.c ***/
  112111. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112112. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112113. // tasks..
  112114. #if JUCE_MSVC
  112115. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112116. #endif
  112117. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112118. #if JUCE_USE_OGGVORBIS
  112119. #include <stdlib.h>
  112120. #include <string.h>
  112121. #include <stdio.h>
  112122. #include <math.h>
  112123. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112124. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112125. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112126. int ch=vi->channels;
  112127. int i,j;
  112128. int n=e->winlength=128;
  112129. e->searchstep=64; /* not random */
  112130. e->minenergy=gi->preecho_minenergy;
  112131. e->ch=ch;
  112132. e->storage=128;
  112133. e->cursor=ci->blocksizes[1]/2;
  112134. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112135. mdct_init(&e->mdct,n);
  112136. for(i=0;i<n;i++){
  112137. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112138. e->mdct_win[i]*=e->mdct_win[i];
  112139. }
  112140. /* magic follows */
  112141. e->band[0].begin=2; e->band[0].end=4;
  112142. e->band[1].begin=4; e->band[1].end=5;
  112143. e->band[2].begin=6; e->band[2].end=6;
  112144. e->band[3].begin=9; e->band[3].end=8;
  112145. e->band[4].begin=13; e->band[4].end=8;
  112146. e->band[5].begin=17; e->band[5].end=8;
  112147. e->band[6].begin=22; e->band[6].end=8;
  112148. for(j=0;j<VE_BANDS;j++){
  112149. n=e->band[j].end;
  112150. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112151. for(i=0;i<n;i++){
  112152. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112153. e->band[j].total+=e->band[j].window[i];
  112154. }
  112155. e->band[j].total=1./e->band[j].total;
  112156. }
  112157. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112158. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112159. }
  112160. void _ve_envelope_clear(envelope_lookup *e){
  112161. int i;
  112162. mdct_clear(&e->mdct);
  112163. for(i=0;i<VE_BANDS;i++)
  112164. _ogg_free(e->band[i].window);
  112165. _ogg_free(e->mdct_win);
  112166. _ogg_free(e->filter);
  112167. _ogg_free(e->mark);
  112168. memset(e,0,sizeof(*e));
  112169. }
  112170. /* fairly straight threshhold-by-band based until we find something
  112171. that works better and isn't patented. */
  112172. static int _ve_amp(envelope_lookup *ve,
  112173. vorbis_info_psy_global *gi,
  112174. float *data,
  112175. envelope_band *bands,
  112176. envelope_filter_state *filters,
  112177. long pos){
  112178. long n=ve->winlength;
  112179. int ret=0;
  112180. long i,j;
  112181. float decay;
  112182. /* we want to have a 'minimum bar' for energy, else we're just
  112183. basing blocks on quantization noise that outweighs the signal
  112184. itself (for low power signals) */
  112185. float minV=ve->minenergy;
  112186. float *vec=(float*) alloca(n*sizeof(*vec));
  112187. /* stretch is used to gradually lengthen the number of windows
  112188. considered prevoius-to-potential-trigger */
  112189. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112190. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112191. if(penalty<0.f)penalty=0.f;
  112192. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112193. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112194. totalshift+pos*ve->searchstep);*/
  112195. /* window and transform */
  112196. for(i=0;i<n;i++)
  112197. vec[i]=data[i]*ve->mdct_win[i];
  112198. mdct_forward(&ve->mdct,vec,vec);
  112199. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112200. /* near-DC spreading function; this has nothing to do with
  112201. psychoacoustics, just sidelobe leakage and window size */
  112202. {
  112203. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112204. int ptr=filters->nearptr;
  112205. /* the accumulation is regularly refreshed from scratch to avoid
  112206. floating point creep */
  112207. if(ptr==0){
  112208. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112209. filters->nearDC_partialacc=temp;
  112210. }else{
  112211. decay=filters->nearDC_acc+=temp;
  112212. filters->nearDC_partialacc+=temp;
  112213. }
  112214. filters->nearDC_acc-=filters->nearDC[ptr];
  112215. filters->nearDC[ptr]=temp;
  112216. decay*=(1./(VE_NEARDC+1));
  112217. filters->nearptr++;
  112218. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112219. decay=todB(&decay)*.5-15.f;
  112220. }
  112221. /* perform spreading and limiting, also smooth the spectrum. yes,
  112222. the MDCT results in all real coefficients, but it still *behaves*
  112223. like real/imaginary pairs */
  112224. for(i=0;i<n/2;i+=2){
  112225. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112226. val=todB(&val)*.5f;
  112227. if(val<decay)val=decay;
  112228. if(val<minV)val=minV;
  112229. vec[i>>1]=val;
  112230. decay-=8.;
  112231. }
  112232. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112233. /* perform preecho/postecho triggering by band */
  112234. for(j=0;j<VE_BANDS;j++){
  112235. float acc=0.;
  112236. float valmax,valmin;
  112237. /* accumulate amplitude */
  112238. for(i=0;i<bands[j].end;i++)
  112239. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112240. acc*=bands[j].total;
  112241. /* convert amplitude to delta */
  112242. {
  112243. int p,thisx=filters[j].ampptr;
  112244. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112245. p=thisx;
  112246. p--;
  112247. if(p<0)p+=VE_AMP;
  112248. postmax=max(acc,filters[j].ampbuf[p]);
  112249. postmin=min(acc,filters[j].ampbuf[p]);
  112250. for(i=0;i<stretch;i++){
  112251. p--;
  112252. if(p<0)p+=VE_AMP;
  112253. premax=max(premax,filters[j].ampbuf[p]);
  112254. premin=min(premin,filters[j].ampbuf[p]);
  112255. }
  112256. valmin=postmin-premin;
  112257. valmax=postmax-premax;
  112258. /*filters[j].markers[pos]=valmax;*/
  112259. filters[j].ampbuf[thisx]=acc;
  112260. filters[j].ampptr++;
  112261. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112262. }
  112263. /* look at min/max, decide trigger */
  112264. if(valmax>gi->preecho_thresh[j]+penalty){
  112265. ret|=1;
  112266. ret|=4;
  112267. }
  112268. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112269. }
  112270. return(ret);
  112271. }
  112272. #if 0
  112273. static int seq=0;
  112274. static ogg_int64_t totalshift=-1024;
  112275. #endif
  112276. long _ve_envelope_search(vorbis_dsp_state *v){
  112277. vorbis_info *vi=v->vi;
  112278. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112279. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112280. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112281. long i,j;
  112282. int first=ve->current/ve->searchstep;
  112283. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112284. if(first<0)first=0;
  112285. /* make sure we have enough storage to match the PCM */
  112286. if(last+VE_WIN+VE_POST>ve->storage){
  112287. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112288. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112289. }
  112290. for(j=first;j<last;j++){
  112291. int ret=0;
  112292. ve->stretch++;
  112293. if(ve->stretch>VE_MAXSTRETCH*2)
  112294. ve->stretch=VE_MAXSTRETCH*2;
  112295. for(i=0;i<ve->ch;i++){
  112296. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112297. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112298. }
  112299. ve->mark[j+VE_POST]=0;
  112300. if(ret&1){
  112301. ve->mark[j]=1;
  112302. ve->mark[j+1]=1;
  112303. }
  112304. if(ret&2){
  112305. ve->mark[j]=1;
  112306. if(j>0)ve->mark[j-1]=1;
  112307. }
  112308. if(ret&4)ve->stretch=-1;
  112309. }
  112310. ve->current=last*ve->searchstep;
  112311. {
  112312. long centerW=v->centerW;
  112313. long testW=
  112314. centerW+
  112315. ci->blocksizes[v->W]/4+
  112316. ci->blocksizes[1]/2+
  112317. ci->blocksizes[0]/4;
  112318. j=ve->cursor;
  112319. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112320. working back one window */
  112321. if(j>=testW)return(1);
  112322. ve->cursor=j;
  112323. if(ve->mark[j/ve->searchstep]){
  112324. if(j>centerW){
  112325. #if 0
  112326. if(j>ve->curmark){
  112327. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112328. int l,m;
  112329. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112330. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112331. seq,
  112332. (totalshift+ve->cursor)/44100.,
  112333. (totalshift+j)/44100.);
  112334. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112335. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112336. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112337. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112338. for(m=0;m<VE_BANDS;m++){
  112339. char buf[80];
  112340. sprintf(buf,"delL%d",m);
  112341. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112342. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112343. }
  112344. for(m=0;m<VE_BANDS;m++){
  112345. char buf[80];
  112346. sprintf(buf,"delR%d",m);
  112347. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112348. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112349. }
  112350. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112351. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112352. seq++;
  112353. }
  112354. #endif
  112355. ve->curmark=j;
  112356. if(j>=testW)return(1);
  112357. return(0);
  112358. }
  112359. }
  112360. j+=ve->searchstep;
  112361. }
  112362. }
  112363. return(-1);
  112364. }
  112365. int _ve_envelope_mark(vorbis_dsp_state *v){
  112366. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112367. vorbis_info *vi=v->vi;
  112368. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112369. long centerW=v->centerW;
  112370. long beginW=centerW-ci->blocksizes[v->W]/4;
  112371. long endW=centerW+ci->blocksizes[v->W]/4;
  112372. if(v->W){
  112373. beginW-=ci->blocksizes[v->lW]/4;
  112374. endW+=ci->blocksizes[v->nW]/4;
  112375. }else{
  112376. beginW-=ci->blocksizes[0]/4;
  112377. endW+=ci->blocksizes[0]/4;
  112378. }
  112379. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112380. {
  112381. long first=beginW/ve->searchstep;
  112382. long last=endW/ve->searchstep;
  112383. long i;
  112384. for(i=first;i<last;i++)
  112385. if(ve->mark[i])return(1);
  112386. }
  112387. return(0);
  112388. }
  112389. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112390. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112391. ahead of ve->current */
  112392. int smallshift=shift/e->searchstep;
  112393. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112394. #if 0
  112395. for(i=0;i<VE_BANDS*e->ch;i++)
  112396. memmove(e->filter[i].markers,
  112397. e->filter[i].markers+smallshift,
  112398. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112399. totalshift+=shift;
  112400. #endif
  112401. e->current-=shift;
  112402. if(e->curmark>=0)
  112403. e->curmark-=shift;
  112404. e->cursor-=shift;
  112405. }
  112406. #endif
  112407. /*** End of inlined file: envelope.c ***/
  112408. /*** Start of inlined file: floor0.c ***/
  112409. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112410. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112411. // tasks..
  112412. #if JUCE_MSVC
  112413. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112414. #endif
  112415. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112416. #if JUCE_USE_OGGVORBIS
  112417. #include <stdlib.h>
  112418. #include <string.h>
  112419. #include <math.h>
  112420. /*** Start of inlined file: lsp.h ***/
  112421. #ifndef _V_LSP_H_
  112422. #define _V_LSP_H_
  112423. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112424. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112425. float *lsp,int m,
  112426. float amp,float ampoffset);
  112427. #endif
  112428. /*** End of inlined file: lsp.h ***/
  112429. #include <stdio.h>
  112430. typedef struct {
  112431. int ln;
  112432. int m;
  112433. int **linearmap;
  112434. int n[2];
  112435. vorbis_info_floor0 *vi;
  112436. long bits;
  112437. long frames;
  112438. } vorbis_look_floor0;
  112439. /***********************************************/
  112440. static void floor0_free_info(vorbis_info_floor *i){
  112441. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112442. if(info){
  112443. memset(info,0,sizeof(*info));
  112444. _ogg_free(info);
  112445. }
  112446. }
  112447. static void floor0_free_look(vorbis_look_floor *i){
  112448. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112449. if(look){
  112450. if(look->linearmap){
  112451. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112452. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112453. _ogg_free(look->linearmap);
  112454. }
  112455. memset(look,0,sizeof(*look));
  112456. _ogg_free(look);
  112457. }
  112458. }
  112459. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112460. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112461. int j;
  112462. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112463. info->order=oggpack_read(opb,8);
  112464. info->rate=oggpack_read(opb,16);
  112465. info->barkmap=oggpack_read(opb,16);
  112466. info->ampbits=oggpack_read(opb,6);
  112467. info->ampdB=oggpack_read(opb,8);
  112468. info->numbooks=oggpack_read(opb,4)+1;
  112469. if(info->order<1)goto err_out;
  112470. if(info->rate<1)goto err_out;
  112471. if(info->barkmap<1)goto err_out;
  112472. if(info->numbooks<1)goto err_out;
  112473. for(j=0;j<info->numbooks;j++){
  112474. info->books[j]=oggpack_read(opb,8);
  112475. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112476. }
  112477. return(info);
  112478. err_out:
  112479. floor0_free_info(info);
  112480. return(NULL);
  112481. }
  112482. /* initialize Bark scale and normalization lookups. We could do this
  112483. with static tables, but Vorbis allows a number of possible
  112484. combinations, so it's best to do it computationally.
  112485. The below is authoritative in terms of defining scale mapping.
  112486. Note that the scale depends on the sampling rate as well as the
  112487. linear block and mapping sizes */
  112488. static void floor0_map_lazy_init(vorbis_block *vb,
  112489. vorbis_info_floor *infoX,
  112490. vorbis_look_floor0 *look){
  112491. if(!look->linearmap[vb->W]){
  112492. vorbis_dsp_state *vd=vb->vd;
  112493. vorbis_info *vi=vd->vi;
  112494. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112495. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112496. int W=vb->W;
  112497. int n=ci->blocksizes[W]/2,j;
  112498. /* we choose a scaling constant so that:
  112499. floor(bark(rate/2-1)*C)=mapped-1
  112500. floor(bark(rate/2)*C)=mapped */
  112501. float scale=look->ln/toBARK(info->rate/2.f);
  112502. /* the mapping from a linear scale to a smaller bark scale is
  112503. straightforward. We do *not* make sure that the linear mapping
  112504. does not skip bark-scale bins; the decoder simply skips them and
  112505. the encoder may do what it wishes in filling them. They're
  112506. necessary in some mapping combinations to keep the scale spacing
  112507. accurate */
  112508. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112509. for(j=0;j<n;j++){
  112510. int val=floor( toBARK((info->rate/2.f)/n*j)
  112511. *scale); /* bark numbers represent band edges */
  112512. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112513. look->linearmap[W][j]=val;
  112514. }
  112515. look->linearmap[W][j]=-1;
  112516. look->n[W]=n;
  112517. }
  112518. }
  112519. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112520. vorbis_info_floor *i){
  112521. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112522. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112523. look->m=info->order;
  112524. look->ln=info->barkmap;
  112525. look->vi=info;
  112526. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112527. return look;
  112528. }
  112529. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112530. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112531. vorbis_info_floor0 *info=look->vi;
  112532. int j,k;
  112533. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112534. if(ampraw>0){ /* also handles the -1 out of data case */
  112535. long maxval=(1<<info->ampbits)-1;
  112536. float amp=(float)ampraw/maxval*info->ampdB;
  112537. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112538. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112539. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112540. codebook *b=ci->fullbooks+info->books[booknum];
  112541. float last=0.f;
  112542. /* the additional b->dim is a guard against any possible stack
  112543. smash; b->dim is provably more than we can overflow the
  112544. vector */
  112545. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112546. for(j=0;j<look->m;j+=b->dim)
  112547. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112548. for(j=0;j<look->m;){
  112549. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112550. last=lsp[j-1];
  112551. }
  112552. lsp[look->m]=amp;
  112553. return(lsp);
  112554. }
  112555. }
  112556. eop:
  112557. return(NULL);
  112558. }
  112559. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112560. void *memo,float *out){
  112561. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112562. vorbis_info_floor0 *info=look->vi;
  112563. floor0_map_lazy_init(vb,info,look);
  112564. if(memo){
  112565. float *lsp=(float *)memo;
  112566. float amp=lsp[look->m];
  112567. /* take the coefficients back to a spectral envelope curve */
  112568. vorbis_lsp_to_curve(out,
  112569. look->linearmap[vb->W],
  112570. look->n[vb->W],
  112571. look->ln,
  112572. lsp,look->m,amp,(float)info->ampdB);
  112573. return(1);
  112574. }
  112575. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112576. return(0);
  112577. }
  112578. /* export hooks */
  112579. vorbis_func_floor floor0_exportbundle={
  112580. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112581. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112582. };
  112583. #endif
  112584. /*** End of inlined file: floor0.c ***/
  112585. /*** Start of inlined file: floor1.c ***/
  112586. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112587. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112588. // tasks..
  112589. #if JUCE_MSVC
  112590. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112591. #endif
  112592. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112593. #if JUCE_USE_OGGVORBIS
  112594. #include <stdlib.h>
  112595. #include <string.h>
  112596. #include <math.h>
  112597. #include <stdio.h>
  112598. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112599. typedef struct {
  112600. int sorted_index[VIF_POSIT+2];
  112601. int forward_index[VIF_POSIT+2];
  112602. int reverse_index[VIF_POSIT+2];
  112603. int hineighbor[VIF_POSIT];
  112604. int loneighbor[VIF_POSIT];
  112605. int posts;
  112606. int n;
  112607. int quant_q;
  112608. vorbis_info_floor1 *vi;
  112609. long phrasebits;
  112610. long postbits;
  112611. long frames;
  112612. } vorbis_look_floor1;
  112613. typedef struct lsfit_acc{
  112614. long x0;
  112615. long x1;
  112616. long xa;
  112617. long ya;
  112618. long x2a;
  112619. long y2a;
  112620. long xya;
  112621. long an;
  112622. } lsfit_acc;
  112623. /***********************************************/
  112624. static void floor1_free_info(vorbis_info_floor *i){
  112625. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112626. if(info){
  112627. memset(info,0,sizeof(*info));
  112628. _ogg_free(info);
  112629. }
  112630. }
  112631. static void floor1_free_look(vorbis_look_floor *i){
  112632. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112633. if(look){
  112634. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112635. (float)look->phrasebits/look->frames,
  112636. (float)look->postbits/look->frames,
  112637. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112638. memset(look,0,sizeof(*look));
  112639. _ogg_free(look);
  112640. }
  112641. }
  112642. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112643. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112644. int j,k;
  112645. int count=0;
  112646. int rangebits;
  112647. int maxposit=info->postlist[1];
  112648. int maxclass=-1;
  112649. /* save out partitions */
  112650. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112651. for(j=0;j<info->partitions;j++){
  112652. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112653. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112654. }
  112655. /* save out partition classes */
  112656. for(j=0;j<maxclass+1;j++){
  112657. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112658. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112659. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112660. for(k=0;k<(1<<info->class_subs[j]);k++)
  112661. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112662. }
  112663. /* save out the post list */
  112664. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112665. oggpack_write(opb,ilog2(maxposit),4);
  112666. rangebits=ilog2(maxposit);
  112667. for(j=0,k=0;j<info->partitions;j++){
  112668. count+=info->class_dim[info->partitionclass[j]];
  112669. for(;k<count;k++)
  112670. oggpack_write(opb,info->postlist[k+2],rangebits);
  112671. }
  112672. }
  112673. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112674. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112675. int j,k,count=0,maxclass=-1,rangebits;
  112676. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112677. /* read partitions */
  112678. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112679. for(j=0;j<info->partitions;j++){
  112680. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112681. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112682. }
  112683. /* read partition classes */
  112684. for(j=0;j<maxclass+1;j++){
  112685. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112686. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112687. if(info->class_subs[j]<0)
  112688. goto err_out;
  112689. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112690. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112691. goto err_out;
  112692. for(k=0;k<(1<<info->class_subs[j]);k++){
  112693. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112694. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112695. goto err_out;
  112696. }
  112697. }
  112698. /* read the post list */
  112699. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112700. rangebits=oggpack_read(opb,4);
  112701. for(j=0,k=0;j<info->partitions;j++){
  112702. count+=info->class_dim[info->partitionclass[j]];
  112703. for(;k<count;k++){
  112704. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112705. if(t<0 || t>=(1<<rangebits))
  112706. goto err_out;
  112707. }
  112708. }
  112709. info->postlist[0]=0;
  112710. info->postlist[1]=1<<rangebits;
  112711. return(info);
  112712. err_out:
  112713. floor1_free_info(info);
  112714. return(NULL);
  112715. }
  112716. static int JUCE_CDECL icomp(const void *a,const void *b){
  112717. return(**(int **)a-**(int **)b);
  112718. }
  112719. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112720. vorbis_info_floor *in){
  112721. int *sortpointer[VIF_POSIT+2];
  112722. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112723. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112724. int i,j,n=0;
  112725. look->vi=info;
  112726. look->n=info->postlist[1];
  112727. /* we drop each position value in-between already decoded values,
  112728. and use linear interpolation to predict each new value past the
  112729. edges. The positions are read in the order of the position
  112730. list... we precompute the bounding positions in the lookup. Of
  112731. course, the neighbors can change (if a position is declined), but
  112732. this is an initial mapping */
  112733. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112734. n+=2;
  112735. look->posts=n;
  112736. /* also store a sorted position index */
  112737. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112738. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112739. /* points from sort order back to range number */
  112740. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112741. /* points from range order to sorted position */
  112742. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112743. /* we actually need the post values too */
  112744. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112745. /* quantize values to multiplier spec */
  112746. switch(info->mult){
  112747. case 1: /* 1024 -> 256 */
  112748. look->quant_q=256;
  112749. break;
  112750. case 2: /* 1024 -> 128 */
  112751. look->quant_q=128;
  112752. break;
  112753. case 3: /* 1024 -> 86 */
  112754. look->quant_q=86;
  112755. break;
  112756. case 4: /* 1024 -> 64 */
  112757. look->quant_q=64;
  112758. break;
  112759. }
  112760. /* discover our neighbors for decode where we don't use fit flags
  112761. (that would push the neighbors outward) */
  112762. for(i=0;i<n-2;i++){
  112763. int lo=0;
  112764. int hi=1;
  112765. int lx=0;
  112766. int hx=look->n;
  112767. int currentx=info->postlist[i+2];
  112768. for(j=0;j<i+2;j++){
  112769. int x=info->postlist[j];
  112770. if(x>lx && x<currentx){
  112771. lo=j;
  112772. lx=x;
  112773. }
  112774. if(x<hx && x>currentx){
  112775. hi=j;
  112776. hx=x;
  112777. }
  112778. }
  112779. look->loneighbor[i]=lo;
  112780. look->hineighbor[i]=hi;
  112781. }
  112782. return(look);
  112783. }
  112784. static int render_point(int x0,int x1,int y0,int y1,int x){
  112785. y0&=0x7fff; /* mask off flag */
  112786. y1&=0x7fff;
  112787. {
  112788. int dy=y1-y0;
  112789. int adx=x1-x0;
  112790. int ady=abs(dy);
  112791. int err=ady*(x-x0);
  112792. int off=err/adx;
  112793. if(dy<0)return(y0-off);
  112794. return(y0+off);
  112795. }
  112796. }
  112797. static int vorbis_dBquant(const float *x){
  112798. int i= *x*7.3142857f+1023.5f;
  112799. if(i>1023)return(1023);
  112800. if(i<0)return(0);
  112801. return i;
  112802. }
  112803. static float FLOOR1_fromdB_LOOKUP[256]={
  112804. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112805. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112806. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112807. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112808. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112809. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112810. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112811. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112812. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112813. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112814. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112815. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112816. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112817. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112818. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112819. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112820. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112821. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112822. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112823. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112824. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112825. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112826. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112827. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112828. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112829. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112830. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112831. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112832. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112833. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112834. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112835. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112836. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112837. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112838. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112839. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112840. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112841. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112842. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112843. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112844. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112845. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112846. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112847. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112848. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112849. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112850. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112851. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112852. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112853. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112854. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112855. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112856. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112857. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112858. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112859. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112860. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112861. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112862. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112863. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112864. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112865. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112866. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112867. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112868. };
  112869. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112870. int dy=y1-y0;
  112871. int adx=x1-x0;
  112872. int ady=abs(dy);
  112873. int base=dy/adx;
  112874. int sy=(dy<0?base-1:base+1);
  112875. int x=x0;
  112876. int y=y0;
  112877. int err=0;
  112878. ady-=abs(base*adx);
  112879. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112880. while(++x<x1){
  112881. err=err+ady;
  112882. if(err>=adx){
  112883. err-=adx;
  112884. y+=sy;
  112885. }else{
  112886. y+=base;
  112887. }
  112888. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112889. }
  112890. }
  112891. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112892. int dy=y1-y0;
  112893. int adx=x1-x0;
  112894. int ady=abs(dy);
  112895. int base=dy/adx;
  112896. int sy=(dy<0?base-1:base+1);
  112897. int x=x0;
  112898. int y=y0;
  112899. int err=0;
  112900. ady-=abs(base*adx);
  112901. d[x]=y;
  112902. while(++x<x1){
  112903. err=err+ady;
  112904. if(err>=adx){
  112905. err-=adx;
  112906. y+=sy;
  112907. }else{
  112908. y+=base;
  112909. }
  112910. d[x]=y;
  112911. }
  112912. }
  112913. /* the floor has already been filtered to only include relevant sections */
  112914. static int accumulate_fit(const float *flr,const float *mdct,
  112915. int x0, int x1,lsfit_acc *a,
  112916. int n,vorbis_info_floor1 *info){
  112917. long i;
  112918. 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;
  112919. memset(a,0,sizeof(*a));
  112920. a->x0=x0;
  112921. a->x1=x1;
  112922. if(x1>=n)x1=n-1;
  112923. for(i=x0;i<=x1;i++){
  112924. int quantized=vorbis_dBquant(flr+i);
  112925. if(quantized){
  112926. if(mdct[i]+info->twofitatten>=flr[i]){
  112927. xa += i;
  112928. ya += quantized;
  112929. x2a += i*i;
  112930. y2a += quantized*quantized;
  112931. xya += i*quantized;
  112932. na++;
  112933. }else{
  112934. xb += i;
  112935. yb += quantized;
  112936. x2b += i*i;
  112937. y2b += quantized*quantized;
  112938. xyb += i*quantized;
  112939. nb++;
  112940. }
  112941. }
  112942. }
  112943. xb+=xa;
  112944. yb+=ya;
  112945. x2b+=x2a;
  112946. y2b+=y2a;
  112947. xyb+=xya;
  112948. nb+=na;
  112949. /* weight toward the actually used frequencies if we meet the threshhold */
  112950. {
  112951. int weight=nb*info->twofitweight/(na+1);
  112952. a->xa=xa*weight+xb;
  112953. a->ya=ya*weight+yb;
  112954. a->x2a=x2a*weight+x2b;
  112955. a->y2a=y2a*weight+y2b;
  112956. a->xya=xya*weight+xyb;
  112957. a->an=na*weight+nb;
  112958. }
  112959. return(na);
  112960. }
  112961. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112962. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112963. long x0=a[0].x0;
  112964. long x1=a[fits-1].x1;
  112965. for(i=0;i<fits;i++){
  112966. x+=a[i].xa;
  112967. y+=a[i].ya;
  112968. x2+=a[i].x2a;
  112969. y2+=a[i].y2a;
  112970. xy+=a[i].xya;
  112971. an+=a[i].an;
  112972. }
  112973. if(*y0>=0){
  112974. x+= x0;
  112975. y+= *y0;
  112976. x2+= x0 * x0;
  112977. y2+= *y0 * *y0;
  112978. xy+= *y0 * x0;
  112979. an++;
  112980. }
  112981. if(*y1>=0){
  112982. x+= x1;
  112983. y+= *y1;
  112984. x2+= x1 * x1;
  112985. y2+= *y1 * *y1;
  112986. xy+= *y1 * x1;
  112987. an++;
  112988. }
  112989. if(an){
  112990. /* need 64 bit multiplies, which C doesn't give portably as int */
  112991. double fx=x;
  112992. double fy=y;
  112993. double fx2=x2;
  112994. double fxy=xy;
  112995. double denom=1./(an*fx2-fx*fx);
  112996. double a=(fy*fx2-fxy*fx)*denom;
  112997. double b=(an*fxy-fx*fy)*denom;
  112998. *y0=rint(a+b*x0);
  112999. *y1=rint(a+b*x1);
  113000. /* limit to our range! */
  113001. if(*y0>1023)*y0=1023;
  113002. if(*y1>1023)*y1=1023;
  113003. if(*y0<0)*y0=0;
  113004. if(*y1<0)*y1=0;
  113005. }else{
  113006. *y0=0;
  113007. *y1=0;
  113008. }
  113009. }
  113010. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113011. long y=0;
  113012. int i;
  113013. for(i=0;i<fits && y==0;i++)
  113014. y+=a[i].ya;
  113015. *y0=*y1=y;
  113016. }*/
  113017. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113018. const float *mdct,
  113019. vorbis_info_floor1 *info){
  113020. int dy=y1-y0;
  113021. int adx=x1-x0;
  113022. int ady=abs(dy);
  113023. int base=dy/adx;
  113024. int sy=(dy<0?base-1:base+1);
  113025. int x=x0;
  113026. int y=y0;
  113027. int err=0;
  113028. int val=vorbis_dBquant(mask+x);
  113029. int mse=0;
  113030. int n=0;
  113031. ady-=abs(base*adx);
  113032. mse=(y-val);
  113033. mse*=mse;
  113034. n++;
  113035. if(mdct[x]+info->twofitatten>=mask[x]){
  113036. if(y+info->maxover<val)return(1);
  113037. if(y-info->maxunder>val)return(1);
  113038. }
  113039. while(++x<x1){
  113040. err=err+ady;
  113041. if(err>=adx){
  113042. err-=adx;
  113043. y+=sy;
  113044. }else{
  113045. y+=base;
  113046. }
  113047. val=vorbis_dBquant(mask+x);
  113048. mse+=((y-val)*(y-val));
  113049. n++;
  113050. if(mdct[x]+info->twofitatten>=mask[x]){
  113051. if(val){
  113052. if(y+info->maxover<val)return(1);
  113053. if(y-info->maxunder>val)return(1);
  113054. }
  113055. }
  113056. }
  113057. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113058. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113059. if(mse/n>info->maxerr)return(1);
  113060. return(0);
  113061. }
  113062. static int post_Y(int *A,int *B,int pos){
  113063. if(A[pos]<0)
  113064. return B[pos];
  113065. if(B[pos]<0)
  113066. return A[pos];
  113067. return (A[pos]+B[pos])>>1;
  113068. }
  113069. int *floor1_fit(vorbis_block *vb,void *look_,
  113070. const float *logmdct, /* in */
  113071. const float *logmask){
  113072. long i,j;
  113073. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113074. vorbis_info_floor1 *info=look->vi;
  113075. long n=look->n;
  113076. long posts=look->posts;
  113077. long nonzero=0;
  113078. lsfit_acc fits[VIF_POSIT+1];
  113079. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113080. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113081. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113082. int hineighbor[VIF_POSIT+2];
  113083. int *output=NULL;
  113084. int memo[VIF_POSIT+2];
  113085. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113086. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113087. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113088. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113089. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113090. /* quantize the relevant floor points and collect them into line fit
  113091. structures (one per minimal division) at the same time */
  113092. if(posts==0){
  113093. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113094. }else{
  113095. for(i=0;i<posts-1;i++)
  113096. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113097. look->sorted_index[i+1],fits+i,
  113098. n,info);
  113099. }
  113100. if(nonzero){
  113101. /* start by fitting the implicit base case.... */
  113102. int y0=-200;
  113103. int y1=-200;
  113104. fit_line(fits,posts-1,&y0,&y1);
  113105. fit_valueA[0]=y0;
  113106. fit_valueB[0]=y0;
  113107. fit_valueB[1]=y1;
  113108. fit_valueA[1]=y1;
  113109. /* Non degenerate case */
  113110. /* start progressive splitting. This is a greedy, non-optimal
  113111. algorithm, but simple and close enough to the best
  113112. answer. */
  113113. for(i=2;i<posts;i++){
  113114. int sortpos=look->reverse_index[i];
  113115. int ln=loneighbor[sortpos];
  113116. int hn=hineighbor[sortpos];
  113117. /* eliminate repeat searches of a particular range with a memo */
  113118. if(memo[ln]!=hn){
  113119. /* haven't performed this error search yet */
  113120. int lsortpos=look->reverse_index[ln];
  113121. int hsortpos=look->reverse_index[hn];
  113122. memo[ln]=hn;
  113123. {
  113124. /* A note: we want to bound/minimize *local*, not global, error */
  113125. int lx=info->postlist[ln];
  113126. int hx=info->postlist[hn];
  113127. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113128. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113129. if(ly==-1 || hy==-1){
  113130. exit(1);
  113131. }
  113132. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113133. /* outside error bounds/begin search area. Split it. */
  113134. int ly0=-200;
  113135. int ly1=-200;
  113136. int hy0=-200;
  113137. int hy1=-200;
  113138. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113139. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113140. /* store new edge values */
  113141. fit_valueB[ln]=ly0;
  113142. if(ln==0)fit_valueA[ln]=ly0;
  113143. fit_valueA[i]=ly1;
  113144. fit_valueB[i]=hy0;
  113145. fit_valueA[hn]=hy1;
  113146. if(hn==1)fit_valueB[hn]=hy1;
  113147. if(ly1>=0 || hy0>=0){
  113148. /* store new neighbor values */
  113149. for(j=sortpos-1;j>=0;j--)
  113150. if(hineighbor[j]==hn)
  113151. hineighbor[j]=i;
  113152. else
  113153. break;
  113154. for(j=sortpos+1;j<posts;j++)
  113155. if(loneighbor[j]==ln)
  113156. loneighbor[j]=i;
  113157. else
  113158. break;
  113159. }
  113160. }else{
  113161. fit_valueA[i]=-200;
  113162. fit_valueB[i]=-200;
  113163. }
  113164. }
  113165. }
  113166. }
  113167. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113168. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113169. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113170. /* fill in posts marked as not using a fit; we will zero
  113171. back out to 'unused' when encoding them so long as curve
  113172. interpolation doesn't force them into use */
  113173. for(i=2;i<posts;i++){
  113174. int ln=look->loneighbor[i-2];
  113175. int hn=look->hineighbor[i-2];
  113176. int x0=info->postlist[ln];
  113177. int x1=info->postlist[hn];
  113178. int y0=output[ln];
  113179. int y1=output[hn];
  113180. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113181. int vx=post_Y(fit_valueA,fit_valueB,i);
  113182. if(vx>=0 && predicted!=vx){
  113183. output[i]=vx;
  113184. }else{
  113185. output[i]= predicted|0x8000;
  113186. }
  113187. }
  113188. }
  113189. return(output);
  113190. }
  113191. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113192. int *A,int *B,
  113193. int del){
  113194. long i;
  113195. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113196. long posts=look->posts;
  113197. int *output=NULL;
  113198. if(A && B){
  113199. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113200. for(i=0;i<posts;i++){
  113201. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113202. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113203. }
  113204. }
  113205. return(output);
  113206. }
  113207. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113208. void*look_,
  113209. int *post,int *ilogmask){
  113210. long i,j;
  113211. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113212. vorbis_info_floor1 *info=look->vi;
  113213. long posts=look->posts;
  113214. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113215. int out[VIF_POSIT+2];
  113216. static_codebook **sbooks=ci->book_param;
  113217. codebook *books=ci->fullbooks;
  113218. static long seq=0;
  113219. /* quantize values to multiplier spec */
  113220. if(post){
  113221. for(i=0;i<posts;i++){
  113222. int val=post[i]&0x7fff;
  113223. switch(info->mult){
  113224. case 1: /* 1024 -> 256 */
  113225. val>>=2;
  113226. break;
  113227. case 2: /* 1024 -> 128 */
  113228. val>>=3;
  113229. break;
  113230. case 3: /* 1024 -> 86 */
  113231. val/=12;
  113232. break;
  113233. case 4: /* 1024 -> 64 */
  113234. val>>=4;
  113235. break;
  113236. }
  113237. post[i]=val | (post[i]&0x8000);
  113238. }
  113239. out[0]=post[0];
  113240. out[1]=post[1];
  113241. /* find prediction values for each post and subtract them */
  113242. for(i=2;i<posts;i++){
  113243. int ln=look->loneighbor[i-2];
  113244. int hn=look->hineighbor[i-2];
  113245. int x0=info->postlist[ln];
  113246. int x1=info->postlist[hn];
  113247. int y0=post[ln];
  113248. int y1=post[hn];
  113249. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113250. if((post[i]&0x8000) || (predicted==post[i])){
  113251. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113252. in interpolation */
  113253. out[i]=0;
  113254. }else{
  113255. int headroom=(look->quant_q-predicted<predicted?
  113256. look->quant_q-predicted:predicted);
  113257. int val=post[i]-predicted;
  113258. /* at this point the 'deviation' value is in the range +/- max
  113259. range, but the real, unique range can always be mapped to
  113260. only [0-maxrange). So we want to wrap the deviation into
  113261. this limited range, but do it in the way that least screws
  113262. an essentially gaussian probability distribution. */
  113263. if(val<0)
  113264. if(val<-headroom)
  113265. val=headroom-val-1;
  113266. else
  113267. val=-1-(val<<1);
  113268. else
  113269. if(val>=headroom)
  113270. val= val+headroom;
  113271. else
  113272. val<<=1;
  113273. out[i]=val;
  113274. post[ln]&=0x7fff;
  113275. post[hn]&=0x7fff;
  113276. }
  113277. }
  113278. /* we have everything we need. pack it out */
  113279. /* mark nontrivial floor */
  113280. oggpack_write(opb,1,1);
  113281. /* beginning/end post */
  113282. look->frames++;
  113283. look->postbits+=ilog(look->quant_q-1)*2;
  113284. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113285. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113286. /* partition by partition */
  113287. for(i=0,j=2;i<info->partitions;i++){
  113288. int classx=info->partitionclass[i];
  113289. int cdim=info->class_dim[classx];
  113290. int csubbits=info->class_subs[classx];
  113291. int csub=1<<csubbits;
  113292. int bookas[8]={0,0,0,0,0,0,0,0};
  113293. int cval=0;
  113294. int cshift=0;
  113295. int k,l;
  113296. /* generate the partition's first stage cascade value */
  113297. if(csubbits){
  113298. int maxval[8];
  113299. for(k=0;k<csub;k++){
  113300. int booknum=info->class_subbook[classx][k];
  113301. if(booknum<0){
  113302. maxval[k]=1;
  113303. }else{
  113304. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113305. }
  113306. }
  113307. for(k=0;k<cdim;k++){
  113308. for(l=0;l<csub;l++){
  113309. int val=out[j+k];
  113310. if(val<maxval[l]){
  113311. bookas[k]=l;
  113312. break;
  113313. }
  113314. }
  113315. cval|= bookas[k]<<cshift;
  113316. cshift+=csubbits;
  113317. }
  113318. /* write it */
  113319. look->phrasebits+=
  113320. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113321. #ifdef TRAIN_FLOOR1
  113322. {
  113323. FILE *of;
  113324. char buffer[80];
  113325. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113326. vb->pcmend/2,posts-2,class);
  113327. of=fopen(buffer,"a");
  113328. fprintf(of,"%d\n",cval);
  113329. fclose(of);
  113330. }
  113331. #endif
  113332. }
  113333. /* write post values */
  113334. for(k=0;k<cdim;k++){
  113335. int book=info->class_subbook[classx][bookas[k]];
  113336. if(book>=0){
  113337. /* hack to allow training with 'bad' books */
  113338. if(out[j+k]<(books+book)->entries)
  113339. look->postbits+=vorbis_book_encode(books+book,
  113340. out[j+k],opb);
  113341. /*else
  113342. fprintf(stderr,"+!");*/
  113343. #ifdef TRAIN_FLOOR1
  113344. {
  113345. FILE *of;
  113346. char buffer[80];
  113347. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113348. vb->pcmend/2,posts-2,class,bookas[k]);
  113349. of=fopen(buffer,"a");
  113350. fprintf(of,"%d\n",out[j+k]);
  113351. fclose(of);
  113352. }
  113353. #endif
  113354. }
  113355. }
  113356. j+=cdim;
  113357. }
  113358. {
  113359. /* generate quantized floor equivalent to what we'd unpack in decode */
  113360. /* render the lines */
  113361. int hx=0;
  113362. int lx=0;
  113363. int ly=post[0]*info->mult;
  113364. for(j=1;j<look->posts;j++){
  113365. int current=look->forward_index[j];
  113366. int hy=post[current]&0x7fff;
  113367. if(hy==post[current]){
  113368. hy*=info->mult;
  113369. hx=info->postlist[current];
  113370. render_line0(lx,hx,ly,hy,ilogmask);
  113371. lx=hx;
  113372. ly=hy;
  113373. }
  113374. }
  113375. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113376. seq++;
  113377. return(1);
  113378. }
  113379. }else{
  113380. oggpack_write(opb,0,1);
  113381. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113382. seq++;
  113383. return(0);
  113384. }
  113385. }
  113386. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113387. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113388. vorbis_info_floor1 *info=look->vi;
  113389. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113390. int i,j,k;
  113391. codebook *books=ci->fullbooks;
  113392. /* unpack wrapped/predicted values from stream */
  113393. if(oggpack_read(&vb->opb,1)==1){
  113394. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113395. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113396. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113397. /* partition by partition */
  113398. for(i=0,j=2;i<info->partitions;i++){
  113399. int classx=info->partitionclass[i];
  113400. int cdim=info->class_dim[classx];
  113401. int csubbits=info->class_subs[classx];
  113402. int csub=1<<csubbits;
  113403. int cval=0;
  113404. /* decode the partition's first stage cascade value */
  113405. if(csubbits){
  113406. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113407. if(cval==-1)goto eop;
  113408. }
  113409. for(k=0;k<cdim;k++){
  113410. int book=info->class_subbook[classx][cval&(csub-1)];
  113411. cval>>=csubbits;
  113412. if(book>=0){
  113413. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113414. goto eop;
  113415. }else{
  113416. fit_value[j+k]=0;
  113417. }
  113418. }
  113419. j+=cdim;
  113420. }
  113421. /* unwrap positive values and reconsitute via linear interpolation */
  113422. for(i=2;i<look->posts;i++){
  113423. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113424. info->postlist[look->hineighbor[i-2]],
  113425. fit_value[look->loneighbor[i-2]],
  113426. fit_value[look->hineighbor[i-2]],
  113427. info->postlist[i]);
  113428. int hiroom=look->quant_q-predicted;
  113429. int loroom=predicted;
  113430. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113431. int val=fit_value[i];
  113432. if(val){
  113433. if(val>=room){
  113434. if(hiroom>loroom){
  113435. val = val-loroom;
  113436. }else{
  113437. val = -1-(val-hiroom);
  113438. }
  113439. }else{
  113440. if(val&1){
  113441. val= -((val+1)>>1);
  113442. }else{
  113443. val>>=1;
  113444. }
  113445. }
  113446. fit_value[i]=val+predicted;
  113447. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113448. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113449. }else{
  113450. fit_value[i]=predicted|0x8000;
  113451. }
  113452. }
  113453. return(fit_value);
  113454. }
  113455. eop:
  113456. return(NULL);
  113457. }
  113458. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113459. float *out){
  113460. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113461. vorbis_info_floor1 *info=look->vi;
  113462. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113463. int n=ci->blocksizes[vb->W]/2;
  113464. int j;
  113465. if(memo){
  113466. /* render the lines */
  113467. int *fit_value=(int *)memo;
  113468. int hx=0;
  113469. int lx=0;
  113470. int ly=fit_value[0]*info->mult;
  113471. for(j=1;j<look->posts;j++){
  113472. int current=look->forward_index[j];
  113473. int hy=fit_value[current]&0x7fff;
  113474. if(hy==fit_value[current]){
  113475. hy*=info->mult;
  113476. hx=info->postlist[current];
  113477. render_line(lx,hx,ly,hy,out);
  113478. lx=hx;
  113479. ly=hy;
  113480. }
  113481. }
  113482. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113483. return(1);
  113484. }
  113485. memset(out,0,sizeof(*out)*n);
  113486. return(0);
  113487. }
  113488. /* export hooks */
  113489. vorbis_func_floor floor1_exportbundle={
  113490. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113491. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113492. };
  113493. #endif
  113494. /*** End of inlined file: floor1.c ***/
  113495. /*** Start of inlined file: info.c ***/
  113496. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113497. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113498. // tasks..
  113499. #if JUCE_MSVC
  113500. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113501. #endif
  113502. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113503. #if JUCE_USE_OGGVORBIS
  113504. /* general handling of the header and the vorbis_info structure (and
  113505. substructures) */
  113506. #include <stdlib.h>
  113507. #include <string.h>
  113508. #include <ctype.h>
  113509. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113510. while(bytes--){
  113511. oggpack_write(o,*s++,8);
  113512. }
  113513. }
  113514. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113515. while(bytes--){
  113516. *buf++=oggpack_read(o,8);
  113517. }
  113518. }
  113519. void vorbis_comment_init(vorbis_comment *vc){
  113520. memset(vc,0,sizeof(*vc));
  113521. }
  113522. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113523. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113524. (vc->comments+2)*sizeof(*vc->user_comments));
  113525. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113526. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113527. vc->comment_lengths[vc->comments]=strlen(comment);
  113528. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113529. strcpy(vc->user_comments[vc->comments], comment);
  113530. vc->comments++;
  113531. vc->user_comments[vc->comments]=NULL;
  113532. }
  113533. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113534. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113535. strcpy(comment, tag);
  113536. strcat(comment, "=");
  113537. strcat(comment, contents);
  113538. vorbis_comment_add(vc, comment);
  113539. }
  113540. /* This is more or less the same as strncasecmp - but that doesn't exist
  113541. * everywhere, and this is a fairly trivial function, so we include it */
  113542. static int tagcompare(const char *s1, const char *s2, int n){
  113543. int c=0;
  113544. while(c < n){
  113545. if(toupper(s1[c]) != toupper(s2[c]))
  113546. return !0;
  113547. c++;
  113548. }
  113549. return 0;
  113550. }
  113551. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113552. long i;
  113553. int found = 0;
  113554. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113555. char *fulltag = (char*)alloca(taglen+ 1);
  113556. strcpy(fulltag, tag);
  113557. strcat(fulltag, "=");
  113558. for(i=0;i<vc->comments;i++){
  113559. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113560. if(count == found)
  113561. /* We return a pointer to the data, not a copy */
  113562. return vc->user_comments[i] + taglen;
  113563. else
  113564. found++;
  113565. }
  113566. }
  113567. return NULL; /* didn't find anything */
  113568. }
  113569. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113570. int i,count=0;
  113571. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113572. char *fulltag = (char*)alloca(taglen+1);
  113573. strcpy(fulltag,tag);
  113574. strcat(fulltag, "=");
  113575. for(i=0;i<vc->comments;i++){
  113576. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113577. count++;
  113578. }
  113579. return count;
  113580. }
  113581. void vorbis_comment_clear(vorbis_comment *vc){
  113582. if(vc){
  113583. long i;
  113584. for(i=0;i<vc->comments;i++)
  113585. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113586. if(vc->user_comments)_ogg_free(vc->user_comments);
  113587. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113588. if(vc->vendor)_ogg_free(vc->vendor);
  113589. }
  113590. memset(vc,0,sizeof(*vc));
  113591. }
  113592. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113593. They may be equal, but short will never ge greater than long */
  113594. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113595. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113596. return ci ? ci->blocksizes[zo] : -1;
  113597. }
  113598. /* used by synthesis, which has a full, alloced vi */
  113599. void vorbis_info_init(vorbis_info *vi){
  113600. memset(vi,0,sizeof(*vi));
  113601. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113602. }
  113603. void vorbis_info_clear(vorbis_info *vi){
  113604. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113605. int i;
  113606. if(ci){
  113607. for(i=0;i<ci->modes;i++)
  113608. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113609. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113610. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113611. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113612. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113613. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113614. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113615. for(i=0;i<ci->books;i++){
  113616. if(ci->book_param[i]){
  113617. /* knows if the book was not alloced */
  113618. vorbis_staticbook_destroy(ci->book_param[i]);
  113619. }
  113620. if(ci->fullbooks)
  113621. vorbis_book_clear(ci->fullbooks+i);
  113622. }
  113623. if(ci->fullbooks)
  113624. _ogg_free(ci->fullbooks);
  113625. for(i=0;i<ci->psys;i++)
  113626. _vi_psy_free(ci->psy_param[i]);
  113627. _ogg_free(ci);
  113628. }
  113629. memset(vi,0,sizeof(*vi));
  113630. }
  113631. /* Header packing/unpacking ********************************************/
  113632. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113633. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113634. if(!ci)return(OV_EFAULT);
  113635. vi->version=oggpack_read(opb,32);
  113636. if(vi->version!=0)return(OV_EVERSION);
  113637. vi->channels=oggpack_read(opb,8);
  113638. vi->rate=oggpack_read(opb,32);
  113639. vi->bitrate_upper=oggpack_read(opb,32);
  113640. vi->bitrate_nominal=oggpack_read(opb,32);
  113641. vi->bitrate_lower=oggpack_read(opb,32);
  113642. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113643. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113644. if(vi->rate<1)goto err_out;
  113645. if(vi->channels<1)goto err_out;
  113646. if(ci->blocksizes[0]<8)goto err_out;
  113647. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113648. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113649. return(0);
  113650. err_out:
  113651. vorbis_info_clear(vi);
  113652. return(OV_EBADHEADER);
  113653. }
  113654. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113655. int i;
  113656. int vendorlen=oggpack_read(opb,32);
  113657. if(vendorlen<0)goto err_out;
  113658. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113659. _v_readstring(opb,vc->vendor,vendorlen);
  113660. vc->comments=oggpack_read(opb,32);
  113661. if(vc->comments<0)goto err_out;
  113662. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113663. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113664. for(i=0;i<vc->comments;i++){
  113665. int len=oggpack_read(opb,32);
  113666. if(len<0)goto err_out;
  113667. vc->comment_lengths[i]=len;
  113668. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113669. _v_readstring(opb,vc->user_comments[i],len);
  113670. }
  113671. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113672. return(0);
  113673. err_out:
  113674. vorbis_comment_clear(vc);
  113675. return(OV_EBADHEADER);
  113676. }
  113677. /* all of the real encoding details are here. The modes, books,
  113678. everything */
  113679. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113680. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113681. int i;
  113682. if(!ci)return(OV_EFAULT);
  113683. /* codebooks */
  113684. ci->books=oggpack_read(opb,8)+1;
  113685. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113686. for(i=0;i<ci->books;i++){
  113687. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113688. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113689. }
  113690. /* time backend settings; hooks are unused */
  113691. {
  113692. int times=oggpack_read(opb,6)+1;
  113693. for(i=0;i<times;i++){
  113694. int test=oggpack_read(opb,16);
  113695. if(test<0 || test>=VI_TIMEB)goto err_out;
  113696. }
  113697. }
  113698. /* floor backend settings */
  113699. ci->floors=oggpack_read(opb,6)+1;
  113700. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113701. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113702. for(i=0;i<ci->floors;i++){
  113703. ci->floor_type[i]=oggpack_read(opb,16);
  113704. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113705. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113706. if(!ci->floor_param[i])goto err_out;
  113707. }
  113708. /* residue backend settings */
  113709. ci->residues=oggpack_read(opb,6)+1;
  113710. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113711. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113712. for(i=0;i<ci->residues;i++){
  113713. ci->residue_type[i]=oggpack_read(opb,16);
  113714. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113715. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113716. if(!ci->residue_param[i])goto err_out;
  113717. }
  113718. /* map backend settings */
  113719. ci->maps=oggpack_read(opb,6)+1;
  113720. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113721. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113722. for(i=0;i<ci->maps;i++){
  113723. ci->map_type[i]=oggpack_read(opb,16);
  113724. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113725. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113726. if(!ci->map_param[i])goto err_out;
  113727. }
  113728. /* mode settings */
  113729. ci->modes=oggpack_read(opb,6)+1;
  113730. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113731. for(i=0;i<ci->modes;i++){
  113732. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113733. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113734. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113735. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113736. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113737. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113738. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113739. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113740. }
  113741. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113742. return(0);
  113743. err_out:
  113744. vorbis_info_clear(vi);
  113745. return(OV_EBADHEADER);
  113746. }
  113747. /* The Vorbis header is in three packets; the initial small packet in
  113748. the first page that identifies basic parameters, a second packet
  113749. with bitstream comments and a third packet that holds the
  113750. codebook. */
  113751. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113752. oggpack_buffer opb;
  113753. if(op){
  113754. oggpack_readinit(&opb,op->packet,op->bytes);
  113755. /* Which of the three types of header is this? */
  113756. /* Also verify header-ness, vorbis */
  113757. {
  113758. char buffer[6];
  113759. int packtype=oggpack_read(&opb,8);
  113760. memset(buffer,0,6);
  113761. _v_readstring(&opb,buffer,6);
  113762. if(memcmp(buffer,"vorbis",6)){
  113763. /* not a vorbis header */
  113764. return(OV_ENOTVORBIS);
  113765. }
  113766. switch(packtype){
  113767. case 0x01: /* least significant *bit* is read first */
  113768. if(!op->b_o_s){
  113769. /* Not the initial packet */
  113770. return(OV_EBADHEADER);
  113771. }
  113772. if(vi->rate!=0){
  113773. /* previously initialized info header */
  113774. return(OV_EBADHEADER);
  113775. }
  113776. return(_vorbis_unpack_info(vi,&opb));
  113777. case 0x03: /* least significant *bit* is read first */
  113778. if(vi->rate==0){
  113779. /* um... we didn't get the initial header */
  113780. return(OV_EBADHEADER);
  113781. }
  113782. return(_vorbis_unpack_comment(vc,&opb));
  113783. case 0x05: /* least significant *bit* is read first */
  113784. if(vi->rate==0 || vc->vendor==NULL){
  113785. /* um... we didn;t get the initial header or comments yet */
  113786. return(OV_EBADHEADER);
  113787. }
  113788. return(_vorbis_unpack_books(vi,&opb));
  113789. default:
  113790. /* Not a valid vorbis header type */
  113791. return(OV_EBADHEADER);
  113792. break;
  113793. }
  113794. }
  113795. }
  113796. return(OV_EBADHEADER);
  113797. }
  113798. /* pack side **********************************************************/
  113799. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113800. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113801. if(!ci)return(OV_EFAULT);
  113802. /* preamble */
  113803. oggpack_write(opb,0x01,8);
  113804. _v_writestring(opb,"vorbis", 6);
  113805. /* basic information about the stream */
  113806. oggpack_write(opb,0x00,32);
  113807. oggpack_write(opb,vi->channels,8);
  113808. oggpack_write(opb,vi->rate,32);
  113809. oggpack_write(opb,vi->bitrate_upper,32);
  113810. oggpack_write(opb,vi->bitrate_nominal,32);
  113811. oggpack_write(opb,vi->bitrate_lower,32);
  113812. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113813. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113814. oggpack_write(opb,1,1);
  113815. return(0);
  113816. }
  113817. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113818. char temp[]="Xiph.Org libVorbis I 20050304";
  113819. int bytes = strlen(temp);
  113820. /* preamble */
  113821. oggpack_write(opb,0x03,8);
  113822. _v_writestring(opb,"vorbis", 6);
  113823. /* vendor */
  113824. oggpack_write(opb,bytes,32);
  113825. _v_writestring(opb,temp, bytes);
  113826. /* comments */
  113827. oggpack_write(opb,vc->comments,32);
  113828. if(vc->comments){
  113829. int i;
  113830. for(i=0;i<vc->comments;i++){
  113831. if(vc->user_comments[i]){
  113832. oggpack_write(opb,vc->comment_lengths[i],32);
  113833. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113834. }else{
  113835. oggpack_write(opb,0,32);
  113836. }
  113837. }
  113838. }
  113839. oggpack_write(opb,1,1);
  113840. return(0);
  113841. }
  113842. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113843. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113844. int i;
  113845. if(!ci)return(OV_EFAULT);
  113846. oggpack_write(opb,0x05,8);
  113847. _v_writestring(opb,"vorbis", 6);
  113848. /* books */
  113849. oggpack_write(opb,ci->books-1,8);
  113850. for(i=0;i<ci->books;i++)
  113851. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113852. /* times; hook placeholders */
  113853. oggpack_write(opb,0,6);
  113854. oggpack_write(opb,0,16);
  113855. /* floors */
  113856. oggpack_write(opb,ci->floors-1,6);
  113857. for(i=0;i<ci->floors;i++){
  113858. oggpack_write(opb,ci->floor_type[i],16);
  113859. if(_floor_P[ci->floor_type[i]]->pack)
  113860. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113861. else
  113862. goto err_out;
  113863. }
  113864. /* residues */
  113865. oggpack_write(opb,ci->residues-1,6);
  113866. for(i=0;i<ci->residues;i++){
  113867. oggpack_write(opb,ci->residue_type[i],16);
  113868. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113869. }
  113870. /* maps */
  113871. oggpack_write(opb,ci->maps-1,6);
  113872. for(i=0;i<ci->maps;i++){
  113873. oggpack_write(opb,ci->map_type[i],16);
  113874. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113875. }
  113876. /* modes */
  113877. oggpack_write(opb,ci->modes-1,6);
  113878. for(i=0;i<ci->modes;i++){
  113879. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113880. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113881. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113882. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113883. }
  113884. oggpack_write(opb,1,1);
  113885. return(0);
  113886. err_out:
  113887. return(-1);
  113888. }
  113889. int vorbis_commentheader_out(vorbis_comment *vc,
  113890. ogg_packet *op){
  113891. oggpack_buffer opb;
  113892. oggpack_writeinit(&opb);
  113893. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113894. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113895. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113896. op->bytes=oggpack_bytes(&opb);
  113897. op->b_o_s=0;
  113898. op->e_o_s=0;
  113899. op->granulepos=0;
  113900. op->packetno=1;
  113901. return 0;
  113902. }
  113903. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113904. vorbis_comment *vc,
  113905. ogg_packet *op,
  113906. ogg_packet *op_comm,
  113907. ogg_packet *op_code){
  113908. int ret=OV_EIMPL;
  113909. vorbis_info *vi=v->vi;
  113910. oggpack_buffer opb;
  113911. private_state *b=(private_state*)v->backend_state;
  113912. if(!b){
  113913. ret=OV_EFAULT;
  113914. goto err_out;
  113915. }
  113916. /* first header packet **********************************************/
  113917. oggpack_writeinit(&opb);
  113918. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113919. /* build the packet */
  113920. if(b->header)_ogg_free(b->header);
  113921. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113922. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113923. op->packet=b->header;
  113924. op->bytes=oggpack_bytes(&opb);
  113925. op->b_o_s=1;
  113926. op->e_o_s=0;
  113927. op->granulepos=0;
  113928. op->packetno=0;
  113929. /* second header packet (comments) **********************************/
  113930. oggpack_reset(&opb);
  113931. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113932. if(b->header1)_ogg_free(b->header1);
  113933. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113934. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113935. op_comm->packet=b->header1;
  113936. op_comm->bytes=oggpack_bytes(&opb);
  113937. op_comm->b_o_s=0;
  113938. op_comm->e_o_s=0;
  113939. op_comm->granulepos=0;
  113940. op_comm->packetno=1;
  113941. /* third header packet (modes/codebooks) ****************************/
  113942. oggpack_reset(&opb);
  113943. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113944. if(b->header2)_ogg_free(b->header2);
  113945. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113946. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113947. op_code->packet=b->header2;
  113948. op_code->bytes=oggpack_bytes(&opb);
  113949. op_code->b_o_s=0;
  113950. op_code->e_o_s=0;
  113951. op_code->granulepos=0;
  113952. op_code->packetno=2;
  113953. oggpack_writeclear(&opb);
  113954. return(0);
  113955. err_out:
  113956. oggpack_writeclear(&opb);
  113957. memset(op,0,sizeof(*op));
  113958. memset(op_comm,0,sizeof(*op_comm));
  113959. memset(op_code,0,sizeof(*op_code));
  113960. if(b->header)_ogg_free(b->header);
  113961. if(b->header1)_ogg_free(b->header1);
  113962. if(b->header2)_ogg_free(b->header2);
  113963. b->header=NULL;
  113964. b->header1=NULL;
  113965. b->header2=NULL;
  113966. return(ret);
  113967. }
  113968. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113969. if(granulepos>=0)
  113970. return((double)granulepos/v->vi->rate);
  113971. return(-1);
  113972. }
  113973. #endif
  113974. /*** End of inlined file: info.c ***/
  113975. /*** Start of inlined file: lpc.c ***/
  113976. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113977. are derived from code written by Jutta Degener and Carsten Bormann;
  113978. thus we include their copyright below. The entirety of this file
  113979. is freely redistributable on the condition that both of these
  113980. copyright notices are preserved without modification. */
  113981. /* Preserved Copyright: *********************************************/
  113982. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113983. Technische Universita"t Berlin
  113984. Any use of this software is permitted provided that this notice is not
  113985. removed and that neither the authors nor the Technische Universita"t
  113986. Berlin are deemed to have made any representations as to the
  113987. suitability of this software for any purpose nor are held responsible
  113988. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113989. THIS SOFTWARE.
  113990. As a matter of courtesy, the authors request to be informed about uses
  113991. this software has found, about bugs in this software, and about any
  113992. improvements that may be of general interest.
  113993. Berlin, 28.11.1994
  113994. Jutta Degener
  113995. Carsten Bormann
  113996. *********************************************************************/
  113997. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113998. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113999. // tasks..
  114000. #if JUCE_MSVC
  114001. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114002. #endif
  114003. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114004. #if JUCE_USE_OGGVORBIS
  114005. #include <stdlib.h>
  114006. #include <string.h>
  114007. #include <math.h>
  114008. /* Autocorrelation LPC coeff generation algorithm invented by
  114009. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114010. /* Input : n elements of time doamin data
  114011. Output: m lpc coefficients, excitation energy */
  114012. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114013. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114014. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114015. double error;
  114016. int i,j;
  114017. /* autocorrelation, p+1 lag coefficients */
  114018. j=m+1;
  114019. while(j--){
  114020. double d=0; /* double needed for accumulator depth */
  114021. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114022. aut[j]=d;
  114023. }
  114024. /* Generate lpc coefficients from autocorr values */
  114025. error=aut[0];
  114026. for(i=0;i<m;i++){
  114027. double r= -aut[i+1];
  114028. if(error==0){
  114029. memset(lpci,0,m*sizeof(*lpci));
  114030. return 0;
  114031. }
  114032. /* Sum up this iteration's reflection coefficient; note that in
  114033. Vorbis we don't save it. If anyone wants to recycle this code
  114034. and needs reflection coefficients, save the results of 'r' from
  114035. each iteration. */
  114036. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114037. r/=error;
  114038. /* Update LPC coefficients and total error */
  114039. lpc[i]=r;
  114040. for(j=0;j<i/2;j++){
  114041. double tmp=lpc[j];
  114042. lpc[j]+=r*lpc[i-1-j];
  114043. lpc[i-1-j]+=r*tmp;
  114044. }
  114045. if(i%2)lpc[j]+=lpc[j]*r;
  114046. error*=1.f-r*r;
  114047. }
  114048. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114049. /* we need the error value to know how big an impulse to hit the
  114050. filter with later */
  114051. return error;
  114052. }
  114053. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114054. float *data,long n){
  114055. /* in: coeff[0...m-1] LPC coefficients
  114056. prime[0...m-1] initial values (allocated size of n+m-1)
  114057. out: data[0...n-1] data samples */
  114058. long i,j,o,p;
  114059. float y;
  114060. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114061. if(!prime)
  114062. for(i=0;i<m;i++)
  114063. work[i]=0.f;
  114064. else
  114065. for(i=0;i<m;i++)
  114066. work[i]=prime[i];
  114067. for(i=0;i<n;i++){
  114068. y=0;
  114069. o=i;
  114070. p=m;
  114071. for(j=0;j<m;j++)
  114072. y-=work[o++]*coeff[--p];
  114073. data[i]=work[o]=y;
  114074. }
  114075. }
  114076. #endif
  114077. /*** End of inlined file: lpc.c ***/
  114078. /*** Start of inlined file: lsp.c ***/
  114079. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114080. an iterative root polisher (CACM algorithm 283). It *is* possible
  114081. to confuse this algorithm into not converging; that should only
  114082. happen with absurdly closely spaced roots (very sharp peaks in the
  114083. LPC f response) which in turn should be impossible in our use of
  114084. the code. If this *does* happen anyway, it's a bug in the floor
  114085. finder; find the cause of the confusion (probably a single bin
  114086. spike or accidental near-float-limit resolution problems) and
  114087. correct it. */
  114088. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114089. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114090. // tasks..
  114091. #if JUCE_MSVC
  114092. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114093. #endif
  114094. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114095. #if JUCE_USE_OGGVORBIS
  114096. #include <math.h>
  114097. #include <string.h>
  114098. #include <stdlib.h>
  114099. /*** Start of inlined file: lookup.h ***/
  114100. #ifndef _V_LOOKUP_H_
  114101. #ifdef FLOAT_LOOKUP
  114102. extern float vorbis_coslook(float a);
  114103. extern float vorbis_invsqlook(float a);
  114104. extern float vorbis_invsq2explook(int a);
  114105. extern float vorbis_fromdBlook(float a);
  114106. #endif
  114107. #ifdef INT_LOOKUP
  114108. extern long vorbis_invsqlook_i(long a,long e);
  114109. extern long vorbis_coslook_i(long a);
  114110. extern float vorbis_fromdBlook_i(long a);
  114111. #endif
  114112. #endif
  114113. /*** End of inlined file: lookup.h ***/
  114114. /* three possible LSP to f curve functions; the exact computation
  114115. (float), a lookup based float implementation, and an integer
  114116. implementation. The float lookup is likely the optimal choice on
  114117. any machine with an FPU. The integer implementation is *not* fixed
  114118. point (due to the need for a large dynamic range and thus a
  114119. seperately tracked exponent) and thus much more complex than the
  114120. relatively simple float implementations. It's mostly for future
  114121. work on a fully fixed point implementation for processors like the
  114122. ARM family. */
  114123. /* undefine both for the 'old' but more precise implementation */
  114124. #define FLOAT_LOOKUP
  114125. #undef INT_LOOKUP
  114126. #ifdef FLOAT_LOOKUP
  114127. /*** Start of inlined file: lookup.c ***/
  114128. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114129. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114130. // tasks..
  114131. #if JUCE_MSVC
  114132. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114133. #endif
  114134. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114135. #if JUCE_USE_OGGVORBIS
  114136. #include <math.h>
  114137. /*** Start of inlined file: lookup.h ***/
  114138. #ifndef _V_LOOKUP_H_
  114139. #ifdef FLOAT_LOOKUP
  114140. extern float vorbis_coslook(float a);
  114141. extern float vorbis_invsqlook(float a);
  114142. extern float vorbis_invsq2explook(int a);
  114143. extern float vorbis_fromdBlook(float a);
  114144. #endif
  114145. #ifdef INT_LOOKUP
  114146. extern long vorbis_invsqlook_i(long a,long e);
  114147. extern long vorbis_coslook_i(long a);
  114148. extern float vorbis_fromdBlook_i(long a);
  114149. #endif
  114150. #endif
  114151. /*** End of inlined file: lookup.h ***/
  114152. /*** Start of inlined file: lookup_data.h ***/
  114153. #ifndef _V_LOOKUP_DATA_H_
  114154. #ifdef FLOAT_LOOKUP
  114155. #define COS_LOOKUP_SZ 128
  114156. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114157. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114158. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114159. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114160. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114161. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114162. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114163. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114164. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114165. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114166. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114167. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114168. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114169. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114170. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114171. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114172. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114173. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114174. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114175. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114176. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114177. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114178. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114179. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114180. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114181. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114182. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114183. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114184. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114185. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114186. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114187. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114188. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114189. -1.0000000000000f,
  114190. };
  114191. #define INVSQ_LOOKUP_SZ 32
  114192. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114193. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114194. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114195. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114196. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114197. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114198. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114199. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114200. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114201. 1.000000000000f,
  114202. };
  114203. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114204. #define INVSQ2EXP_LOOKUP_MAX 32
  114205. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114206. INVSQ2EXP_LOOKUP_MIN+1]={
  114207. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114208. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114209. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114210. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114211. 256.f, 181.019336f, 128.f, 90.50966799f,
  114212. 64.f, 45.254834f, 32.f, 22.627417f,
  114213. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114214. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114215. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114216. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114217. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114218. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114219. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114220. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114221. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114222. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114223. 1.525878906e-05f,
  114224. };
  114225. #endif
  114226. #define FROMdB_LOOKUP_SZ 35
  114227. #define FROMdB2_LOOKUP_SZ 32
  114228. #define FROMdB_SHIFT 5
  114229. #define FROMdB2_SHIFT 3
  114230. #define FROMdB2_MASK 31
  114231. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114232. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114233. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114234. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114235. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114236. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114237. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114238. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114239. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114240. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114241. };
  114242. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114243. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114244. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114245. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114246. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114247. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114248. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114249. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114250. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114251. };
  114252. #ifdef INT_LOOKUP
  114253. #define INVSQ_LOOKUP_I_SHIFT 10
  114254. #define INVSQ_LOOKUP_I_MASK 1023
  114255. static long INVSQ_LOOKUP_I[64+1]={
  114256. 92682l, 91966l, 91267l, 90583l,
  114257. 89915l, 89261l, 88621l, 87995l,
  114258. 87381l, 86781l, 86192l, 85616l,
  114259. 85051l, 84497l, 83953l, 83420l,
  114260. 82897l, 82384l, 81880l, 81385l,
  114261. 80899l, 80422l, 79953l, 79492l,
  114262. 79039l, 78594l, 78156l, 77726l,
  114263. 77302l, 76885l, 76475l, 76072l,
  114264. 75674l, 75283l, 74898l, 74519l,
  114265. 74146l, 73778l, 73415l, 73058l,
  114266. 72706l, 72359l, 72016l, 71679l,
  114267. 71347l, 71019l, 70695l, 70376l,
  114268. 70061l, 69750l, 69444l, 69141l,
  114269. 68842l, 68548l, 68256l, 67969l,
  114270. 67685l, 67405l, 67128l, 66855l,
  114271. 66585l, 66318l, 66054l, 65794l,
  114272. 65536l,
  114273. };
  114274. #define COS_LOOKUP_I_SHIFT 9
  114275. #define COS_LOOKUP_I_MASK 511
  114276. #define COS_LOOKUP_I_SZ 128
  114277. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114278. 16384l, 16379l, 16364l, 16340l,
  114279. 16305l, 16261l, 16207l, 16143l,
  114280. 16069l, 15986l, 15893l, 15791l,
  114281. 15679l, 15557l, 15426l, 15286l,
  114282. 15137l, 14978l, 14811l, 14635l,
  114283. 14449l, 14256l, 14053l, 13842l,
  114284. 13623l, 13395l, 13160l, 12916l,
  114285. 12665l, 12406l, 12140l, 11866l,
  114286. 11585l, 11297l, 11003l, 10702l,
  114287. 10394l, 10080l, 9760l, 9434l,
  114288. 9102l, 8765l, 8423l, 8076l,
  114289. 7723l, 7366l, 7005l, 6639l,
  114290. 6270l, 5897l, 5520l, 5139l,
  114291. 4756l, 4370l, 3981l, 3590l,
  114292. 3196l, 2801l, 2404l, 2006l,
  114293. 1606l, 1205l, 804l, 402l,
  114294. 0l, -401l, -803l, -1204l,
  114295. -1605l, -2005l, -2403l, -2800l,
  114296. -3195l, -3589l, -3980l, -4369l,
  114297. -4755l, -5138l, -5519l, -5896l,
  114298. -6269l, -6638l, -7004l, -7365l,
  114299. -7722l, -8075l, -8422l, -8764l,
  114300. -9101l, -9433l, -9759l, -10079l,
  114301. -10393l, -10701l, -11002l, -11296l,
  114302. -11584l, -11865l, -12139l, -12405l,
  114303. -12664l, -12915l, -13159l, -13394l,
  114304. -13622l, -13841l, -14052l, -14255l,
  114305. -14448l, -14634l, -14810l, -14977l,
  114306. -15136l, -15285l, -15425l, -15556l,
  114307. -15678l, -15790l, -15892l, -15985l,
  114308. -16068l, -16142l, -16206l, -16260l,
  114309. -16304l, -16339l, -16363l, -16378l,
  114310. -16383l,
  114311. };
  114312. #endif
  114313. #endif
  114314. /*** End of inlined file: lookup_data.h ***/
  114315. #ifdef FLOAT_LOOKUP
  114316. /* interpolated lookup based cos function, domain 0 to PI only */
  114317. float vorbis_coslook(float a){
  114318. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114319. int i=vorbis_ftoi(d-.5);
  114320. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114321. }
  114322. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114323. float vorbis_invsqlook(float a){
  114324. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114325. int i=vorbis_ftoi(d-.5f);
  114326. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114327. }
  114328. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114329. float vorbis_invsq2explook(int a){
  114330. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114331. }
  114332. #include <stdio.h>
  114333. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114334. float vorbis_fromdBlook(float a){
  114335. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114336. return (i<0)?1.f:
  114337. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114338. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114339. }
  114340. #endif
  114341. #ifdef INT_LOOKUP
  114342. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114343. 16.16 format
  114344. returns in m.8 format */
  114345. long vorbis_invsqlook_i(long a,long e){
  114346. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114347. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114348. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114349. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114350. d)>>16); /* result 1.16 */
  114351. e+=32;
  114352. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114353. e=(e>>1)-8;
  114354. return(val>>e);
  114355. }
  114356. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114357. /* a is in n.12 format */
  114358. float vorbis_fromdBlook_i(long a){
  114359. int i=(-a)>>(12-FROMdB2_SHIFT);
  114360. return (i<0)?1.f:
  114361. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114362. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114363. }
  114364. /* interpolated lookup based cos function, domain 0 to PI only */
  114365. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114366. long vorbis_coslook_i(long a){
  114367. int i=a>>COS_LOOKUP_I_SHIFT;
  114368. int d=a&COS_LOOKUP_I_MASK;
  114369. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114370. COS_LOOKUP_I_SHIFT);
  114371. }
  114372. #endif
  114373. #endif
  114374. /*** End of inlined file: lookup.c ***/
  114375. /* catch this in the build system; we #include for
  114376. compilers (like gcc) that can't inline across
  114377. modules */
  114378. /* side effect: changes *lsp to cosines of lsp */
  114379. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114380. float amp,float ampoffset){
  114381. int i;
  114382. float wdel=M_PI/ln;
  114383. vorbis_fpu_control fpu;
  114384. (void) fpu; // to avoid an unused variable warning
  114385. vorbis_fpu_setround(&fpu);
  114386. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114387. i=0;
  114388. while(i<n){
  114389. int k=map[i];
  114390. int qexp;
  114391. float p=.7071067812f;
  114392. float q=.7071067812f;
  114393. float w=vorbis_coslook(wdel*k);
  114394. float *ftmp=lsp;
  114395. int c=m>>1;
  114396. do{
  114397. q*=ftmp[0]-w;
  114398. p*=ftmp[1]-w;
  114399. ftmp+=2;
  114400. }while(--c);
  114401. if(m&1){
  114402. /* odd order filter; slightly assymetric */
  114403. /* the last coefficient */
  114404. q*=ftmp[0]-w;
  114405. q*=q;
  114406. p*=p*(1.f-w*w);
  114407. }else{
  114408. /* even order filter; still symmetric */
  114409. q*=q*(1.f+w);
  114410. p*=p*(1.f-w);
  114411. }
  114412. q=frexp(p+q,&qexp);
  114413. q=vorbis_fromdBlook(amp*
  114414. vorbis_invsqlook(q)*
  114415. vorbis_invsq2explook(qexp+m)-
  114416. ampoffset);
  114417. do{
  114418. curve[i++]*=q;
  114419. }while(map[i]==k);
  114420. }
  114421. vorbis_fpu_restore(fpu);
  114422. }
  114423. #else
  114424. #ifdef INT_LOOKUP
  114425. /*** Start of inlined file: lookup.c ***/
  114426. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114427. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114428. // tasks..
  114429. #if JUCE_MSVC
  114430. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114431. #endif
  114432. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114433. #if JUCE_USE_OGGVORBIS
  114434. #include <math.h>
  114435. /*** Start of inlined file: lookup.h ***/
  114436. #ifndef _V_LOOKUP_H_
  114437. #ifdef FLOAT_LOOKUP
  114438. extern float vorbis_coslook(float a);
  114439. extern float vorbis_invsqlook(float a);
  114440. extern float vorbis_invsq2explook(int a);
  114441. extern float vorbis_fromdBlook(float a);
  114442. #endif
  114443. #ifdef INT_LOOKUP
  114444. extern long vorbis_invsqlook_i(long a,long e);
  114445. extern long vorbis_coslook_i(long a);
  114446. extern float vorbis_fromdBlook_i(long a);
  114447. #endif
  114448. #endif
  114449. /*** End of inlined file: lookup.h ***/
  114450. /*** Start of inlined file: lookup_data.h ***/
  114451. #ifndef _V_LOOKUP_DATA_H_
  114452. #ifdef FLOAT_LOOKUP
  114453. #define COS_LOOKUP_SZ 128
  114454. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114455. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114456. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114457. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114458. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114459. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114460. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114461. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114462. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114463. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114464. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114465. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114466. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114467. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114468. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114469. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114470. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114471. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114472. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114473. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114474. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114475. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114476. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114477. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114478. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114479. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114480. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114481. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114482. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114483. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114484. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114485. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114486. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114487. -1.0000000000000f,
  114488. };
  114489. #define INVSQ_LOOKUP_SZ 32
  114490. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114491. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114492. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114493. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114494. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114495. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114496. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114497. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114498. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114499. 1.000000000000f,
  114500. };
  114501. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114502. #define INVSQ2EXP_LOOKUP_MAX 32
  114503. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114504. INVSQ2EXP_LOOKUP_MIN+1]={
  114505. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114506. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114507. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114508. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114509. 256.f, 181.019336f, 128.f, 90.50966799f,
  114510. 64.f, 45.254834f, 32.f, 22.627417f,
  114511. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114512. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114513. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114514. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114515. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114516. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114517. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114518. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114519. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114520. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114521. 1.525878906e-05f,
  114522. };
  114523. #endif
  114524. #define FROMdB_LOOKUP_SZ 35
  114525. #define FROMdB2_LOOKUP_SZ 32
  114526. #define FROMdB_SHIFT 5
  114527. #define FROMdB2_SHIFT 3
  114528. #define FROMdB2_MASK 31
  114529. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114530. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114531. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114532. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114533. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114534. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114535. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114536. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114537. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114538. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114539. };
  114540. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114541. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114542. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114543. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114544. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114545. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114546. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114547. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114548. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114549. };
  114550. #ifdef INT_LOOKUP
  114551. #define INVSQ_LOOKUP_I_SHIFT 10
  114552. #define INVSQ_LOOKUP_I_MASK 1023
  114553. static long INVSQ_LOOKUP_I[64+1]={
  114554. 92682l, 91966l, 91267l, 90583l,
  114555. 89915l, 89261l, 88621l, 87995l,
  114556. 87381l, 86781l, 86192l, 85616l,
  114557. 85051l, 84497l, 83953l, 83420l,
  114558. 82897l, 82384l, 81880l, 81385l,
  114559. 80899l, 80422l, 79953l, 79492l,
  114560. 79039l, 78594l, 78156l, 77726l,
  114561. 77302l, 76885l, 76475l, 76072l,
  114562. 75674l, 75283l, 74898l, 74519l,
  114563. 74146l, 73778l, 73415l, 73058l,
  114564. 72706l, 72359l, 72016l, 71679l,
  114565. 71347l, 71019l, 70695l, 70376l,
  114566. 70061l, 69750l, 69444l, 69141l,
  114567. 68842l, 68548l, 68256l, 67969l,
  114568. 67685l, 67405l, 67128l, 66855l,
  114569. 66585l, 66318l, 66054l, 65794l,
  114570. 65536l,
  114571. };
  114572. #define COS_LOOKUP_I_SHIFT 9
  114573. #define COS_LOOKUP_I_MASK 511
  114574. #define COS_LOOKUP_I_SZ 128
  114575. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114576. 16384l, 16379l, 16364l, 16340l,
  114577. 16305l, 16261l, 16207l, 16143l,
  114578. 16069l, 15986l, 15893l, 15791l,
  114579. 15679l, 15557l, 15426l, 15286l,
  114580. 15137l, 14978l, 14811l, 14635l,
  114581. 14449l, 14256l, 14053l, 13842l,
  114582. 13623l, 13395l, 13160l, 12916l,
  114583. 12665l, 12406l, 12140l, 11866l,
  114584. 11585l, 11297l, 11003l, 10702l,
  114585. 10394l, 10080l, 9760l, 9434l,
  114586. 9102l, 8765l, 8423l, 8076l,
  114587. 7723l, 7366l, 7005l, 6639l,
  114588. 6270l, 5897l, 5520l, 5139l,
  114589. 4756l, 4370l, 3981l, 3590l,
  114590. 3196l, 2801l, 2404l, 2006l,
  114591. 1606l, 1205l, 804l, 402l,
  114592. 0l, -401l, -803l, -1204l,
  114593. -1605l, -2005l, -2403l, -2800l,
  114594. -3195l, -3589l, -3980l, -4369l,
  114595. -4755l, -5138l, -5519l, -5896l,
  114596. -6269l, -6638l, -7004l, -7365l,
  114597. -7722l, -8075l, -8422l, -8764l,
  114598. -9101l, -9433l, -9759l, -10079l,
  114599. -10393l, -10701l, -11002l, -11296l,
  114600. -11584l, -11865l, -12139l, -12405l,
  114601. -12664l, -12915l, -13159l, -13394l,
  114602. -13622l, -13841l, -14052l, -14255l,
  114603. -14448l, -14634l, -14810l, -14977l,
  114604. -15136l, -15285l, -15425l, -15556l,
  114605. -15678l, -15790l, -15892l, -15985l,
  114606. -16068l, -16142l, -16206l, -16260l,
  114607. -16304l, -16339l, -16363l, -16378l,
  114608. -16383l,
  114609. };
  114610. #endif
  114611. #endif
  114612. /*** End of inlined file: lookup_data.h ***/
  114613. #ifdef FLOAT_LOOKUP
  114614. /* interpolated lookup based cos function, domain 0 to PI only */
  114615. float vorbis_coslook(float a){
  114616. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114617. int i=vorbis_ftoi(d-.5);
  114618. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114619. }
  114620. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114621. float vorbis_invsqlook(float a){
  114622. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114623. int i=vorbis_ftoi(d-.5f);
  114624. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114625. }
  114626. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114627. float vorbis_invsq2explook(int a){
  114628. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114629. }
  114630. #include <stdio.h>
  114631. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114632. float vorbis_fromdBlook(float a){
  114633. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114634. return (i<0)?1.f:
  114635. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114636. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114637. }
  114638. #endif
  114639. #ifdef INT_LOOKUP
  114640. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114641. 16.16 format
  114642. returns in m.8 format */
  114643. long vorbis_invsqlook_i(long a,long e){
  114644. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114645. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114646. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114647. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114648. d)>>16); /* result 1.16 */
  114649. e+=32;
  114650. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114651. e=(e>>1)-8;
  114652. return(val>>e);
  114653. }
  114654. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114655. /* a is in n.12 format */
  114656. float vorbis_fromdBlook_i(long a){
  114657. int i=(-a)>>(12-FROMdB2_SHIFT);
  114658. return (i<0)?1.f:
  114659. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114660. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114661. }
  114662. /* interpolated lookup based cos function, domain 0 to PI only */
  114663. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114664. long vorbis_coslook_i(long a){
  114665. int i=a>>COS_LOOKUP_I_SHIFT;
  114666. int d=a&COS_LOOKUP_I_MASK;
  114667. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114668. COS_LOOKUP_I_SHIFT);
  114669. }
  114670. #endif
  114671. #endif
  114672. /*** End of inlined file: lookup.c ***/
  114673. /* catch this in the build system; we #include for
  114674. compilers (like gcc) that can't inline across
  114675. modules */
  114676. static int MLOOP_1[64]={
  114677. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114678. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114679. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114680. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114681. };
  114682. static int MLOOP_2[64]={
  114683. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114684. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114685. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114686. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114687. };
  114688. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114689. /* side effect: changes *lsp to cosines of lsp */
  114690. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114691. float amp,float ampoffset){
  114692. /* 0 <= m < 256 */
  114693. /* set up for using all int later */
  114694. int i;
  114695. int ampoffseti=rint(ampoffset*4096.f);
  114696. int ampi=rint(amp*16.f);
  114697. long *ilsp=alloca(m*sizeof(*ilsp));
  114698. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114699. i=0;
  114700. while(i<n){
  114701. int j,k=map[i];
  114702. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114703. unsigned long qi=46341;
  114704. int qexp=0,shift;
  114705. long wi=vorbis_coslook_i(k*65536/ln);
  114706. qi*=labs(ilsp[0]-wi);
  114707. pi*=labs(ilsp[1]-wi);
  114708. for(j=3;j<m;j+=2){
  114709. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114710. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114711. shift=MLOOP_3[(pi|qi)>>16];
  114712. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114713. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114714. qexp+=shift;
  114715. }
  114716. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114717. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114718. shift=MLOOP_3[(pi|qi)>>16];
  114719. /* pi,qi normalized collectively, both tracked using qexp */
  114720. if(m&1){
  114721. /* odd order filter; slightly assymetric */
  114722. /* the last coefficient */
  114723. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114724. pi=(pi>>shift)<<14;
  114725. qexp+=shift;
  114726. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114727. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114728. shift=MLOOP_3[(pi|qi)>>16];
  114729. pi>>=shift;
  114730. qi>>=shift;
  114731. qexp+=shift-14*((m+1)>>1);
  114732. pi=((pi*pi)>>16);
  114733. qi=((qi*qi)>>16);
  114734. qexp=qexp*2+m;
  114735. pi*=(1<<14)-((wi*wi)>>14);
  114736. qi+=pi>>14;
  114737. }else{
  114738. /* even order filter; still symmetric */
  114739. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114740. worth tracking step by step */
  114741. pi>>=shift;
  114742. qi>>=shift;
  114743. qexp+=shift-7*m;
  114744. pi=((pi*pi)>>16);
  114745. qi=((qi*qi)>>16);
  114746. qexp=qexp*2+m;
  114747. pi*=(1<<14)-wi;
  114748. qi*=(1<<14)+wi;
  114749. qi=(qi+pi)>>14;
  114750. }
  114751. /* we've let the normalization drift because it wasn't important;
  114752. however, for the lookup, things must be normalized again. We
  114753. need at most one right shift or a number of left shifts */
  114754. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114755. qi>>=1; qexp++;
  114756. }else
  114757. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114758. qi<<=1; qexp--;
  114759. }
  114760. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114761. vorbis_invsqlook_i(qi,qexp)-
  114762. /* m.8, m+n<=8 */
  114763. ampoffseti); /* 8.12[0] */
  114764. curve[i]*=amp;
  114765. while(map[++i]==k)curve[i]*=amp;
  114766. }
  114767. }
  114768. #else
  114769. /* old, nonoptimized but simple version for any poor sap who needs to
  114770. figure out what the hell this code does, or wants the other
  114771. fraction of a dB precision */
  114772. /* side effect: changes *lsp to cosines of lsp */
  114773. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114774. float amp,float ampoffset){
  114775. int i;
  114776. float wdel=M_PI/ln;
  114777. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114778. i=0;
  114779. while(i<n){
  114780. int j,k=map[i];
  114781. float p=.5f;
  114782. float q=.5f;
  114783. float w=2.f*cos(wdel*k);
  114784. for(j=1;j<m;j+=2){
  114785. q *= w-lsp[j-1];
  114786. p *= w-lsp[j];
  114787. }
  114788. if(j==m){
  114789. /* odd order filter; slightly assymetric */
  114790. /* the last coefficient */
  114791. q*=w-lsp[j-1];
  114792. p*=p*(4.f-w*w);
  114793. q*=q;
  114794. }else{
  114795. /* even order filter; still symmetric */
  114796. p*=p*(2.f-w);
  114797. q*=q*(2.f+w);
  114798. }
  114799. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114800. curve[i]*=q;
  114801. while(map[++i]==k)curve[i]*=q;
  114802. }
  114803. }
  114804. #endif
  114805. #endif
  114806. static void cheby(float *g, int ord) {
  114807. int i, j;
  114808. g[0] *= .5f;
  114809. for(i=2; i<= ord; i++) {
  114810. for(j=ord; j >= i; j--) {
  114811. g[j-2] -= g[j];
  114812. g[j] += g[j];
  114813. }
  114814. }
  114815. }
  114816. static int JUCE_CDECL comp(const void *a,const void *b){
  114817. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114818. }
  114819. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114820. but there are root sets for which it gets into limit cycles
  114821. (exacerbated by zero suppression) and fails. We can't afford to
  114822. fail, even if the failure is 1 in 100,000,000, so we now use
  114823. Laguerre and later polish with Newton-Raphson (which can then
  114824. afford to fail) */
  114825. #define EPSILON 10e-7
  114826. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114827. int i,m;
  114828. double lastdelta=0.f;
  114829. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114830. for(i=0;i<=ord;i++)defl[i]=a[i];
  114831. for(m=ord;m>0;m--){
  114832. double newx=0.f,delta;
  114833. /* iterate a root */
  114834. while(1){
  114835. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114836. /* eval the polynomial and its first two derivatives */
  114837. for(i=m;i>0;i--){
  114838. ppp = newx*ppp + pp;
  114839. pp = newx*pp + p;
  114840. p = newx*p + defl[i-1];
  114841. }
  114842. /* Laguerre's method */
  114843. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114844. if(denom<0)
  114845. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114846. if(pp>0){
  114847. denom = pp + sqrt(denom);
  114848. if(denom<EPSILON)denom=EPSILON;
  114849. }else{
  114850. denom = pp - sqrt(denom);
  114851. if(denom>-(EPSILON))denom=-(EPSILON);
  114852. }
  114853. delta = m*p/denom;
  114854. newx -= delta;
  114855. if(delta<0.f)delta*=-1;
  114856. if(fabs(delta/newx)<10e-12)break;
  114857. lastdelta=delta;
  114858. }
  114859. r[m-1]=newx;
  114860. /* forward deflation */
  114861. for(i=m;i>0;i--)
  114862. defl[i-1]+=newx*defl[i];
  114863. defl++;
  114864. }
  114865. return(0);
  114866. }
  114867. /* for spit-and-polish only */
  114868. static int Newton_Raphson(float *a,int ord,float *r){
  114869. int i, k, count=0;
  114870. double error=1.f;
  114871. double *root=(double*)alloca(ord*sizeof(*root));
  114872. for(i=0; i<ord;i++) root[i] = r[i];
  114873. while(error>1e-20){
  114874. error=0;
  114875. for(i=0; i<ord; i++) { /* Update each point. */
  114876. double pp=0.,delta;
  114877. double rooti=root[i];
  114878. double p=a[ord];
  114879. for(k=ord-1; k>= 0; k--) {
  114880. pp= pp* rooti + p;
  114881. p = p * rooti + a[k];
  114882. }
  114883. delta = p/pp;
  114884. root[i] -= delta;
  114885. error+= delta*delta;
  114886. }
  114887. if(count>40)return(-1);
  114888. count++;
  114889. }
  114890. /* Replaced the original bubble sort with a real sort. With your
  114891. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114892. for(i=0; i<ord;i++) r[i] = root[i];
  114893. return(0);
  114894. }
  114895. /* Convert lpc coefficients to lsp coefficients */
  114896. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114897. int order2=(m+1)>>1;
  114898. int g1_order,g2_order;
  114899. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114900. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114901. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114902. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114903. int i;
  114904. /* even and odd are slightly different base cases */
  114905. g1_order=(m+1)>>1;
  114906. g2_order=(m) >>1;
  114907. /* Compute the lengths of the x polynomials. */
  114908. /* Compute the first half of K & R F1 & F2 polynomials. */
  114909. /* Compute half of the symmetric and antisymmetric polynomials. */
  114910. /* Remove the roots at +1 and -1. */
  114911. g1[g1_order] = 1.f;
  114912. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114913. g2[g2_order] = 1.f;
  114914. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114915. if(g1_order>g2_order){
  114916. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114917. }else{
  114918. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114919. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114920. }
  114921. /* Convert into polynomials in cos(alpha) */
  114922. cheby(g1,g1_order);
  114923. cheby(g2,g2_order);
  114924. /* Find the roots of the 2 even polynomials.*/
  114925. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114926. Laguerre_With_Deflation(g2,g2_order,g2r))
  114927. return(-1);
  114928. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114929. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114930. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114931. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114932. for(i=0;i<g1_order;i++)
  114933. lsp[i*2] = acos(g1r[i]);
  114934. for(i=0;i<g2_order;i++)
  114935. lsp[i*2+1] = acos(g2r[i]);
  114936. return(0);
  114937. }
  114938. #endif
  114939. /*** End of inlined file: lsp.c ***/
  114940. /*** Start of inlined file: mapping0.c ***/
  114941. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114942. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114943. // tasks..
  114944. #if JUCE_MSVC
  114945. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114946. #endif
  114947. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114948. #if JUCE_USE_OGGVORBIS
  114949. #include <stdlib.h>
  114950. #include <stdio.h>
  114951. #include <string.h>
  114952. #include <math.h>
  114953. /* simplistic, wasteful way of doing this (unique lookup for each
  114954. mode/submapping); there should be a central repository for
  114955. identical lookups. That will require minor work, so I'm putting it
  114956. off as low priority.
  114957. Why a lookup for each backend in a given mode? Because the
  114958. blocksize is set by the mode, and low backend lookups may require
  114959. parameters from other areas of the mode/mapping */
  114960. static void mapping0_free_info(vorbis_info_mapping *i){
  114961. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114962. if(info){
  114963. memset(info,0,sizeof(*info));
  114964. _ogg_free(info);
  114965. }
  114966. }
  114967. static int ilog3(unsigned int v){
  114968. int ret=0;
  114969. if(v)--v;
  114970. while(v){
  114971. ret++;
  114972. v>>=1;
  114973. }
  114974. return(ret);
  114975. }
  114976. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114977. oggpack_buffer *opb){
  114978. int i;
  114979. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114980. /* another 'we meant to do it this way' hack... up to beta 4, we
  114981. packed 4 binary zeros here to signify one submapping in use. We
  114982. now redefine that to mean four bitflags that indicate use of
  114983. deeper features; bit0:submappings, bit1:coupling,
  114984. bit2,3:reserved. This is backward compatable with all actual uses
  114985. of the beta code. */
  114986. if(info->submaps>1){
  114987. oggpack_write(opb,1,1);
  114988. oggpack_write(opb,info->submaps-1,4);
  114989. }else
  114990. oggpack_write(opb,0,1);
  114991. if(info->coupling_steps>0){
  114992. oggpack_write(opb,1,1);
  114993. oggpack_write(opb,info->coupling_steps-1,8);
  114994. for(i=0;i<info->coupling_steps;i++){
  114995. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114996. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114997. }
  114998. }else
  114999. oggpack_write(opb,0,1);
  115000. oggpack_write(opb,0,2); /* 2,3:reserved */
  115001. /* we don't write the channel submappings if we only have one... */
  115002. if(info->submaps>1){
  115003. for(i=0;i<vi->channels;i++)
  115004. oggpack_write(opb,info->chmuxlist[i],4);
  115005. }
  115006. for(i=0;i<info->submaps;i++){
  115007. oggpack_write(opb,0,8); /* time submap unused */
  115008. oggpack_write(opb,info->floorsubmap[i],8);
  115009. oggpack_write(opb,info->residuesubmap[i],8);
  115010. }
  115011. }
  115012. /* also responsible for range checking */
  115013. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115014. int i;
  115015. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115016. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115017. memset(info,0,sizeof(*info));
  115018. if(oggpack_read(opb,1))
  115019. info->submaps=oggpack_read(opb,4)+1;
  115020. else
  115021. info->submaps=1;
  115022. if(oggpack_read(opb,1)){
  115023. info->coupling_steps=oggpack_read(opb,8)+1;
  115024. for(i=0;i<info->coupling_steps;i++){
  115025. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115026. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115027. if(testM<0 ||
  115028. testA<0 ||
  115029. testM==testA ||
  115030. testM>=vi->channels ||
  115031. testA>=vi->channels) goto err_out;
  115032. }
  115033. }
  115034. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115035. if(info->submaps>1){
  115036. for(i=0;i<vi->channels;i++){
  115037. info->chmuxlist[i]=oggpack_read(opb,4);
  115038. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115039. }
  115040. }
  115041. for(i=0;i<info->submaps;i++){
  115042. oggpack_read(opb,8); /* time submap unused */
  115043. info->floorsubmap[i]=oggpack_read(opb,8);
  115044. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115045. info->residuesubmap[i]=oggpack_read(opb,8);
  115046. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115047. }
  115048. return info;
  115049. err_out:
  115050. mapping0_free_info(info);
  115051. return(NULL);
  115052. }
  115053. #if 0
  115054. static long seq=0;
  115055. static ogg_int64_t total=0;
  115056. static float FLOOR1_fromdB_LOOKUP[256]={
  115057. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115058. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115059. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115060. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115061. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115062. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115063. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115064. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115065. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115066. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115067. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115068. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115069. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115070. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115071. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115072. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115073. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115074. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115075. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115076. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115077. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115078. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115079. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115080. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115081. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115082. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115083. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115084. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115085. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115086. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115087. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115088. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115089. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115090. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115091. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115092. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115093. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115094. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115095. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115096. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115097. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115098. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115099. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115100. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115101. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115102. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115103. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115104. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115105. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115106. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115107. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115108. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115109. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115110. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115111. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115112. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115113. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115114. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115115. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115116. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115117. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115118. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115119. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115120. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115121. };
  115122. #endif
  115123. extern int *floor1_fit(vorbis_block *vb,void *look,
  115124. const float *logmdct, /* in */
  115125. const float *logmask);
  115126. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115127. int *A,int *B,
  115128. int del);
  115129. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115130. void*look,
  115131. int *post,int *ilogmask);
  115132. static int mapping0_forward(vorbis_block *vb){
  115133. vorbis_dsp_state *vd=vb->vd;
  115134. vorbis_info *vi=vd->vi;
  115135. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115136. private_state *b=(private_state*)vb->vd->backend_state;
  115137. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115138. int n=vb->pcmend;
  115139. int i,j,k;
  115140. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115141. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115142. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115143. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115144. float global_ampmax=vbi->ampmax;
  115145. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115146. int blocktype=vbi->blocktype;
  115147. int modenumber=vb->W;
  115148. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115149. vorbis_look_psy *psy_look=
  115150. b->psy+blocktype+(vb->W?2:0);
  115151. vb->mode=modenumber;
  115152. for(i=0;i<vi->channels;i++){
  115153. float scale=4.f/n;
  115154. float scale_dB;
  115155. float *pcm =vb->pcm[i];
  115156. float *logfft =pcm;
  115157. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115158. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115159. todB estimation used on IEEE 754
  115160. compliant machines had a bug that
  115161. returned dB values about a third
  115162. of a decibel too high. The bug
  115163. was harmless because tunings
  115164. implicitly took that into
  115165. account. However, fixing the bug
  115166. in the estimator requires
  115167. changing all the tunings as well.
  115168. For now, it's easier to sync
  115169. things back up here, and
  115170. recalibrate the tunings in the
  115171. next major model upgrade. */
  115172. #if 0
  115173. if(vi->channels==2)
  115174. if(i==0)
  115175. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115176. else
  115177. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115178. #endif
  115179. /* window the PCM data */
  115180. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115181. #if 0
  115182. if(vi->channels==2)
  115183. if(i==0)
  115184. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115185. else
  115186. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115187. #endif
  115188. /* transform the PCM data */
  115189. /* only MDCT right now.... */
  115190. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115191. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115192. drft_forward(&b->fft_look[vb->W],pcm);
  115193. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115194. original todB estimation used on
  115195. IEEE 754 compliant machines had a
  115196. bug that returned dB values about
  115197. a third of a decibel too high.
  115198. The bug was harmless because
  115199. tunings implicitly took that into
  115200. account. However, fixing the bug
  115201. in the estimator requires
  115202. changing all the tunings as well.
  115203. For now, it's easier to sync
  115204. things back up here, and
  115205. recalibrate the tunings in the
  115206. next major model upgrade. */
  115207. local_ampmax[i]=logfft[0];
  115208. for(j=1;j<n-1;j+=2){
  115209. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115210. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115211. .345 is a hack; the original todB
  115212. estimation used on IEEE 754
  115213. compliant machines had a bug that
  115214. returned dB values about a third
  115215. of a decibel too high. The bug
  115216. was harmless because tunings
  115217. implicitly took that into
  115218. account. However, fixing the bug
  115219. in the estimator requires
  115220. changing all the tunings as well.
  115221. For now, it's easier to sync
  115222. things back up here, and
  115223. recalibrate the tunings in the
  115224. next major model upgrade. */
  115225. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115226. }
  115227. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115228. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115229. #if 0
  115230. if(vi->channels==2){
  115231. if(i==0){
  115232. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115233. }else{
  115234. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115235. }
  115236. }
  115237. #endif
  115238. }
  115239. {
  115240. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115241. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115242. for(i=0;i<vi->channels;i++){
  115243. /* the encoder setup assumes that all the modes used by any
  115244. specific bitrate tweaking use the same floor */
  115245. int submap=info->chmuxlist[i];
  115246. /* the following makes things clearer to *me* anyway */
  115247. float *mdct =gmdct[i];
  115248. float *logfft =vb->pcm[i];
  115249. float *logmdct =logfft+n/2;
  115250. float *logmask =logfft;
  115251. vb->mode=modenumber;
  115252. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115253. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115254. for(j=0;j<n/2;j++)
  115255. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115256. todB estimation used on IEEE 754
  115257. compliant machines had a bug that
  115258. returned dB values about a third
  115259. of a decibel too high. The bug
  115260. was harmless because tunings
  115261. implicitly took that into
  115262. account. However, fixing the bug
  115263. in the estimator requires
  115264. changing all the tunings as well.
  115265. For now, it's easier to sync
  115266. things back up here, and
  115267. recalibrate the tunings in the
  115268. next major model upgrade. */
  115269. #if 0
  115270. if(vi->channels==2){
  115271. if(i==0)
  115272. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115273. else
  115274. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115275. }else{
  115276. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115277. }
  115278. #endif
  115279. /* first step; noise masking. Not only does 'noise masking'
  115280. give us curves from which we can decide how much resolution
  115281. to give noise parts of the spectrum, it also implicitly hands
  115282. us a tonality estimate (the larger the value in the
  115283. 'noise_depth' vector, the more tonal that area is) */
  115284. _vp_noisemask(psy_look,
  115285. logmdct,
  115286. noise); /* noise does not have by-frequency offset
  115287. bias applied yet */
  115288. #if 0
  115289. if(vi->channels==2){
  115290. if(i==0)
  115291. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115292. else
  115293. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115294. }
  115295. #endif
  115296. /* second step: 'all the other crap'; all the stuff that isn't
  115297. computed/fit for bitrate management goes in the second psy
  115298. vector. This includes tone masking, peak limiting and ATH */
  115299. _vp_tonemask(psy_look,
  115300. logfft,
  115301. tone,
  115302. global_ampmax,
  115303. local_ampmax[i]);
  115304. #if 0
  115305. if(vi->channels==2){
  115306. if(i==0)
  115307. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115308. else
  115309. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115310. }
  115311. #endif
  115312. /* third step; we offset the noise vectors, overlay tone
  115313. masking. We then do a floor1-specific line fit. If we're
  115314. performing bitrate management, the line fit is performed
  115315. multiple times for up/down tweakage on demand. */
  115316. #if 0
  115317. {
  115318. float aotuv[psy_look->n];
  115319. #endif
  115320. _vp_offset_and_mix(psy_look,
  115321. noise,
  115322. tone,
  115323. 1,
  115324. logmask,
  115325. mdct,
  115326. logmdct);
  115327. #if 0
  115328. if(vi->channels==2){
  115329. if(i==0)
  115330. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115331. else
  115332. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115333. }
  115334. }
  115335. #endif
  115336. #if 0
  115337. if(vi->channels==2){
  115338. if(i==0)
  115339. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115340. else
  115341. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115342. }
  115343. #endif
  115344. /* this algorithm is hardwired to floor 1 for now; abort out if
  115345. we're *not* floor1. This won't happen unless someone has
  115346. broken the encode setup lib. Guard it anyway. */
  115347. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115348. floor_posts[i][PACKETBLOBS/2]=
  115349. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115350. logmdct,
  115351. logmask);
  115352. /* are we managing bitrate? If so, perform two more fits for
  115353. later rate tweaking (fits represent hi/lo) */
  115354. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115355. /* higher rate by way of lower noise curve */
  115356. _vp_offset_and_mix(psy_look,
  115357. noise,
  115358. tone,
  115359. 2,
  115360. logmask,
  115361. mdct,
  115362. logmdct);
  115363. #if 0
  115364. if(vi->channels==2){
  115365. if(i==0)
  115366. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115367. else
  115368. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115369. }
  115370. #endif
  115371. floor_posts[i][PACKETBLOBS-1]=
  115372. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115373. logmdct,
  115374. logmask);
  115375. /* lower rate by way of higher noise curve */
  115376. _vp_offset_and_mix(psy_look,
  115377. noise,
  115378. tone,
  115379. 0,
  115380. logmask,
  115381. mdct,
  115382. logmdct);
  115383. #if 0
  115384. if(vi->channels==2)
  115385. if(i==0)
  115386. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115387. else
  115388. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115389. #endif
  115390. floor_posts[i][0]=
  115391. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115392. logmdct,
  115393. logmask);
  115394. /* we also interpolate a range of intermediate curves for
  115395. intermediate rates */
  115396. for(k=1;k<PACKETBLOBS/2;k++)
  115397. floor_posts[i][k]=
  115398. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115399. floor_posts[i][0],
  115400. floor_posts[i][PACKETBLOBS/2],
  115401. k*65536/(PACKETBLOBS/2));
  115402. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115403. floor_posts[i][k]=
  115404. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115405. floor_posts[i][PACKETBLOBS/2],
  115406. floor_posts[i][PACKETBLOBS-1],
  115407. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115408. }
  115409. }
  115410. }
  115411. vbi->ampmax=global_ampmax;
  115412. /*
  115413. the next phases are performed once for vbr-only and PACKETBLOB
  115414. times for bitrate managed modes.
  115415. 1) encode actual mode being used
  115416. 2) encode the floor for each channel, compute coded mask curve/res
  115417. 3) normalize and couple.
  115418. 4) encode residue
  115419. 5) save packet bytes to the packetblob vector
  115420. */
  115421. /* iterate over the many masking curve fits we've created */
  115422. {
  115423. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115424. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115425. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115426. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115427. float **mag_memo;
  115428. int **mag_sort;
  115429. if(info->coupling_steps){
  115430. mag_memo=_vp_quantize_couple_memo(vb,
  115431. &ci->psy_g_param,
  115432. psy_look,
  115433. info,
  115434. gmdct);
  115435. mag_sort=_vp_quantize_couple_sort(vb,
  115436. psy_look,
  115437. info,
  115438. mag_memo);
  115439. hf_reduction(&ci->psy_g_param,
  115440. psy_look,
  115441. info,
  115442. mag_memo);
  115443. }
  115444. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115445. if(psy_look->vi->normal_channel_p){
  115446. for(i=0;i<vi->channels;i++){
  115447. float *mdct =gmdct[i];
  115448. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115449. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115450. }
  115451. }
  115452. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115453. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115454. k++){
  115455. oggpack_buffer *opb=vbi->packetblob[k];
  115456. /* start out our new packet blob with packet type and mode */
  115457. /* Encode the packet type */
  115458. oggpack_write(opb,0,1);
  115459. /* Encode the modenumber */
  115460. /* Encode frame mode, pre,post windowsize, then dispatch */
  115461. oggpack_write(opb,modenumber,b->modebits);
  115462. if(vb->W){
  115463. oggpack_write(opb,vb->lW,1);
  115464. oggpack_write(opb,vb->nW,1);
  115465. }
  115466. /* encode floor, compute masking curve, sep out residue */
  115467. for(i=0;i<vi->channels;i++){
  115468. int submap=info->chmuxlist[i];
  115469. float *mdct =gmdct[i];
  115470. float *res =vb->pcm[i];
  115471. int *ilogmask=ilogmaskch[i]=
  115472. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115473. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115474. floor_posts[i][k],
  115475. ilogmask);
  115476. #if 0
  115477. {
  115478. char buf[80];
  115479. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115480. float work[n/2];
  115481. for(j=0;j<n/2;j++)
  115482. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115483. _analysis_output(buf,seq,work,n/2,1,1,0);
  115484. }
  115485. #endif
  115486. _vp_remove_floor(psy_look,
  115487. mdct,
  115488. ilogmask,
  115489. res,
  115490. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115491. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115492. #if 0
  115493. {
  115494. char buf[80];
  115495. float work[n/2];
  115496. for(j=0;j<n/2;j++)
  115497. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115498. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115499. _analysis_output(buf,seq,work,n/2,1,1,0);
  115500. }
  115501. #endif
  115502. }
  115503. /* our iteration is now based on masking curve, not prequant and
  115504. coupling. Only one prequant/coupling step */
  115505. /* quantize/couple */
  115506. /* incomplete implementation that assumes the tree is all depth
  115507. one, or no tree at all */
  115508. if(info->coupling_steps){
  115509. _vp_couple(k,
  115510. &ci->psy_g_param,
  115511. psy_look,
  115512. info,
  115513. vb->pcm,
  115514. mag_memo,
  115515. mag_sort,
  115516. ilogmaskch,
  115517. nonzero,
  115518. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115519. }
  115520. /* classify and encode by submap */
  115521. for(i=0;i<info->submaps;i++){
  115522. int ch_in_bundle=0;
  115523. long **classifications;
  115524. int resnum=info->residuesubmap[i];
  115525. for(j=0;j<vi->channels;j++){
  115526. if(info->chmuxlist[j]==i){
  115527. zerobundle[ch_in_bundle]=0;
  115528. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115529. res_bundle[ch_in_bundle]=vb->pcm[j];
  115530. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115531. }
  115532. }
  115533. classifications=_residue_P[ci->residue_type[resnum]]->
  115534. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115535. _residue_P[ci->residue_type[resnum]]->
  115536. forward(opb,vb,b->residue[resnum],
  115537. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115538. }
  115539. /* ok, done encoding. Next protopacket. */
  115540. }
  115541. }
  115542. #if 0
  115543. seq++;
  115544. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115545. #endif
  115546. return(0);
  115547. }
  115548. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115549. vorbis_dsp_state *vd=vb->vd;
  115550. vorbis_info *vi=vd->vi;
  115551. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115552. private_state *b=(private_state*)vd->backend_state;
  115553. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115554. int i,j;
  115555. long n=vb->pcmend=ci->blocksizes[vb->W];
  115556. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115557. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115558. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115559. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115560. /* recover the spectral envelope; store it in the PCM vector for now */
  115561. for(i=0;i<vi->channels;i++){
  115562. int submap=info->chmuxlist[i];
  115563. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115564. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115565. if(floormemo[i])
  115566. nonzero[i]=1;
  115567. else
  115568. nonzero[i]=0;
  115569. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115570. }
  115571. /* channel coupling can 'dirty' the nonzero listing */
  115572. for(i=0;i<info->coupling_steps;i++){
  115573. if(nonzero[info->coupling_mag[i]] ||
  115574. nonzero[info->coupling_ang[i]]){
  115575. nonzero[info->coupling_mag[i]]=1;
  115576. nonzero[info->coupling_ang[i]]=1;
  115577. }
  115578. }
  115579. /* recover the residue into our working vectors */
  115580. for(i=0;i<info->submaps;i++){
  115581. int ch_in_bundle=0;
  115582. for(j=0;j<vi->channels;j++){
  115583. if(info->chmuxlist[j]==i){
  115584. if(nonzero[j])
  115585. zerobundle[ch_in_bundle]=1;
  115586. else
  115587. zerobundle[ch_in_bundle]=0;
  115588. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115589. }
  115590. }
  115591. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115592. inverse(vb,b->residue[info->residuesubmap[i]],
  115593. pcmbundle,zerobundle,ch_in_bundle);
  115594. }
  115595. /* channel coupling */
  115596. for(i=info->coupling_steps-1;i>=0;i--){
  115597. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115598. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115599. for(j=0;j<n/2;j++){
  115600. float mag=pcmM[j];
  115601. float ang=pcmA[j];
  115602. if(mag>0)
  115603. if(ang>0){
  115604. pcmM[j]=mag;
  115605. pcmA[j]=mag-ang;
  115606. }else{
  115607. pcmA[j]=mag;
  115608. pcmM[j]=mag+ang;
  115609. }
  115610. else
  115611. if(ang>0){
  115612. pcmM[j]=mag;
  115613. pcmA[j]=mag+ang;
  115614. }else{
  115615. pcmA[j]=mag;
  115616. pcmM[j]=mag-ang;
  115617. }
  115618. }
  115619. }
  115620. /* compute and apply spectral envelope */
  115621. for(i=0;i<vi->channels;i++){
  115622. float *pcm=vb->pcm[i];
  115623. int submap=info->chmuxlist[i];
  115624. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115625. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115626. floormemo[i],pcm);
  115627. }
  115628. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115629. /* only MDCT right now.... */
  115630. for(i=0;i<vi->channels;i++){
  115631. float *pcm=vb->pcm[i];
  115632. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115633. }
  115634. /* all done! */
  115635. return(0);
  115636. }
  115637. /* export hooks */
  115638. vorbis_func_mapping mapping0_exportbundle={
  115639. &mapping0_pack,
  115640. &mapping0_unpack,
  115641. &mapping0_free_info,
  115642. &mapping0_forward,
  115643. &mapping0_inverse
  115644. };
  115645. #endif
  115646. /*** End of inlined file: mapping0.c ***/
  115647. /*** Start of inlined file: mdct.c ***/
  115648. /* this can also be run as an integer transform by uncommenting a
  115649. define in mdct.h; the integerization is a first pass and although
  115650. it's likely stable for Vorbis, the dynamic range is constrained and
  115651. roundoff isn't done (so it's noisy). Consider it functional, but
  115652. only a starting point. There's no point on a machine with an FPU */
  115653. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115654. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115655. // tasks..
  115656. #if JUCE_MSVC
  115657. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115658. #endif
  115659. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115660. #if JUCE_USE_OGGVORBIS
  115661. #include <stdio.h>
  115662. #include <stdlib.h>
  115663. #include <string.h>
  115664. #include <math.h>
  115665. /* build lookups for trig functions; also pre-figure scaling and
  115666. some window function algebra. */
  115667. void mdct_init(mdct_lookup *lookup,int n){
  115668. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115669. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115670. int i;
  115671. int n2=n>>1;
  115672. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115673. lookup->n=n;
  115674. lookup->trig=T;
  115675. lookup->bitrev=bitrev;
  115676. /* trig lookups... */
  115677. for(i=0;i<n/4;i++){
  115678. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115679. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115680. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115681. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115682. }
  115683. for(i=0;i<n/8;i++){
  115684. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115685. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115686. }
  115687. /* bitreverse lookup... */
  115688. {
  115689. int mask=(1<<(log2n-1))-1,i,j;
  115690. int msb=1<<(log2n-2);
  115691. for(i=0;i<n/8;i++){
  115692. int acc=0;
  115693. for(j=0;msb>>j;j++)
  115694. if((msb>>j)&i)acc|=1<<j;
  115695. bitrev[i*2]=((~acc)&mask)-1;
  115696. bitrev[i*2+1]=acc;
  115697. }
  115698. }
  115699. lookup->scale=FLOAT_CONV(4.f/n);
  115700. }
  115701. /* 8 point butterfly (in place, 4 register) */
  115702. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115703. REG_TYPE r0 = x[6] + x[2];
  115704. REG_TYPE r1 = x[6] - x[2];
  115705. REG_TYPE r2 = x[4] + x[0];
  115706. REG_TYPE r3 = x[4] - x[0];
  115707. x[6] = r0 + r2;
  115708. x[4] = r0 - r2;
  115709. r0 = x[5] - x[1];
  115710. r2 = x[7] - x[3];
  115711. x[0] = r1 + r0;
  115712. x[2] = r1 - r0;
  115713. r0 = x[5] + x[1];
  115714. r1 = x[7] + x[3];
  115715. x[3] = r2 + r3;
  115716. x[1] = r2 - r3;
  115717. x[7] = r1 + r0;
  115718. x[5] = r1 - r0;
  115719. }
  115720. /* 16 point butterfly (in place, 4 register) */
  115721. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115722. REG_TYPE r0 = x[1] - x[9];
  115723. REG_TYPE r1 = x[0] - x[8];
  115724. x[8] += x[0];
  115725. x[9] += x[1];
  115726. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115727. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115728. r0 = x[3] - x[11];
  115729. r1 = x[10] - x[2];
  115730. x[10] += x[2];
  115731. x[11] += x[3];
  115732. x[2] = r0;
  115733. x[3] = r1;
  115734. r0 = x[12] - x[4];
  115735. r1 = x[13] - x[5];
  115736. x[12] += x[4];
  115737. x[13] += x[5];
  115738. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115739. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115740. r0 = x[14] - x[6];
  115741. r1 = x[15] - x[7];
  115742. x[14] += x[6];
  115743. x[15] += x[7];
  115744. x[6] = r0;
  115745. x[7] = r1;
  115746. mdct_butterfly_8(x);
  115747. mdct_butterfly_8(x+8);
  115748. }
  115749. /* 32 point butterfly (in place, 4 register) */
  115750. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115751. REG_TYPE r0 = x[30] - x[14];
  115752. REG_TYPE r1 = x[31] - x[15];
  115753. x[30] += x[14];
  115754. x[31] += x[15];
  115755. x[14] = r0;
  115756. x[15] = r1;
  115757. r0 = x[28] - x[12];
  115758. r1 = x[29] - x[13];
  115759. x[28] += x[12];
  115760. x[29] += x[13];
  115761. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115762. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115763. r0 = x[26] - x[10];
  115764. r1 = x[27] - x[11];
  115765. x[26] += x[10];
  115766. x[27] += x[11];
  115767. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115768. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115769. r0 = x[24] - x[8];
  115770. r1 = x[25] - x[9];
  115771. x[24] += x[8];
  115772. x[25] += x[9];
  115773. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115774. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115775. r0 = x[22] - x[6];
  115776. r1 = x[7] - x[23];
  115777. x[22] += x[6];
  115778. x[23] += x[7];
  115779. x[6] = r1;
  115780. x[7] = r0;
  115781. r0 = x[4] - x[20];
  115782. r1 = x[5] - x[21];
  115783. x[20] += x[4];
  115784. x[21] += x[5];
  115785. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115786. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115787. r0 = x[2] - x[18];
  115788. r1 = x[3] - x[19];
  115789. x[18] += x[2];
  115790. x[19] += x[3];
  115791. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115792. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115793. r0 = x[0] - x[16];
  115794. r1 = x[1] - x[17];
  115795. x[16] += x[0];
  115796. x[17] += x[1];
  115797. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115798. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115799. mdct_butterfly_16(x);
  115800. mdct_butterfly_16(x+16);
  115801. }
  115802. /* N point first stage butterfly (in place, 2 register) */
  115803. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115804. DATA_TYPE *x,
  115805. int points){
  115806. DATA_TYPE *x1 = x + points - 8;
  115807. DATA_TYPE *x2 = x + (points>>1) - 8;
  115808. REG_TYPE r0;
  115809. REG_TYPE r1;
  115810. do{
  115811. r0 = x1[6] - x2[6];
  115812. r1 = x1[7] - x2[7];
  115813. x1[6] += x2[6];
  115814. x1[7] += x2[7];
  115815. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115816. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115817. r0 = x1[4] - x2[4];
  115818. r1 = x1[5] - x2[5];
  115819. x1[4] += x2[4];
  115820. x1[5] += x2[5];
  115821. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115822. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115823. r0 = x1[2] - x2[2];
  115824. r1 = x1[3] - x2[3];
  115825. x1[2] += x2[2];
  115826. x1[3] += x2[3];
  115827. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115828. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115829. r0 = x1[0] - x2[0];
  115830. r1 = x1[1] - x2[1];
  115831. x1[0] += x2[0];
  115832. x1[1] += x2[1];
  115833. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115834. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115835. x1-=8;
  115836. x2-=8;
  115837. T+=16;
  115838. }while(x2>=x);
  115839. }
  115840. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115841. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115842. DATA_TYPE *x,
  115843. int points,
  115844. int trigint){
  115845. DATA_TYPE *x1 = x + points - 8;
  115846. DATA_TYPE *x2 = x + (points>>1) - 8;
  115847. REG_TYPE r0;
  115848. REG_TYPE r1;
  115849. do{
  115850. r0 = x1[6] - x2[6];
  115851. r1 = x1[7] - x2[7];
  115852. x1[6] += x2[6];
  115853. x1[7] += x2[7];
  115854. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115855. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115856. T+=trigint;
  115857. r0 = x1[4] - x2[4];
  115858. r1 = x1[5] - x2[5];
  115859. x1[4] += x2[4];
  115860. x1[5] += x2[5];
  115861. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115862. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115863. T+=trigint;
  115864. r0 = x1[2] - x2[2];
  115865. r1 = x1[3] - x2[3];
  115866. x1[2] += x2[2];
  115867. x1[3] += x2[3];
  115868. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115869. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115870. T+=trigint;
  115871. r0 = x1[0] - x2[0];
  115872. r1 = x1[1] - x2[1];
  115873. x1[0] += x2[0];
  115874. x1[1] += x2[1];
  115875. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115876. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115877. T+=trigint;
  115878. x1-=8;
  115879. x2-=8;
  115880. }while(x2>=x);
  115881. }
  115882. STIN void mdct_butterflies(mdct_lookup *init,
  115883. DATA_TYPE *x,
  115884. int points){
  115885. DATA_TYPE *T=init->trig;
  115886. int stages=init->log2n-5;
  115887. int i,j;
  115888. if(--stages>0){
  115889. mdct_butterfly_first(T,x,points);
  115890. }
  115891. for(i=1;--stages>0;i++){
  115892. for(j=0;j<(1<<i);j++)
  115893. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115894. }
  115895. for(j=0;j<points;j+=32)
  115896. mdct_butterfly_32(x+j);
  115897. }
  115898. void mdct_clear(mdct_lookup *l){
  115899. if(l){
  115900. if(l->trig)_ogg_free(l->trig);
  115901. if(l->bitrev)_ogg_free(l->bitrev);
  115902. memset(l,0,sizeof(*l));
  115903. }
  115904. }
  115905. STIN void mdct_bitreverse(mdct_lookup *init,
  115906. DATA_TYPE *x){
  115907. int n = init->n;
  115908. int *bit = init->bitrev;
  115909. DATA_TYPE *w0 = x;
  115910. DATA_TYPE *w1 = x = w0+(n>>1);
  115911. DATA_TYPE *T = init->trig+n;
  115912. do{
  115913. DATA_TYPE *x0 = x+bit[0];
  115914. DATA_TYPE *x1 = x+bit[1];
  115915. REG_TYPE r0 = x0[1] - x1[1];
  115916. REG_TYPE r1 = x0[0] + x1[0];
  115917. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115918. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115919. w1 -= 4;
  115920. r0 = HALVE(x0[1] + x1[1]);
  115921. r1 = HALVE(x0[0] - x1[0]);
  115922. w0[0] = r0 + r2;
  115923. w1[2] = r0 - r2;
  115924. w0[1] = r1 + r3;
  115925. w1[3] = r3 - r1;
  115926. x0 = x+bit[2];
  115927. x1 = x+bit[3];
  115928. r0 = x0[1] - x1[1];
  115929. r1 = x0[0] + x1[0];
  115930. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115931. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115932. r0 = HALVE(x0[1] + x1[1]);
  115933. r1 = HALVE(x0[0] - x1[0]);
  115934. w0[2] = r0 + r2;
  115935. w1[0] = r0 - r2;
  115936. w0[3] = r1 + r3;
  115937. w1[1] = r3 - r1;
  115938. T += 4;
  115939. bit += 4;
  115940. w0 += 4;
  115941. }while(w0<w1);
  115942. }
  115943. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115944. int n=init->n;
  115945. int n2=n>>1;
  115946. int n4=n>>2;
  115947. /* rotate */
  115948. DATA_TYPE *iX = in+n2-7;
  115949. DATA_TYPE *oX = out+n2+n4;
  115950. DATA_TYPE *T = init->trig+n4;
  115951. do{
  115952. oX -= 4;
  115953. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115954. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115955. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115956. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115957. iX -= 8;
  115958. T += 4;
  115959. }while(iX>=in);
  115960. iX = in+n2-8;
  115961. oX = out+n2+n4;
  115962. T = init->trig+n4;
  115963. do{
  115964. T -= 4;
  115965. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115966. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115967. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115968. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115969. iX -= 8;
  115970. oX += 4;
  115971. }while(iX>=in);
  115972. mdct_butterflies(init,out+n2,n2);
  115973. mdct_bitreverse(init,out);
  115974. /* roatate + window */
  115975. {
  115976. DATA_TYPE *oX1=out+n2+n4;
  115977. DATA_TYPE *oX2=out+n2+n4;
  115978. DATA_TYPE *iX =out;
  115979. T =init->trig+n2;
  115980. do{
  115981. oX1-=4;
  115982. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115983. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115984. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115985. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115986. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115987. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115988. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115989. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115990. oX2+=4;
  115991. iX += 8;
  115992. T += 8;
  115993. }while(iX<oX1);
  115994. iX=out+n2+n4;
  115995. oX1=out+n4;
  115996. oX2=oX1;
  115997. do{
  115998. oX1-=4;
  115999. iX-=4;
  116000. oX2[0] = -(oX1[3] = iX[3]);
  116001. oX2[1] = -(oX1[2] = iX[2]);
  116002. oX2[2] = -(oX1[1] = iX[1]);
  116003. oX2[3] = -(oX1[0] = iX[0]);
  116004. oX2+=4;
  116005. }while(oX2<iX);
  116006. iX=out+n2+n4;
  116007. oX1=out+n2+n4;
  116008. oX2=out+n2;
  116009. do{
  116010. oX1-=4;
  116011. oX1[0]= iX[3];
  116012. oX1[1]= iX[2];
  116013. oX1[2]= iX[1];
  116014. oX1[3]= iX[0];
  116015. iX+=4;
  116016. }while(oX1>oX2);
  116017. }
  116018. }
  116019. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116020. int n=init->n;
  116021. int n2=n>>1;
  116022. int n4=n>>2;
  116023. int n8=n>>3;
  116024. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116025. DATA_TYPE *w2=w+n2;
  116026. /* rotate */
  116027. /* window + rotate + step 1 */
  116028. REG_TYPE r0;
  116029. REG_TYPE r1;
  116030. DATA_TYPE *x0=in+n2+n4;
  116031. DATA_TYPE *x1=x0+1;
  116032. DATA_TYPE *T=init->trig+n2;
  116033. int i=0;
  116034. for(i=0;i<n8;i+=2){
  116035. x0 -=4;
  116036. T-=2;
  116037. r0= x0[2] + x1[0];
  116038. r1= x0[0] + x1[2];
  116039. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116040. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116041. x1 +=4;
  116042. }
  116043. x1=in+1;
  116044. for(;i<n2-n8;i+=2){
  116045. T-=2;
  116046. x0 -=4;
  116047. r0= x0[2] - x1[0];
  116048. r1= x0[0] - x1[2];
  116049. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116050. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116051. x1 +=4;
  116052. }
  116053. x0=in+n;
  116054. for(;i<n2;i+=2){
  116055. T-=2;
  116056. x0 -=4;
  116057. r0= -x0[2] - x1[0];
  116058. r1= -x0[0] - x1[2];
  116059. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116060. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116061. x1 +=4;
  116062. }
  116063. mdct_butterflies(init,w+n2,n2);
  116064. mdct_bitreverse(init,w);
  116065. /* roatate + window */
  116066. T=init->trig+n2;
  116067. x0=out+n2;
  116068. for(i=0;i<n4;i++){
  116069. x0--;
  116070. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116071. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116072. w+=2;
  116073. T+=2;
  116074. }
  116075. }
  116076. #endif
  116077. /*** End of inlined file: mdct.c ***/
  116078. /*** Start of inlined file: psy.c ***/
  116079. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116080. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116081. // tasks..
  116082. #if JUCE_MSVC
  116083. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116084. #endif
  116085. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116086. #if JUCE_USE_OGGVORBIS
  116087. #include <stdlib.h>
  116088. #include <math.h>
  116089. #include <string.h>
  116090. /*** Start of inlined file: masking.h ***/
  116091. #ifndef _V_MASKING_H_
  116092. #define _V_MASKING_H_
  116093. /* more detailed ATH; the bass if flat to save stressing the floor
  116094. overly for only a bin or two of savings. */
  116095. #define MAX_ATH 88
  116096. static float ATH[]={
  116097. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116098. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116099. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116100. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116101. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116102. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116103. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116104. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116105. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116106. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116107. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116108. };
  116109. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116110. replaced by an empirically collected data set. The previously
  116111. published values were, far too often, simply on crack. */
  116112. #define EHMER_OFFSET 16
  116113. #define EHMER_MAX 56
  116114. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116115. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116116. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116117. for collection of these curves) */
  116118. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116119. /* 62.5 Hz */
  116120. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116121. -60, -60, -60, -60, -62, -62, -65, -73,
  116122. -69, -68, -68, -67, -70, -70, -72, -74,
  116123. -75, -79, -79, -80, -83, -88, -93, -100,
  116124. -110, -999, -999, -999, -999, -999, -999, -999,
  116125. -999, -999, -999, -999, -999, -999, -999, -999,
  116126. -999, -999, -999, -999, -999, -999, -999, -999},
  116127. { -48, -48, -48, -48, -48, -48, -48, -48,
  116128. -48, -48, -48, -48, -48, -53, -61, -66,
  116129. -66, -68, -67, -70, -76, -76, -72, -73,
  116130. -75, -76, -78, -79, -83, -88, -93, -100,
  116131. -110, -999, -999, -999, -999, -999, -999, -999,
  116132. -999, -999, -999, -999, -999, -999, -999, -999,
  116133. -999, -999, -999, -999, -999, -999, -999, -999},
  116134. { -37, -37, -37, -37, -37, -37, -37, -37,
  116135. -38, -40, -42, -46, -48, -53, -55, -62,
  116136. -65, -58, -56, -56, -61, -60, -65, -67,
  116137. -69, -71, -77, -77, -78, -80, -82, -84,
  116138. -88, -93, -98, -106, -112, -999, -999, -999,
  116139. -999, -999, -999, -999, -999, -999, -999, -999,
  116140. -999, -999, -999, -999, -999, -999, -999, -999},
  116141. { -25, -25, -25, -25, -25, -25, -25, -25,
  116142. -25, -26, -27, -29, -32, -38, -48, -52,
  116143. -52, -50, -48, -48, -51, -52, -54, -60,
  116144. -67, -67, -66, -68, -69, -73, -73, -76,
  116145. -80, -81, -81, -85, -85, -86, -88, -93,
  116146. -100, -110, -999, -999, -999, -999, -999, -999,
  116147. -999, -999, -999, -999, -999, -999, -999, -999},
  116148. { -16, -16, -16, -16, -16, -16, -16, -16,
  116149. -17, -19, -20, -22, -26, -28, -31, -40,
  116150. -47, -39, -39, -40, -42, -43, -47, -51,
  116151. -57, -52, -55, -55, -60, -58, -62, -63,
  116152. -70, -67, -69, -72, -73, -77, -80, -82,
  116153. -83, -87, -90, -94, -98, -104, -115, -999,
  116154. -999, -999, -999, -999, -999, -999, -999, -999},
  116155. { -8, -8, -8, -8, -8, -8, -8, -8,
  116156. -8, -8, -10, -11, -15, -19, -25, -30,
  116157. -34, -31, -30, -31, -29, -32, -35, -42,
  116158. -48, -42, -44, -46, -50, -50, -51, -52,
  116159. -59, -54, -55, -55, -58, -62, -63, -66,
  116160. -72, -73, -76, -75, -78, -80, -80, -81,
  116161. -84, -88, -90, -94, -98, -101, -106, -110}},
  116162. /* 88Hz */
  116163. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116164. -66, -66, -66, -66, -66, -67, -67, -67,
  116165. -76, -72, -71, -74, -76, -76, -75, -78,
  116166. -79, -79, -81, -83, -86, -89, -93, -97,
  116167. -100, -105, -110, -999, -999, -999, -999, -999,
  116168. -999, -999, -999, -999, -999, -999, -999, -999,
  116169. -999, -999, -999, -999, -999, -999, -999, -999},
  116170. { -47, -47, -47, -47, -47, -47, -47, -47,
  116171. -47, -47, -47, -48, -51, -55, -59, -66,
  116172. -66, -66, -67, -66, -68, -69, -70, -74,
  116173. -79, -77, -77, -78, -80, -81, -82, -84,
  116174. -86, -88, -91, -95, -100, -108, -116, -999,
  116175. -999, -999, -999, -999, -999, -999, -999, -999,
  116176. -999, -999, -999, -999, -999, -999, -999, -999},
  116177. { -36, -36, -36, -36, -36, -36, -36, -36,
  116178. -36, -37, -37, -41, -44, -48, -51, -58,
  116179. -62, -60, -57, -59, -59, -60, -63, -65,
  116180. -72, -71, -70, -72, -74, -77, -76, -78,
  116181. -81, -81, -80, -83, -86, -91, -96, -100,
  116182. -105, -110, -999, -999, -999, -999, -999, -999,
  116183. -999, -999, -999, -999, -999, -999, -999, -999},
  116184. { -28, -28, -28, -28, -28, -28, -28, -28,
  116185. -28, -30, -32, -32, -33, -35, -41, -49,
  116186. -50, -49, -47, -48, -48, -52, -51, -57,
  116187. -65, -61, -59, -61, -64, -69, -70, -74,
  116188. -77, -77, -78, -81, -84, -85, -87, -90,
  116189. -92, -96, -100, -107, -112, -999, -999, -999,
  116190. -999, -999, -999, -999, -999, -999, -999, -999},
  116191. { -19, -19, -19, -19, -19, -19, -19, -19,
  116192. -20, -21, -23, -27, -30, -35, -36, -41,
  116193. -46, -44, -42, -40, -41, -41, -43, -48,
  116194. -55, -53, -52, -53, -56, -59, -58, -60,
  116195. -67, -66, -69, -71, -72, -75, -79, -81,
  116196. -84, -87, -90, -93, -97, -101, -107, -114,
  116197. -999, -999, -999, -999, -999, -999, -999, -999},
  116198. { -9, -9, -9, -9, -9, -9, -9, -9,
  116199. -11, -12, -12, -15, -16, -20, -23, -30,
  116200. -37, -34, -33, -34, -31, -32, -32, -38,
  116201. -47, -44, -41, -40, -47, -49, -46, -46,
  116202. -58, -50, -50, -54, -58, -62, -64, -67,
  116203. -67, -70, -72, -76, -79, -83, -87, -91,
  116204. -96, -100, -104, -110, -999, -999, -999, -999}},
  116205. /* 125 Hz */
  116206. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116207. -62, -62, -63, -64, -66, -67, -66, -68,
  116208. -75, -72, -76, -75, -76, -78, -79, -82,
  116209. -84, -85, -90, -94, -101, -110, -999, -999,
  116210. -999, -999, -999, -999, -999, -999, -999, -999,
  116211. -999, -999, -999, -999, -999, -999, -999, -999,
  116212. -999, -999, -999, -999, -999, -999, -999, -999},
  116213. { -59, -59, -59, -59, -59, -59, -59, -59,
  116214. -59, -59, -59, -60, -60, -61, -63, -66,
  116215. -71, -68, -70, -70, -71, -72, -72, -75,
  116216. -81, -78, -79, -82, -83, -86, -90, -97,
  116217. -103, -113, -999, -999, -999, -999, -999, -999,
  116218. -999, -999, -999, -999, -999, -999, -999, -999,
  116219. -999, -999, -999, -999, -999, -999, -999, -999},
  116220. { -53, -53, -53, -53, -53, -53, -53, -53,
  116221. -53, -54, -55, -57, -56, -57, -55, -61,
  116222. -65, -60, -60, -62, -63, -63, -66, -68,
  116223. -74, -73, -75, -75, -78, -80, -80, -82,
  116224. -85, -90, -96, -101, -108, -999, -999, -999,
  116225. -999, -999, -999, -999, -999, -999, -999, -999,
  116226. -999, -999, -999, -999, -999, -999, -999, -999},
  116227. { -46, -46, -46, -46, -46, -46, -46, -46,
  116228. -46, -46, -47, -47, -47, -47, -48, -51,
  116229. -57, -51, -49, -50, -51, -53, -54, -59,
  116230. -66, -60, -62, -67, -67, -70, -72, -75,
  116231. -76, -78, -81, -85, -88, -94, -97, -104,
  116232. -112, -999, -999, -999, -999, -999, -999, -999,
  116233. -999, -999, -999, -999, -999, -999, -999, -999},
  116234. { -36, -36, -36, -36, -36, -36, -36, -36,
  116235. -39, -41, -42, -42, -39, -38, -41, -43,
  116236. -52, -44, -40, -39, -37, -37, -40, -47,
  116237. -54, -50, -48, -50, -55, -61, -59, -62,
  116238. -66, -66, -66, -69, -69, -73, -74, -74,
  116239. -75, -77, -79, -82, -87, -91, -95, -100,
  116240. -108, -115, -999, -999, -999, -999, -999, -999},
  116241. { -28, -26, -24, -22, -20, -20, -23, -29,
  116242. -30, -31, -28, -27, -28, -28, -28, -35,
  116243. -40, -33, -32, -29, -30, -30, -30, -37,
  116244. -45, -41, -37, -38, -45, -47, -47, -48,
  116245. -53, -49, -48, -50, -49, -49, -51, -52,
  116246. -58, -56, -57, -56, -60, -61, -62, -70,
  116247. -72, -74, -78, -83, -88, -93, -100, -106}},
  116248. /* 177 Hz */
  116249. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116250. -999, -110, -105, -100, -95, -91, -87, -83,
  116251. -80, -78, -76, -78, -78, -81, -83, -85,
  116252. -86, -85, -86, -87, -90, -97, -107, -999,
  116253. -999, -999, -999, -999, -999, -999, -999, -999,
  116254. -999, -999, -999, -999, -999, -999, -999, -999,
  116255. -999, -999, -999, -999, -999, -999, -999, -999},
  116256. {-999, -999, -999, -110, -105, -100, -95, -90,
  116257. -85, -81, -77, -73, -70, -67, -67, -68,
  116258. -75, -73, -70, -69, -70, -72, -75, -79,
  116259. -84, -83, -84, -86, -88, -89, -89, -93,
  116260. -98, -105, -112, -999, -999, -999, -999, -999,
  116261. -999, -999, -999, -999, -999, -999, -999, -999,
  116262. -999, -999, -999, -999, -999, -999, -999, -999},
  116263. {-105, -100, -95, -90, -85, -80, -76, -71,
  116264. -68, -68, -65, -63, -63, -62, -62, -64,
  116265. -65, -64, -61, -62, -63, -64, -66, -68,
  116266. -73, -73, -74, -75, -76, -81, -83, -85,
  116267. -88, -89, -92, -95, -100, -108, -999, -999,
  116268. -999, -999, -999, -999, -999, -999, -999, -999,
  116269. -999, -999, -999, -999, -999, -999, -999, -999},
  116270. { -80, -75, -71, -68, -65, -63, -62, -61,
  116271. -61, -61, -61, -59, -56, -57, -53, -50,
  116272. -58, -52, -50, -50, -52, -53, -54, -58,
  116273. -67, -63, -67, -68, -72, -75, -78, -80,
  116274. -81, -81, -82, -85, -89, -90, -93, -97,
  116275. -101, -107, -114, -999, -999, -999, -999, -999,
  116276. -999, -999, -999, -999, -999, -999, -999, -999},
  116277. { -65, -61, -59, -57, -56, -55, -55, -56,
  116278. -56, -57, -55, -53, -52, -47, -44, -44,
  116279. -50, -44, -41, -39, -39, -42, -40, -46,
  116280. -51, -49, -50, -53, -54, -63, -60, -61,
  116281. -62, -66, -66, -66, -70, -73, -74, -75,
  116282. -76, -75, -79, -85, -89, -91, -96, -102,
  116283. -110, -999, -999, -999, -999, -999, -999, -999},
  116284. { -52, -50, -49, -49, -48, -48, -48, -49,
  116285. -50, -50, -49, -46, -43, -39, -35, -33,
  116286. -38, -36, -32, -29, -32, -32, -32, -35,
  116287. -44, -39, -38, -38, -46, -50, -45, -46,
  116288. -53, -50, -50, -50, -54, -54, -53, -53,
  116289. -56, -57, -59, -66, -70, -72, -74, -79,
  116290. -83, -85, -90, -97, -114, -999, -999, -999}},
  116291. /* 250 Hz */
  116292. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116293. -100, -95, -90, -86, -80, -75, -75, -79,
  116294. -80, -79, -80, -81, -82, -88, -95, -103,
  116295. -110, -999, -999, -999, -999, -999, -999, -999,
  116296. -999, -999, -999, -999, -999, -999, -999, -999,
  116297. -999, -999, -999, -999, -999, -999, -999, -999,
  116298. -999, -999, -999, -999, -999, -999, -999, -999},
  116299. {-999, -999, -999, -999, -108, -103, -98, -93,
  116300. -88, -83, -79, -78, -75, -71, -67, -68,
  116301. -73, -73, -72, -73, -75, -77, -80, -82,
  116302. -88, -93, -100, -107, -114, -999, -999, -999,
  116303. -999, -999, -999, -999, -999, -999, -999, -999,
  116304. -999, -999, -999, -999, -999, -999, -999, -999,
  116305. -999, -999, -999, -999, -999, -999, -999, -999},
  116306. {-999, -999, -999, -110, -105, -101, -96, -90,
  116307. -86, -81, -77, -73, -69, -66, -61, -62,
  116308. -66, -64, -62, -65, -66, -70, -72, -76,
  116309. -81, -80, -84, -90, -95, -102, -110, -999,
  116310. -999, -999, -999, -999, -999, -999, -999, -999,
  116311. -999, -999, -999, -999, -999, -999, -999, -999,
  116312. -999, -999, -999, -999, -999, -999, -999, -999},
  116313. {-999, -999, -999, -107, -103, -97, -92, -88,
  116314. -83, -79, -74, -70, -66, -59, -53, -58,
  116315. -62, -55, -54, -54, -54, -58, -61, -62,
  116316. -72, -70, -72, -75, -78, -80, -81, -80,
  116317. -83, -83, -88, -93, -100, -107, -115, -999,
  116318. -999, -999, -999, -999, -999, -999, -999, -999,
  116319. -999, -999, -999, -999, -999, -999, -999, -999},
  116320. {-999, -999, -999, -105, -100, -95, -90, -85,
  116321. -80, -75, -70, -66, -62, -56, -48, -44,
  116322. -48, -46, -46, -43, -46, -48, -48, -51,
  116323. -58, -58, -59, -60, -62, -62, -61, -61,
  116324. -65, -64, -65, -68, -70, -74, -75, -78,
  116325. -81, -86, -95, -110, -999, -999, -999, -999,
  116326. -999, -999, -999, -999, -999, -999, -999, -999},
  116327. {-999, -999, -105, -100, -95, -90, -85, -80,
  116328. -75, -70, -65, -61, -55, -49, -39, -33,
  116329. -40, -35, -32, -38, -40, -33, -35, -37,
  116330. -46, -41, -45, -44, -46, -42, -45, -46,
  116331. -52, -50, -50, -50, -54, -54, -55, -57,
  116332. -62, -64, -66, -68, -70, -76, -81, -90,
  116333. -100, -110, -999, -999, -999, -999, -999, -999}},
  116334. /* 354 hz */
  116335. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116336. -105, -98, -90, -85, -82, -83, -80, -78,
  116337. -84, -79, -80, -83, -87, -89, -91, -93,
  116338. -99, -106, -117, -999, -999, -999, -999, -999,
  116339. -999, -999, -999, -999, -999, -999, -999, -999,
  116340. -999, -999, -999, -999, -999, -999, -999, -999,
  116341. -999, -999, -999, -999, -999, -999, -999, -999},
  116342. {-999, -999, -999, -999, -999, -999, -999, -999,
  116343. -105, -98, -90, -85, -80, -75, -70, -68,
  116344. -74, -72, -74, -77, -80, -82, -85, -87,
  116345. -92, -89, -91, -95, -100, -106, -112, -999,
  116346. -999, -999, -999, -999, -999, -999, -999, -999,
  116347. -999, -999, -999, -999, -999, -999, -999, -999,
  116348. -999, -999, -999, -999, -999, -999, -999, -999},
  116349. {-999, -999, -999, -999, -999, -999, -999, -999,
  116350. -105, -98, -90, -83, -75, -71, -63, -64,
  116351. -67, -62, -64, -67, -70, -73, -77, -81,
  116352. -84, -83, -85, -89, -90, -93, -98, -104,
  116353. -109, -114, -999, -999, -999, -999, -999, -999,
  116354. -999, -999, -999, -999, -999, -999, -999, -999,
  116355. -999, -999, -999, -999, -999, -999, -999, -999},
  116356. {-999, -999, -999, -999, -999, -999, -999, -999,
  116357. -103, -96, -88, -81, -75, -68, -58, -54,
  116358. -56, -54, -56, -56, -58, -60, -63, -66,
  116359. -74, -69, -72, -72, -75, -74, -77, -81,
  116360. -81, -82, -84, -87, -93, -96, -99, -104,
  116361. -110, -999, -999, -999, -999, -999, -999, -999,
  116362. -999, -999, -999, -999, -999, -999, -999, -999},
  116363. {-999, -999, -999, -999, -999, -108, -102, -96,
  116364. -91, -85, -80, -74, -68, -60, -51, -46,
  116365. -48, -46, -43, -45, -47, -47, -49, -48,
  116366. -56, -53, -55, -58, -57, -63, -58, -60,
  116367. -66, -64, -67, -70, -70, -74, -77, -84,
  116368. -86, -89, -91, -93, -94, -101, -109, -118,
  116369. -999, -999, -999, -999, -999, -999, -999, -999},
  116370. {-999, -999, -999, -108, -103, -98, -93, -88,
  116371. -83, -78, -73, -68, -60, -53, -44, -35,
  116372. -38, -38, -34, -34, -36, -40, -41, -44,
  116373. -51, -45, -46, -47, -46, -54, -50, -49,
  116374. -50, -50, -50, -51, -54, -57, -58, -60,
  116375. -66, -66, -66, -64, -65, -68, -77, -82,
  116376. -87, -95, -110, -999, -999, -999, -999, -999}},
  116377. /* 500 Hz */
  116378. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116379. -107, -102, -97, -92, -87, -83, -78, -75,
  116380. -82, -79, -83, -85, -89, -92, -95, -98,
  116381. -101, -105, -109, -113, -999, -999, -999, -999,
  116382. -999, -999, -999, -999, -999, -999, -999, -999,
  116383. -999, -999, -999, -999, -999, -999, -999, -999,
  116384. -999, -999, -999, -999, -999, -999, -999, -999},
  116385. {-999, -999, -999, -999, -999, -999, -999, -106,
  116386. -100, -95, -90, -86, -81, -78, -74, -69,
  116387. -74, -74, -76, -79, -83, -84, -86, -89,
  116388. -92, -97, -93, -100, -103, -107, -110, -999,
  116389. -999, -999, -999, -999, -999, -999, -999, -999,
  116390. -999, -999, -999, -999, -999, -999, -999, -999,
  116391. -999, -999, -999, -999, -999, -999, -999, -999},
  116392. {-999, -999, -999, -999, -999, -999, -106, -100,
  116393. -95, -90, -87, -83, -80, -75, -69, -60,
  116394. -66, -66, -68, -70, -74, -78, -79, -81,
  116395. -81, -83, -84, -87, -93, -96, -99, -103,
  116396. -107, -110, -999, -999, -999, -999, -999, -999,
  116397. -999, -999, -999, -999, -999, -999, -999, -999,
  116398. -999, -999, -999, -999, -999, -999, -999, -999},
  116399. {-999, -999, -999, -999, -999, -108, -103, -98,
  116400. -93, -89, -85, -82, -78, -71, -62, -55,
  116401. -58, -58, -54, -54, -55, -59, -61, -62,
  116402. -70, -66, -66, -67, -70, -72, -75, -78,
  116403. -84, -84, -84, -88, -91, -90, -95, -98,
  116404. -102, -103, -106, -110, -999, -999, -999, -999,
  116405. -999, -999, -999, -999, -999, -999, -999, -999},
  116406. {-999, -999, -999, -999, -108, -103, -98, -94,
  116407. -90, -87, -82, -79, -73, -67, -58, -47,
  116408. -50, -45, -41, -45, -48, -44, -44, -49,
  116409. -54, -51, -48, -47, -49, -50, -51, -57,
  116410. -58, -60, -63, -69, -70, -69, -71, -74,
  116411. -78, -82, -90, -95, -101, -105, -110, -999,
  116412. -999, -999, -999, -999, -999, -999, -999, -999},
  116413. {-999, -999, -999, -105, -101, -97, -93, -90,
  116414. -85, -80, -77, -72, -65, -56, -48, -37,
  116415. -40, -36, -34, -40, -50, -47, -38, -41,
  116416. -47, -38, -35, -39, -38, -43, -40, -45,
  116417. -50, -45, -44, -47, -50, -55, -48, -48,
  116418. -52, -66, -70, -76, -82, -90, -97, -105,
  116419. -110, -999, -999, -999, -999, -999, -999, -999}},
  116420. /* 707 Hz */
  116421. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116422. -999, -108, -103, -98, -93, -86, -79, -76,
  116423. -83, -81, -85, -87, -89, -93, -98, -102,
  116424. -107, -112, -999, -999, -999, -999, -999, -999,
  116425. -999, -999, -999, -999, -999, -999, -999, -999,
  116426. -999, -999, -999, -999, -999, -999, -999, -999,
  116427. -999, -999, -999, -999, -999, -999, -999, -999},
  116428. {-999, -999, -999, -999, -999, -999, -999, -999,
  116429. -999, -108, -103, -98, -93, -86, -79, -71,
  116430. -77, -74, -77, -79, -81, -84, -85, -90,
  116431. -92, -93, -92, -98, -101, -108, -112, -999,
  116432. -999, -999, -999, -999, -999, -999, -999, -999,
  116433. -999, -999, -999, -999, -999, -999, -999, -999,
  116434. -999, -999, -999, -999, -999, -999, -999, -999},
  116435. {-999, -999, -999, -999, -999, -999, -999, -999,
  116436. -108, -103, -98, -93, -87, -78, -68, -65,
  116437. -66, -62, -65, -67, -70, -73, -75, -78,
  116438. -82, -82, -83, -84, -91, -93, -98, -102,
  116439. -106, -110, -999, -999, -999, -999, -999, -999,
  116440. -999, -999, -999, -999, -999, -999, -999, -999,
  116441. -999, -999, -999, -999, -999, -999, -999, -999},
  116442. {-999, -999, -999, -999, -999, -999, -999, -999,
  116443. -105, -100, -95, -90, -82, -74, -62, -57,
  116444. -58, -56, -51, -52, -52, -54, -54, -58,
  116445. -66, -59, -60, -63, -66, -69, -73, -79,
  116446. -83, -84, -80, -81, -81, -82, -88, -92,
  116447. -98, -105, -113, -999, -999, -999, -999, -999,
  116448. -999, -999, -999, -999, -999, -999, -999, -999},
  116449. {-999, -999, -999, -999, -999, -999, -999, -107,
  116450. -102, -97, -92, -84, -79, -69, -57, -47,
  116451. -52, -47, -44, -45, -50, -52, -42, -42,
  116452. -53, -43, -43, -48, -51, -56, -55, -52,
  116453. -57, -59, -61, -62, -67, -71, -78, -83,
  116454. -86, -94, -98, -103, -110, -999, -999, -999,
  116455. -999, -999, -999, -999, -999, -999, -999, -999},
  116456. {-999, -999, -999, -999, -999, -999, -105, -100,
  116457. -95, -90, -84, -78, -70, -61, -51, -41,
  116458. -40, -38, -40, -46, -52, -51, -41, -40,
  116459. -46, -40, -38, -38, -41, -46, -41, -46,
  116460. -47, -43, -43, -45, -41, -45, -56, -67,
  116461. -68, -83, -87, -90, -95, -102, -107, -113,
  116462. -999, -999, -999, -999, -999, -999, -999, -999}},
  116463. /* 1000 Hz */
  116464. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116465. -999, -109, -105, -101, -96, -91, -84, -77,
  116466. -82, -82, -85, -89, -94, -100, -106, -110,
  116467. -999, -999, -999, -999, -999, -999, -999, -999,
  116468. -999, -999, -999, -999, -999, -999, -999, -999,
  116469. -999, -999, -999, -999, -999, -999, -999, -999,
  116470. -999, -999, -999, -999, -999, -999, -999, -999},
  116471. {-999, -999, -999, -999, -999, -999, -999, -999,
  116472. -999, -106, -103, -98, -92, -85, -80, -71,
  116473. -75, -72, -76, -80, -84, -86, -89, -93,
  116474. -100, -107, -113, -999, -999, -999, -999, -999,
  116475. -999, -999, -999, -999, -999, -999, -999, -999,
  116476. -999, -999, -999, -999, -999, -999, -999, -999,
  116477. -999, -999, -999, -999, -999, -999, -999, -999},
  116478. {-999, -999, -999, -999, -999, -999, -999, -107,
  116479. -104, -101, -97, -92, -88, -84, -80, -64,
  116480. -66, -63, -64, -66, -69, -73, -77, -83,
  116481. -83, -86, -91, -98, -104, -111, -999, -999,
  116482. -999, -999, -999, -999, -999, -999, -999, -999,
  116483. -999, -999, -999, -999, -999, -999, -999, -999,
  116484. -999, -999, -999, -999, -999, -999, -999, -999},
  116485. {-999, -999, -999, -999, -999, -999, -999, -107,
  116486. -104, -101, -97, -92, -90, -84, -74, -57,
  116487. -58, -52, -55, -54, -50, -52, -50, -52,
  116488. -63, -62, -69, -76, -77, -78, -78, -79,
  116489. -82, -88, -94, -100, -106, -111, -999, -999,
  116490. -999, -999, -999, -999, -999, -999, -999, -999,
  116491. -999, -999, -999, -999, -999, -999, -999, -999},
  116492. {-999, -999, -999, -999, -999, -999, -106, -102,
  116493. -98, -95, -90, -85, -83, -78, -70, -50,
  116494. -50, -41, -44, -49, -47, -50, -50, -44,
  116495. -55, -46, -47, -48, -48, -54, -49, -49,
  116496. -58, -62, -71, -81, -87, -92, -97, -102,
  116497. -108, -114, -999, -999, -999, -999, -999, -999,
  116498. -999, -999, -999, -999, -999, -999, -999, -999},
  116499. {-999, -999, -999, -999, -999, -999, -106, -102,
  116500. -98, -95, -90, -85, -83, -78, -70, -45,
  116501. -43, -41, -47, -50, -51, -50, -49, -45,
  116502. -47, -41, -44, -41, -39, -43, -38, -37,
  116503. -40, -41, -44, -50, -58, -65, -73, -79,
  116504. -85, -92, -97, -101, -105, -109, -113, -999,
  116505. -999, -999, -999, -999, -999, -999, -999, -999}},
  116506. /* 1414 Hz */
  116507. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116508. -999, -999, -999, -107, -100, -95, -87, -81,
  116509. -85, -83, -88, -93, -100, -107, -114, -999,
  116510. -999, -999, -999, -999, -999, -999, -999, -999,
  116511. -999, -999, -999, -999, -999, -999, -999, -999,
  116512. -999, -999, -999, -999, -999, -999, -999, -999,
  116513. -999, -999, -999, -999, -999, -999, -999, -999},
  116514. {-999, -999, -999, -999, -999, -999, -999, -999,
  116515. -999, -999, -107, -101, -95, -88, -83, -76,
  116516. -73, -72, -79, -84, -90, -95, -100, -105,
  116517. -110, -115, -999, -999, -999, -999, -999, -999,
  116518. -999, -999, -999, -999, -999, -999, -999, -999,
  116519. -999, -999, -999, -999, -999, -999, -999, -999,
  116520. -999, -999, -999, -999, -999, -999, -999, -999},
  116521. {-999, -999, -999, -999, -999, -999, -999, -999,
  116522. -999, -999, -104, -98, -92, -87, -81, -70,
  116523. -65, -62, -67, -71, -74, -80, -85, -91,
  116524. -95, -99, -103, -108, -111, -114, -999, -999,
  116525. -999, -999, -999, -999, -999, -999, -999, -999,
  116526. -999, -999, -999, -999, -999, -999, -999, -999,
  116527. -999, -999, -999, -999, -999, -999, -999, -999},
  116528. {-999, -999, -999, -999, -999, -999, -999, -999,
  116529. -999, -999, -103, -97, -90, -85, -76, -60,
  116530. -56, -54, -60, -62, -61, -56, -63, -65,
  116531. -73, -74, -77, -75, -78, -81, -86, -87,
  116532. -88, -91, -94, -98, -103, -110, -999, -999,
  116533. -999, -999, -999, -999, -999, -999, -999, -999,
  116534. -999, -999, -999, -999, -999, -999, -999, -999},
  116535. {-999, -999, -999, -999, -999, -999, -999, -105,
  116536. -100, -97, -92, -86, -81, -79, -70, -57,
  116537. -51, -47, -51, -58, -60, -56, -53, -50,
  116538. -58, -52, -50, -50, -53, -55, -64, -69,
  116539. -71, -85, -82, -78, -81, -85, -95, -102,
  116540. -112, -999, -999, -999, -999, -999, -999, -999,
  116541. -999, -999, -999, -999, -999, -999, -999, -999},
  116542. {-999, -999, -999, -999, -999, -999, -999, -105,
  116543. -100, -97, -92, -85, -83, -79, -72, -49,
  116544. -40, -43, -43, -54, -56, -51, -50, -40,
  116545. -43, -38, -36, -35, -37, -38, -37, -44,
  116546. -54, -60, -57, -60, -70, -75, -84, -92,
  116547. -103, -112, -999, -999, -999, -999, -999, -999,
  116548. -999, -999, -999, -999, -999, -999, -999, -999}},
  116549. /* 2000 Hz */
  116550. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116551. -999, -999, -999, -110, -102, -95, -89, -82,
  116552. -83, -84, -90, -92, -99, -107, -113, -999,
  116553. -999, -999, -999, -999, -999, -999, -999, -999,
  116554. -999, -999, -999, -999, -999, -999, -999, -999,
  116555. -999, -999, -999, -999, -999, -999, -999, -999,
  116556. -999, -999, -999, -999, -999, -999, -999, -999},
  116557. {-999, -999, -999, -999, -999, -999, -999, -999,
  116558. -999, -999, -107, -101, -95, -89, -83, -72,
  116559. -74, -78, -85, -88, -88, -90, -92, -98,
  116560. -105, -111, -999, -999, -999, -999, -999, -999,
  116561. -999, -999, -999, -999, -999, -999, -999, -999,
  116562. -999, -999, -999, -999, -999, -999, -999, -999,
  116563. -999, -999, -999, -999, -999, -999, -999, -999},
  116564. {-999, -999, -999, -999, -999, -999, -999, -999,
  116565. -999, -109, -103, -97, -93, -87, -81, -70,
  116566. -70, -67, -75, -73, -76, -79, -81, -83,
  116567. -88, -89, -97, -103, -110, -999, -999, -999,
  116568. -999, -999, -999, -999, -999, -999, -999, -999,
  116569. -999, -999, -999, -999, -999, -999, -999, -999,
  116570. -999, -999, -999, -999, -999, -999, -999, -999},
  116571. {-999, -999, -999, -999, -999, -999, -999, -999,
  116572. -999, -107, -100, -94, -88, -83, -75, -63,
  116573. -59, -59, -63, -66, -60, -62, -67, -67,
  116574. -77, -76, -81, -88, -86, -92, -96, -102,
  116575. -109, -116, -999, -999, -999, -999, -999, -999,
  116576. -999, -999, -999, -999, -999, -999, -999, -999,
  116577. -999, -999, -999, -999, -999, -999, -999, -999},
  116578. {-999, -999, -999, -999, -999, -999, -999, -999,
  116579. -999, -105, -98, -92, -86, -81, -73, -56,
  116580. -52, -47, -55, -60, -58, -52, -51, -45,
  116581. -49, -50, -53, -54, -61, -71, -70, -69,
  116582. -78, -79, -87, -90, -96, -104, -112, -999,
  116583. -999, -999, -999, -999, -999, -999, -999, -999,
  116584. -999, -999, -999, -999, -999, -999, -999, -999},
  116585. {-999, -999, -999, -999, -999, -999, -999, -999,
  116586. -999, -103, -96, -90, -86, -78, -70, -51,
  116587. -42, -47, -48, -55, -54, -54, -53, -42,
  116588. -35, -28, -33, -38, -37, -44, -47, -49,
  116589. -54, -63, -68, -78, -82, -89, -94, -99,
  116590. -104, -109, -114, -999, -999, -999, -999, -999,
  116591. -999, -999, -999, -999, -999, -999, -999, -999}},
  116592. /* 2828 Hz */
  116593. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116594. -999, -999, -999, -999, -110, -100, -90, -79,
  116595. -85, -81, -82, -82, -89, -94, -99, -103,
  116596. -109, -115, -999, -999, -999, -999, -999, -999,
  116597. -999, -999, -999, -999, -999, -999, -999, -999,
  116598. -999, -999, -999, -999, -999, -999, -999, -999,
  116599. -999, -999, -999, -999, -999, -999, -999, -999},
  116600. {-999, -999, -999, -999, -999, -999, -999, -999,
  116601. -999, -999, -999, -999, -105, -97, -85, -72,
  116602. -74, -70, -70, -70, -76, -85, -91, -93,
  116603. -97, -103, -109, -115, -999, -999, -999, -999,
  116604. -999, -999, -999, -999, -999, -999, -999, -999,
  116605. -999, -999, -999, -999, -999, -999, -999, -999,
  116606. -999, -999, -999, -999, -999, -999, -999, -999},
  116607. {-999, -999, -999, -999, -999, -999, -999, -999,
  116608. -999, -999, -999, -999, -112, -93, -81, -68,
  116609. -62, -60, -60, -57, -63, -70, -77, -82,
  116610. -90, -93, -98, -104, -109, -113, -999, -999,
  116611. -999, -999, -999, -999, -999, -999, -999, -999,
  116612. -999, -999, -999, -999, -999, -999, -999, -999,
  116613. -999, -999, -999, -999, -999, -999, -999, -999},
  116614. {-999, -999, -999, -999, -999, -999, -999, -999,
  116615. -999, -999, -999, -113, -100, -93, -84, -63,
  116616. -58, -48, -53, -54, -52, -52, -57, -64,
  116617. -66, -76, -83, -81, -85, -85, -90, -95,
  116618. -98, -101, -103, -106, -108, -111, -999, -999,
  116619. -999, -999, -999, -999, -999, -999, -999, -999,
  116620. -999, -999, -999, -999, -999, -999, -999, -999},
  116621. {-999, -999, -999, -999, -999, -999, -999, -999,
  116622. -999, -999, -999, -105, -95, -86, -74, -53,
  116623. -50, -38, -43, -49, -43, -42, -39, -39,
  116624. -46, -52, -57, -56, -72, -69, -74, -81,
  116625. -87, -92, -94, -97, -99, -102, -105, -108,
  116626. -999, -999, -999, -999, -999, -999, -999, -999,
  116627. -999, -999, -999, -999, -999, -999, -999, -999},
  116628. {-999, -999, -999, -999, -999, -999, -999, -999,
  116629. -999, -999, -108, -99, -90, -76, -66, -45,
  116630. -43, -41, -44, -47, -43, -47, -40, -30,
  116631. -31, -31, -39, -33, -40, -41, -43, -53,
  116632. -59, -70, -73, -77, -79, -82, -84, -87,
  116633. -999, -999, -999, -999, -999, -999, -999, -999,
  116634. -999, -999, -999, -999, -999, -999, -999, -999}},
  116635. /* 4000 Hz */
  116636. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116637. -999, -999, -999, -999, -999, -110, -91, -76,
  116638. -75, -85, -93, -98, -104, -110, -999, -999,
  116639. -999, -999, -999, -999, -999, -999, -999, -999,
  116640. -999, -999, -999, -999, -999, -999, -999, -999,
  116641. -999, -999, -999, -999, -999, -999, -999, -999,
  116642. -999, -999, -999, -999, -999, -999, -999, -999},
  116643. {-999, -999, -999, -999, -999, -999, -999, -999,
  116644. -999, -999, -999, -999, -999, -110, -91, -70,
  116645. -70, -75, -86, -89, -94, -98, -101, -106,
  116646. -110, -999, -999, -999, -999, -999, -999, -999,
  116647. -999, -999, -999, -999, -999, -999, -999, -999,
  116648. -999, -999, -999, -999, -999, -999, -999, -999,
  116649. -999, -999, -999, -999, -999, -999, -999, -999},
  116650. {-999, -999, -999, -999, -999, -999, -999, -999,
  116651. -999, -999, -999, -999, -110, -95, -80, -60,
  116652. -65, -64, -74, -83, -88, -91, -95, -99,
  116653. -103, -107, -110, -999, -999, -999, -999, -999,
  116654. -999, -999, -999, -999, -999, -999, -999, -999,
  116655. -999, -999, -999, -999, -999, -999, -999, -999,
  116656. -999, -999, -999, -999, -999, -999, -999, -999},
  116657. {-999, -999, -999, -999, -999, -999, -999, -999,
  116658. -999, -999, -999, -999, -110, -95, -80, -58,
  116659. -55, -49, -66, -68, -71, -78, -78, -80,
  116660. -88, -85, -89, -97, -100, -105, -110, -999,
  116661. -999, -999, -999, -999, -999, -999, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999,
  116663. -999, -999, -999, -999, -999, -999, -999, -999},
  116664. {-999, -999, -999, -999, -999, -999, -999, -999,
  116665. -999, -999, -999, -999, -110, -95, -80, -53,
  116666. -52, -41, -59, -59, -49, -58, -56, -63,
  116667. -86, -79, -90, -93, -98, -103, -107, -112,
  116668. -999, -999, -999, -999, -999, -999, -999, -999,
  116669. -999, -999, -999, -999, -999, -999, -999, -999,
  116670. -999, -999, -999, -999, -999, -999, -999, -999},
  116671. {-999, -999, -999, -999, -999, -999, -999, -999,
  116672. -999, -999, -999, -110, -97, -91, -73, -45,
  116673. -40, -33, -53, -61, -49, -54, -50, -50,
  116674. -60, -52, -67, -74, -81, -92, -96, -100,
  116675. -105, -110, -999, -999, -999, -999, -999, -999,
  116676. -999, -999, -999, -999, -999, -999, -999, -999,
  116677. -999, -999, -999, -999, -999, -999, -999, -999}},
  116678. /* 5657 Hz */
  116679. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116680. -999, -999, -999, -113, -106, -99, -92, -77,
  116681. -80, -88, -97, -106, -115, -999, -999, -999,
  116682. -999, -999, -999, -999, -999, -999, -999, -999,
  116683. -999, -999, -999, -999, -999, -999, -999, -999,
  116684. -999, -999, -999, -999, -999, -999, -999, -999,
  116685. -999, -999, -999, -999, -999, -999, -999, -999},
  116686. {-999, -999, -999, -999, -999, -999, -999, -999,
  116687. -999, -999, -116, -109, -102, -95, -89, -74,
  116688. -72, -88, -87, -95, -102, -109, -116, -999,
  116689. -999, -999, -999, -999, -999, -999, -999, -999,
  116690. -999, -999, -999, -999, -999, -999, -999, -999,
  116691. -999, -999, -999, -999, -999, -999, -999, -999,
  116692. -999, -999, -999, -999, -999, -999, -999, -999},
  116693. {-999, -999, -999, -999, -999, -999, -999, -999,
  116694. -999, -999, -116, -109, -102, -95, -89, -75,
  116695. -66, -74, -77, -78, -86, -87, -90, -96,
  116696. -105, -115, -999, -999, -999, -999, -999, -999,
  116697. -999, -999, -999, -999, -999, -999, -999, -999,
  116698. -999, -999, -999, -999, -999, -999, -999, -999,
  116699. -999, -999, -999, -999, -999, -999, -999, -999},
  116700. {-999, -999, -999, -999, -999, -999, -999, -999,
  116701. -999, -999, -115, -108, -101, -94, -88, -66,
  116702. -56, -61, -70, -65, -78, -72, -83, -84,
  116703. -93, -98, -105, -110, -999, -999, -999, -999,
  116704. -999, -999, -999, -999, -999, -999, -999, -999,
  116705. -999, -999, -999, -999, -999, -999, -999, -999,
  116706. -999, -999, -999, -999, -999, -999, -999, -999},
  116707. {-999, -999, -999, -999, -999, -999, -999, -999,
  116708. -999, -999, -110, -105, -95, -89, -82, -57,
  116709. -52, -52, -59, -56, -59, -58, -69, -67,
  116710. -88, -82, -82, -89, -94, -100, -108, -999,
  116711. -999, -999, -999, -999, -999, -999, -999, -999,
  116712. -999, -999, -999, -999, -999, -999, -999, -999,
  116713. -999, -999, -999, -999, -999, -999, -999, -999},
  116714. {-999, -999, -999, -999, -999, -999, -999, -999,
  116715. -999, -110, -101, -96, -90, -83, -77, -54,
  116716. -43, -38, -50, -48, -52, -48, -42, -42,
  116717. -51, -52, -53, -59, -65, -71, -78, -85,
  116718. -95, -999, -999, -999, -999, -999, -999, -999,
  116719. -999, -999, -999, -999, -999, -999, -999, -999,
  116720. -999, -999, -999, -999, -999, -999, -999, -999}},
  116721. /* 8000 Hz */
  116722. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116723. -999, -999, -999, -999, -120, -105, -86, -68,
  116724. -78, -79, -90, -100, -110, -999, -999, -999,
  116725. -999, -999, -999, -999, -999, -999, -999, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999,
  116727. -999, -999, -999, -999, -999, -999, -999, -999,
  116728. -999, -999, -999, -999, -999, -999, -999, -999},
  116729. {-999, -999, -999, -999, -999, -999, -999, -999,
  116730. -999, -999, -999, -999, -120, -105, -86, -66,
  116731. -73, -77, -88, -96, -105, -115, -999, -999,
  116732. -999, -999, -999, -999, -999, -999, -999, -999,
  116733. -999, -999, -999, -999, -999, -999, -999, -999,
  116734. -999, -999, -999, -999, -999, -999, -999, -999,
  116735. -999, -999, -999, -999, -999, -999, -999, -999},
  116736. {-999, -999, -999, -999, -999, -999, -999, -999,
  116737. -999, -999, -999, -120, -105, -92, -80, -61,
  116738. -64, -68, -80, -87, -92, -100, -110, -999,
  116739. -999, -999, -999, -999, -999, -999, -999, -999,
  116740. -999, -999, -999, -999, -999, -999, -999, -999,
  116741. -999, -999, -999, -999, -999, -999, -999, -999,
  116742. -999, -999, -999, -999, -999, -999, -999, -999},
  116743. {-999, -999, -999, -999, -999, -999, -999, -999,
  116744. -999, -999, -999, -120, -104, -91, -79, -52,
  116745. -60, -54, -64, -69, -77, -80, -82, -84,
  116746. -85, -87, -88, -90, -999, -999, -999, -999,
  116747. -999, -999, -999, -999, -999, -999, -999, -999,
  116748. -999, -999, -999, -999, -999, -999, -999, -999,
  116749. -999, -999, -999, -999, -999, -999, -999, -999},
  116750. {-999, -999, -999, -999, -999, -999, -999, -999,
  116751. -999, -999, -999, -118, -100, -87, -77, -49,
  116752. -50, -44, -58, -61, -61, -67, -65, -62,
  116753. -62, -62, -65, -68, -999, -999, -999, -999,
  116754. -999, -999, -999, -999, -999, -999, -999, -999,
  116755. -999, -999, -999, -999, -999, -999, -999, -999,
  116756. -999, -999, -999, -999, -999, -999, -999, -999},
  116757. {-999, -999, -999, -999, -999, -999, -999, -999,
  116758. -999, -999, -999, -115, -98, -84, -62, -49,
  116759. -44, -38, -46, -49, -49, -46, -39, -37,
  116760. -39, -40, -42, -43, -999, -999, -999, -999,
  116761. -999, -999, -999, -999, -999, -999, -999, -999,
  116762. -999, -999, -999, -999, -999, -999, -999, -999,
  116763. -999, -999, -999, -999, -999, -999, -999, -999}},
  116764. /* 11314 Hz */
  116765. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116766. -999, -999, -999, -999, -999, -110, -88, -74,
  116767. -77, -82, -82, -85, -90, -94, -99, -104,
  116768. -999, -999, -999, -999, -999, -999, -999, -999,
  116769. -999, -999, -999, -999, -999, -999, -999, -999,
  116770. -999, -999, -999, -999, -999, -999, -999, -999,
  116771. -999, -999, -999, -999, -999, -999, -999, -999},
  116772. {-999, -999, -999, -999, -999, -999, -999, -999,
  116773. -999, -999, -999, -999, -999, -110, -88, -66,
  116774. -70, -81, -80, -81, -84, -88, -91, -93,
  116775. -999, -999, -999, -999, -999, -999, -999, -999,
  116776. -999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -999, -999, -999, -999, -999, -999, -999,
  116778. -999, -999, -999, -999, -999, -999, -999, -999},
  116779. {-999, -999, -999, -999, -999, -999, -999, -999,
  116780. -999, -999, -999, -999, -999, -110, -88, -61,
  116781. -63, -70, -71, -74, -77, -80, -83, -85,
  116782. -999, -999, -999, -999, -999, -999, -999, -999,
  116783. -999, -999, -999, -999, -999, -999, -999, -999,
  116784. -999, -999, -999, -999, -999, -999, -999, -999,
  116785. -999, -999, -999, -999, -999, -999, -999, -999},
  116786. {-999, -999, -999, -999, -999, -999, -999, -999,
  116787. -999, -999, -999, -999, -999, -110, -86, -62,
  116788. -63, -62, -62, -58, -52, -50, -50, -52,
  116789. -54, -999, -999, -999, -999, -999, -999, -999,
  116790. -999, -999, -999, -999, -999, -999, -999, -999,
  116791. -999, -999, -999, -999, -999, -999, -999, -999,
  116792. -999, -999, -999, -999, -999, -999, -999, -999},
  116793. {-999, -999, -999, -999, -999, -999, -999, -999,
  116794. -999, -999, -999, -999, -118, -108, -84, -53,
  116795. -50, -50, -50, -55, -47, -45, -40, -40,
  116796. -40, -999, -999, -999, -999, -999, -999, -999,
  116797. -999, -999, -999, -999, -999, -999, -999, -999,
  116798. -999, -999, -999, -999, -999, -999, -999, -999,
  116799. -999, -999, -999, -999, -999, -999, -999, -999},
  116800. {-999, -999, -999, -999, -999, -999, -999, -999,
  116801. -999, -999, -999, -999, -118, -100, -73, -43,
  116802. -37, -42, -43, -53, -38, -37, -35, -35,
  116803. -38, -999, -999, -999, -999, -999, -999, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999,
  116805. -999, -999, -999, -999, -999, -999, -999, -999,
  116806. -999, -999, -999, -999, -999, -999, -999, -999}},
  116807. /* 16000 Hz */
  116808. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116809. -999, -999, -999, -110, -100, -91, -84, -74,
  116810. -80, -80, -80, -80, -80, -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, -999, -999, -999, -999,
  116814. -999, -999, -999, -999, -999, -999, -999, -999},
  116815. {-999, -999, -999, -999, -999, -999, -999, -999,
  116816. -999, -999, -999, -110, -100, -91, -84, -74,
  116817. -68, -68, -68, -68, -68, -999, -999, -999,
  116818. -999, -999, -999, -999, -999, -999, -999, -999,
  116819. -999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -999, -999, -999, -999, -999, -999,
  116821. -999, -999, -999, -999, -999, -999, -999, -999},
  116822. {-999, -999, -999, -999, -999, -999, -999, -999,
  116823. -999, -999, -999, -110, -100, -86, -78, -70,
  116824. -60, -45, -30, -21, -999, -999, -999, -999,
  116825. -999, -999, -999, -999, -999, -999, -999, -999,
  116826. -999, -999, -999, -999, -999, -999, -999, -999,
  116827. -999, -999, -999, -999, -999, -999, -999, -999,
  116828. -999, -999, -999, -999, -999, -999, -999, -999},
  116829. {-999, -999, -999, -999, -999, -999, -999, -999,
  116830. -999, -999, -999, -110, -100, -87, -78, -67,
  116831. -48, -38, -29, -21, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999,
  116833. -999, -999, -999, -999, -999, -999, -999, -999,
  116834. -999, -999, -999, -999, -999, -999, -999, -999,
  116835. -999, -999, -999, -999, -999, -999, -999, -999},
  116836. {-999, -999, -999, -999, -999, -999, -999, -999,
  116837. -999, -999, -999, -110, -100, -86, -69, -56,
  116838. -45, -35, -33, -29, -999, -999, -999, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999,
  116840. -999, -999, -999, -999, -999, -999, -999, -999,
  116841. -999, -999, -999, -999, -999, -999, -999, -999,
  116842. -999, -999, -999, -999, -999, -999, -999, -999},
  116843. {-999, -999, -999, -999, -999, -999, -999, -999,
  116844. -999, -999, -999, -110, -100, -83, -71, -48,
  116845. -27, -38, -37, -34, -999, -999, -999, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999,
  116848. -999, -999, -999, -999, -999, -999, -999, -999,
  116849. -999, -999, -999, -999, -999, -999, -999, -999}}
  116850. };
  116851. #endif
  116852. /*** End of inlined file: masking.h ***/
  116853. #define NEGINF -9999.f
  116854. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116855. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116856. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116857. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116858. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116859. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116860. look->channels=vi->channels;
  116861. look->ampmax=-9999.;
  116862. look->gi=gi;
  116863. return(look);
  116864. }
  116865. void _vp_global_free(vorbis_look_psy_global *look){
  116866. if(look){
  116867. memset(look,0,sizeof(*look));
  116868. _ogg_free(look);
  116869. }
  116870. }
  116871. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116872. if(i){
  116873. memset(i,0,sizeof(*i));
  116874. _ogg_free(i);
  116875. }
  116876. }
  116877. void _vi_psy_free(vorbis_info_psy *i){
  116878. if(i){
  116879. memset(i,0,sizeof(*i));
  116880. _ogg_free(i);
  116881. }
  116882. }
  116883. static void min_curve(float *c,
  116884. float *c2){
  116885. int i;
  116886. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116887. }
  116888. static void max_curve(float *c,
  116889. float *c2){
  116890. int i;
  116891. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116892. }
  116893. static void attenuate_curve(float *c,float att){
  116894. int i;
  116895. for(i=0;i<EHMER_MAX;i++)
  116896. c[i]+=att;
  116897. }
  116898. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116899. float center_boost, float center_decay_rate){
  116900. int i,j,k,m;
  116901. float ath[EHMER_MAX];
  116902. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116903. float athc[P_LEVELS][EHMER_MAX];
  116904. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116905. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116906. memset(workc,0,sizeof(workc));
  116907. for(i=0;i<P_BANDS;i++){
  116908. /* we add back in the ATH to avoid low level curves falling off to
  116909. -infinity and unnecessarily cutting off high level curves in the
  116910. curve limiting (last step). */
  116911. /* A half-band's settings must be valid over the whole band, and
  116912. it's better to mask too little than too much */
  116913. int ath_offset=i*4;
  116914. for(j=0;j<EHMER_MAX;j++){
  116915. float min=999.;
  116916. for(k=0;k<4;k++)
  116917. if(j+k+ath_offset<MAX_ATH){
  116918. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116919. }else{
  116920. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116921. }
  116922. ath[j]=min;
  116923. }
  116924. /* copy curves into working space, replicate the 50dB curve to 30
  116925. and 40, replicate the 100dB curve to 110 */
  116926. for(j=0;j<6;j++)
  116927. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116928. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116929. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116930. /* apply centered curve boost/decay */
  116931. for(j=0;j<P_LEVELS;j++){
  116932. for(k=0;k<EHMER_MAX;k++){
  116933. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116934. if(adj<0. && center_boost>0)adj=0.;
  116935. if(adj>0. && center_boost<0)adj=0.;
  116936. workc[i][j][k]+=adj;
  116937. }
  116938. }
  116939. /* normalize curves so the driving amplitude is 0dB */
  116940. /* make temp curves with the ATH overlayed */
  116941. for(j=0;j<P_LEVELS;j++){
  116942. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116943. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116944. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116945. max_curve(athc[j],workc[i][j]);
  116946. }
  116947. /* Now limit the louder curves.
  116948. the idea is this: We don't know what the playback attenuation
  116949. will be; 0dB SL moves every time the user twiddles the volume
  116950. knob. So that means we have to use a single 'most pessimal' curve
  116951. for all masking amplitudes, right? Wrong. The *loudest* sound
  116952. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116953. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116954. etc... */
  116955. for(j=1;j<P_LEVELS;j++){
  116956. min_curve(athc[j],athc[j-1]);
  116957. min_curve(workc[i][j],athc[j]);
  116958. }
  116959. }
  116960. for(i=0;i<P_BANDS;i++){
  116961. int hi_curve,lo_curve,bin;
  116962. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116963. /* low frequency curves are measured with greater resolution than
  116964. the MDCT/FFT will actually give us; we want the curve applied
  116965. to the tone data to be pessimistic and thus apply the minimum
  116966. masking possible for a given bin. That means that a single bin
  116967. could span more than one octave and that the curve will be a
  116968. composite of multiple octaves. It also may mean that a single
  116969. bin may span > an eighth of an octave and that the eighth
  116970. octave values may also be composited. */
  116971. /* which octave curves will we be compositing? */
  116972. bin=floor(fromOC(i*.5)/binHz);
  116973. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116974. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116975. if(lo_curve>i)lo_curve=i;
  116976. if(lo_curve<0)lo_curve=0;
  116977. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116978. for(m=0;m<P_LEVELS;m++){
  116979. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116980. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116981. /* render the curve into bins, then pull values back into curve.
  116982. The point is that any inherent subsampling aliasing results in
  116983. a safe minimum */
  116984. for(k=lo_curve;k<=hi_curve;k++){
  116985. int l=0;
  116986. for(j=0;j<EHMER_MAX;j++){
  116987. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116988. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116989. if(lo_bin<0)lo_bin=0;
  116990. if(lo_bin>n)lo_bin=n;
  116991. if(lo_bin<l)l=lo_bin;
  116992. if(hi_bin<0)hi_bin=0;
  116993. if(hi_bin>n)hi_bin=n;
  116994. for(;l<hi_bin && l<n;l++)
  116995. if(brute_buffer[l]>workc[k][m][j])
  116996. brute_buffer[l]=workc[k][m][j];
  116997. }
  116998. for(;l<n;l++)
  116999. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117000. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117001. }
  117002. /* be equally paranoid about being valid up to next half ocatve */
  117003. if(i+1<P_BANDS){
  117004. int l=0;
  117005. k=i+1;
  117006. for(j=0;j<EHMER_MAX;j++){
  117007. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117008. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117009. if(lo_bin<0)lo_bin=0;
  117010. if(lo_bin>n)lo_bin=n;
  117011. if(lo_bin<l)l=lo_bin;
  117012. if(hi_bin<0)hi_bin=0;
  117013. if(hi_bin>n)hi_bin=n;
  117014. for(;l<hi_bin && l<n;l++)
  117015. if(brute_buffer[l]>workc[k][m][j])
  117016. brute_buffer[l]=workc[k][m][j];
  117017. }
  117018. for(;l<n;l++)
  117019. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117020. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117021. }
  117022. for(j=0;j<EHMER_MAX;j++){
  117023. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117024. if(bin<0){
  117025. ret[i][m][j+2]=-999.;
  117026. }else{
  117027. if(bin>=n){
  117028. ret[i][m][j+2]=-999.;
  117029. }else{
  117030. ret[i][m][j+2]=brute_buffer[bin];
  117031. }
  117032. }
  117033. }
  117034. /* add fenceposts */
  117035. for(j=0;j<EHMER_OFFSET;j++)
  117036. if(ret[i][m][j+2]>-200.f)break;
  117037. ret[i][m][0]=j;
  117038. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117039. if(ret[i][m][j+2]>-200.f)
  117040. break;
  117041. ret[i][m][1]=j;
  117042. }
  117043. }
  117044. return(ret);
  117045. }
  117046. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117047. vorbis_info_psy_global *gi,int n,long rate){
  117048. long i,j,lo=-99,hi=1;
  117049. long maxoc;
  117050. memset(p,0,sizeof(*p));
  117051. p->eighth_octave_lines=gi->eighth_octave_lines;
  117052. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117053. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117054. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117055. p->total_octave_lines=maxoc-p->firstoc+1;
  117056. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117057. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117058. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117059. p->vi=vi;
  117060. p->n=n;
  117061. p->rate=rate;
  117062. /* AoTuV HF weighting */
  117063. p->m_val = 1.;
  117064. if(rate < 26000) p->m_val = 0;
  117065. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117066. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117067. /* set up the lookups for a given blocksize and sample rate */
  117068. for(i=0,j=0;i<MAX_ATH-1;i++){
  117069. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117070. float base=ATH[i];
  117071. if(j<endpos){
  117072. float delta=(ATH[i+1]-base)/(endpos-j);
  117073. for(;j<endpos && j<n;j++){
  117074. p->ath[j]=base+100.;
  117075. base+=delta;
  117076. }
  117077. }
  117078. }
  117079. for(i=0;i<n;i++){
  117080. float bark=toBARK(rate/(2*n)*i);
  117081. for(;lo+vi->noisewindowlomin<i &&
  117082. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117083. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117084. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117085. p->bark[i]=((lo-1)<<16)+(hi-1);
  117086. }
  117087. for(i=0;i<n;i++)
  117088. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117089. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117090. vi->tone_centerboost,vi->tone_decay);
  117091. /* set up rolling noise median */
  117092. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117093. for(i=0;i<P_NOISECURVES;i++)
  117094. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117095. for(i=0;i<n;i++){
  117096. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117097. int inthalfoc;
  117098. float del;
  117099. if(halfoc<0)halfoc=0;
  117100. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117101. inthalfoc=(int)halfoc;
  117102. del=halfoc-inthalfoc;
  117103. for(j=0;j<P_NOISECURVES;j++)
  117104. p->noiseoffset[j][i]=
  117105. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117106. p->vi->noiseoff[j][inthalfoc+1]*del;
  117107. }
  117108. #if 0
  117109. {
  117110. static int ls=0;
  117111. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117112. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117113. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117114. }
  117115. #endif
  117116. }
  117117. void _vp_psy_clear(vorbis_look_psy *p){
  117118. int i,j;
  117119. if(p){
  117120. if(p->ath)_ogg_free(p->ath);
  117121. if(p->octave)_ogg_free(p->octave);
  117122. if(p->bark)_ogg_free(p->bark);
  117123. if(p->tonecurves){
  117124. for(i=0;i<P_BANDS;i++){
  117125. for(j=0;j<P_LEVELS;j++){
  117126. _ogg_free(p->tonecurves[i][j]);
  117127. }
  117128. _ogg_free(p->tonecurves[i]);
  117129. }
  117130. _ogg_free(p->tonecurves);
  117131. }
  117132. if(p->noiseoffset){
  117133. for(i=0;i<P_NOISECURVES;i++){
  117134. _ogg_free(p->noiseoffset[i]);
  117135. }
  117136. _ogg_free(p->noiseoffset);
  117137. }
  117138. memset(p,0,sizeof(*p));
  117139. }
  117140. }
  117141. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117142. static void seed_curve(float *seed,
  117143. const float **curves,
  117144. float amp,
  117145. int oc, int n,
  117146. int linesper,float dBoffset){
  117147. int i,post1;
  117148. int seedptr;
  117149. const float *posts,*curve;
  117150. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117151. choice=max(choice,0);
  117152. choice=min(choice,P_LEVELS-1);
  117153. posts=curves[choice];
  117154. curve=posts+2;
  117155. post1=(int)posts[1];
  117156. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117157. for(i=posts[0];i<post1;i++){
  117158. if(seedptr>0){
  117159. float lin=amp+curve[i];
  117160. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117161. }
  117162. seedptr+=linesper;
  117163. if(seedptr>=n)break;
  117164. }
  117165. }
  117166. static void seed_loop(vorbis_look_psy *p,
  117167. const float ***curves,
  117168. const float *f,
  117169. const float *flr,
  117170. float *seed,
  117171. float specmax){
  117172. vorbis_info_psy *vi=p->vi;
  117173. long n=p->n,i;
  117174. float dBoffset=vi->max_curve_dB-specmax;
  117175. /* prime the working vector with peak values */
  117176. for(i=0;i<n;i++){
  117177. float max=f[i];
  117178. long oc=p->octave[i];
  117179. while(i+1<n && p->octave[i+1]==oc){
  117180. i++;
  117181. if(f[i]>max)max=f[i];
  117182. }
  117183. if(max+6.f>flr[i]){
  117184. oc=oc>>p->shiftoc;
  117185. if(oc>=P_BANDS)oc=P_BANDS-1;
  117186. if(oc<0)oc=0;
  117187. seed_curve(seed,
  117188. curves[oc],
  117189. max,
  117190. p->octave[i]-p->firstoc,
  117191. p->total_octave_lines,
  117192. p->eighth_octave_lines,
  117193. dBoffset);
  117194. }
  117195. }
  117196. }
  117197. static void seed_chase(float *seeds, int linesper, long n){
  117198. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117199. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117200. long stack=0;
  117201. long pos=0;
  117202. long i;
  117203. for(i=0;i<n;i++){
  117204. if(stack<2){
  117205. posstack[stack]=i;
  117206. ampstack[stack++]=seeds[i];
  117207. }else{
  117208. while(1){
  117209. if(seeds[i]<ampstack[stack-1]){
  117210. posstack[stack]=i;
  117211. ampstack[stack++]=seeds[i];
  117212. break;
  117213. }else{
  117214. if(i<posstack[stack-1]+linesper){
  117215. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117216. i<posstack[stack-2]+linesper){
  117217. /* we completely overlap, making stack-1 irrelevant. pop it */
  117218. stack--;
  117219. continue;
  117220. }
  117221. }
  117222. posstack[stack]=i;
  117223. ampstack[stack++]=seeds[i];
  117224. break;
  117225. }
  117226. }
  117227. }
  117228. }
  117229. /* the stack now contains only the positions that are relevant. Scan
  117230. 'em straight through */
  117231. for(i=0;i<stack;i++){
  117232. long endpos;
  117233. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117234. endpos=posstack[i+1];
  117235. }else{
  117236. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117237. discarded in short frames */
  117238. }
  117239. if(endpos>n)endpos=n;
  117240. for(;pos<endpos;pos++)
  117241. seeds[pos]=ampstack[i];
  117242. }
  117243. /* there. Linear time. I now remember this was on a problem set I
  117244. had in Grad Skool... I didn't solve it at the time ;-) */
  117245. }
  117246. /* bleaugh, this is more complicated than it needs to be */
  117247. #include<stdio.h>
  117248. static void max_seeds(vorbis_look_psy *p,
  117249. float *seed,
  117250. float *flr){
  117251. long n=p->total_octave_lines;
  117252. int linesper=p->eighth_octave_lines;
  117253. long linpos=0;
  117254. long pos;
  117255. seed_chase(seed,linesper,n); /* for masking */
  117256. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117257. while(linpos+1<p->n){
  117258. float minV=seed[pos];
  117259. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117260. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117261. while(pos+1<=end){
  117262. pos++;
  117263. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117264. minV=seed[pos];
  117265. }
  117266. end=pos+p->firstoc;
  117267. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117268. if(flr[linpos]<minV)flr[linpos]=minV;
  117269. }
  117270. {
  117271. float minV=seed[p->total_octave_lines-1];
  117272. for(;linpos<p->n;linpos++)
  117273. if(flr[linpos]<minV)flr[linpos]=minV;
  117274. }
  117275. }
  117276. static void bark_noise_hybridmp(int n,const long *b,
  117277. const float *f,
  117278. float *noise,
  117279. const float offset,
  117280. const int fixed){
  117281. float *N=(float*) alloca(n*sizeof(*N));
  117282. float *X=(float*) alloca(n*sizeof(*N));
  117283. float *XX=(float*) alloca(n*sizeof(*N));
  117284. float *Y=(float*) alloca(n*sizeof(*N));
  117285. float *XY=(float*) alloca(n*sizeof(*N));
  117286. float tN, tX, tXX, tY, tXY;
  117287. int i;
  117288. int lo, hi;
  117289. float R, A, B, D;
  117290. float w, x, y;
  117291. tN = tX = tXX = tY = tXY = 0.f;
  117292. y = f[0] + offset;
  117293. if (y < 1.f) y = 1.f;
  117294. w = y * y * .5;
  117295. tN += w;
  117296. tX += w;
  117297. tY += w * y;
  117298. N[0] = tN;
  117299. X[0] = tX;
  117300. XX[0] = tXX;
  117301. Y[0] = tY;
  117302. XY[0] = tXY;
  117303. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117304. y = f[i] + offset;
  117305. if (y < 1.f) y = 1.f;
  117306. w = y * y;
  117307. tN += w;
  117308. tX += w * x;
  117309. tXX += w * x * x;
  117310. tY += w * y;
  117311. tXY += w * x * y;
  117312. N[i] = tN;
  117313. X[i] = tX;
  117314. XX[i] = tXX;
  117315. Y[i] = tY;
  117316. XY[i] = tXY;
  117317. }
  117318. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117319. lo = b[i] >> 16;
  117320. if( lo>=0 ) break;
  117321. hi = b[i] & 0xffff;
  117322. tN = N[hi] + N[-lo];
  117323. tX = X[hi] - X[-lo];
  117324. tXX = XX[hi] + XX[-lo];
  117325. tY = Y[hi] + Y[-lo];
  117326. tXY = XY[hi] - XY[-lo];
  117327. A = tY * tXX - tX * tXY;
  117328. B = tN * tXY - tX * tY;
  117329. D = tN * tXX - tX * tX;
  117330. R = (A + x * B) / D;
  117331. if (R < 0.f)
  117332. R = 0.f;
  117333. noise[i] = R - offset;
  117334. }
  117335. for ( ;; i++, x += 1.f) {
  117336. lo = b[i] >> 16;
  117337. hi = b[i] & 0xffff;
  117338. if(hi>=n)break;
  117339. tN = N[hi] - N[lo];
  117340. tX = X[hi] - X[lo];
  117341. tXX = XX[hi] - XX[lo];
  117342. tY = Y[hi] - Y[lo];
  117343. tXY = XY[hi] - XY[lo];
  117344. A = tY * tXX - tX * tXY;
  117345. B = tN * tXY - tX * tY;
  117346. D = tN * tXX - tX * tX;
  117347. R = (A + x * B) / D;
  117348. if (R < 0.f) R = 0.f;
  117349. noise[i] = R - offset;
  117350. }
  117351. for ( ; i < n; i++, x += 1.f) {
  117352. R = (A + x * B) / D;
  117353. if (R < 0.f) R = 0.f;
  117354. noise[i] = R - offset;
  117355. }
  117356. if (fixed <= 0) return;
  117357. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117358. hi = i + fixed / 2;
  117359. lo = hi - fixed;
  117360. if(lo>=0)break;
  117361. tN = N[hi] + N[-lo];
  117362. tX = X[hi] - X[-lo];
  117363. tXX = XX[hi] + XX[-lo];
  117364. tY = Y[hi] + Y[-lo];
  117365. tXY = XY[hi] - XY[-lo];
  117366. A = tY * tXX - tX * tXY;
  117367. B = tN * tXY - tX * tY;
  117368. D = tN * tXX - tX * tX;
  117369. R = (A + x * B) / D;
  117370. if (R - offset < noise[i]) noise[i] = R - offset;
  117371. }
  117372. for ( ;; i++, x += 1.f) {
  117373. hi = i + fixed / 2;
  117374. lo = hi - fixed;
  117375. if(hi>=n)break;
  117376. tN = N[hi] - N[lo];
  117377. tX = X[hi] - X[lo];
  117378. tXX = XX[hi] - XX[lo];
  117379. tY = Y[hi] - Y[lo];
  117380. tXY = XY[hi] - XY[lo];
  117381. A = tY * tXX - tX * tXY;
  117382. B = tN * tXY - tX * tY;
  117383. D = tN * tXX - tX * tX;
  117384. R = (A + x * B) / D;
  117385. if (R - offset < noise[i]) noise[i] = R - offset;
  117386. }
  117387. for ( ; i < n; i++, x += 1.f) {
  117388. R = (A + x * B) / D;
  117389. if (R - offset < noise[i]) noise[i] = R - offset;
  117390. }
  117391. }
  117392. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117393. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117394. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117395. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117396. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117397. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117398. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117399. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117400. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117401. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117402. 973377.F, 913981.F, 858210.F, 805842.F,
  117403. 756669.F, 710497.F, 667142.F, 626433.F,
  117404. 588208.F, 552316.F, 518613.F, 486967.F,
  117405. 457252.F, 429351.F, 403152.F, 378551.F,
  117406. 355452.F, 333762.F, 313396.F, 294273.F,
  117407. 276316.F, 259455.F, 243623.F, 228757.F,
  117408. 214798.F, 201691.F, 189384.F, 177828.F,
  117409. 166977.F, 156788.F, 147221.F, 138237.F,
  117410. 129802.F, 121881.F, 114444.F, 107461.F,
  117411. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117412. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117413. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117414. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117415. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117416. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117417. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117418. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117419. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117420. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117421. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117422. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117423. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117424. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117425. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117426. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117427. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117428. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117429. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117430. 842.910F, 791.475F, 743.179F, 697.830F,
  117431. 655.249F, 615.265F, 577.722F, 542.469F,
  117432. 509.367F, 478.286F, 449.101F, 421.696F,
  117433. 395.964F, 371.803F, 349.115F, 327.812F,
  117434. 307.809F, 289.026F, 271.390F, 254.830F,
  117435. 239.280F, 224.679F, 210.969F, 198.096F,
  117436. 186.008F, 174.658F, 164.000F, 153.993F,
  117437. 144.596F, 135.773F, 127.488F, 119.708F,
  117438. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117439. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117440. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117441. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117442. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117443. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117444. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117445. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117446. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117447. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117448. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117449. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117450. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117451. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117452. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117453. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117454. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117455. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117456. 1.20790F, 1.13419F, 1.06499F, 1.F
  117457. };
  117458. void _vp_remove_floor(vorbis_look_psy *p,
  117459. float *mdct,
  117460. int *codedflr,
  117461. float *residue,
  117462. int sliding_lowpass){
  117463. int i,n=p->n;
  117464. if(sliding_lowpass>n)sliding_lowpass=n;
  117465. for(i=0;i<sliding_lowpass;i++){
  117466. residue[i]=
  117467. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117468. }
  117469. for(;i<n;i++)
  117470. residue[i]=0.;
  117471. }
  117472. void _vp_noisemask(vorbis_look_psy *p,
  117473. float *logmdct,
  117474. float *logmask){
  117475. int i,n=p->n;
  117476. float *work=(float*) alloca(n*sizeof(*work));
  117477. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117478. 140.,-1);
  117479. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117480. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117481. p->vi->noisewindowfixed);
  117482. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117483. #if 0
  117484. {
  117485. static int seq=0;
  117486. float work2[n];
  117487. for(i=0;i<n;i++){
  117488. work2[i]=logmask[i]+work[i];
  117489. }
  117490. if(seq&1)
  117491. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117492. else
  117493. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117494. if(seq&1)
  117495. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117496. else
  117497. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117498. seq++;
  117499. }
  117500. #endif
  117501. for(i=0;i<n;i++){
  117502. int dB=logmask[i]+.5;
  117503. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117504. if(dB<0)dB=0;
  117505. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117506. }
  117507. }
  117508. void _vp_tonemask(vorbis_look_psy *p,
  117509. float *logfft,
  117510. float *logmask,
  117511. float global_specmax,
  117512. float local_specmax){
  117513. int i,n=p->n;
  117514. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117515. float att=local_specmax+p->vi->ath_adjatt;
  117516. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117517. /* set the ATH (floating below localmax, not global max by a
  117518. specified att) */
  117519. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117520. for(i=0;i<n;i++)
  117521. logmask[i]=p->ath[i]+att;
  117522. /* tone masking */
  117523. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117524. max_seeds(p,seed,logmask);
  117525. }
  117526. void _vp_offset_and_mix(vorbis_look_psy *p,
  117527. float *noise,
  117528. float *tone,
  117529. int offset_select,
  117530. float *logmask,
  117531. float *mdct,
  117532. float *logmdct){
  117533. int i,n=p->n;
  117534. float de, coeffi, cx;/* AoTuV */
  117535. float toneatt=p->vi->tone_masteratt[offset_select];
  117536. cx = p->m_val;
  117537. for(i=0;i<n;i++){
  117538. float val= noise[i]+p->noiseoffset[offset_select][i];
  117539. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117540. logmask[i]=max(val,tone[i]+toneatt);
  117541. /* AoTuV */
  117542. /** @ M1 **
  117543. The following codes improve a noise problem.
  117544. A fundamental idea uses the value of masking and carries out
  117545. the relative compensation of the MDCT.
  117546. However, this code is not perfect and all noise problems cannot be solved.
  117547. by Aoyumi @ 2004/04/18
  117548. */
  117549. if(offset_select == 1) {
  117550. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117551. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117552. if(val > coeffi){
  117553. /* mdct value is > -17.2 dB below floor */
  117554. de = 1.0-((val-coeffi)*0.005*cx);
  117555. /* pro-rated attenuation:
  117556. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117557. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117558. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117559. etc... */
  117560. if(de < 0) de = 0.0001;
  117561. }else
  117562. /* mdct value is <= -17.2 dB below floor */
  117563. de = 1.0-((val-coeffi)*0.0003*cx);
  117564. /* pro-rated attenuation:
  117565. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117566. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117567. etc... */
  117568. mdct[i] *= de;
  117569. }
  117570. }
  117571. }
  117572. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117573. vorbis_info *vi=vd->vi;
  117574. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117575. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117576. int n=ci->blocksizes[vd->W]/2;
  117577. float secs=(float)n/vi->rate;
  117578. amp+=secs*gi->ampmax_att_per_sec;
  117579. if(amp<-9999)amp=-9999;
  117580. return(amp);
  117581. }
  117582. static void couple_lossless(float A, float B,
  117583. float *qA, float *qB){
  117584. int test1=fabs(*qA)>fabs(*qB);
  117585. test1-= fabs(*qA)<fabs(*qB);
  117586. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117587. if(test1==1){
  117588. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117589. }else{
  117590. float temp=*qB;
  117591. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117592. *qA=temp;
  117593. }
  117594. if(*qB>fabs(*qA)*1.9999f){
  117595. *qB= -fabs(*qA)*2.f;
  117596. *qA= -*qA;
  117597. }
  117598. }
  117599. static float hypot_lookup[32]={
  117600. -0.009935, -0.011245, -0.012726, -0.014397,
  117601. -0.016282, -0.018407, -0.020800, -0.023494,
  117602. -0.026522, -0.029923, -0.033737, -0.038010,
  117603. -0.042787, -0.048121, -0.054064, -0.060671,
  117604. -0.068000, -0.076109, -0.085054, -0.094892,
  117605. -0.105675, -0.117451, -0.130260, -0.144134,
  117606. -0.159093, -0.175146, -0.192286, -0.210490,
  117607. -0.229718, -0.249913, -0.271001, -0.292893};
  117608. static void precomputed_couple_point(float premag,
  117609. int floorA,int floorB,
  117610. float *mag, float *ang){
  117611. int test=(floorA>floorB)-1;
  117612. int offset=31-abs(floorA-floorB);
  117613. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117614. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117615. *mag=premag*floormag;
  117616. *ang=0.f;
  117617. }
  117618. /* just like below, this is currently set up to only do
  117619. single-step-depth coupling. Otherwise, we'd have to do more
  117620. copying (which will be inevitable later) */
  117621. /* doing the real circular magnitude calculation is audibly superior
  117622. to (A+B)/sqrt(2) */
  117623. static float dipole_hypot(float a, float b){
  117624. if(a>0.){
  117625. if(b>0.)return sqrt(a*a+b*b);
  117626. if(a>-b)return sqrt(a*a-b*b);
  117627. return -sqrt(b*b-a*a);
  117628. }
  117629. if(b<0.)return -sqrt(a*a+b*b);
  117630. if(-a>b)return -sqrt(a*a-b*b);
  117631. return sqrt(b*b-a*a);
  117632. }
  117633. static float round_hypot(float a, float b){
  117634. if(a>0.){
  117635. if(b>0.)return sqrt(a*a+b*b);
  117636. if(a>-b)return sqrt(a*a+b*b);
  117637. return -sqrt(b*b+a*a);
  117638. }
  117639. if(b<0.)return -sqrt(a*a+b*b);
  117640. if(-a>b)return -sqrt(a*a+b*b);
  117641. return sqrt(b*b+a*a);
  117642. }
  117643. /* revert to round hypot for now */
  117644. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117645. vorbis_info_psy_global *g,
  117646. vorbis_look_psy *p,
  117647. vorbis_info_mapping0 *vi,
  117648. float **mdct){
  117649. int i,j,n=p->n;
  117650. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117651. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117652. for(i=0;i<vi->coupling_steps;i++){
  117653. float *mdctM=mdct[vi->coupling_mag[i]];
  117654. float *mdctA=mdct[vi->coupling_ang[i]];
  117655. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117656. for(j=0;j<limit;j++)
  117657. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117658. for(;j<n;j++)
  117659. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117660. }
  117661. return(ret);
  117662. }
  117663. /* this is for per-channel noise normalization */
  117664. static int JUCE_CDECL apsort(const void *a, const void *b){
  117665. float f1=fabs(**(float**)a);
  117666. float f2=fabs(**(float**)b);
  117667. return (f1<f2)-(f1>f2);
  117668. }
  117669. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117670. vorbis_look_psy *p,
  117671. vorbis_info_mapping0 *vi,
  117672. float **mags){
  117673. if(p->vi->normal_point_p){
  117674. int i,j,k,n=p->n;
  117675. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117676. int partition=p->vi->normal_partition;
  117677. float **work=(float**) alloca(sizeof(*work)*partition);
  117678. for(i=0;i<vi->coupling_steps;i++){
  117679. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117680. for(j=0;j<n;j+=partition){
  117681. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117682. qsort(work,partition,sizeof(*work),apsort);
  117683. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117684. }
  117685. }
  117686. return(ret);
  117687. }
  117688. return(NULL);
  117689. }
  117690. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117691. float *magnitudes,int *sortedindex){
  117692. int i,j,n=p->n;
  117693. vorbis_info_psy *vi=p->vi;
  117694. int partition=vi->normal_partition;
  117695. float **work=(float**) alloca(sizeof(*work)*partition);
  117696. int start=vi->normal_start;
  117697. for(j=start;j<n;j+=partition){
  117698. if(j+partition>n)partition=n-j;
  117699. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117700. qsort(work,partition,sizeof(*work),apsort);
  117701. for(i=0;i<partition;i++){
  117702. sortedindex[i+j-start]=work[i]-magnitudes;
  117703. }
  117704. }
  117705. }
  117706. void _vp_noise_normalize(vorbis_look_psy *p,
  117707. float *in,float *out,int *sortedindex){
  117708. int flag=0,i,j=0,n=p->n;
  117709. vorbis_info_psy *vi=p->vi;
  117710. int partition=vi->normal_partition;
  117711. int start=vi->normal_start;
  117712. if(start>n)start=n;
  117713. if(vi->normal_channel_p){
  117714. for(;j<start;j++)
  117715. out[j]=rint(in[j]);
  117716. for(;j+partition<=n;j+=partition){
  117717. float acc=0.;
  117718. int k;
  117719. for(i=j;i<j+partition;i++)
  117720. acc+=in[i]*in[i];
  117721. for(i=0;i<partition;i++){
  117722. k=sortedindex[i+j-start];
  117723. if(in[k]*in[k]>=.25f){
  117724. out[k]=rint(in[k]);
  117725. acc-=in[k]*in[k];
  117726. flag=1;
  117727. }else{
  117728. if(acc<vi->normal_thresh)break;
  117729. out[k]=unitnorm(in[k]);
  117730. acc-=1.;
  117731. }
  117732. }
  117733. for(;i<partition;i++){
  117734. k=sortedindex[i+j-start];
  117735. out[k]=0.;
  117736. }
  117737. }
  117738. }
  117739. for(;j<n;j++)
  117740. out[j]=rint(in[j]);
  117741. }
  117742. void _vp_couple(int blobno,
  117743. vorbis_info_psy_global *g,
  117744. vorbis_look_psy *p,
  117745. vorbis_info_mapping0 *vi,
  117746. float **res,
  117747. float **mag_memo,
  117748. int **mag_sort,
  117749. int **ifloor,
  117750. int *nonzero,
  117751. int sliding_lowpass){
  117752. int i,j,k,n=p->n;
  117753. /* perform any requested channel coupling */
  117754. /* point stereo can only be used in a first stage (in this encoder)
  117755. because of the dependency on floor lookups */
  117756. for(i=0;i<vi->coupling_steps;i++){
  117757. /* once we're doing multistage coupling in which a channel goes
  117758. through more than one coupling step, the floor vector
  117759. magnitudes will also have to be recalculated an propogated
  117760. along with PCM. Right now, we're not (that will wait until 5.1
  117761. most likely), so the code isn't here yet. The memory management
  117762. here is all assuming single depth couplings anyway. */
  117763. /* make sure coupling a zero and a nonzero channel results in two
  117764. nonzero channels. */
  117765. if(nonzero[vi->coupling_mag[i]] ||
  117766. nonzero[vi->coupling_ang[i]]){
  117767. float *rM=res[vi->coupling_mag[i]];
  117768. float *rA=res[vi->coupling_ang[i]];
  117769. float *qM=rM+n;
  117770. float *qA=rA+n;
  117771. int *floorM=ifloor[vi->coupling_mag[i]];
  117772. int *floorA=ifloor[vi->coupling_ang[i]];
  117773. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117774. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117775. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117776. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117777. int pointlimit=limit;
  117778. nonzero[vi->coupling_mag[i]]=1;
  117779. nonzero[vi->coupling_ang[i]]=1;
  117780. /* The threshold of a stereo is changed with the size of n */
  117781. if(n > 1000)
  117782. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117783. for(j=0;j<p->n;j+=partition){
  117784. float acc=0.f;
  117785. for(k=0;k<partition;k++){
  117786. int l=k+j;
  117787. if(l<sliding_lowpass){
  117788. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117789. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117790. precomputed_couple_point(mag_memo[i][l],
  117791. floorM[l],floorA[l],
  117792. qM+l,qA+l);
  117793. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117794. }else{
  117795. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117796. }
  117797. }else{
  117798. qM[l]=0.;
  117799. qA[l]=0.;
  117800. }
  117801. }
  117802. if(p->vi->normal_point_p){
  117803. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117804. int l=mag_sort[i][j+k];
  117805. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117806. qM[l]=unitnorm(qM[l]);
  117807. acc-=1.f;
  117808. }
  117809. }
  117810. }
  117811. }
  117812. }
  117813. }
  117814. }
  117815. /* AoTuV */
  117816. /** @ M2 **
  117817. The boost problem by the combination of noise normalization and point stereo is eased.
  117818. However, this is a temporary patch.
  117819. by Aoyumi @ 2004/04/18
  117820. */
  117821. void hf_reduction(vorbis_info_psy_global *g,
  117822. vorbis_look_psy *p,
  117823. vorbis_info_mapping0 *vi,
  117824. float **mdct){
  117825. int i,j,n=p->n, de=0.3*p->m_val;
  117826. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117827. for(i=0; i<vi->coupling_steps; i++){
  117828. /* for(j=start; j<limit; j++){} // ???*/
  117829. for(j=limit; j<n; j++)
  117830. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117831. }
  117832. }
  117833. #endif
  117834. /*** End of inlined file: psy.c ***/
  117835. /*** Start of inlined file: registry.c ***/
  117836. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117837. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117838. // tasks..
  117839. #if JUCE_MSVC
  117840. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117841. #endif
  117842. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117843. #if JUCE_USE_OGGVORBIS
  117844. /* seems like major overkill now; the backend numbers will grow into
  117845. the infrastructure soon enough */
  117846. extern vorbis_func_floor floor0_exportbundle;
  117847. extern vorbis_func_floor floor1_exportbundle;
  117848. extern vorbis_func_residue residue0_exportbundle;
  117849. extern vorbis_func_residue residue1_exportbundle;
  117850. extern vorbis_func_residue residue2_exportbundle;
  117851. extern vorbis_func_mapping mapping0_exportbundle;
  117852. vorbis_func_floor *_floor_P[]={
  117853. &floor0_exportbundle,
  117854. &floor1_exportbundle,
  117855. };
  117856. vorbis_func_residue *_residue_P[]={
  117857. &residue0_exportbundle,
  117858. &residue1_exportbundle,
  117859. &residue2_exportbundle,
  117860. };
  117861. vorbis_func_mapping *_mapping_P[]={
  117862. &mapping0_exportbundle,
  117863. };
  117864. #endif
  117865. /*** End of inlined file: registry.c ***/
  117866. /*** Start of inlined file: res0.c ***/
  117867. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117868. encode/decode loops are coded for clarity and performance is not
  117869. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117870. it's slow. */
  117871. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117872. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117873. // tasks..
  117874. #if JUCE_MSVC
  117875. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117876. #endif
  117877. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117878. #if JUCE_USE_OGGVORBIS
  117879. #include <stdlib.h>
  117880. #include <string.h>
  117881. #include <math.h>
  117882. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117883. #include <stdio.h>
  117884. #endif
  117885. typedef struct {
  117886. vorbis_info_residue0 *info;
  117887. int parts;
  117888. int stages;
  117889. codebook *fullbooks;
  117890. codebook *phrasebook;
  117891. codebook ***partbooks;
  117892. int partvals;
  117893. int **decodemap;
  117894. long postbits;
  117895. long phrasebits;
  117896. long frames;
  117897. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117898. int train_seq;
  117899. long *training_data[8][64];
  117900. float training_max[8][64];
  117901. float training_min[8][64];
  117902. float tmin;
  117903. float tmax;
  117904. #endif
  117905. } vorbis_look_residue0;
  117906. void res0_free_info(vorbis_info_residue *i){
  117907. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117908. if(info){
  117909. memset(info,0,sizeof(*info));
  117910. _ogg_free(info);
  117911. }
  117912. }
  117913. void res0_free_look(vorbis_look_residue *i){
  117914. int j;
  117915. if(i){
  117916. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117917. #ifdef TRAIN_RES
  117918. {
  117919. int j,k,l;
  117920. for(j=0;j<look->parts;j++){
  117921. /*fprintf(stderr,"partition %d: ",j);*/
  117922. for(k=0;k<8;k++)
  117923. if(look->training_data[k][j]){
  117924. char buffer[80];
  117925. FILE *of;
  117926. codebook *statebook=look->partbooks[j][k];
  117927. /* long and short into the same bucket by current convention */
  117928. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117929. of=fopen(buffer,"a");
  117930. for(l=0;l<statebook->entries;l++)
  117931. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117932. fclose(of);
  117933. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117934. look->training_min[k][j],look->training_max[k][j]);*/
  117935. _ogg_free(look->training_data[k][j]);
  117936. look->training_data[k][j]=NULL;
  117937. }
  117938. /*fprintf(stderr,"\n");*/
  117939. }
  117940. }
  117941. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117942. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117943. (float)look->phrasebits/look->frames,
  117944. (float)look->postbits/look->frames,
  117945. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117946. #endif
  117947. /*vorbis_info_residue0 *info=look->info;
  117948. fprintf(stderr,
  117949. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117950. "(%g/frame) \n",look->frames,look->phrasebits,
  117951. look->resbitsflat,
  117952. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117953. for(j=0;j<look->parts;j++){
  117954. long acc=0;
  117955. fprintf(stderr,"\t[%d] == ",j);
  117956. for(k=0;k<look->stages;k++)
  117957. if((info->secondstages[j]>>k)&1){
  117958. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117959. acc+=look->resbits[j][k];
  117960. }
  117961. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117962. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117963. }
  117964. fprintf(stderr,"\n");*/
  117965. for(j=0;j<look->parts;j++)
  117966. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117967. _ogg_free(look->partbooks);
  117968. for(j=0;j<look->partvals;j++)
  117969. _ogg_free(look->decodemap[j]);
  117970. _ogg_free(look->decodemap);
  117971. memset(look,0,sizeof(*look));
  117972. _ogg_free(look);
  117973. }
  117974. }
  117975. static int icount(unsigned int v){
  117976. int ret=0;
  117977. while(v){
  117978. ret+=v&1;
  117979. v>>=1;
  117980. }
  117981. return(ret);
  117982. }
  117983. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117984. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117985. int j,acc=0;
  117986. oggpack_write(opb,info->begin,24);
  117987. oggpack_write(opb,info->end,24);
  117988. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117989. code with a partitioned book */
  117990. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117991. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117992. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117993. bitmask of one indicates this partition class has bits to write
  117994. this pass */
  117995. for(j=0;j<info->partitions;j++){
  117996. if(ilog(info->secondstages[j])>3){
  117997. /* yes, this is a minor hack due to not thinking ahead */
  117998. oggpack_write(opb,info->secondstages[j],3);
  117999. oggpack_write(opb,1,1);
  118000. oggpack_write(opb,info->secondstages[j]>>3,5);
  118001. }else
  118002. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118003. acc+=icount(info->secondstages[j]);
  118004. }
  118005. for(j=0;j<acc;j++)
  118006. oggpack_write(opb,info->booklist[j],8);
  118007. }
  118008. /* vorbis_info is for range checking */
  118009. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118010. int j,acc=0;
  118011. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118012. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118013. info->begin=oggpack_read(opb,24);
  118014. info->end=oggpack_read(opb,24);
  118015. info->grouping=oggpack_read(opb,24)+1;
  118016. info->partitions=oggpack_read(opb,6)+1;
  118017. info->groupbook=oggpack_read(opb,8);
  118018. for(j=0;j<info->partitions;j++){
  118019. int cascade=oggpack_read(opb,3);
  118020. if(oggpack_read(opb,1))
  118021. cascade|=(oggpack_read(opb,5)<<3);
  118022. info->secondstages[j]=cascade;
  118023. acc+=icount(cascade);
  118024. }
  118025. for(j=0;j<acc;j++)
  118026. info->booklist[j]=oggpack_read(opb,8);
  118027. if(info->groupbook>=ci->books)goto errout;
  118028. for(j=0;j<acc;j++)
  118029. if(info->booklist[j]>=ci->books)goto errout;
  118030. return(info);
  118031. errout:
  118032. res0_free_info(info);
  118033. return(NULL);
  118034. }
  118035. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118036. vorbis_info_residue *vr){
  118037. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118038. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118039. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118040. int j,k,acc=0;
  118041. int dim;
  118042. int maxstage=0;
  118043. look->info=info;
  118044. look->parts=info->partitions;
  118045. look->fullbooks=ci->fullbooks;
  118046. look->phrasebook=ci->fullbooks+info->groupbook;
  118047. dim=look->phrasebook->dim;
  118048. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118049. for(j=0;j<look->parts;j++){
  118050. int stages=ilog(info->secondstages[j]);
  118051. if(stages){
  118052. if(stages>maxstage)maxstage=stages;
  118053. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118054. for(k=0;k<stages;k++)
  118055. if(info->secondstages[j]&(1<<k)){
  118056. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118057. #ifdef TRAIN_RES
  118058. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118059. sizeof(***look->training_data));
  118060. #endif
  118061. }
  118062. }
  118063. }
  118064. look->partvals=rint(pow((float)look->parts,(float)dim));
  118065. look->stages=maxstage;
  118066. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118067. for(j=0;j<look->partvals;j++){
  118068. long val=j;
  118069. long mult=look->partvals/look->parts;
  118070. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118071. for(k=0;k<dim;k++){
  118072. long deco=val/mult;
  118073. val-=deco*mult;
  118074. mult/=look->parts;
  118075. look->decodemap[j][k]=deco;
  118076. }
  118077. }
  118078. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118079. {
  118080. static int train_seq=0;
  118081. look->train_seq=train_seq++;
  118082. }
  118083. #endif
  118084. return(look);
  118085. }
  118086. /* break an abstraction and copy some code for performance purposes */
  118087. static int local_book_besterror(codebook *book,float *a){
  118088. int dim=book->dim,i,k,o;
  118089. int best=0;
  118090. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118091. /* find the quant val of each scalar */
  118092. for(k=0,o=dim;k<dim;++k){
  118093. float val=a[--o];
  118094. i=tt->threshvals>>1;
  118095. if(val<tt->quantthresh[i]){
  118096. if(val<tt->quantthresh[i-1]){
  118097. for(--i;i>0;--i)
  118098. if(val>=tt->quantthresh[i-1])
  118099. break;
  118100. }
  118101. }else{
  118102. for(++i;i<tt->threshvals-1;++i)
  118103. if(val<tt->quantthresh[i])break;
  118104. }
  118105. best=(best*tt->quantvals)+tt->quantmap[i];
  118106. }
  118107. /* regular lattices are easy :-) */
  118108. if(book->c->lengthlist[best]<=0){
  118109. const static_codebook *c=book->c;
  118110. int i,j;
  118111. float bestf=0.f;
  118112. float *e=book->valuelist;
  118113. best=-1;
  118114. for(i=0;i<book->entries;i++){
  118115. if(c->lengthlist[i]>0){
  118116. float thisx=0.f;
  118117. for(j=0;j<dim;j++){
  118118. float val=(e[j]-a[j]);
  118119. thisx+=val*val;
  118120. }
  118121. if(best==-1 || thisx<bestf){
  118122. bestf=thisx;
  118123. best=i;
  118124. }
  118125. }
  118126. e+=dim;
  118127. }
  118128. }
  118129. {
  118130. float *ptr=book->valuelist+best*dim;
  118131. for(i=0;i<dim;i++)
  118132. *a++ -= *ptr++;
  118133. }
  118134. return(best);
  118135. }
  118136. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118137. codebook *book,long *acc){
  118138. int i,bits=0;
  118139. int dim=book->dim;
  118140. int step=n/dim;
  118141. for(i=0;i<step;i++){
  118142. int entry=local_book_besterror(book,vec+i*dim);
  118143. #ifdef TRAIN_RES
  118144. acc[entry]++;
  118145. #endif
  118146. bits+=vorbis_book_encode(book,entry,opb);
  118147. }
  118148. return(bits);
  118149. }
  118150. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118151. float **in,int ch){
  118152. long i,j,k;
  118153. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118154. vorbis_info_residue0 *info=look->info;
  118155. /* move all this setup out later */
  118156. int samples_per_partition=info->grouping;
  118157. int possible_partitions=info->partitions;
  118158. int n=info->end-info->begin;
  118159. int partvals=n/samples_per_partition;
  118160. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118161. float scale=100./samples_per_partition;
  118162. /* we find the partition type for each partition of each
  118163. channel. We'll go back and do the interleaved encoding in a
  118164. bit. For now, clarity */
  118165. for(i=0;i<ch;i++){
  118166. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118167. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118168. }
  118169. for(i=0;i<partvals;i++){
  118170. int offset=i*samples_per_partition+info->begin;
  118171. for(j=0;j<ch;j++){
  118172. float max=0.;
  118173. float ent=0.;
  118174. for(k=0;k<samples_per_partition;k++){
  118175. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118176. ent+=fabs(rint(in[j][offset+k]));
  118177. }
  118178. ent*=scale;
  118179. for(k=0;k<possible_partitions-1;k++)
  118180. if(max<=info->classmetric1[k] &&
  118181. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118182. break;
  118183. partword[j][i]=k;
  118184. }
  118185. }
  118186. #ifdef TRAIN_RESAUX
  118187. {
  118188. FILE *of;
  118189. char buffer[80];
  118190. for(i=0;i<ch;i++){
  118191. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118192. of=fopen(buffer,"a");
  118193. for(j=0;j<partvals;j++)
  118194. fprintf(of,"%ld, ",partword[i][j]);
  118195. fprintf(of,"\n");
  118196. fclose(of);
  118197. }
  118198. }
  118199. #endif
  118200. look->frames++;
  118201. return(partword);
  118202. }
  118203. /* designed for stereo or other modes where the partition size is an
  118204. integer multiple of the number of channels encoded in the current
  118205. submap */
  118206. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118207. int ch){
  118208. long i,j,k,l;
  118209. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118210. vorbis_info_residue0 *info=look->info;
  118211. /* move all this setup out later */
  118212. int samples_per_partition=info->grouping;
  118213. int possible_partitions=info->partitions;
  118214. int n=info->end-info->begin;
  118215. int partvals=n/samples_per_partition;
  118216. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118217. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118218. FILE *of;
  118219. char buffer[80];
  118220. #endif
  118221. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118222. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118223. for(i=0,l=info->begin/ch;i<partvals;i++){
  118224. float magmax=0.f;
  118225. float angmax=0.f;
  118226. for(j=0;j<samples_per_partition;j+=ch){
  118227. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118228. for(k=1;k<ch;k++)
  118229. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118230. l++;
  118231. }
  118232. for(j=0;j<possible_partitions-1;j++)
  118233. if(magmax<=info->classmetric1[j] &&
  118234. angmax<=info->classmetric2[j])
  118235. break;
  118236. partword[0][i]=j;
  118237. }
  118238. #ifdef TRAIN_RESAUX
  118239. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118240. of=fopen(buffer,"a");
  118241. for(i=0;i<partvals;i++)
  118242. fprintf(of,"%ld, ",partword[0][i]);
  118243. fprintf(of,"\n");
  118244. fclose(of);
  118245. #endif
  118246. look->frames++;
  118247. return(partword);
  118248. }
  118249. static int _01forward(oggpack_buffer *opb,
  118250. vorbis_block *vb,vorbis_look_residue *vl,
  118251. float **in,int ch,
  118252. long **partword,
  118253. int (*encode)(oggpack_buffer *,float *,int,
  118254. codebook *,long *)){
  118255. long i,j,k,s;
  118256. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118257. vorbis_info_residue0 *info=look->info;
  118258. /* move all this setup out later */
  118259. int samples_per_partition=info->grouping;
  118260. int possible_partitions=info->partitions;
  118261. int partitions_per_word=look->phrasebook->dim;
  118262. int n=info->end-info->begin;
  118263. int partvals=n/samples_per_partition;
  118264. long resbits[128];
  118265. long resvals[128];
  118266. #ifdef TRAIN_RES
  118267. for(i=0;i<ch;i++)
  118268. for(j=info->begin;j<info->end;j++){
  118269. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118270. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118271. }
  118272. #endif
  118273. memset(resbits,0,sizeof(resbits));
  118274. memset(resvals,0,sizeof(resvals));
  118275. /* we code the partition words for each channel, then the residual
  118276. words for a partition per channel until we've written all the
  118277. residual words for that partition word. Then write the next
  118278. partition channel words... */
  118279. for(s=0;s<look->stages;s++){
  118280. for(i=0;i<partvals;){
  118281. /* first we encode a partition codeword for each channel */
  118282. if(s==0){
  118283. for(j=0;j<ch;j++){
  118284. long val=partword[j][i];
  118285. for(k=1;k<partitions_per_word;k++){
  118286. val*=possible_partitions;
  118287. if(i+k<partvals)
  118288. val+=partword[j][i+k];
  118289. }
  118290. /* training hack */
  118291. if(val<look->phrasebook->entries)
  118292. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118293. #if 0 /*def TRAIN_RES*/
  118294. else
  118295. fprintf(stderr,"!");
  118296. #endif
  118297. }
  118298. }
  118299. /* now we encode interleaved residual values for the partitions */
  118300. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118301. long offset=i*samples_per_partition+info->begin;
  118302. for(j=0;j<ch;j++){
  118303. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118304. if(info->secondstages[partword[j][i]]&(1<<s)){
  118305. codebook *statebook=look->partbooks[partword[j][i]][s];
  118306. if(statebook){
  118307. int ret;
  118308. long *accumulator=NULL;
  118309. #ifdef TRAIN_RES
  118310. accumulator=look->training_data[s][partword[j][i]];
  118311. {
  118312. int l;
  118313. float *samples=in[j]+offset;
  118314. for(l=0;l<samples_per_partition;l++){
  118315. if(samples[l]<look->training_min[s][partword[j][i]])
  118316. look->training_min[s][partword[j][i]]=samples[l];
  118317. if(samples[l]>look->training_max[s][partword[j][i]])
  118318. look->training_max[s][partword[j][i]]=samples[l];
  118319. }
  118320. }
  118321. #endif
  118322. ret=encode(opb,in[j]+offset,samples_per_partition,
  118323. statebook,accumulator);
  118324. look->postbits+=ret;
  118325. resbits[partword[j][i]]+=ret;
  118326. }
  118327. }
  118328. }
  118329. }
  118330. }
  118331. }
  118332. /*{
  118333. long total=0;
  118334. long totalbits=0;
  118335. fprintf(stderr,"%d :: ",vb->mode);
  118336. for(k=0;k<possible_partitions;k++){
  118337. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118338. total+=resvals[k];
  118339. totalbits+=resbits[k];
  118340. }
  118341. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118342. }*/
  118343. return(0);
  118344. }
  118345. /* a truncated packet here just means 'stop working'; it's not an error */
  118346. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118347. float **in,int ch,
  118348. long (*decodepart)(codebook *, float *,
  118349. oggpack_buffer *,int)){
  118350. long i,j,k,l,s;
  118351. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118352. vorbis_info_residue0 *info=look->info;
  118353. /* move all this setup out later */
  118354. int samples_per_partition=info->grouping;
  118355. int partitions_per_word=look->phrasebook->dim;
  118356. int n=info->end-info->begin;
  118357. int partvals=n/samples_per_partition;
  118358. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118359. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118360. for(j=0;j<ch;j++)
  118361. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118362. for(s=0;s<look->stages;s++){
  118363. /* each loop decodes on partition codeword containing
  118364. partitions_pre_word partitions */
  118365. for(i=0,l=0;i<partvals;l++){
  118366. if(s==0){
  118367. /* fetch the partition word for each channel */
  118368. for(j=0;j<ch;j++){
  118369. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118370. if(temp==-1)goto eopbreak;
  118371. partword[j][l]=look->decodemap[temp];
  118372. if(partword[j][l]==NULL)goto errout;
  118373. }
  118374. }
  118375. /* now we decode residual values for the partitions */
  118376. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118377. for(j=0;j<ch;j++){
  118378. long offset=info->begin+i*samples_per_partition;
  118379. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118380. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118381. if(stagebook){
  118382. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118383. samples_per_partition)==-1)goto eopbreak;
  118384. }
  118385. }
  118386. }
  118387. }
  118388. }
  118389. errout:
  118390. eopbreak:
  118391. return(0);
  118392. }
  118393. #if 0
  118394. /* residue 0 and 1 are just slight variants of one another. 0 is
  118395. interleaved, 1 is not */
  118396. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118397. float **in,int *nonzero,int ch){
  118398. /* we encode only the nonzero parts of a bundle */
  118399. int i,used=0;
  118400. for(i=0;i<ch;i++)
  118401. if(nonzero[i])
  118402. in[used++]=in[i];
  118403. if(used)
  118404. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118405. return(_01class(vb,vl,in,used));
  118406. else
  118407. return(0);
  118408. }
  118409. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118410. float **in,float **out,int *nonzero,int ch,
  118411. long **partword){
  118412. /* we encode only the nonzero parts of a bundle */
  118413. int i,j,used=0,n=vb->pcmend/2;
  118414. for(i=0;i<ch;i++)
  118415. if(nonzero[i]){
  118416. if(out)
  118417. for(j=0;j<n;j++)
  118418. out[i][j]+=in[i][j];
  118419. in[used++]=in[i];
  118420. }
  118421. if(used){
  118422. int ret=_01forward(vb,vl,in,used,partword,
  118423. _interleaved_encodepart);
  118424. if(out){
  118425. used=0;
  118426. for(i=0;i<ch;i++)
  118427. if(nonzero[i]){
  118428. for(j=0;j<n;j++)
  118429. out[i][j]-=in[used][j];
  118430. used++;
  118431. }
  118432. }
  118433. return(ret);
  118434. }else{
  118435. return(0);
  118436. }
  118437. }
  118438. #endif
  118439. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118440. float **in,int *nonzero,int ch){
  118441. int i,used=0;
  118442. for(i=0;i<ch;i++)
  118443. if(nonzero[i])
  118444. in[used++]=in[i];
  118445. if(used)
  118446. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118447. else
  118448. return(0);
  118449. }
  118450. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118451. float **in,float **out,int *nonzero,int ch,
  118452. long **partword){
  118453. int i,j,used=0,n=vb->pcmend/2;
  118454. for(i=0;i<ch;i++)
  118455. if(nonzero[i]){
  118456. if(out)
  118457. for(j=0;j<n;j++)
  118458. out[i][j]+=in[i][j];
  118459. in[used++]=in[i];
  118460. }
  118461. if(used){
  118462. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118463. if(out){
  118464. used=0;
  118465. for(i=0;i<ch;i++)
  118466. if(nonzero[i]){
  118467. for(j=0;j<n;j++)
  118468. out[i][j]-=in[used][j];
  118469. used++;
  118470. }
  118471. }
  118472. return(ret);
  118473. }else{
  118474. return(0);
  118475. }
  118476. }
  118477. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118478. float **in,int *nonzero,int ch){
  118479. int i,used=0;
  118480. for(i=0;i<ch;i++)
  118481. if(nonzero[i])
  118482. in[used++]=in[i];
  118483. if(used)
  118484. return(_01class(vb,vl,in,used));
  118485. else
  118486. return(0);
  118487. }
  118488. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118489. float **in,int *nonzero,int ch){
  118490. int i,used=0;
  118491. for(i=0;i<ch;i++)
  118492. if(nonzero[i])
  118493. in[used++]=in[i];
  118494. if(used)
  118495. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118496. else
  118497. return(0);
  118498. }
  118499. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118500. float **in,int *nonzero,int ch){
  118501. int i,used=0;
  118502. for(i=0;i<ch;i++)
  118503. if(nonzero[i])used++;
  118504. if(used)
  118505. return(_2class(vb,vl,in,ch));
  118506. else
  118507. return(0);
  118508. }
  118509. /* res2 is slightly more different; all the channels are interleaved
  118510. into a single vector and encoded. */
  118511. int res2_forward(oggpack_buffer *opb,
  118512. vorbis_block *vb,vorbis_look_residue *vl,
  118513. float **in,float **out,int *nonzero,int ch,
  118514. long **partword){
  118515. long i,j,k,n=vb->pcmend/2,used=0;
  118516. /* don't duplicate the code; use a working vector hack for now and
  118517. reshape ourselves into a single channel res1 */
  118518. /* ugly; reallocs for each coupling pass :-( */
  118519. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118520. for(i=0;i<ch;i++){
  118521. float *pcm=in[i];
  118522. if(nonzero[i])used++;
  118523. for(j=0,k=i;j<n;j++,k+=ch)
  118524. work[k]=pcm[j];
  118525. }
  118526. if(used){
  118527. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118528. /* update the sofar vector */
  118529. if(out){
  118530. for(i=0;i<ch;i++){
  118531. float *pcm=in[i];
  118532. float *sofar=out[i];
  118533. for(j=0,k=i;j<n;j++,k+=ch)
  118534. sofar[j]+=pcm[j]-work[k];
  118535. }
  118536. }
  118537. return(ret);
  118538. }else{
  118539. return(0);
  118540. }
  118541. }
  118542. /* duplicate code here as speed is somewhat more important */
  118543. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118544. float **in,int *nonzero,int ch){
  118545. long i,k,l,s;
  118546. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118547. vorbis_info_residue0 *info=look->info;
  118548. /* move all this setup out later */
  118549. int samples_per_partition=info->grouping;
  118550. int partitions_per_word=look->phrasebook->dim;
  118551. int n=info->end-info->begin;
  118552. int partvals=n/samples_per_partition;
  118553. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118554. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118555. for(i=0;i<ch;i++)if(nonzero[i])break;
  118556. if(i==ch)return(0); /* no nonzero vectors */
  118557. for(s=0;s<look->stages;s++){
  118558. for(i=0,l=0;i<partvals;l++){
  118559. if(s==0){
  118560. /* fetch the partition word */
  118561. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118562. if(temp==-1)goto eopbreak;
  118563. partword[l]=look->decodemap[temp];
  118564. if(partword[l]==NULL)goto errout;
  118565. }
  118566. /* now we decode residual values for the partitions */
  118567. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118568. if(info->secondstages[partword[l][k]]&(1<<s)){
  118569. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118570. if(stagebook){
  118571. if(vorbis_book_decodevv_add(stagebook,in,
  118572. i*samples_per_partition+info->begin,ch,
  118573. &vb->opb,samples_per_partition)==-1)
  118574. goto eopbreak;
  118575. }
  118576. }
  118577. }
  118578. }
  118579. errout:
  118580. eopbreak:
  118581. return(0);
  118582. }
  118583. vorbis_func_residue residue0_exportbundle={
  118584. NULL,
  118585. &res0_unpack,
  118586. &res0_look,
  118587. &res0_free_info,
  118588. &res0_free_look,
  118589. NULL,
  118590. NULL,
  118591. &res0_inverse
  118592. };
  118593. vorbis_func_residue residue1_exportbundle={
  118594. &res0_pack,
  118595. &res0_unpack,
  118596. &res0_look,
  118597. &res0_free_info,
  118598. &res0_free_look,
  118599. &res1_class,
  118600. &res1_forward,
  118601. &res1_inverse
  118602. };
  118603. vorbis_func_residue residue2_exportbundle={
  118604. &res0_pack,
  118605. &res0_unpack,
  118606. &res0_look,
  118607. &res0_free_info,
  118608. &res0_free_look,
  118609. &res2_class,
  118610. &res2_forward,
  118611. &res2_inverse
  118612. };
  118613. #endif
  118614. /*** End of inlined file: res0.c ***/
  118615. /*** Start of inlined file: sharedbook.c ***/
  118616. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118617. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118618. // tasks..
  118619. #if JUCE_MSVC
  118620. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118621. #endif
  118622. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118623. #if JUCE_USE_OGGVORBIS
  118624. #include <stdlib.h>
  118625. #include <math.h>
  118626. #include <string.h>
  118627. /**** pack/unpack helpers ******************************************/
  118628. int _ilog(unsigned int v){
  118629. int ret=0;
  118630. while(v){
  118631. ret++;
  118632. v>>=1;
  118633. }
  118634. return(ret);
  118635. }
  118636. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118637. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118638. Why not IEEE? It's just not that important here. */
  118639. #define VQ_FEXP 10
  118640. #define VQ_FMAN 21
  118641. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118642. /* doesn't currently guard under/overflow */
  118643. long _float32_pack(float val){
  118644. int sign=0;
  118645. long exp;
  118646. long mant;
  118647. if(val<0){
  118648. sign=0x80000000;
  118649. val= -val;
  118650. }
  118651. exp= floor(log(val)/log(2.f));
  118652. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118653. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118654. return(sign|exp|mant);
  118655. }
  118656. float _float32_unpack(long val){
  118657. double mant=val&0x1fffff;
  118658. int sign=val&0x80000000;
  118659. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118660. if(sign)mant= -mant;
  118661. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118662. }
  118663. /* given a list of word lengths, generate a list of codewords. Works
  118664. for length ordered or unordered, always assigns the lowest valued
  118665. codewords first. Extended to handle unused entries (length 0) */
  118666. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118667. long i,j,count=0;
  118668. ogg_uint32_t marker[33];
  118669. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118670. memset(marker,0,sizeof(marker));
  118671. for(i=0;i<n;i++){
  118672. long length=l[i];
  118673. if(length>0){
  118674. ogg_uint32_t entry=marker[length];
  118675. /* when we claim a node for an entry, we also claim the nodes
  118676. below it (pruning off the imagined tree that may have dangled
  118677. from it) as well as blocking the use of any nodes directly
  118678. above for leaves */
  118679. /* update ourself */
  118680. if(length<32 && (entry>>length)){
  118681. /* error condition; the lengths must specify an overpopulated tree */
  118682. _ogg_free(r);
  118683. return(NULL);
  118684. }
  118685. r[count++]=entry;
  118686. /* Look to see if the next shorter marker points to the node
  118687. above. if so, update it and repeat. */
  118688. {
  118689. for(j=length;j>0;j--){
  118690. if(marker[j]&1){
  118691. /* have to jump branches */
  118692. if(j==1)
  118693. marker[1]++;
  118694. else
  118695. marker[j]=marker[j-1]<<1;
  118696. break; /* invariant says next upper marker would already
  118697. have been moved if it was on the same path */
  118698. }
  118699. marker[j]++;
  118700. }
  118701. }
  118702. /* prune the tree; the implicit invariant says all the longer
  118703. markers were dangling from our just-taken node. Dangle them
  118704. from our *new* node. */
  118705. for(j=length+1;j<33;j++)
  118706. if((marker[j]>>1) == entry){
  118707. entry=marker[j];
  118708. marker[j]=marker[j-1]<<1;
  118709. }else
  118710. break;
  118711. }else
  118712. if(sparsecount==0)count++;
  118713. }
  118714. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118715. endian */
  118716. for(i=0,count=0;i<n;i++){
  118717. ogg_uint32_t temp=0;
  118718. for(j=0;j<l[i];j++){
  118719. temp<<=1;
  118720. temp|=(r[count]>>j)&1;
  118721. }
  118722. if(sparsecount){
  118723. if(l[i])
  118724. r[count++]=temp;
  118725. }else
  118726. r[count++]=temp;
  118727. }
  118728. return(r);
  118729. }
  118730. /* there might be a straightforward one-line way to do the below
  118731. that's portable and totally safe against roundoff, but I haven't
  118732. thought of it. Therefore, we opt on the side of caution */
  118733. long _book_maptype1_quantvals(const static_codebook *b){
  118734. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118735. /* the above *should* be reliable, but we'll not assume that FP is
  118736. ever reliable when bitstream sync is at stake; verify via integer
  118737. means that vals really is the greatest value of dim for which
  118738. vals^b->bim <= b->entries */
  118739. /* treat the above as an initial guess */
  118740. while(1){
  118741. long acc=1;
  118742. long acc1=1;
  118743. int i;
  118744. for(i=0;i<b->dim;i++){
  118745. acc*=vals;
  118746. acc1*=vals+1;
  118747. }
  118748. if(acc<=b->entries && acc1>b->entries){
  118749. return(vals);
  118750. }else{
  118751. if(acc>b->entries){
  118752. vals--;
  118753. }else{
  118754. vals++;
  118755. }
  118756. }
  118757. }
  118758. }
  118759. /* unpack the quantized list of values for encode/decode ***********/
  118760. /* we need to deal with two map types: in map type 1, the values are
  118761. generated algorithmically (each column of the vector counts through
  118762. the values in the quant vector). in map type 2, all the values came
  118763. in in an explicit list. Both value lists must be unpacked */
  118764. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118765. long j,k,count=0;
  118766. if(b->maptype==1 || b->maptype==2){
  118767. int quantvals;
  118768. float mindel=_float32_unpack(b->q_min);
  118769. float delta=_float32_unpack(b->q_delta);
  118770. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118771. /* maptype 1 and 2 both use a quantized value vector, but
  118772. different sizes */
  118773. switch(b->maptype){
  118774. case 1:
  118775. /* most of the time, entries%dimensions == 0, but we need to be
  118776. well defined. We define that the possible vales at each
  118777. scalar is values == entries/dim. If entries%dim != 0, we'll
  118778. have 'too few' values (values*dim<entries), which means that
  118779. we'll have 'left over' entries; left over entries use zeroed
  118780. values (and are wasted). So don't generate codebooks like
  118781. that */
  118782. quantvals=_book_maptype1_quantvals(b);
  118783. for(j=0;j<b->entries;j++){
  118784. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118785. float last=0.f;
  118786. int indexdiv=1;
  118787. for(k=0;k<b->dim;k++){
  118788. int index= (j/indexdiv)%quantvals;
  118789. float val=b->quantlist[index];
  118790. val=fabs(val)*delta+mindel+last;
  118791. if(b->q_sequencep)last=val;
  118792. if(sparsemap)
  118793. r[sparsemap[count]*b->dim+k]=val;
  118794. else
  118795. r[count*b->dim+k]=val;
  118796. indexdiv*=quantvals;
  118797. }
  118798. count++;
  118799. }
  118800. }
  118801. break;
  118802. case 2:
  118803. for(j=0;j<b->entries;j++){
  118804. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118805. float last=0.f;
  118806. for(k=0;k<b->dim;k++){
  118807. float val=b->quantlist[j*b->dim+k];
  118808. val=fabs(val)*delta+mindel+last;
  118809. if(b->q_sequencep)last=val;
  118810. if(sparsemap)
  118811. r[sparsemap[count]*b->dim+k]=val;
  118812. else
  118813. r[count*b->dim+k]=val;
  118814. }
  118815. count++;
  118816. }
  118817. }
  118818. break;
  118819. }
  118820. return(r);
  118821. }
  118822. return(NULL);
  118823. }
  118824. void vorbis_staticbook_clear(static_codebook *b){
  118825. if(b->allocedp){
  118826. if(b->quantlist)_ogg_free(b->quantlist);
  118827. if(b->lengthlist)_ogg_free(b->lengthlist);
  118828. if(b->nearest_tree){
  118829. _ogg_free(b->nearest_tree->ptr0);
  118830. _ogg_free(b->nearest_tree->ptr1);
  118831. _ogg_free(b->nearest_tree->p);
  118832. _ogg_free(b->nearest_tree->q);
  118833. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118834. _ogg_free(b->nearest_tree);
  118835. }
  118836. if(b->thresh_tree){
  118837. _ogg_free(b->thresh_tree->quantthresh);
  118838. _ogg_free(b->thresh_tree->quantmap);
  118839. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118840. _ogg_free(b->thresh_tree);
  118841. }
  118842. memset(b,0,sizeof(*b));
  118843. }
  118844. }
  118845. void vorbis_staticbook_destroy(static_codebook *b){
  118846. if(b->allocedp){
  118847. vorbis_staticbook_clear(b);
  118848. _ogg_free(b);
  118849. }
  118850. }
  118851. void vorbis_book_clear(codebook *b){
  118852. /* static book is not cleared; we're likely called on the lookup and
  118853. the static codebook belongs to the info struct */
  118854. if(b->valuelist)_ogg_free(b->valuelist);
  118855. if(b->codelist)_ogg_free(b->codelist);
  118856. if(b->dec_index)_ogg_free(b->dec_index);
  118857. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118858. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118859. memset(b,0,sizeof(*b));
  118860. }
  118861. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118862. memset(c,0,sizeof(*c));
  118863. c->c=s;
  118864. c->entries=s->entries;
  118865. c->used_entries=s->entries;
  118866. c->dim=s->dim;
  118867. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118868. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118869. return(0);
  118870. }
  118871. static int JUCE_CDECL sort32a(const void *a,const void *b){
  118872. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118873. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118874. }
  118875. /* decode codebook arrangement is more heavily optimized than encode */
  118876. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118877. int i,j,n=0,tabn;
  118878. int *sortindex;
  118879. memset(c,0,sizeof(*c));
  118880. /* count actually used entries */
  118881. for(i=0;i<s->entries;i++)
  118882. if(s->lengthlist[i]>0)
  118883. n++;
  118884. c->entries=s->entries;
  118885. c->used_entries=n;
  118886. c->dim=s->dim;
  118887. /* two different remappings go on here.
  118888. First, we collapse the likely sparse codebook down only to
  118889. actually represented values/words. This collapsing needs to be
  118890. indexed as map-valueless books are used to encode original entry
  118891. positions as integers.
  118892. Second, we reorder all vectors, including the entry index above,
  118893. by sorted bitreversed codeword to allow treeless decode. */
  118894. {
  118895. /* perform sort */
  118896. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118897. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118898. if(codes==NULL)goto err_out;
  118899. for(i=0;i<n;i++){
  118900. codes[i]=ogg_bitreverse(codes[i]);
  118901. codep[i]=codes+i;
  118902. }
  118903. qsort(codep,n,sizeof(*codep),sort32a);
  118904. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118905. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118906. /* the index is a reverse index */
  118907. for(i=0;i<n;i++){
  118908. int position=codep[i]-codes;
  118909. sortindex[position]=i;
  118910. }
  118911. for(i=0;i<n;i++)
  118912. c->codelist[sortindex[i]]=codes[i];
  118913. _ogg_free(codes);
  118914. }
  118915. c->valuelist=_book_unquantize(s,n,sortindex);
  118916. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118917. for(n=0,i=0;i<s->entries;i++)
  118918. if(s->lengthlist[i]>0)
  118919. c->dec_index[sortindex[n++]]=i;
  118920. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118921. for(n=0,i=0;i<s->entries;i++)
  118922. if(s->lengthlist[i]>0)
  118923. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118924. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118925. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118926. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118927. tabn=1<<c->dec_firsttablen;
  118928. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118929. c->dec_maxlength=0;
  118930. for(i=0;i<n;i++){
  118931. if(c->dec_maxlength<c->dec_codelengths[i])
  118932. c->dec_maxlength=c->dec_codelengths[i];
  118933. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118934. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118935. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118936. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118937. }
  118938. }
  118939. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118940. hints for the non-direct-hits */
  118941. {
  118942. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118943. long lo=0,hi=0;
  118944. for(i=0;i<tabn;i++){
  118945. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118946. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118947. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118948. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118949. /* we only actually have 15 bits per hint to play with here.
  118950. In order to overflow gracefully (nothing breaks, efficiency
  118951. just drops), encode as the difference from the extremes. */
  118952. {
  118953. unsigned long loval=lo;
  118954. unsigned long hival=n-hi;
  118955. if(loval>0x7fff)loval=0x7fff;
  118956. if(hival>0x7fff)hival=0x7fff;
  118957. c->dec_firsttable[ogg_bitreverse(word)]=
  118958. 0x80000000UL | (loval<<15) | hival;
  118959. }
  118960. }
  118961. }
  118962. }
  118963. return(0);
  118964. err_out:
  118965. vorbis_book_clear(c);
  118966. return(-1);
  118967. }
  118968. static float _dist(int el,float *ref, float *b,int step){
  118969. int i;
  118970. float acc=0.f;
  118971. for(i=0;i<el;i++){
  118972. float val=(ref[i]-b[i*step]);
  118973. acc+=val*val;
  118974. }
  118975. return(acc);
  118976. }
  118977. int _best(codebook *book, float *a, int step){
  118978. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118979. #if 0
  118980. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118981. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118982. #endif
  118983. int dim=book->dim;
  118984. int k,o;
  118985. /*int savebest=-1;
  118986. float saverr;*/
  118987. /* do we have a threshhold encode hint? */
  118988. if(tt){
  118989. int index=0,i;
  118990. /* find the quant val of each scalar */
  118991. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118992. i=tt->threshvals>>1;
  118993. if(a[o]<tt->quantthresh[i]){
  118994. for(;i>0;i--)
  118995. if(a[o]>=tt->quantthresh[i-1])
  118996. break;
  118997. }else{
  118998. for(i++;i<tt->threshvals-1;i++)
  118999. if(a[o]<tt->quantthresh[i])break;
  119000. }
  119001. index=(index*tt->quantvals)+tt->quantmap[i];
  119002. }
  119003. /* regular lattices are easy :-) */
  119004. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119005. use a decision tree after all
  119006. and fall through*/
  119007. return(index);
  119008. }
  119009. #if 0
  119010. /* do we have a pigeonhole encode hint? */
  119011. if(pt){
  119012. const static_codebook *c=book->c;
  119013. int i,besti=-1;
  119014. float best=0.f;
  119015. int entry=0;
  119016. /* dealing with sequentialness is a pain in the ass */
  119017. if(c->q_sequencep){
  119018. int pv;
  119019. long mul=1;
  119020. float qlast=0;
  119021. for(k=0,o=0;k<dim;k++,o+=step){
  119022. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119023. if(pv<0 || pv>=pt->mapentries)break;
  119024. entry+=pt->pigeonmap[pv]*mul;
  119025. mul*=pt->quantvals;
  119026. qlast+=pv*pt->del+pt->min;
  119027. }
  119028. }else{
  119029. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119030. int pv=(int)((a[o]-pt->min)/pt->del);
  119031. if(pv<0 || pv>=pt->mapentries)break;
  119032. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119033. }
  119034. }
  119035. /* must be within the pigeonholable range; if we quant outside (or
  119036. in an entry that we define no list for), brute force it */
  119037. if(k==dim && pt->fitlength[entry]){
  119038. /* search the abbreviated list */
  119039. long *list=pt->fitlist+pt->fitmap[entry];
  119040. for(i=0;i<pt->fitlength[entry];i++){
  119041. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119042. if(besti==-1 || this<best){
  119043. best=this;
  119044. besti=list[i];
  119045. }
  119046. }
  119047. return(besti);
  119048. }
  119049. }
  119050. if(nt){
  119051. /* optimized using the decision tree */
  119052. while(1){
  119053. float c=0.f;
  119054. float *p=book->valuelist+nt->p[ptr];
  119055. float *q=book->valuelist+nt->q[ptr];
  119056. for(k=0,o=0;k<dim;k++,o+=step)
  119057. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119058. if(c>0.f) /* in A */
  119059. ptr= -nt->ptr0[ptr];
  119060. else /* in B */
  119061. ptr= -nt->ptr1[ptr];
  119062. if(ptr<=0)break;
  119063. }
  119064. return(-ptr);
  119065. }
  119066. #endif
  119067. /* brute force it! */
  119068. {
  119069. const static_codebook *c=book->c;
  119070. int i,besti=-1;
  119071. float best=0.f;
  119072. float *e=book->valuelist;
  119073. for(i=0;i<book->entries;i++){
  119074. if(c->lengthlist[i]>0){
  119075. float thisx=_dist(dim,e,a,step);
  119076. if(besti==-1 || thisx<best){
  119077. best=thisx;
  119078. besti=i;
  119079. }
  119080. }
  119081. e+=dim;
  119082. }
  119083. /*if(savebest!=-1 && savebest!=besti){
  119084. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119085. "original:");
  119086. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119087. fprintf(stderr,"\n"
  119088. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119089. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119090. (book->valuelist+savebest*dim)[i]);
  119091. fprintf(stderr,"\n"
  119092. "bruteforce (entry %d, err %g):",besti,best);
  119093. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119094. (book->valuelist+besti*dim)[i]);
  119095. fprintf(stderr,"\n");
  119096. }*/
  119097. return(besti);
  119098. }
  119099. }
  119100. long vorbis_book_codeword(codebook *book,int entry){
  119101. if(book->c) /* only use with encode; decode optimizations are
  119102. allowed to break this */
  119103. return book->codelist[entry];
  119104. return -1;
  119105. }
  119106. long vorbis_book_codelen(codebook *book,int entry){
  119107. if(book->c) /* only use with encode; decode optimizations are
  119108. allowed to break this */
  119109. return book->c->lengthlist[entry];
  119110. return -1;
  119111. }
  119112. #ifdef _V_SELFTEST
  119113. /* Unit tests of the dequantizer; this stuff will be OK
  119114. cross-platform, I simply want to be sure that special mapping cases
  119115. actually work properly; a bug could go unnoticed for a while */
  119116. #include <stdio.h>
  119117. /* cases:
  119118. no mapping
  119119. full, explicit mapping
  119120. algorithmic mapping
  119121. nonsequential
  119122. sequential
  119123. */
  119124. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119125. static long partial_quantlist1[]={0,7,2};
  119126. /* no mapping */
  119127. static_codebook test1={
  119128. 4,16,
  119129. NULL,
  119130. 0,
  119131. 0,0,0,0,
  119132. NULL,
  119133. NULL,NULL
  119134. };
  119135. static float *test1_result=NULL;
  119136. /* linear, full mapping, nonsequential */
  119137. static_codebook test2={
  119138. 4,3,
  119139. NULL,
  119140. 2,
  119141. -533200896,1611661312,4,0,
  119142. full_quantlist1,
  119143. NULL,NULL
  119144. };
  119145. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119146. /* linear, full mapping, sequential */
  119147. static_codebook test3={
  119148. 4,3,
  119149. NULL,
  119150. 2,
  119151. -533200896,1611661312,4,1,
  119152. full_quantlist1,
  119153. NULL,NULL
  119154. };
  119155. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119156. /* linear, algorithmic mapping, nonsequential */
  119157. static_codebook test4={
  119158. 3,27,
  119159. NULL,
  119160. 1,
  119161. -533200896,1611661312,4,0,
  119162. partial_quantlist1,
  119163. NULL,NULL
  119164. };
  119165. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119166. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119167. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119168. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119169. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119170. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119171. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119172. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119173. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119174. /* linear, algorithmic mapping, sequential */
  119175. static_codebook test5={
  119176. 3,27,
  119177. NULL,
  119178. 1,
  119179. -533200896,1611661312,4,1,
  119180. partial_quantlist1,
  119181. NULL,NULL
  119182. };
  119183. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119184. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119185. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119186. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119187. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119188. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119189. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119190. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119191. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119192. void run_test(static_codebook *b,float *comp){
  119193. float *out=_book_unquantize(b,b->entries,NULL);
  119194. int i;
  119195. if(comp){
  119196. if(!out){
  119197. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119198. exit(1);
  119199. }
  119200. for(i=0;i<b->entries*b->dim;i++)
  119201. if(fabs(out[i]-comp[i])>.0001){
  119202. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119203. "position %d, %g != %g\n",i,out[i],comp[i]);
  119204. exit(1);
  119205. }
  119206. }else{
  119207. if(out){
  119208. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119209. " correct result should have been NULL\n");
  119210. exit(1);
  119211. }
  119212. }
  119213. }
  119214. int main(){
  119215. /* run the nine dequant tests, and compare to the hand-rolled results */
  119216. fprintf(stderr,"Dequant test 1... ");
  119217. run_test(&test1,test1_result);
  119218. fprintf(stderr,"OK\nDequant test 2... ");
  119219. run_test(&test2,test2_result);
  119220. fprintf(stderr,"OK\nDequant test 3... ");
  119221. run_test(&test3,test3_result);
  119222. fprintf(stderr,"OK\nDequant test 4... ");
  119223. run_test(&test4,test4_result);
  119224. fprintf(stderr,"OK\nDequant test 5... ");
  119225. run_test(&test5,test5_result);
  119226. fprintf(stderr,"OK\n\n");
  119227. return(0);
  119228. }
  119229. #endif
  119230. #endif
  119231. /*** End of inlined file: sharedbook.c ***/
  119232. /*** Start of inlined file: smallft.c ***/
  119233. /* FFT implementation from OggSquish, minus cosine transforms,
  119234. * minus all but radix 2/4 case. In Vorbis we only need this
  119235. * cut-down version.
  119236. *
  119237. * To do more than just power-of-two sized vectors, see the full
  119238. * version I wrote for NetLib.
  119239. *
  119240. * Note that the packing is a little strange; rather than the FFT r/i
  119241. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119242. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119243. * FORTRAN version
  119244. */
  119245. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119246. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119247. // tasks..
  119248. #if JUCE_MSVC
  119249. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119250. #endif
  119251. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119252. #if JUCE_USE_OGGVORBIS
  119253. #include <stdlib.h>
  119254. #include <string.h>
  119255. #include <math.h>
  119256. static void drfti1(int n, float *wa, int *ifac){
  119257. static int ntryh[4] = { 4,2,3,5 };
  119258. static float tpi = 6.28318530717958648f;
  119259. float arg,argh,argld,fi;
  119260. int ntry=0,i,j=-1;
  119261. int k1, l1, l2, ib;
  119262. int ld, ii, ip, is, nq, nr;
  119263. int ido, ipm, nfm1;
  119264. int nl=n;
  119265. int nf=0;
  119266. L101:
  119267. j++;
  119268. if (j < 4)
  119269. ntry=ntryh[j];
  119270. else
  119271. ntry+=2;
  119272. L104:
  119273. nq=nl/ntry;
  119274. nr=nl-ntry*nq;
  119275. if (nr!=0) goto L101;
  119276. nf++;
  119277. ifac[nf+1]=ntry;
  119278. nl=nq;
  119279. if(ntry!=2)goto L107;
  119280. if(nf==1)goto L107;
  119281. for (i=1;i<nf;i++){
  119282. ib=nf-i+1;
  119283. ifac[ib+1]=ifac[ib];
  119284. }
  119285. ifac[2] = 2;
  119286. L107:
  119287. if(nl!=1)goto L104;
  119288. ifac[0]=n;
  119289. ifac[1]=nf;
  119290. argh=tpi/n;
  119291. is=0;
  119292. nfm1=nf-1;
  119293. l1=1;
  119294. if(nfm1==0)return;
  119295. for (k1=0;k1<nfm1;k1++){
  119296. ip=ifac[k1+2];
  119297. ld=0;
  119298. l2=l1*ip;
  119299. ido=n/l2;
  119300. ipm=ip-1;
  119301. for (j=0;j<ipm;j++){
  119302. ld+=l1;
  119303. i=is;
  119304. argld=(float)ld*argh;
  119305. fi=0.f;
  119306. for (ii=2;ii<ido;ii+=2){
  119307. fi+=1.f;
  119308. arg=fi*argld;
  119309. wa[i++]=cos(arg);
  119310. wa[i++]=sin(arg);
  119311. }
  119312. is+=ido;
  119313. }
  119314. l1=l2;
  119315. }
  119316. }
  119317. static void fdrffti(int n, float *wsave, int *ifac){
  119318. if (n == 1) return;
  119319. drfti1(n, wsave+n, ifac);
  119320. }
  119321. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119322. int i,k;
  119323. float ti2,tr2;
  119324. int t0,t1,t2,t3,t4,t5,t6;
  119325. t1=0;
  119326. t0=(t2=l1*ido);
  119327. t3=ido<<1;
  119328. for(k=0;k<l1;k++){
  119329. ch[t1<<1]=cc[t1]+cc[t2];
  119330. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119331. t1+=ido;
  119332. t2+=ido;
  119333. }
  119334. if(ido<2)return;
  119335. if(ido==2)goto L105;
  119336. t1=0;
  119337. t2=t0;
  119338. for(k=0;k<l1;k++){
  119339. t3=t2;
  119340. t4=(t1<<1)+(ido<<1);
  119341. t5=t1;
  119342. t6=t1+t1;
  119343. for(i=2;i<ido;i+=2){
  119344. t3+=2;
  119345. t4-=2;
  119346. t5+=2;
  119347. t6+=2;
  119348. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119349. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119350. ch[t6]=cc[t5]+ti2;
  119351. ch[t4]=ti2-cc[t5];
  119352. ch[t6-1]=cc[t5-1]+tr2;
  119353. ch[t4-1]=cc[t5-1]-tr2;
  119354. }
  119355. t1+=ido;
  119356. t2+=ido;
  119357. }
  119358. if(ido%2==1)return;
  119359. L105:
  119360. t3=(t2=(t1=ido)-1);
  119361. t2+=t0;
  119362. for(k=0;k<l1;k++){
  119363. ch[t1]=-cc[t2];
  119364. ch[t1-1]=cc[t3];
  119365. t1+=ido<<1;
  119366. t2+=ido;
  119367. t3+=ido;
  119368. }
  119369. }
  119370. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119371. float *wa2,float *wa3){
  119372. static float hsqt2 = .70710678118654752f;
  119373. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119374. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119375. t0=l1*ido;
  119376. t1=t0;
  119377. t4=t1<<1;
  119378. t2=t1+(t1<<1);
  119379. t3=0;
  119380. for(k=0;k<l1;k++){
  119381. tr1=cc[t1]+cc[t2];
  119382. tr2=cc[t3]+cc[t4];
  119383. ch[t5=t3<<2]=tr1+tr2;
  119384. ch[(ido<<2)+t5-1]=tr2-tr1;
  119385. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119386. ch[t5]=cc[t2]-cc[t1];
  119387. t1+=ido;
  119388. t2+=ido;
  119389. t3+=ido;
  119390. t4+=ido;
  119391. }
  119392. if(ido<2)return;
  119393. if(ido==2)goto L105;
  119394. t1=0;
  119395. for(k=0;k<l1;k++){
  119396. t2=t1;
  119397. t4=t1<<2;
  119398. t5=(t6=ido<<1)+t4;
  119399. for(i=2;i<ido;i+=2){
  119400. t3=(t2+=2);
  119401. t4+=2;
  119402. t5-=2;
  119403. t3+=t0;
  119404. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119405. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119406. t3+=t0;
  119407. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119408. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119409. t3+=t0;
  119410. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119411. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119412. tr1=cr2+cr4;
  119413. tr4=cr4-cr2;
  119414. ti1=ci2+ci4;
  119415. ti4=ci2-ci4;
  119416. ti2=cc[t2]+ci3;
  119417. ti3=cc[t2]-ci3;
  119418. tr2=cc[t2-1]+cr3;
  119419. tr3=cc[t2-1]-cr3;
  119420. ch[t4-1]=tr1+tr2;
  119421. ch[t4]=ti1+ti2;
  119422. ch[t5-1]=tr3-ti4;
  119423. ch[t5]=tr4-ti3;
  119424. ch[t4+t6-1]=ti4+tr3;
  119425. ch[t4+t6]=tr4+ti3;
  119426. ch[t5+t6-1]=tr2-tr1;
  119427. ch[t5+t6]=ti1-ti2;
  119428. }
  119429. t1+=ido;
  119430. }
  119431. if(ido&1)return;
  119432. L105:
  119433. t2=(t1=t0+ido-1)+(t0<<1);
  119434. t3=ido<<2;
  119435. t4=ido;
  119436. t5=ido<<1;
  119437. t6=ido;
  119438. for(k=0;k<l1;k++){
  119439. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119440. tr1=hsqt2*(cc[t1]-cc[t2]);
  119441. ch[t4-1]=tr1+cc[t6-1];
  119442. ch[t4+t5-1]=cc[t6-1]-tr1;
  119443. ch[t4]=ti1-cc[t1+t0];
  119444. ch[t4+t5]=ti1+cc[t1+t0];
  119445. t1+=ido;
  119446. t2+=ido;
  119447. t4+=t3;
  119448. t6+=ido;
  119449. }
  119450. }
  119451. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119452. float *c2,float *ch,float *ch2,float *wa){
  119453. static float tpi=6.283185307179586f;
  119454. int idij,ipph,i,j,k,l,ic,ik,is;
  119455. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119456. float dc2,ai1,ai2,ar1,ar2,ds2;
  119457. int nbd;
  119458. float dcp,arg,dsp,ar1h,ar2h;
  119459. int idp2,ipp2;
  119460. arg=tpi/(float)ip;
  119461. dcp=cos(arg);
  119462. dsp=sin(arg);
  119463. ipph=(ip+1)>>1;
  119464. ipp2=ip;
  119465. idp2=ido;
  119466. nbd=(ido-1)>>1;
  119467. t0=l1*ido;
  119468. t10=ip*ido;
  119469. if(ido==1)goto L119;
  119470. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119471. t1=0;
  119472. for(j=1;j<ip;j++){
  119473. t1+=t0;
  119474. t2=t1;
  119475. for(k=0;k<l1;k++){
  119476. ch[t2]=c1[t2];
  119477. t2+=ido;
  119478. }
  119479. }
  119480. is=-ido;
  119481. t1=0;
  119482. if(nbd>l1){
  119483. for(j=1;j<ip;j++){
  119484. t1+=t0;
  119485. is+=ido;
  119486. t2= -ido+t1;
  119487. for(k=0;k<l1;k++){
  119488. idij=is-1;
  119489. t2+=ido;
  119490. t3=t2;
  119491. for(i=2;i<ido;i+=2){
  119492. idij+=2;
  119493. t3+=2;
  119494. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119495. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119496. }
  119497. }
  119498. }
  119499. }else{
  119500. for(j=1;j<ip;j++){
  119501. is+=ido;
  119502. idij=is-1;
  119503. t1+=t0;
  119504. t2=t1;
  119505. for(i=2;i<ido;i+=2){
  119506. idij+=2;
  119507. t2+=2;
  119508. t3=t2;
  119509. for(k=0;k<l1;k++){
  119510. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119511. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119512. t3+=ido;
  119513. }
  119514. }
  119515. }
  119516. }
  119517. t1=0;
  119518. t2=ipp2*t0;
  119519. if(nbd<l1){
  119520. for(j=1;j<ipph;j++){
  119521. t1+=t0;
  119522. t2-=t0;
  119523. t3=t1;
  119524. t4=t2;
  119525. for(i=2;i<ido;i+=2){
  119526. t3+=2;
  119527. t4+=2;
  119528. t5=t3-ido;
  119529. t6=t4-ido;
  119530. for(k=0;k<l1;k++){
  119531. t5+=ido;
  119532. t6+=ido;
  119533. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119534. c1[t6-1]=ch[t5]-ch[t6];
  119535. c1[t5]=ch[t5]+ch[t6];
  119536. c1[t6]=ch[t6-1]-ch[t5-1];
  119537. }
  119538. }
  119539. }
  119540. }else{
  119541. for(j=1;j<ipph;j++){
  119542. t1+=t0;
  119543. t2-=t0;
  119544. t3=t1;
  119545. t4=t2;
  119546. for(k=0;k<l1;k++){
  119547. t5=t3;
  119548. t6=t4;
  119549. for(i=2;i<ido;i+=2){
  119550. t5+=2;
  119551. t6+=2;
  119552. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119553. c1[t6-1]=ch[t5]-ch[t6];
  119554. c1[t5]=ch[t5]+ch[t6];
  119555. c1[t6]=ch[t6-1]-ch[t5-1];
  119556. }
  119557. t3+=ido;
  119558. t4+=ido;
  119559. }
  119560. }
  119561. }
  119562. L119:
  119563. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119564. t1=0;
  119565. t2=ipp2*idl1;
  119566. for(j=1;j<ipph;j++){
  119567. t1+=t0;
  119568. t2-=t0;
  119569. t3=t1-ido;
  119570. t4=t2-ido;
  119571. for(k=0;k<l1;k++){
  119572. t3+=ido;
  119573. t4+=ido;
  119574. c1[t3]=ch[t3]+ch[t4];
  119575. c1[t4]=ch[t4]-ch[t3];
  119576. }
  119577. }
  119578. ar1=1.f;
  119579. ai1=0.f;
  119580. t1=0;
  119581. t2=ipp2*idl1;
  119582. t3=(ip-1)*idl1;
  119583. for(l=1;l<ipph;l++){
  119584. t1+=idl1;
  119585. t2-=idl1;
  119586. ar1h=dcp*ar1-dsp*ai1;
  119587. ai1=dcp*ai1+dsp*ar1;
  119588. ar1=ar1h;
  119589. t4=t1;
  119590. t5=t2;
  119591. t6=t3;
  119592. t7=idl1;
  119593. for(ik=0;ik<idl1;ik++){
  119594. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119595. ch2[t5++]=ai1*c2[t6++];
  119596. }
  119597. dc2=ar1;
  119598. ds2=ai1;
  119599. ar2=ar1;
  119600. ai2=ai1;
  119601. t4=idl1;
  119602. t5=(ipp2-1)*idl1;
  119603. for(j=2;j<ipph;j++){
  119604. t4+=idl1;
  119605. t5-=idl1;
  119606. ar2h=dc2*ar2-ds2*ai2;
  119607. ai2=dc2*ai2+ds2*ar2;
  119608. ar2=ar2h;
  119609. t6=t1;
  119610. t7=t2;
  119611. t8=t4;
  119612. t9=t5;
  119613. for(ik=0;ik<idl1;ik++){
  119614. ch2[t6++]+=ar2*c2[t8++];
  119615. ch2[t7++]+=ai2*c2[t9++];
  119616. }
  119617. }
  119618. }
  119619. t1=0;
  119620. for(j=1;j<ipph;j++){
  119621. t1+=idl1;
  119622. t2=t1;
  119623. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119624. }
  119625. if(ido<l1)goto L132;
  119626. t1=0;
  119627. t2=0;
  119628. for(k=0;k<l1;k++){
  119629. t3=t1;
  119630. t4=t2;
  119631. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119632. t1+=ido;
  119633. t2+=t10;
  119634. }
  119635. goto L135;
  119636. L132:
  119637. for(i=0;i<ido;i++){
  119638. t1=i;
  119639. t2=i;
  119640. for(k=0;k<l1;k++){
  119641. cc[t2]=ch[t1];
  119642. t1+=ido;
  119643. t2+=t10;
  119644. }
  119645. }
  119646. L135:
  119647. t1=0;
  119648. t2=ido<<1;
  119649. t3=0;
  119650. t4=ipp2*t0;
  119651. for(j=1;j<ipph;j++){
  119652. t1+=t2;
  119653. t3+=t0;
  119654. t4-=t0;
  119655. t5=t1;
  119656. t6=t3;
  119657. t7=t4;
  119658. for(k=0;k<l1;k++){
  119659. cc[t5-1]=ch[t6];
  119660. cc[t5]=ch[t7];
  119661. t5+=t10;
  119662. t6+=ido;
  119663. t7+=ido;
  119664. }
  119665. }
  119666. if(ido==1)return;
  119667. if(nbd<l1)goto L141;
  119668. t1=-ido;
  119669. t3=0;
  119670. t4=0;
  119671. t5=ipp2*t0;
  119672. for(j=1;j<ipph;j++){
  119673. t1+=t2;
  119674. t3+=t2;
  119675. t4+=t0;
  119676. t5-=t0;
  119677. t6=t1;
  119678. t7=t3;
  119679. t8=t4;
  119680. t9=t5;
  119681. for(k=0;k<l1;k++){
  119682. for(i=2;i<ido;i+=2){
  119683. ic=idp2-i;
  119684. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119685. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119686. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119687. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119688. }
  119689. t6+=t10;
  119690. t7+=t10;
  119691. t8+=ido;
  119692. t9+=ido;
  119693. }
  119694. }
  119695. return;
  119696. L141:
  119697. t1=-ido;
  119698. t3=0;
  119699. t4=0;
  119700. t5=ipp2*t0;
  119701. for(j=1;j<ipph;j++){
  119702. t1+=t2;
  119703. t3+=t2;
  119704. t4+=t0;
  119705. t5-=t0;
  119706. for(i=2;i<ido;i+=2){
  119707. t6=idp2+t1-i;
  119708. t7=i+t3;
  119709. t8=i+t4;
  119710. t9=i+t5;
  119711. for(k=0;k<l1;k++){
  119712. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119713. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119714. cc[t7]=ch[t8]+ch[t9];
  119715. cc[t6]=ch[t9]-ch[t8];
  119716. t6+=t10;
  119717. t7+=t10;
  119718. t8+=ido;
  119719. t9+=ido;
  119720. }
  119721. }
  119722. }
  119723. }
  119724. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119725. int i,k1,l1,l2;
  119726. int na,kh,nf;
  119727. int ip,iw,ido,idl1,ix2,ix3;
  119728. nf=ifac[1];
  119729. na=1;
  119730. l2=n;
  119731. iw=n;
  119732. for(k1=0;k1<nf;k1++){
  119733. kh=nf-k1;
  119734. ip=ifac[kh+1];
  119735. l1=l2/ip;
  119736. ido=n/l2;
  119737. idl1=ido*l1;
  119738. iw-=(ip-1)*ido;
  119739. na=1-na;
  119740. if(ip!=4)goto L102;
  119741. ix2=iw+ido;
  119742. ix3=ix2+ido;
  119743. if(na!=0)
  119744. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119745. else
  119746. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119747. goto L110;
  119748. L102:
  119749. if(ip!=2)goto L104;
  119750. if(na!=0)goto L103;
  119751. dradf2(ido,l1,c,ch,wa+iw-1);
  119752. goto L110;
  119753. L103:
  119754. dradf2(ido,l1,ch,c,wa+iw-1);
  119755. goto L110;
  119756. L104:
  119757. if(ido==1)na=1-na;
  119758. if(na!=0)goto L109;
  119759. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119760. na=1;
  119761. goto L110;
  119762. L109:
  119763. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119764. na=0;
  119765. L110:
  119766. l2=l1;
  119767. }
  119768. if(na==1)return;
  119769. for(i=0;i<n;i++)c[i]=ch[i];
  119770. }
  119771. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119772. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119773. float ti2,tr2;
  119774. t0=l1*ido;
  119775. t1=0;
  119776. t2=0;
  119777. t3=(ido<<1)-1;
  119778. for(k=0;k<l1;k++){
  119779. ch[t1]=cc[t2]+cc[t3+t2];
  119780. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119781. t2=(t1+=ido)<<1;
  119782. }
  119783. if(ido<2)return;
  119784. if(ido==2)goto L105;
  119785. t1=0;
  119786. t2=0;
  119787. for(k=0;k<l1;k++){
  119788. t3=t1;
  119789. t5=(t4=t2)+(ido<<1);
  119790. t6=t0+t1;
  119791. for(i=2;i<ido;i+=2){
  119792. t3+=2;
  119793. t4+=2;
  119794. t5-=2;
  119795. t6+=2;
  119796. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119797. tr2=cc[t4-1]-cc[t5-1];
  119798. ch[t3]=cc[t4]-cc[t5];
  119799. ti2=cc[t4]+cc[t5];
  119800. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119801. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119802. }
  119803. t2=(t1+=ido)<<1;
  119804. }
  119805. if(ido%2==1)return;
  119806. L105:
  119807. t1=ido-1;
  119808. t2=ido-1;
  119809. for(k=0;k<l1;k++){
  119810. ch[t1]=cc[t2]+cc[t2];
  119811. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119812. t1+=ido;
  119813. t2+=ido<<1;
  119814. }
  119815. }
  119816. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119817. float *wa2){
  119818. static float taur = -.5f;
  119819. static float taui = .8660254037844386f;
  119820. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119821. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119822. t0=l1*ido;
  119823. t1=0;
  119824. t2=t0<<1;
  119825. t3=ido<<1;
  119826. t4=ido+(ido<<1);
  119827. t5=0;
  119828. for(k=0;k<l1;k++){
  119829. tr2=cc[t3-1]+cc[t3-1];
  119830. cr2=cc[t5]+(taur*tr2);
  119831. ch[t1]=cc[t5]+tr2;
  119832. ci3=taui*(cc[t3]+cc[t3]);
  119833. ch[t1+t0]=cr2-ci3;
  119834. ch[t1+t2]=cr2+ci3;
  119835. t1+=ido;
  119836. t3+=t4;
  119837. t5+=t4;
  119838. }
  119839. if(ido==1)return;
  119840. t1=0;
  119841. t3=ido<<1;
  119842. for(k=0;k<l1;k++){
  119843. t7=t1+(t1<<1);
  119844. t6=(t5=t7+t3);
  119845. t8=t1;
  119846. t10=(t9=t1+t0)+t0;
  119847. for(i=2;i<ido;i+=2){
  119848. t5+=2;
  119849. t6-=2;
  119850. t7+=2;
  119851. t8+=2;
  119852. t9+=2;
  119853. t10+=2;
  119854. tr2=cc[t5-1]+cc[t6-1];
  119855. cr2=cc[t7-1]+(taur*tr2);
  119856. ch[t8-1]=cc[t7-1]+tr2;
  119857. ti2=cc[t5]-cc[t6];
  119858. ci2=cc[t7]+(taur*ti2);
  119859. ch[t8]=cc[t7]+ti2;
  119860. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119861. ci3=taui*(cc[t5]+cc[t6]);
  119862. dr2=cr2-ci3;
  119863. dr3=cr2+ci3;
  119864. di2=ci2+cr3;
  119865. di3=ci2-cr3;
  119866. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119867. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119868. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119869. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119870. }
  119871. t1+=ido;
  119872. }
  119873. }
  119874. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119875. float *wa2,float *wa3){
  119876. static float sqrt2=1.414213562373095f;
  119877. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119878. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119879. t0=l1*ido;
  119880. t1=0;
  119881. t2=ido<<2;
  119882. t3=0;
  119883. t6=ido<<1;
  119884. for(k=0;k<l1;k++){
  119885. t4=t3+t6;
  119886. t5=t1;
  119887. tr3=cc[t4-1]+cc[t4-1];
  119888. tr4=cc[t4]+cc[t4];
  119889. tr1=cc[t3]-cc[(t4+=t6)-1];
  119890. tr2=cc[t3]+cc[t4-1];
  119891. ch[t5]=tr2+tr3;
  119892. ch[t5+=t0]=tr1-tr4;
  119893. ch[t5+=t0]=tr2-tr3;
  119894. ch[t5+=t0]=tr1+tr4;
  119895. t1+=ido;
  119896. t3+=t2;
  119897. }
  119898. if(ido<2)return;
  119899. if(ido==2)goto L105;
  119900. t1=0;
  119901. for(k=0;k<l1;k++){
  119902. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119903. t7=t1;
  119904. for(i=2;i<ido;i+=2){
  119905. t2+=2;
  119906. t3+=2;
  119907. t4-=2;
  119908. t5-=2;
  119909. t7+=2;
  119910. ti1=cc[t2]+cc[t5];
  119911. ti2=cc[t2]-cc[t5];
  119912. ti3=cc[t3]-cc[t4];
  119913. tr4=cc[t3]+cc[t4];
  119914. tr1=cc[t2-1]-cc[t5-1];
  119915. tr2=cc[t2-1]+cc[t5-1];
  119916. ti4=cc[t3-1]-cc[t4-1];
  119917. tr3=cc[t3-1]+cc[t4-1];
  119918. ch[t7-1]=tr2+tr3;
  119919. cr3=tr2-tr3;
  119920. ch[t7]=ti2+ti3;
  119921. ci3=ti2-ti3;
  119922. cr2=tr1-tr4;
  119923. cr4=tr1+tr4;
  119924. ci2=ti1+ti4;
  119925. ci4=ti1-ti4;
  119926. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119927. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119928. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119929. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119930. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119931. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119932. }
  119933. t1+=ido;
  119934. }
  119935. if(ido%2 == 1)return;
  119936. L105:
  119937. t1=ido;
  119938. t2=ido<<2;
  119939. t3=ido-1;
  119940. t4=ido+(ido<<1);
  119941. for(k=0;k<l1;k++){
  119942. t5=t3;
  119943. ti1=cc[t1]+cc[t4];
  119944. ti2=cc[t4]-cc[t1];
  119945. tr1=cc[t1-1]-cc[t4-1];
  119946. tr2=cc[t1-1]+cc[t4-1];
  119947. ch[t5]=tr2+tr2;
  119948. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119949. ch[t5+=t0]=ti2+ti2;
  119950. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119951. t3+=ido;
  119952. t1+=t2;
  119953. t4+=t2;
  119954. }
  119955. }
  119956. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119957. float *c2,float *ch,float *ch2,float *wa){
  119958. static float tpi=6.283185307179586f;
  119959. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119960. t11,t12;
  119961. float dc2,ai1,ai2,ar1,ar2,ds2;
  119962. int nbd;
  119963. float dcp,arg,dsp,ar1h,ar2h;
  119964. int ipp2;
  119965. t10=ip*ido;
  119966. t0=l1*ido;
  119967. arg=tpi/(float)ip;
  119968. dcp=cos(arg);
  119969. dsp=sin(arg);
  119970. nbd=(ido-1)>>1;
  119971. ipp2=ip;
  119972. ipph=(ip+1)>>1;
  119973. if(ido<l1)goto L103;
  119974. t1=0;
  119975. t2=0;
  119976. for(k=0;k<l1;k++){
  119977. t3=t1;
  119978. t4=t2;
  119979. for(i=0;i<ido;i++){
  119980. ch[t3]=cc[t4];
  119981. t3++;
  119982. t4++;
  119983. }
  119984. t1+=ido;
  119985. t2+=t10;
  119986. }
  119987. goto L106;
  119988. L103:
  119989. t1=0;
  119990. for(i=0;i<ido;i++){
  119991. t2=t1;
  119992. t3=t1;
  119993. for(k=0;k<l1;k++){
  119994. ch[t2]=cc[t3];
  119995. t2+=ido;
  119996. t3+=t10;
  119997. }
  119998. t1++;
  119999. }
  120000. L106:
  120001. t1=0;
  120002. t2=ipp2*t0;
  120003. t7=(t5=ido<<1);
  120004. for(j=1;j<ipph;j++){
  120005. t1+=t0;
  120006. t2-=t0;
  120007. t3=t1;
  120008. t4=t2;
  120009. t6=t5;
  120010. for(k=0;k<l1;k++){
  120011. ch[t3]=cc[t6-1]+cc[t6-1];
  120012. ch[t4]=cc[t6]+cc[t6];
  120013. t3+=ido;
  120014. t4+=ido;
  120015. t6+=t10;
  120016. }
  120017. t5+=t7;
  120018. }
  120019. if (ido == 1)goto L116;
  120020. if(nbd<l1)goto L112;
  120021. t1=0;
  120022. t2=ipp2*t0;
  120023. t7=0;
  120024. for(j=1;j<ipph;j++){
  120025. t1+=t0;
  120026. t2-=t0;
  120027. t3=t1;
  120028. t4=t2;
  120029. t7+=(ido<<1);
  120030. t8=t7;
  120031. for(k=0;k<l1;k++){
  120032. t5=t3;
  120033. t6=t4;
  120034. t9=t8;
  120035. t11=t8;
  120036. for(i=2;i<ido;i+=2){
  120037. t5+=2;
  120038. t6+=2;
  120039. t9+=2;
  120040. t11-=2;
  120041. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120042. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120043. ch[t5]=cc[t9]-cc[t11];
  120044. ch[t6]=cc[t9]+cc[t11];
  120045. }
  120046. t3+=ido;
  120047. t4+=ido;
  120048. t8+=t10;
  120049. }
  120050. }
  120051. goto L116;
  120052. L112:
  120053. t1=0;
  120054. t2=ipp2*t0;
  120055. t7=0;
  120056. for(j=1;j<ipph;j++){
  120057. t1+=t0;
  120058. t2-=t0;
  120059. t3=t1;
  120060. t4=t2;
  120061. t7+=(ido<<1);
  120062. t8=t7;
  120063. t9=t7;
  120064. for(i=2;i<ido;i+=2){
  120065. t3+=2;
  120066. t4+=2;
  120067. t8+=2;
  120068. t9-=2;
  120069. t5=t3;
  120070. t6=t4;
  120071. t11=t8;
  120072. t12=t9;
  120073. for(k=0;k<l1;k++){
  120074. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120075. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120076. ch[t5]=cc[t11]-cc[t12];
  120077. ch[t6]=cc[t11]+cc[t12];
  120078. t5+=ido;
  120079. t6+=ido;
  120080. t11+=t10;
  120081. t12+=t10;
  120082. }
  120083. }
  120084. }
  120085. L116:
  120086. ar1=1.f;
  120087. ai1=0.f;
  120088. t1=0;
  120089. t9=(t2=ipp2*idl1);
  120090. t3=(ip-1)*idl1;
  120091. for(l=1;l<ipph;l++){
  120092. t1+=idl1;
  120093. t2-=idl1;
  120094. ar1h=dcp*ar1-dsp*ai1;
  120095. ai1=dcp*ai1+dsp*ar1;
  120096. ar1=ar1h;
  120097. t4=t1;
  120098. t5=t2;
  120099. t6=0;
  120100. t7=idl1;
  120101. t8=t3;
  120102. for(ik=0;ik<idl1;ik++){
  120103. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120104. c2[t5++]=ai1*ch2[t8++];
  120105. }
  120106. dc2=ar1;
  120107. ds2=ai1;
  120108. ar2=ar1;
  120109. ai2=ai1;
  120110. t6=idl1;
  120111. t7=t9-idl1;
  120112. for(j=2;j<ipph;j++){
  120113. t6+=idl1;
  120114. t7-=idl1;
  120115. ar2h=dc2*ar2-ds2*ai2;
  120116. ai2=dc2*ai2+ds2*ar2;
  120117. ar2=ar2h;
  120118. t4=t1;
  120119. t5=t2;
  120120. t11=t6;
  120121. t12=t7;
  120122. for(ik=0;ik<idl1;ik++){
  120123. c2[t4++]+=ar2*ch2[t11++];
  120124. c2[t5++]+=ai2*ch2[t12++];
  120125. }
  120126. }
  120127. }
  120128. t1=0;
  120129. for(j=1;j<ipph;j++){
  120130. t1+=idl1;
  120131. t2=t1;
  120132. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120133. }
  120134. t1=0;
  120135. t2=ipp2*t0;
  120136. for(j=1;j<ipph;j++){
  120137. t1+=t0;
  120138. t2-=t0;
  120139. t3=t1;
  120140. t4=t2;
  120141. for(k=0;k<l1;k++){
  120142. ch[t3]=c1[t3]-c1[t4];
  120143. ch[t4]=c1[t3]+c1[t4];
  120144. t3+=ido;
  120145. t4+=ido;
  120146. }
  120147. }
  120148. if(ido==1)goto L132;
  120149. if(nbd<l1)goto L128;
  120150. t1=0;
  120151. t2=ipp2*t0;
  120152. for(j=1;j<ipph;j++){
  120153. t1+=t0;
  120154. t2-=t0;
  120155. t3=t1;
  120156. t4=t2;
  120157. for(k=0;k<l1;k++){
  120158. t5=t3;
  120159. t6=t4;
  120160. for(i=2;i<ido;i+=2){
  120161. t5+=2;
  120162. t6+=2;
  120163. ch[t5-1]=c1[t5-1]-c1[t6];
  120164. ch[t6-1]=c1[t5-1]+c1[t6];
  120165. ch[t5]=c1[t5]+c1[t6-1];
  120166. ch[t6]=c1[t5]-c1[t6-1];
  120167. }
  120168. t3+=ido;
  120169. t4+=ido;
  120170. }
  120171. }
  120172. goto L132;
  120173. L128:
  120174. t1=0;
  120175. t2=ipp2*t0;
  120176. for(j=1;j<ipph;j++){
  120177. t1+=t0;
  120178. t2-=t0;
  120179. t3=t1;
  120180. t4=t2;
  120181. for(i=2;i<ido;i+=2){
  120182. t3+=2;
  120183. t4+=2;
  120184. t5=t3;
  120185. t6=t4;
  120186. for(k=0;k<l1;k++){
  120187. ch[t5-1]=c1[t5-1]-c1[t6];
  120188. ch[t6-1]=c1[t5-1]+c1[t6];
  120189. ch[t5]=c1[t5]+c1[t6-1];
  120190. ch[t6]=c1[t5]-c1[t6-1];
  120191. t5+=ido;
  120192. t6+=ido;
  120193. }
  120194. }
  120195. }
  120196. L132:
  120197. if(ido==1)return;
  120198. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120199. t1=0;
  120200. for(j=1;j<ip;j++){
  120201. t2=(t1+=t0);
  120202. for(k=0;k<l1;k++){
  120203. c1[t2]=ch[t2];
  120204. t2+=ido;
  120205. }
  120206. }
  120207. if(nbd>l1)goto L139;
  120208. is= -ido-1;
  120209. t1=0;
  120210. for(j=1;j<ip;j++){
  120211. is+=ido;
  120212. t1+=t0;
  120213. idij=is;
  120214. t2=t1;
  120215. for(i=2;i<ido;i+=2){
  120216. t2+=2;
  120217. idij+=2;
  120218. t3=t2;
  120219. for(k=0;k<l1;k++){
  120220. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120221. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120222. t3+=ido;
  120223. }
  120224. }
  120225. }
  120226. return;
  120227. L139:
  120228. is= -ido-1;
  120229. t1=0;
  120230. for(j=1;j<ip;j++){
  120231. is+=ido;
  120232. t1+=t0;
  120233. t2=t1;
  120234. for(k=0;k<l1;k++){
  120235. idij=is;
  120236. t3=t2;
  120237. for(i=2;i<ido;i+=2){
  120238. idij+=2;
  120239. t3+=2;
  120240. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120241. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120242. }
  120243. t2+=ido;
  120244. }
  120245. }
  120246. }
  120247. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120248. int i,k1,l1,l2;
  120249. int na;
  120250. int nf,ip,iw,ix2,ix3,ido,idl1;
  120251. nf=ifac[1];
  120252. na=0;
  120253. l1=1;
  120254. iw=1;
  120255. for(k1=0;k1<nf;k1++){
  120256. ip=ifac[k1 + 2];
  120257. l2=ip*l1;
  120258. ido=n/l2;
  120259. idl1=ido*l1;
  120260. if(ip!=4)goto L103;
  120261. ix2=iw+ido;
  120262. ix3=ix2+ido;
  120263. if(na!=0)
  120264. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120265. else
  120266. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120267. na=1-na;
  120268. goto L115;
  120269. L103:
  120270. if(ip!=2)goto L106;
  120271. if(na!=0)
  120272. dradb2(ido,l1,ch,c,wa+iw-1);
  120273. else
  120274. dradb2(ido,l1,c,ch,wa+iw-1);
  120275. na=1-na;
  120276. goto L115;
  120277. L106:
  120278. if(ip!=3)goto L109;
  120279. ix2=iw+ido;
  120280. if(na!=0)
  120281. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120282. else
  120283. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120284. na=1-na;
  120285. goto L115;
  120286. L109:
  120287. /* The radix five case can be translated later..... */
  120288. /* if(ip!=5)goto L112;
  120289. ix2=iw+ido;
  120290. ix3=ix2+ido;
  120291. ix4=ix3+ido;
  120292. if(na!=0)
  120293. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120294. else
  120295. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120296. na=1-na;
  120297. goto L115;
  120298. L112:*/
  120299. if(na!=0)
  120300. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120301. else
  120302. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120303. if(ido==1)na=1-na;
  120304. L115:
  120305. l1=l2;
  120306. iw+=(ip-1)*ido;
  120307. }
  120308. if(na==0)return;
  120309. for(i=0;i<n;i++)c[i]=ch[i];
  120310. }
  120311. void drft_forward(drft_lookup *l,float *data){
  120312. if(l->n==1)return;
  120313. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120314. }
  120315. void drft_backward(drft_lookup *l,float *data){
  120316. if (l->n==1)return;
  120317. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120318. }
  120319. void drft_init(drft_lookup *l,int n){
  120320. l->n=n;
  120321. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120322. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120323. fdrffti(n, l->trigcache, l->splitcache);
  120324. }
  120325. void drft_clear(drft_lookup *l){
  120326. if(l){
  120327. if(l->trigcache)_ogg_free(l->trigcache);
  120328. if(l->splitcache)_ogg_free(l->splitcache);
  120329. memset(l,0,sizeof(*l));
  120330. }
  120331. }
  120332. #endif
  120333. /*** End of inlined file: smallft.c ***/
  120334. /*** Start of inlined file: synthesis.c ***/
  120335. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120336. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120337. // tasks..
  120338. #if JUCE_MSVC
  120339. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120340. #endif
  120341. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120342. #if JUCE_USE_OGGVORBIS
  120343. #include <stdio.h>
  120344. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120345. vorbis_dsp_state *vd=vb->vd;
  120346. private_state *b=(private_state*)vd->backend_state;
  120347. vorbis_info *vi=vd->vi;
  120348. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120349. oggpack_buffer *opb=&vb->opb;
  120350. int type,mode,i;
  120351. /* first things first. Make sure decode is ready */
  120352. _vorbis_block_ripcord(vb);
  120353. oggpack_readinit(opb,op->packet,op->bytes);
  120354. /* Check the packet type */
  120355. if(oggpack_read(opb,1)!=0){
  120356. /* Oops. This is not an audio data packet */
  120357. return(OV_ENOTAUDIO);
  120358. }
  120359. /* read our mode and pre/post windowsize */
  120360. mode=oggpack_read(opb,b->modebits);
  120361. if(mode==-1)return(OV_EBADPACKET);
  120362. vb->mode=mode;
  120363. vb->W=ci->mode_param[mode]->blockflag;
  120364. if(vb->W){
  120365. /* this doesn;t get mapped through mode selection as it's used
  120366. only for window selection */
  120367. vb->lW=oggpack_read(opb,1);
  120368. vb->nW=oggpack_read(opb,1);
  120369. if(vb->nW==-1) return(OV_EBADPACKET);
  120370. }else{
  120371. vb->lW=0;
  120372. vb->nW=0;
  120373. }
  120374. /* more setup */
  120375. vb->granulepos=op->granulepos;
  120376. vb->sequence=op->packetno;
  120377. vb->eofflag=op->e_o_s;
  120378. /* alloc pcm passback storage */
  120379. vb->pcmend=ci->blocksizes[vb->W];
  120380. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120381. for(i=0;i<vi->channels;i++)
  120382. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120383. /* unpack_header enforces range checking */
  120384. type=ci->map_type[ci->mode_param[mode]->mapping];
  120385. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120386. mapping]));
  120387. }
  120388. /* used to track pcm position without actually performing decode.
  120389. Useful for sequential 'fast forward' */
  120390. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120391. vorbis_dsp_state *vd=vb->vd;
  120392. private_state *b=(private_state*)vd->backend_state;
  120393. vorbis_info *vi=vd->vi;
  120394. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120395. oggpack_buffer *opb=&vb->opb;
  120396. int mode;
  120397. /* first things first. Make sure decode is ready */
  120398. _vorbis_block_ripcord(vb);
  120399. oggpack_readinit(opb,op->packet,op->bytes);
  120400. /* Check the packet type */
  120401. if(oggpack_read(opb,1)!=0){
  120402. /* Oops. This is not an audio data packet */
  120403. return(OV_ENOTAUDIO);
  120404. }
  120405. /* read our mode and pre/post windowsize */
  120406. mode=oggpack_read(opb,b->modebits);
  120407. if(mode==-1)return(OV_EBADPACKET);
  120408. vb->mode=mode;
  120409. vb->W=ci->mode_param[mode]->blockflag;
  120410. if(vb->W){
  120411. vb->lW=oggpack_read(opb,1);
  120412. vb->nW=oggpack_read(opb,1);
  120413. if(vb->nW==-1) return(OV_EBADPACKET);
  120414. }else{
  120415. vb->lW=0;
  120416. vb->nW=0;
  120417. }
  120418. /* more setup */
  120419. vb->granulepos=op->granulepos;
  120420. vb->sequence=op->packetno;
  120421. vb->eofflag=op->e_o_s;
  120422. /* no pcm */
  120423. vb->pcmend=0;
  120424. vb->pcm=NULL;
  120425. return(0);
  120426. }
  120427. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120428. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120429. oggpack_buffer opb;
  120430. int mode;
  120431. oggpack_readinit(&opb,op->packet,op->bytes);
  120432. /* Check the packet type */
  120433. if(oggpack_read(&opb,1)!=0){
  120434. /* Oops. This is not an audio data packet */
  120435. return(OV_ENOTAUDIO);
  120436. }
  120437. {
  120438. int modebits=0;
  120439. int v=ci->modes;
  120440. while(v>1){
  120441. modebits++;
  120442. v>>=1;
  120443. }
  120444. /* read our mode and pre/post windowsize */
  120445. mode=oggpack_read(&opb,modebits);
  120446. }
  120447. if(mode==-1)return(OV_EBADPACKET);
  120448. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120449. }
  120450. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120451. /* set / clear half-sample-rate mode */
  120452. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120453. /* right now, our MDCT can't handle < 64 sample windows. */
  120454. if(ci->blocksizes[0]<=64 && flag)return -1;
  120455. ci->halfrate_flag=(flag?1:0);
  120456. return 0;
  120457. }
  120458. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120459. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120460. return ci->halfrate_flag;
  120461. }
  120462. #endif
  120463. /*** End of inlined file: synthesis.c ***/
  120464. /*** Start of inlined file: vorbisenc.c ***/
  120465. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120466. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120467. // tasks..
  120468. #if JUCE_MSVC
  120469. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120470. #endif
  120471. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120472. #if JUCE_USE_OGGVORBIS
  120473. #include <stdlib.h>
  120474. #include <string.h>
  120475. #include <math.h>
  120476. /* careful with this; it's using static array sizing to make managing
  120477. all the modes a little less annoying. If we use a residue backend
  120478. with > 12 partition types, or a different division of iteration,
  120479. this needs to be updated. */
  120480. typedef struct {
  120481. static_codebook *books[12][3];
  120482. } static_bookblock;
  120483. typedef struct {
  120484. int res_type;
  120485. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120486. vorbis_info_residue0 *res;
  120487. static_codebook *book_aux;
  120488. static_codebook *book_aux_managed;
  120489. static_bookblock *books_base;
  120490. static_bookblock *books_base_managed;
  120491. } vorbis_residue_template;
  120492. typedef struct {
  120493. vorbis_info_mapping0 *map;
  120494. vorbis_residue_template *res;
  120495. } vorbis_mapping_template;
  120496. typedef struct vp_adjblock{
  120497. int block[P_BANDS];
  120498. } vp_adjblock;
  120499. typedef struct {
  120500. int data[NOISE_COMPAND_LEVELS];
  120501. } compandblock;
  120502. /* high level configuration information for setting things up
  120503. step-by-step with the detailed vorbis_encode_ctl interface.
  120504. There's a fair amount of redundancy such that interactive setup
  120505. does not directly deal with any vorbis_info or codec_setup_info
  120506. initialization; it's all stored (until full init) in this highlevel
  120507. setup, then flushed out to the real codec setup structs later. */
  120508. typedef struct {
  120509. int att[P_NOISECURVES];
  120510. float boost;
  120511. float decay;
  120512. } att3;
  120513. typedef struct { int data[P_NOISECURVES]; } adj3;
  120514. typedef struct {
  120515. int pre[PACKETBLOBS];
  120516. int post[PACKETBLOBS];
  120517. float kHz[PACKETBLOBS];
  120518. float lowpasskHz[PACKETBLOBS];
  120519. } adj_stereo;
  120520. typedef struct {
  120521. int lo;
  120522. int hi;
  120523. int fixed;
  120524. } noiseguard;
  120525. typedef struct {
  120526. int data[P_NOISECURVES][17];
  120527. } noise3;
  120528. typedef struct {
  120529. int mappings;
  120530. double *rate_mapping;
  120531. double *quality_mapping;
  120532. int coupling_restriction;
  120533. long samplerate_min_restriction;
  120534. long samplerate_max_restriction;
  120535. int *blocksize_short;
  120536. int *blocksize_long;
  120537. att3 *psy_tone_masteratt;
  120538. int *psy_tone_0dB;
  120539. int *psy_tone_dBsuppress;
  120540. vp_adjblock *psy_tone_adj_impulse;
  120541. vp_adjblock *psy_tone_adj_long;
  120542. vp_adjblock *psy_tone_adj_other;
  120543. noiseguard *psy_noiseguards;
  120544. noise3 *psy_noise_bias_impulse;
  120545. noise3 *psy_noise_bias_padding;
  120546. noise3 *psy_noise_bias_trans;
  120547. noise3 *psy_noise_bias_long;
  120548. int *psy_noise_dBsuppress;
  120549. compandblock *psy_noise_compand;
  120550. double *psy_noise_compand_short_mapping;
  120551. double *psy_noise_compand_long_mapping;
  120552. int *psy_noise_normal_start[2];
  120553. int *psy_noise_normal_partition[2];
  120554. double *psy_noise_normal_thresh;
  120555. int *psy_ath_float;
  120556. int *psy_ath_abs;
  120557. double *psy_lowpass;
  120558. vorbis_info_psy_global *global_params;
  120559. double *global_mapping;
  120560. adj_stereo *stereo_modes;
  120561. static_codebook ***floor_books;
  120562. vorbis_info_floor1 *floor_params;
  120563. int *floor_short_mapping;
  120564. int *floor_long_mapping;
  120565. vorbis_mapping_template *maps;
  120566. } ve_setup_data_template;
  120567. /* a few static coder conventions */
  120568. static vorbis_info_mode _mode_template[2]={
  120569. {0,0,0,0},
  120570. {1,0,0,1}
  120571. };
  120572. static vorbis_info_mapping0 _map_nominal[2]={
  120573. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120574. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120575. };
  120576. /*** Start of inlined file: setup_44.h ***/
  120577. /*** Start of inlined file: floor_all.h ***/
  120578. /*** Start of inlined file: floor_books.h ***/
  120579. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120580. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120581. };
  120582. static static_codebook _huff_book_line_256x7_0sub1 = {
  120583. 1, 9,
  120584. _huff_lengthlist_line_256x7_0sub1,
  120585. 0, 0, 0, 0, 0,
  120586. NULL,
  120587. NULL,
  120588. NULL,
  120589. NULL,
  120590. 0
  120591. };
  120592. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120594. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120595. };
  120596. static static_codebook _huff_book_line_256x7_0sub2 = {
  120597. 1, 25,
  120598. _huff_lengthlist_line_256x7_0sub2,
  120599. 0, 0, 0, 0, 0,
  120600. NULL,
  120601. NULL,
  120602. NULL,
  120603. NULL,
  120604. 0
  120605. };
  120606. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120609. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120610. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120611. };
  120612. static static_codebook _huff_book_line_256x7_0sub3 = {
  120613. 1, 64,
  120614. _huff_lengthlist_line_256x7_0sub3,
  120615. 0, 0, 0, 0, 0,
  120616. NULL,
  120617. NULL,
  120618. NULL,
  120619. NULL,
  120620. 0
  120621. };
  120622. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120623. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120624. };
  120625. static static_codebook _huff_book_line_256x7_1sub1 = {
  120626. 1, 9,
  120627. _huff_lengthlist_line_256x7_1sub1,
  120628. 0, 0, 0, 0, 0,
  120629. NULL,
  120630. NULL,
  120631. NULL,
  120632. NULL,
  120633. 0
  120634. };
  120635. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120637. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120638. };
  120639. static static_codebook _huff_book_line_256x7_1sub2 = {
  120640. 1, 25,
  120641. _huff_lengthlist_line_256x7_1sub2,
  120642. 0, 0, 0, 0, 0,
  120643. NULL,
  120644. NULL,
  120645. NULL,
  120646. NULL,
  120647. 0
  120648. };
  120649. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120652. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120653. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120654. };
  120655. static static_codebook _huff_book_line_256x7_1sub3 = {
  120656. 1, 64,
  120657. _huff_lengthlist_line_256x7_1sub3,
  120658. 0, 0, 0, 0, 0,
  120659. NULL,
  120660. NULL,
  120661. NULL,
  120662. NULL,
  120663. 0
  120664. };
  120665. static long _huff_lengthlist_line_256x7_class0[] = {
  120666. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120667. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120668. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120669. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120670. };
  120671. static static_codebook _huff_book_line_256x7_class0 = {
  120672. 1, 64,
  120673. _huff_lengthlist_line_256x7_class0,
  120674. 0, 0, 0, 0, 0,
  120675. NULL,
  120676. NULL,
  120677. NULL,
  120678. NULL,
  120679. 0
  120680. };
  120681. static long _huff_lengthlist_line_256x7_class1[] = {
  120682. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120683. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120684. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120685. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120686. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120687. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120688. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120689. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120690. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120691. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120692. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120693. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120694. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120695. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120696. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120697. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120698. };
  120699. static static_codebook _huff_book_line_256x7_class1 = {
  120700. 1, 256,
  120701. _huff_lengthlist_line_256x7_class1,
  120702. 0, 0, 0, 0, 0,
  120703. NULL,
  120704. NULL,
  120705. NULL,
  120706. NULL,
  120707. 0
  120708. };
  120709. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120710. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120711. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120712. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120713. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120714. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120715. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120716. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120717. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120718. };
  120719. static static_codebook _huff_book_line_512x17_0sub0 = {
  120720. 1, 128,
  120721. _huff_lengthlist_line_512x17_0sub0,
  120722. 0, 0, 0, 0, 0,
  120723. NULL,
  120724. NULL,
  120725. NULL,
  120726. NULL,
  120727. 0
  120728. };
  120729. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120730. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120731. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120732. };
  120733. static static_codebook _huff_book_line_512x17_1sub0 = {
  120734. 1, 32,
  120735. _huff_lengthlist_line_512x17_1sub0,
  120736. 0, 0, 0, 0, 0,
  120737. NULL,
  120738. NULL,
  120739. NULL,
  120740. NULL,
  120741. 0
  120742. };
  120743. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120746. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120747. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120748. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120749. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120750. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120751. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120752. };
  120753. static static_codebook _huff_book_line_512x17_1sub1 = {
  120754. 1, 128,
  120755. _huff_lengthlist_line_512x17_1sub1,
  120756. 0, 0, 0, 0, 0,
  120757. NULL,
  120758. NULL,
  120759. NULL,
  120760. NULL,
  120761. 0
  120762. };
  120763. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120764. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120765. 5, 3,
  120766. };
  120767. static static_codebook _huff_book_line_512x17_2sub1 = {
  120768. 1, 18,
  120769. _huff_lengthlist_line_512x17_2sub1,
  120770. 0, 0, 0, 0, 0,
  120771. NULL,
  120772. NULL,
  120773. NULL,
  120774. NULL,
  120775. 0
  120776. };
  120777. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120779. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120780. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120781. 9, 8,
  120782. };
  120783. static static_codebook _huff_book_line_512x17_2sub2 = {
  120784. 1, 50,
  120785. _huff_lengthlist_line_512x17_2sub2,
  120786. 0, 0, 0, 0, 0,
  120787. NULL,
  120788. NULL,
  120789. NULL,
  120790. NULL,
  120791. 0
  120792. };
  120793. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120797. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120798. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120799. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120800. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120801. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120802. };
  120803. static static_codebook _huff_book_line_512x17_2sub3 = {
  120804. 1, 128,
  120805. _huff_lengthlist_line_512x17_2sub3,
  120806. 0, 0, 0, 0, 0,
  120807. NULL,
  120808. NULL,
  120809. NULL,
  120810. NULL,
  120811. 0
  120812. };
  120813. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120814. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120815. 5, 5,
  120816. };
  120817. static static_codebook _huff_book_line_512x17_3sub1 = {
  120818. 1, 18,
  120819. _huff_lengthlist_line_512x17_3sub1,
  120820. 0, 0, 0, 0, 0,
  120821. NULL,
  120822. NULL,
  120823. NULL,
  120824. NULL,
  120825. 0
  120826. };
  120827. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120829. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120830. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120831. 11,14,
  120832. };
  120833. static static_codebook _huff_book_line_512x17_3sub2 = {
  120834. 1, 50,
  120835. _huff_lengthlist_line_512x17_3sub2,
  120836. 0, 0, 0, 0, 0,
  120837. NULL,
  120838. NULL,
  120839. NULL,
  120840. NULL,
  120841. 0
  120842. };
  120843. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120847. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120848. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120849. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120850. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120851. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120852. };
  120853. static static_codebook _huff_book_line_512x17_3sub3 = {
  120854. 1, 128,
  120855. _huff_lengthlist_line_512x17_3sub3,
  120856. 0, 0, 0, 0, 0,
  120857. NULL,
  120858. NULL,
  120859. NULL,
  120860. NULL,
  120861. 0
  120862. };
  120863. static long _huff_lengthlist_line_512x17_class1[] = {
  120864. 1, 2, 3, 6, 5, 4, 7, 7,
  120865. };
  120866. static static_codebook _huff_book_line_512x17_class1 = {
  120867. 1, 8,
  120868. _huff_lengthlist_line_512x17_class1,
  120869. 0, 0, 0, 0, 0,
  120870. NULL,
  120871. NULL,
  120872. NULL,
  120873. NULL,
  120874. 0
  120875. };
  120876. static long _huff_lengthlist_line_512x17_class2[] = {
  120877. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120878. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120879. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120880. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120881. };
  120882. static static_codebook _huff_book_line_512x17_class2 = {
  120883. 1, 64,
  120884. _huff_lengthlist_line_512x17_class2,
  120885. 0, 0, 0, 0, 0,
  120886. NULL,
  120887. NULL,
  120888. NULL,
  120889. NULL,
  120890. 0
  120891. };
  120892. static long _huff_lengthlist_line_512x17_class3[] = {
  120893. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120894. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120895. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120896. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120897. };
  120898. static static_codebook _huff_book_line_512x17_class3 = {
  120899. 1, 64,
  120900. _huff_lengthlist_line_512x17_class3,
  120901. 0, 0, 0, 0, 0,
  120902. NULL,
  120903. NULL,
  120904. NULL,
  120905. NULL,
  120906. 0
  120907. };
  120908. static long _huff_lengthlist_line_128x4_class0[] = {
  120909. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120910. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120911. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120912. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120913. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120914. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120915. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120916. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120917. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120918. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120919. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120920. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120921. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120922. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120923. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120924. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120925. };
  120926. static static_codebook _huff_book_line_128x4_class0 = {
  120927. 1, 256,
  120928. _huff_lengthlist_line_128x4_class0,
  120929. 0, 0, 0, 0, 0,
  120930. NULL,
  120931. NULL,
  120932. NULL,
  120933. NULL,
  120934. 0
  120935. };
  120936. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120937. 2, 2, 2, 2,
  120938. };
  120939. static static_codebook _huff_book_line_128x4_0sub0 = {
  120940. 1, 4,
  120941. _huff_lengthlist_line_128x4_0sub0,
  120942. 0, 0, 0, 0, 0,
  120943. NULL,
  120944. NULL,
  120945. NULL,
  120946. NULL,
  120947. 0
  120948. };
  120949. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120950. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120951. };
  120952. static static_codebook _huff_book_line_128x4_0sub1 = {
  120953. 1, 10,
  120954. _huff_lengthlist_line_128x4_0sub1,
  120955. 0, 0, 0, 0, 0,
  120956. NULL,
  120957. NULL,
  120958. NULL,
  120959. NULL,
  120960. 0
  120961. };
  120962. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120964. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120965. };
  120966. static static_codebook _huff_book_line_128x4_0sub2 = {
  120967. 1, 25,
  120968. _huff_lengthlist_line_128x4_0sub2,
  120969. 0, 0, 0, 0, 0,
  120970. NULL,
  120971. NULL,
  120972. NULL,
  120973. NULL,
  120974. 0
  120975. };
  120976. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120979. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120980. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120981. };
  120982. static static_codebook _huff_book_line_128x4_0sub3 = {
  120983. 1, 64,
  120984. _huff_lengthlist_line_128x4_0sub3,
  120985. 0, 0, 0, 0, 0,
  120986. NULL,
  120987. NULL,
  120988. NULL,
  120989. NULL,
  120990. 0
  120991. };
  120992. static long _huff_lengthlist_line_256x4_class0[] = {
  120993. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120994. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120995. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120996. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120997. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120998. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120999. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121000. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121001. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121002. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121003. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121004. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121005. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121006. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121007. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121008. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121009. };
  121010. static static_codebook _huff_book_line_256x4_class0 = {
  121011. 1, 256,
  121012. _huff_lengthlist_line_256x4_class0,
  121013. 0, 0, 0, 0, 0,
  121014. NULL,
  121015. NULL,
  121016. NULL,
  121017. NULL,
  121018. 0
  121019. };
  121020. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121021. 2, 2, 2, 2,
  121022. };
  121023. static static_codebook _huff_book_line_256x4_0sub0 = {
  121024. 1, 4,
  121025. _huff_lengthlist_line_256x4_0sub0,
  121026. 0, 0, 0, 0, 0,
  121027. NULL,
  121028. NULL,
  121029. NULL,
  121030. NULL,
  121031. 0
  121032. };
  121033. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121034. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121035. };
  121036. static static_codebook _huff_book_line_256x4_0sub1 = {
  121037. 1, 10,
  121038. _huff_lengthlist_line_256x4_0sub1,
  121039. 0, 0, 0, 0, 0,
  121040. NULL,
  121041. NULL,
  121042. NULL,
  121043. NULL,
  121044. 0
  121045. };
  121046. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121048. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121049. };
  121050. static static_codebook _huff_book_line_256x4_0sub2 = {
  121051. 1, 25,
  121052. _huff_lengthlist_line_256x4_0sub2,
  121053. 0, 0, 0, 0, 0,
  121054. NULL,
  121055. NULL,
  121056. NULL,
  121057. NULL,
  121058. 0
  121059. };
  121060. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121063. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121064. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121065. };
  121066. static static_codebook _huff_book_line_256x4_0sub3 = {
  121067. 1, 64,
  121068. _huff_lengthlist_line_256x4_0sub3,
  121069. 0, 0, 0, 0, 0,
  121070. NULL,
  121071. NULL,
  121072. NULL,
  121073. NULL,
  121074. 0
  121075. };
  121076. static long _huff_lengthlist_line_128x7_class0[] = {
  121077. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121078. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121079. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121080. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121081. };
  121082. static static_codebook _huff_book_line_128x7_class0 = {
  121083. 1, 64,
  121084. _huff_lengthlist_line_128x7_class0,
  121085. 0, 0, 0, 0, 0,
  121086. NULL,
  121087. NULL,
  121088. NULL,
  121089. NULL,
  121090. 0
  121091. };
  121092. static long _huff_lengthlist_line_128x7_class1[] = {
  121093. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121094. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121095. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121096. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121097. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121098. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121099. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121100. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121101. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121102. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121103. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121104. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121105. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121106. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121107. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121108. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121109. };
  121110. static static_codebook _huff_book_line_128x7_class1 = {
  121111. 1, 256,
  121112. _huff_lengthlist_line_128x7_class1,
  121113. 0, 0, 0, 0, 0,
  121114. NULL,
  121115. NULL,
  121116. NULL,
  121117. NULL,
  121118. 0
  121119. };
  121120. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121121. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121122. };
  121123. static static_codebook _huff_book_line_128x7_0sub1 = {
  121124. 1, 9,
  121125. _huff_lengthlist_line_128x7_0sub1,
  121126. 0, 0, 0, 0, 0,
  121127. NULL,
  121128. NULL,
  121129. NULL,
  121130. NULL,
  121131. 0
  121132. };
  121133. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121135. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121136. };
  121137. static static_codebook _huff_book_line_128x7_0sub2 = {
  121138. 1, 25,
  121139. _huff_lengthlist_line_128x7_0sub2,
  121140. 0, 0, 0, 0, 0,
  121141. NULL,
  121142. NULL,
  121143. NULL,
  121144. NULL,
  121145. 0
  121146. };
  121147. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121150. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121151. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121152. };
  121153. static static_codebook _huff_book_line_128x7_0sub3 = {
  121154. 1, 64,
  121155. _huff_lengthlist_line_128x7_0sub3,
  121156. 0, 0, 0, 0, 0,
  121157. NULL,
  121158. NULL,
  121159. NULL,
  121160. NULL,
  121161. 0
  121162. };
  121163. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121164. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121165. };
  121166. static static_codebook _huff_book_line_128x7_1sub1 = {
  121167. 1, 9,
  121168. _huff_lengthlist_line_128x7_1sub1,
  121169. 0, 0, 0, 0, 0,
  121170. NULL,
  121171. NULL,
  121172. NULL,
  121173. NULL,
  121174. 0
  121175. };
  121176. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121178. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121179. };
  121180. static static_codebook _huff_book_line_128x7_1sub2 = {
  121181. 1, 25,
  121182. _huff_lengthlist_line_128x7_1sub2,
  121183. 0, 0, 0, 0, 0,
  121184. NULL,
  121185. NULL,
  121186. NULL,
  121187. NULL,
  121188. 0
  121189. };
  121190. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121193. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121194. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121195. };
  121196. static static_codebook _huff_book_line_128x7_1sub3 = {
  121197. 1, 64,
  121198. _huff_lengthlist_line_128x7_1sub3,
  121199. 0, 0, 0, 0, 0,
  121200. NULL,
  121201. NULL,
  121202. NULL,
  121203. NULL,
  121204. 0
  121205. };
  121206. static long _huff_lengthlist_line_128x11_class1[] = {
  121207. 1, 6, 3, 7, 2, 4, 5, 7,
  121208. };
  121209. static static_codebook _huff_book_line_128x11_class1 = {
  121210. 1, 8,
  121211. _huff_lengthlist_line_128x11_class1,
  121212. 0, 0, 0, 0, 0,
  121213. NULL,
  121214. NULL,
  121215. NULL,
  121216. NULL,
  121217. 0
  121218. };
  121219. static long _huff_lengthlist_line_128x11_class2[] = {
  121220. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121221. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121222. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121223. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121224. };
  121225. static static_codebook _huff_book_line_128x11_class2 = {
  121226. 1, 64,
  121227. _huff_lengthlist_line_128x11_class2,
  121228. 0, 0, 0, 0, 0,
  121229. NULL,
  121230. NULL,
  121231. NULL,
  121232. NULL,
  121233. 0
  121234. };
  121235. static long _huff_lengthlist_line_128x11_class3[] = {
  121236. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121237. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121238. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121239. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121240. };
  121241. static static_codebook _huff_book_line_128x11_class3 = {
  121242. 1, 64,
  121243. _huff_lengthlist_line_128x11_class3,
  121244. 0, 0, 0, 0, 0,
  121245. NULL,
  121246. NULL,
  121247. NULL,
  121248. NULL,
  121249. 0
  121250. };
  121251. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121252. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121253. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121254. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121255. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121256. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121257. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121258. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121259. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121260. };
  121261. static static_codebook _huff_book_line_128x11_0sub0 = {
  121262. 1, 128,
  121263. _huff_lengthlist_line_128x11_0sub0,
  121264. 0, 0, 0, 0, 0,
  121265. NULL,
  121266. NULL,
  121267. NULL,
  121268. NULL,
  121269. 0
  121270. };
  121271. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121272. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121273. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121274. };
  121275. static static_codebook _huff_book_line_128x11_1sub0 = {
  121276. 1, 32,
  121277. _huff_lengthlist_line_128x11_1sub0,
  121278. 0, 0, 0, 0, 0,
  121279. NULL,
  121280. NULL,
  121281. NULL,
  121282. NULL,
  121283. 0
  121284. };
  121285. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121288. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121289. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121290. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121291. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121292. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121293. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121294. };
  121295. static static_codebook _huff_book_line_128x11_1sub1 = {
  121296. 1, 128,
  121297. _huff_lengthlist_line_128x11_1sub1,
  121298. 0, 0, 0, 0, 0,
  121299. NULL,
  121300. NULL,
  121301. NULL,
  121302. NULL,
  121303. 0
  121304. };
  121305. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121306. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121307. 5, 5,
  121308. };
  121309. static static_codebook _huff_book_line_128x11_2sub1 = {
  121310. 1, 18,
  121311. _huff_lengthlist_line_128x11_2sub1,
  121312. 0, 0, 0, 0, 0,
  121313. NULL,
  121314. NULL,
  121315. NULL,
  121316. NULL,
  121317. 0
  121318. };
  121319. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121321. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121322. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121323. 8,11,
  121324. };
  121325. static static_codebook _huff_book_line_128x11_2sub2 = {
  121326. 1, 50,
  121327. _huff_lengthlist_line_128x11_2sub2,
  121328. 0, 0, 0, 0, 0,
  121329. NULL,
  121330. NULL,
  121331. NULL,
  121332. NULL,
  121333. 0
  121334. };
  121335. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121339. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121340. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121341. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121342. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121343. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121344. };
  121345. static static_codebook _huff_book_line_128x11_2sub3 = {
  121346. 1, 128,
  121347. _huff_lengthlist_line_128x11_2sub3,
  121348. 0, 0, 0, 0, 0,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. NULL,
  121353. 0
  121354. };
  121355. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121356. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121357. 5, 4,
  121358. };
  121359. static static_codebook _huff_book_line_128x11_3sub1 = {
  121360. 1, 18,
  121361. _huff_lengthlist_line_128x11_3sub1,
  121362. 0, 0, 0, 0, 0,
  121363. NULL,
  121364. NULL,
  121365. NULL,
  121366. NULL,
  121367. 0
  121368. };
  121369. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121371. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121372. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121373. 12, 6,
  121374. };
  121375. static static_codebook _huff_book_line_128x11_3sub2 = {
  121376. 1, 50,
  121377. _huff_lengthlist_line_128x11_3sub2,
  121378. 0, 0, 0, 0, 0,
  121379. NULL,
  121380. NULL,
  121381. NULL,
  121382. NULL,
  121383. 0
  121384. };
  121385. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121389. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121390. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121391. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121392. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121393. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121394. };
  121395. static static_codebook _huff_book_line_128x11_3sub3 = {
  121396. 1, 128,
  121397. _huff_lengthlist_line_128x11_3sub3,
  121398. 0, 0, 0, 0, 0,
  121399. NULL,
  121400. NULL,
  121401. NULL,
  121402. NULL,
  121403. 0
  121404. };
  121405. static long _huff_lengthlist_line_128x17_class1[] = {
  121406. 1, 3, 4, 7, 2, 5, 6, 7,
  121407. };
  121408. static static_codebook _huff_book_line_128x17_class1 = {
  121409. 1, 8,
  121410. _huff_lengthlist_line_128x17_class1,
  121411. 0, 0, 0, 0, 0,
  121412. NULL,
  121413. NULL,
  121414. NULL,
  121415. NULL,
  121416. 0
  121417. };
  121418. static long _huff_lengthlist_line_128x17_class2[] = {
  121419. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121420. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121421. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121422. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121423. };
  121424. static static_codebook _huff_book_line_128x17_class2 = {
  121425. 1, 64,
  121426. _huff_lengthlist_line_128x17_class2,
  121427. 0, 0, 0, 0, 0,
  121428. NULL,
  121429. NULL,
  121430. NULL,
  121431. NULL,
  121432. 0
  121433. };
  121434. static long _huff_lengthlist_line_128x17_class3[] = {
  121435. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121436. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121437. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121438. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121439. };
  121440. static static_codebook _huff_book_line_128x17_class3 = {
  121441. 1, 64,
  121442. _huff_lengthlist_line_128x17_class3,
  121443. 0, 0, 0, 0, 0,
  121444. NULL,
  121445. NULL,
  121446. NULL,
  121447. NULL,
  121448. 0
  121449. };
  121450. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121451. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121452. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121453. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121454. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121455. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121456. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121457. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121458. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121459. };
  121460. static static_codebook _huff_book_line_128x17_0sub0 = {
  121461. 1, 128,
  121462. _huff_lengthlist_line_128x17_0sub0,
  121463. 0, 0, 0, 0, 0,
  121464. NULL,
  121465. NULL,
  121466. NULL,
  121467. NULL,
  121468. 0
  121469. };
  121470. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121471. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121472. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121473. };
  121474. static static_codebook _huff_book_line_128x17_1sub0 = {
  121475. 1, 32,
  121476. _huff_lengthlist_line_128x17_1sub0,
  121477. 0, 0, 0, 0, 0,
  121478. NULL,
  121479. NULL,
  121480. NULL,
  121481. NULL,
  121482. 0
  121483. };
  121484. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121487. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121488. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121489. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121490. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121491. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121492. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121493. };
  121494. static static_codebook _huff_book_line_128x17_1sub1 = {
  121495. 1, 128,
  121496. _huff_lengthlist_line_128x17_1sub1,
  121497. 0, 0, 0, 0, 0,
  121498. NULL,
  121499. NULL,
  121500. NULL,
  121501. NULL,
  121502. 0
  121503. };
  121504. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121505. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121506. 9, 4,
  121507. };
  121508. static static_codebook _huff_book_line_128x17_2sub1 = {
  121509. 1, 18,
  121510. _huff_lengthlist_line_128x17_2sub1,
  121511. 0, 0, 0, 0, 0,
  121512. NULL,
  121513. NULL,
  121514. NULL,
  121515. NULL,
  121516. 0
  121517. };
  121518. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121520. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121521. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121522. 13,13,
  121523. };
  121524. static static_codebook _huff_book_line_128x17_2sub2 = {
  121525. 1, 50,
  121526. _huff_lengthlist_line_128x17_2sub2,
  121527. 0, 0, 0, 0, 0,
  121528. NULL,
  121529. NULL,
  121530. NULL,
  121531. NULL,
  121532. 0
  121533. };
  121534. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121538. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121539. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121540. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121541. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121542. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121543. };
  121544. static static_codebook _huff_book_line_128x17_2sub3 = {
  121545. 1, 128,
  121546. _huff_lengthlist_line_128x17_2sub3,
  121547. 0, 0, 0, 0, 0,
  121548. NULL,
  121549. NULL,
  121550. NULL,
  121551. NULL,
  121552. 0
  121553. };
  121554. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121555. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121556. 6, 4,
  121557. };
  121558. static static_codebook _huff_book_line_128x17_3sub1 = {
  121559. 1, 18,
  121560. _huff_lengthlist_line_128x17_3sub1,
  121561. 0, 0, 0, 0, 0,
  121562. NULL,
  121563. NULL,
  121564. NULL,
  121565. NULL,
  121566. 0
  121567. };
  121568. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121570. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121571. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121572. 10, 8,
  121573. };
  121574. static static_codebook _huff_book_line_128x17_3sub2 = {
  121575. 1, 50,
  121576. _huff_lengthlist_line_128x17_3sub2,
  121577. 0, 0, 0, 0, 0,
  121578. NULL,
  121579. NULL,
  121580. NULL,
  121581. NULL,
  121582. 0
  121583. };
  121584. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121588. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121589. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121590. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121592. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121593. };
  121594. static static_codebook _huff_book_line_128x17_3sub3 = {
  121595. 1, 128,
  121596. _huff_lengthlist_line_128x17_3sub3,
  121597. 0, 0, 0, 0, 0,
  121598. NULL,
  121599. NULL,
  121600. NULL,
  121601. NULL,
  121602. 0
  121603. };
  121604. static long _huff_lengthlist_line_1024x27_class1[] = {
  121605. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121606. };
  121607. static static_codebook _huff_book_line_1024x27_class1 = {
  121608. 1, 16,
  121609. _huff_lengthlist_line_1024x27_class1,
  121610. 0, 0, 0, 0, 0,
  121611. NULL,
  121612. NULL,
  121613. NULL,
  121614. NULL,
  121615. 0
  121616. };
  121617. static long _huff_lengthlist_line_1024x27_class2[] = {
  121618. 1, 4, 2, 6, 3, 7, 5, 7,
  121619. };
  121620. static static_codebook _huff_book_line_1024x27_class2 = {
  121621. 1, 8,
  121622. _huff_lengthlist_line_1024x27_class2,
  121623. 0, 0, 0, 0, 0,
  121624. NULL,
  121625. NULL,
  121626. NULL,
  121627. NULL,
  121628. 0
  121629. };
  121630. static long _huff_lengthlist_line_1024x27_class3[] = {
  121631. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121632. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121633. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121634. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121635. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121636. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121637. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121638. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121639. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121640. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121641. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121642. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121643. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121644. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121645. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121646. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121647. };
  121648. static static_codebook _huff_book_line_1024x27_class3 = {
  121649. 1, 256,
  121650. _huff_lengthlist_line_1024x27_class3,
  121651. 0, 0, 0, 0, 0,
  121652. NULL,
  121653. NULL,
  121654. NULL,
  121655. NULL,
  121656. 0
  121657. };
  121658. static long _huff_lengthlist_line_1024x27_class4[] = {
  121659. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121660. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121661. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121662. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121663. };
  121664. static static_codebook _huff_book_line_1024x27_class4 = {
  121665. 1, 64,
  121666. _huff_lengthlist_line_1024x27_class4,
  121667. 0, 0, 0, 0, 0,
  121668. NULL,
  121669. NULL,
  121670. NULL,
  121671. NULL,
  121672. 0
  121673. };
  121674. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121675. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121676. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121677. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121678. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121679. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121680. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121681. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121682. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121683. };
  121684. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121685. 1, 128,
  121686. _huff_lengthlist_line_1024x27_0sub0,
  121687. 0, 0, 0, 0, 0,
  121688. NULL,
  121689. NULL,
  121690. NULL,
  121691. NULL,
  121692. 0
  121693. };
  121694. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121695. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121696. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121697. };
  121698. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121699. 1, 32,
  121700. _huff_lengthlist_line_1024x27_1sub0,
  121701. 0, 0, 0, 0, 0,
  121702. NULL,
  121703. NULL,
  121704. NULL,
  121705. NULL,
  121706. 0
  121707. };
  121708. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121711. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121712. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121713. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121714. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121715. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121716. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121717. };
  121718. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121719. 1, 128,
  121720. _huff_lengthlist_line_1024x27_1sub1,
  121721. 0, 0, 0, 0, 0,
  121722. NULL,
  121723. NULL,
  121724. NULL,
  121725. NULL,
  121726. 0
  121727. };
  121728. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121729. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121730. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121731. };
  121732. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121733. 1, 32,
  121734. _huff_lengthlist_line_1024x27_2sub0,
  121735. 0, 0, 0, 0, 0,
  121736. NULL,
  121737. NULL,
  121738. NULL,
  121739. NULL,
  121740. 0
  121741. };
  121742. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121745. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121746. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121747. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121748. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121749. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121750. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121751. };
  121752. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121753. 1, 128,
  121754. _huff_lengthlist_line_1024x27_2sub1,
  121755. 0, 0, 0, 0, 0,
  121756. NULL,
  121757. NULL,
  121758. NULL,
  121759. NULL,
  121760. 0
  121761. };
  121762. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121763. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121764. 5, 5,
  121765. };
  121766. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121767. 1, 18,
  121768. _huff_lengthlist_line_1024x27_3sub1,
  121769. 0, 0, 0, 0, 0,
  121770. NULL,
  121771. NULL,
  121772. NULL,
  121773. NULL,
  121774. 0
  121775. };
  121776. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121779. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121780. 9,11,
  121781. };
  121782. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121783. 1, 50,
  121784. _huff_lengthlist_line_1024x27_3sub2,
  121785. 0, 0, 0, 0, 0,
  121786. NULL,
  121787. NULL,
  121788. NULL,
  121789. NULL,
  121790. 0
  121791. };
  121792. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121796. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121797. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121798. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121799. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121800. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121801. };
  121802. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121803. 1, 128,
  121804. _huff_lengthlist_line_1024x27_3sub3,
  121805. 0, 0, 0, 0, 0,
  121806. NULL,
  121807. NULL,
  121808. NULL,
  121809. NULL,
  121810. 0
  121811. };
  121812. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121813. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121814. 5, 4,
  121815. };
  121816. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121817. 1, 18,
  121818. _huff_lengthlist_line_1024x27_4sub1,
  121819. 0, 0, 0, 0, 0,
  121820. NULL,
  121821. NULL,
  121822. NULL,
  121823. NULL,
  121824. 0
  121825. };
  121826. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121828. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121829. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121830. 9,12,
  121831. };
  121832. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121833. 1, 50,
  121834. _huff_lengthlist_line_1024x27_4sub2,
  121835. 0, 0, 0, 0, 0,
  121836. NULL,
  121837. NULL,
  121838. NULL,
  121839. NULL,
  121840. 0
  121841. };
  121842. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121846. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121847. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121850. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121851. };
  121852. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121853. 1, 128,
  121854. _huff_lengthlist_line_1024x27_4sub3,
  121855. 0, 0, 0, 0, 0,
  121856. NULL,
  121857. NULL,
  121858. NULL,
  121859. NULL,
  121860. 0
  121861. };
  121862. static long _huff_lengthlist_line_2048x27_class1[] = {
  121863. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121864. };
  121865. static static_codebook _huff_book_line_2048x27_class1 = {
  121866. 1, 16,
  121867. _huff_lengthlist_line_2048x27_class1,
  121868. 0, 0, 0, 0, 0,
  121869. NULL,
  121870. NULL,
  121871. NULL,
  121872. NULL,
  121873. 0
  121874. };
  121875. static long _huff_lengthlist_line_2048x27_class2[] = {
  121876. 1, 2, 3, 6, 4, 7, 5, 7,
  121877. };
  121878. static static_codebook _huff_book_line_2048x27_class2 = {
  121879. 1, 8,
  121880. _huff_lengthlist_line_2048x27_class2,
  121881. 0, 0, 0, 0, 0,
  121882. NULL,
  121883. NULL,
  121884. NULL,
  121885. NULL,
  121886. 0
  121887. };
  121888. static long _huff_lengthlist_line_2048x27_class3[] = {
  121889. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121890. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121891. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121892. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121893. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121894. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121895. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121896. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121897. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121898. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121899. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121900. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121901. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121902. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121903. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121904. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121905. };
  121906. static static_codebook _huff_book_line_2048x27_class3 = {
  121907. 1, 256,
  121908. _huff_lengthlist_line_2048x27_class3,
  121909. 0, 0, 0, 0, 0,
  121910. NULL,
  121911. NULL,
  121912. NULL,
  121913. NULL,
  121914. 0
  121915. };
  121916. static long _huff_lengthlist_line_2048x27_class4[] = {
  121917. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121918. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121919. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121920. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121921. };
  121922. static static_codebook _huff_book_line_2048x27_class4 = {
  121923. 1, 64,
  121924. _huff_lengthlist_line_2048x27_class4,
  121925. 0, 0, 0, 0, 0,
  121926. NULL,
  121927. NULL,
  121928. NULL,
  121929. NULL,
  121930. 0
  121931. };
  121932. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121933. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121934. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121935. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121936. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121937. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121938. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121939. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121940. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121941. };
  121942. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121943. 1, 128,
  121944. _huff_lengthlist_line_2048x27_0sub0,
  121945. 0, 0, 0, 0, 0,
  121946. NULL,
  121947. NULL,
  121948. NULL,
  121949. NULL,
  121950. 0
  121951. };
  121952. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121953. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121954. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121955. };
  121956. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121957. 1, 32,
  121958. _huff_lengthlist_line_2048x27_1sub0,
  121959. 0, 0, 0, 0, 0,
  121960. NULL,
  121961. NULL,
  121962. NULL,
  121963. NULL,
  121964. 0
  121965. };
  121966. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  121967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121969. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121970. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121971. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121972. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121973. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121974. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121975. };
  121976. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121977. 1, 128,
  121978. _huff_lengthlist_line_2048x27_1sub1,
  121979. 0, 0, 0, 0, 0,
  121980. NULL,
  121981. NULL,
  121982. NULL,
  121983. NULL,
  121984. 0
  121985. };
  121986. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121987. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121988. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121989. };
  121990. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121991. 1, 32,
  121992. _huff_lengthlist_line_2048x27_2sub0,
  121993. 0, 0, 0, 0, 0,
  121994. NULL,
  121995. NULL,
  121996. NULL,
  121997. NULL,
  121998. 0
  121999. };
  122000. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122003. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122004. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122005. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122006. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122007. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122008. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122009. };
  122010. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122011. 1, 128,
  122012. _huff_lengthlist_line_2048x27_2sub1,
  122013. 0, 0, 0, 0, 0,
  122014. NULL,
  122015. NULL,
  122016. NULL,
  122017. NULL,
  122018. 0
  122019. };
  122020. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122021. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122022. 5, 5,
  122023. };
  122024. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122025. 1, 18,
  122026. _huff_lengthlist_line_2048x27_3sub1,
  122027. 0, 0, 0, 0, 0,
  122028. NULL,
  122029. NULL,
  122030. NULL,
  122031. NULL,
  122032. 0
  122033. };
  122034. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122036. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122037. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122038. 10,12,
  122039. };
  122040. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122041. 1, 50,
  122042. _huff_lengthlist_line_2048x27_3sub2,
  122043. 0, 0, 0, 0, 0,
  122044. NULL,
  122045. NULL,
  122046. NULL,
  122047. NULL,
  122048. 0
  122049. };
  122050. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122054. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122055. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122056. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122057. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122058. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122059. };
  122060. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122061. 1, 128,
  122062. _huff_lengthlist_line_2048x27_3sub3,
  122063. 0, 0, 0, 0, 0,
  122064. NULL,
  122065. NULL,
  122066. NULL,
  122067. NULL,
  122068. 0
  122069. };
  122070. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122071. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122072. 4, 5,
  122073. };
  122074. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122075. 1, 18,
  122076. _huff_lengthlist_line_2048x27_4sub1,
  122077. 0, 0, 0, 0, 0,
  122078. NULL,
  122079. NULL,
  122080. NULL,
  122081. NULL,
  122082. 0
  122083. };
  122084. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122086. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122087. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122088. 10,10,
  122089. };
  122090. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122091. 1, 50,
  122092. _huff_lengthlist_line_2048x27_4sub2,
  122093. 0, 0, 0, 0, 0,
  122094. NULL,
  122095. NULL,
  122096. NULL,
  122097. NULL,
  122098. 0
  122099. };
  122100. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122104. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122105. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122106. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122107. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122108. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122109. };
  122110. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122111. 1, 128,
  122112. _huff_lengthlist_line_2048x27_4sub3,
  122113. 0, 0, 0, 0, 0,
  122114. NULL,
  122115. NULL,
  122116. NULL,
  122117. NULL,
  122118. 0
  122119. };
  122120. static long _huff_lengthlist_line_256x4low_class0[] = {
  122121. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122122. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122123. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122124. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122125. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122126. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122127. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122128. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122129. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122130. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122131. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122132. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122133. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122134. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122135. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122136. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122137. };
  122138. static static_codebook _huff_book_line_256x4low_class0 = {
  122139. 1, 256,
  122140. _huff_lengthlist_line_256x4low_class0,
  122141. 0, 0, 0, 0, 0,
  122142. NULL,
  122143. NULL,
  122144. NULL,
  122145. NULL,
  122146. 0
  122147. };
  122148. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122149. 1, 3, 2, 3,
  122150. };
  122151. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122152. 1, 4,
  122153. _huff_lengthlist_line_256x4low_0sub0,
  122154. 0, 0, 0, 0, 0,
  122155. NULL,
  122156. NULL,
  122157. NULL,
  122158. NULL,
  122159. 0
  122160. };
  122161. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122162. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122163. };
  122164. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122165. 1, 10,
  122166. _huff_lengthlist_line_256x4low_0sub1,
  122167. 0, 0, 0, 0, 0,
  122168. NULL,
  122169. NULL,
  122170. NULL,
  122171. NULL,
  122172. 0
  122173. };
  122174. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122176. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122177. };
  122178. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122179. 1, 25,
  122180. _huff_lengthlist_line_256x4low_0sub2,
  122181. 0, 0, 0, 0, 0,
  122182. NULL,
  122183. NULL,
  122184. NULL,
  122185. NULL,
  122186. 0
  122187. };
  122188. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122191. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122192. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122193. };
  122194. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122195. 1, 64,
  122196. _huff_lengthlist_line_256x4low_0sub3,
  122197. 0, 0, 0, 0, 0,
  122198. NULL,
  122199. NULL,
  122200. NULL,
  122201. NULL,
  122202. 0
  122203. };
  122204. /*** End of inlined file: floor_books.h ***/
  122205. static static_codebook *_floor_128x4_books[]={
  122206. &_huff_book_line_128x4_class0,
  122207. &_huff_book_line_128x4_0sub0,
  122208. &_huff_book_line_128x4_0sub1,
  122209. &_huff_book_line_128x4_0sub2,
  122210. &_huff_book_line_128x4_0sub3,
  122211. };
  122212. static static_codebook *_floor_256x4_books[]={
  122213. &_huff_book_line_256x4_class0,
  122214. &_huff_book_line_256x4_0sub0,
  122215. &_huff_book_line_256x4_0sub1,
  122216. &_huff_book_line_256x4_0sub2,
  122217. &_huff_book_line_256x4_0sub3,
  122218. };
  122219. static static_codebook *_floor_128x7_books[]={
  122220. &_huff_book_line_128x7_class0,
  122221. &_huff_book_line_128x7_class1,
  122222. &_huff_book_line_128x7_0sub1,
  122223. &_huff_book_line_128x7_0sub2,
  122224. &_huff_book_line_128x7_0sub3,
  122225. &_huff_book_line_128x7_1sub1,
  122226. &_huff_book_line_128x7_1sub2,
  122227. &_huff_book_line_128x7_1sub3,
  122228. };
  122229. static static_codebook *_floor_256x7_books[]={
  122230. &_huff_book_line_256x7_class0,
  122231. &_huff_book_line_256x7_class1,
  122232. &_huff_book_line_256x7_0sub1,
  122233. &_huff_book_line_256x7_0sub2,
  122234. &_huff_book_line_256x7_0sub3,
  122235. &_huff_book_line_256x7_1sub1,
  122236. &_huff_book_line_256x7_1sub2,
  122237. &_huff_book_line_256x7_1sub3,
  122238. };
  122239. static static_codebook *_floor_128x11_books[]={
  122240. &_huff_book_line_128x11_class1,
  122241. &_huff_book_line_128x11_class2,
  122242. &_huff_book_line_128x11_class3,
  122243. &_huff_book_line_128x11_0sub0,
  122244. &_huff_book_line_128x11_1sub0,
  122245. &_huff_book_line_128x11_1sub1,
  122246. &_huff_book_line_128x11_2sub1,
  122247. &_huff_book_line_128x11_2sub2,
  122248. &_huff_book_line_128x11_2sub3,
  122249. &_huff_book_line_128x11_3sub1,
  122250. &_huff_book_line_128x11_3sub2,
  122251. &_huff_book_line_128x11_3sub3,
  122252. };
  122253. static static_codebook *_floor_128x17_books[]={
  122254. &_huff_book_line_128x17_class1,
  122255. &_huff_book_line_128x17_class2,
  122256. &_huff_book_line_128x17_class3,
  122257. &_huff_book_line_128x17_0sub0,
  122258. &_huff_book_line_128x17_1sub0,
  122259. &_huff_book_line_128x17_1sub1,
  122260. &_huff_book_line_128x17_2sub1,
  122261. &_huff_book_line_128x17_2sub2,
  122262. &_huff_book_line_128x17_2sub3,
  122263. &_huff_book_line_128x17_3sub1,
  122264. &_huff_book_line_128x17_3sub2,
  122265. &_huff_book_line_128x17_3sub3,
  122266. };
  122267. static static_codebook *_floor_256x4low_books[]={
  122268. &_huff_book_line_256x4low_class0,
  122269. &_huff_book_line_256x4low_0sub0,
  122270. &_huff_book_line_256x4low_0sub1,
  122271. &_huff_book_line_256x4low_0sub2,
  122272. &_huff_book_line_256x4low_0sub3,
  122273. };
  122274. static static_codebook *_floor_1024x27_books[]={
  122275. &_huff_book_line_1024x27_class1,
  122276. &_huff_book_line_1024x27_class2,
  122277. &_huff_book_line_1024x27_class3,
  122278. &_huff_book_line_1024x27_class4,
  122279. &_huff_book_line_1024x27_0sub0,
  122280. &_huff_book_line_1024x27_1sub0,
  122281. &_huff_book_line_1024x27_1sub1,
  122282. &_huff_book_line_1024x27_2sub0,
  122283. &_huff_book_line_1024x27_2sub1,
  122284. &_huff_book_line_1024x27_3sub1,
  122285. &_huff_book_line_1024x27_3sub2,
  122286. &_huff_book_line_1024x27_3sub3,
  122287. &_huff_book_line_1024x27_4sub1,
  122288. &_huff_book_line_1024x27_4sub2,
  122289. &_huff_book_line_1024x27_4sub3,
  122290. };
  122291. static static_codebook *_floor_2048x27_books[]={
  122292. &_huff_book_line_2048x27_class1,
  122293. &_huff_book_line_2048x27_class2,
  122294. &_huff_book_line_2048x27_class3,
  122295. &_huff_book_line_2048x27_class4,
  122296. &_huff_book_line_2048x27_0sub0,
  122297. &_huff_book_line_2048x27_1sub0,
  122298. &_huff_book_line_2048x27_1sub1,
  122299. &_huff_book_line_2048x27_2sub0,
  122300. &_huff_book_line_2048x27_2sub1,
  122301. &_huff_book_line_2048x27_3sub1,
  122302. &_huff_book_line_2048x27_3sub2,
  122303. &_huff_book_line_2048x27_3sub3,
  122304. &_huff_book_line_2048x27_4sub1,
  122305. &_huff_book_line_2048x27_4sub2,
  122306. &_huff_book_line_2048x27_4sub3,
  122307. };
  122308. static static_codebook *_floor_512x17_books[]={
  122309. &_huff_book_line_512x17_class1,
  122310. &_huff_book_line_512x17_class2,
  122311. &_huff_book_line_512x17_class3,
  122312. &_huff_book_line_512x17_0sub0,
  122313. &_huff_book_line_512x17_1sub0,
  122314. &_huff_book_line_512x17_1sub1,
  122315. &_huff_book_line_512x17_2sub1,
  122316. &_huff_book_line_512x17_2sub2,
  122317. &_huff_book_line_512x17_2sub3,
  122318. &_huff_book_line_512x17_3sub1,
  122319. &_huff_book_line_512x17_3sub2,
  122320. &_huff_book_line_512x17_3sub3,
  122321. };
  122322. static static_codebook **_floor_books[10]={
  122323. _floor_128x4_books,
  122324. _floor_256x4_books,
  122325. _floor_128x7_books,
  122326. _floor_256x7_books,
  122327. _floor_128x11_books,
  122328. _floor_128x17_books,
  122329. _floor_256x4low_books,
  122330. _floor_1024x27_books,
  122331. _floor_2048x27_books,
  122332. _floor_512x17_books,
  122333. };
  122334. static vorbis_info_floor1 _floor[10]={
  122335. /* 128 x 4 */
  122336. {
  122337. 1,{0},{4},{2},{0},
  122338. {{1,2,3,4}},
  122339. 4,{0,128, 33,8,16,70},
  122340. 60,30,500, 1.,18., -1
  122341. },
  122342. /* 256 x 4 */
  122343. {
  122344. 1,{0},{4},{2},{0},
  122345. {{1,2,3,4}},
  122346. 4,{0,256, 66,16,32,140},
  122347. 60,30,500, 1.,18., -1
  122348. },
  122349. /* 128 x 7 */
  122350. {
  122351. 2,{0,1},{3,4},{2,2},{0,1},
  122352. {{-1,2,3,4},{-1,5,6,7}},
  122353. 4,{0,128, 14,4,58, 2,8,28,90},
  122354. 60,30,500, 1.,18., -1
  122355. },
  122356. /* 256 x 7 */
  122357. {
  122358. 2,{0,1},{3,4},{2,2},{0,1},
  122359. {{-1,2,3,4},{-1,5,6,7}},
  122360. 4,{0,256, 28,8,116, 4,16,56,180},
  122361. 60,30,500, 1.,18., -1
  122362. },
  122363. /* 128 x 11 */
  122364. {
  122365. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122366. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122367. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122368. 60,30,500, 1,18., -1
  122369. },
  122370. /* 128 x 17 */
  122371. {
  122372. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122373. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122374. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122375. 60,30,500, 1,18., -1
  122376. },
  122377. /* 256 x 4 (low bitrate version) */
  122378. {
  122379. 1,{0},{4},{2},{0},
  122380. {{1,2,3,4}},
  122381. 4,{0,256, 66,16,32,140},
  122382. 60,30,500, 1.,18., -1
  122383. },
  122384. /* 1024 x 27 */
  122385. {
  122386. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122387. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122388. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122389. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122390. 60,30,500, 3,18., -1 /* lowpass */
  122391. },
  122392. /* 2048 x 27 */
  122393. {
  122394. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122395. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122396. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122397. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122398. 60,30,500, 3,18., -1 /* lowpass */
  122399. },
  122400. /* 512 x 17 */
  122401. {
  122402. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122403. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122404. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122405. 7,23,39, 55,79,110, 156,232,360},
  122406. 60,30,500, 1,18., -1 /* lowpass! */
  122407. },
  122408. };
  122409. /*** End of inlined file: floor_all.h ***/
  122410. /*** Start of inlined file: residue_44.h ***/
  122411. /*** Start of inlined file: res_books_stereo.h ***/
  122412. static long _vq_quantlist__16c0_s_p1_0[] = {
  122413. 1,
  122414. 0,
  122415. 2,
  122416. };
  122417. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122418. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122419. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122423. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122424. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122429. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122464. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122469. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122474. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122510. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122514. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122515. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122519. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122520. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0,
  122829. };
  122830. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122831. -0.5, 0.5,
  122832. };
  122833. static long _vq_quantmap__16c0_s_p1_0[] = {
  122834. 1, 0, 2,
  122835. };
  122836. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122837. _vq_quantthresh__16c0_s_p1_0,
  122838. _vq_quantmap__16c0_s_p1_0,
  122839. 3,
  122840. 3
  122841. };
  122842. static static_codebook _16c0_s_p1_0 = {
  122843. 8, 6561,
  122844. _vq_lengthlist__16c0_s_p1_0,
  122845. 1, -535822336, 1611661312, 2, 0,
  122846. _vq_quantlist__16c0_s_p1_0,
  122847. NULL,
  122848. &_vq_auxt__16c0_s_p1_0,
  122849. NULL,
  122850. 0
  122851. };
  122852. static long _vq_quantlist__16c0_s_p2_0[] = {
  122853. 2,
  122854. 1,
  122855. 3,
  122856. 0,
  122857. 4,
  122858. };
  122859. static long _vq_lengthlist__16c0_s_p2_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,
  122900. };
  122901. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122902. -1.5, -0.5, 0.5, 1.5,
  122903. };
  122904. static long _vq_quantmap__16c0_s_p2_0[] = {
  122905. 3, 1, 0, 2, 4,
  122906. };
  122907. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122908. _vq_quantthresh__16c0_s_p2_0,
  122909. _vq_quantmap__16c0_s_p2_0,
  122910. 5,
  122911. 5
  122912. };
  122913. static static_codebook _16c0_s_p2_0 = {
  122914. 4, 625,
  122915. _vq_lengthlist__16c0_s_p2_0,
  122916. 1, -533725184, 1611661312, 3, 0,
  122917. _vq_quantlist__16c0_s_p2_0,
  122918. NULL,
  122919. &_vq_auxt__16c0_s_p2_0,
  122920. NULL,
  122921. 0
  122922. };
  122923. static long _vq_quantlist__16c0_s_p3_0[] = {
  122924. 2,
  122925. 1,
  122926. 3,
  122927. 0,
  122928. 4,
  122929. };
  122930. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122931. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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,
  122971. };
  122972. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122973. -1.5, -0.5, 0.5, 1.5,
  122974. };
  122975. static long _vq_quantmap__16c0_s_p3_0[] = {
  122976. 3, 1, 0, 2, 4,
  122977. };
  122978. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122979. _vq_quantthresh__16c0_s_p3_0,
  122980. _vq_quantmap__16c0_s_p3_0,
  122981. 5,
  122982. 5
  122983. };
  122984. static static_codebook _16c0_s_p3_0 = {
  122985. 4, 625,
  122986. _vq_lengthlist__16c0_s_p3_0,
  122987. 1, -533725184, 1611661312, 3, 0,
  122988. _vq_quantlist__16c0_s_p3_0,
  122989. NULL,
  122990. &_vq_auxt__16c0_s_p3_0,
  122991. NULL,
  122992. 0
  122993. };
  122994. static long _vq_quantlist__16c0_s_p4_0[] = {
  122995. 4,
  122996. 3,
  122997. 5,
  122998. 2,
  122999. 6,
  123000. 1,
  123001. 7,
  123002. 0,
  123003. 8,
  123004. };
  123005. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123006. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123007. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123008. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123009. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123010. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0,
  123012. };
  123013. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123014. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123015. };
  123016. static long _vq_quantmap__16c0_s_p4_0[] = {
  123017. 7, 5, 3, 1, 0, 2, 4, 6,
  123018. 8,
  123019. };
  123020. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123021. _vq_quantthresh__16c0_s_p4_0,
  123022. _vq_quantmap__16c0_s_p4_0,
  123023. 9,
  123024. 9
  123025. };
  123026. static static_codebook _16c0_s_p4_0 = {
  123027. 2, 81,
  123028. _vq_lengthlist__16c0_s_p4_0,
  123029. 1, -531628032, 1611661312, 4, 0,
  123030. _vq_quantlist__16c0_s_p4_0,
  123031. NULL,
  123032. &_vq_auxt__16c0_s_p4_0,
  123033. NULL,
  123034. 0
  123035. };
  123036. static long _vq_quantlist__16c0_s_p5_0[] = {
  123037. 4,
  123038. 3,
  123039. 5,
  123040. 2,
  123041. 6,
  123042. 1,
  123043. 7,
  123044. 0,
  123045. 8,
  123046. };
  123047. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123048. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123049. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123050. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123051. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123052. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123053. 10,
  123054. };
  123055. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123056. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123057. };
  123058. static long _vq_quantmap__16c0_s_p5_0[] = {
  123059. 7, 5, 3, 1, 0, 2, 4, 6,
  123060. 8,
  123061. };
  123062. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123063. _vq_quantthresh__16c0_s_p5_0,
  123064. _vq_quantmap__16c0_s_p5_0,
  123065. 9,
  123066. 9
  123067. };
  123068. static static_codebook _16c0_s_p5_0 = {
  123069. 2, 81,
  123070. _vq_lengthlist__16c0_s_p5_0,
  123071. 1, -531628032, 1611661312, 4, 0,
  123072. _vq_quantlist__16c0_s_p5_0,
  123073. NULL,
  123074. &_vq_auxt__16c0_s_p5_0,
  123075. NULL,
  123076. 0
  123077. };
  123078. static long _vq_quantlist__16c0_s_p6_0[] = {
  123079. 8,
  123080. 7,
  123081. 9,
  123082. 6,
  123083. 10,
  123084. 5,
  123085. 11,
  123086. 4,
  123087. 12,
  123088. 3,
  123089. 13,
  123090. 2,
  123091. 14,
  123092. 1,
  123093. 15,
  123094. 0,
  123095. 16,
  123096. };
  123097. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123098. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123099. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123100. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123101. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123102. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123103. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123104. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123105. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123106. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123107. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123108. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123109. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123110. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123111. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123112. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123113. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123114. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123116. 14,
  123117. };
  123118. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123119. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123120. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123121. };
  123122. static long _vq_quantmap__16c0_s_p6_0[] = {
  123123. 15, 13, 11, 9, 7, 5, 3, 1,
  123124. 0, 2, 4, 6, 8, 10, 12, 14,
  123125. 16,
  123126. };
  123127. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123128. _vq_quantthresh__16c0_s_p6_0,
  123129. _vq_quantmap__16c0_s_p6_0,
  123130. 17,
  123131. 17
  123132. };
  123133. static static_codebook _16c0_s_p6_0 = {
  123134. 2, 289,
  123135. _vq_lengthlist__16c0_s_p6_0,
  123136. 1, -529530880, 1611661312, 5, 0,
  123137. _vq_quantlist__16c0_s_p6_0,
  123138. NULL,
  123139. &_vq_auxt__16c0_s_p6_0,
  123140. NULL,
  123141. 0
  123142. };
  123143. static long _vq_quantlist__16c0_s_p7_0[] = {
  123144. 1,
  123145. 0,
  123146. 2,
  123147. };
  123148. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123149. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123150. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123151. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123152. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123153. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123154. 13,
  123155. };
  123156. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123157. -5.5, 5.5,
  123158. };
  123159. static long _vq_quantmap__16c0_s_p7_0[] = {
  123160. 1, 0, 2,
  123161. };
  123162. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123163. _vq_quantthresh__16c0_s_p7_0,
  123164. _vq_quantmap__16c0_s_p7_0,
  123165. 3,
  123166. 3
  123167. };
  123168. static static_codebook _16c0_s_p7_0 = {
  123169. 4, 81,
  123170. _vq_lengthlist__16c0_s_p7_0,
  123171. 1, -529137664, 1618345984, 2, 0,
  123172. _vq_quantlist__16c0_s_p7_0,
  123173. NULL,
  123174. &_vq_auxt__16c0_s_p7_0,
  123175. NULL,
  123176. 0
  123177. };
  123178. static long _vq_quantlist__16c0_s_p7_1[] = {
  123179. 5,
  123180. 4,
  123181. 6,
  123182. 3,
  123183. 7,
  123184. 2,
  123185. 8,
  123186. 1,
  123187. 9,
  123188. 0,
  123189. 10,
  123190. };
  123191. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123192. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123193. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123194. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123195. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123196. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123197. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123198. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123199. 11,11,11, 9, 9, 9, 9,10,10,
  123200. };
  123201. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123202. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123203. 3.5, 4.5,
  123204. };
  123205. static long _vq_quantmap__16c0_s_p7_1[] = {
  123206. 9, 7, 5, 3, 1, 0, 2, 4,
  123207. 6, 8, 10,
  123208. };
  123209. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123210. _vq_quantthresh__16c0_s_p7_1,
  123211. _vq_quantmap__16c0_s_p7_1,
  123212. 11,
  123213. 11
  123214. };
  123215. static static_codebook _16c0_s_p7_1 = {
  123216. 2, 121,
  123217. _vq_lengthlist__16c0_s_p7_1,
  123218. 1, -531365888, 1611661312, 4, 0,
  123219. _vq_quantlist__16c0_s_p7_1,
  123220. NULL,
  123221. &_vq_auxt__16c0_s_p7_1,
  123222. NULL,
  123223. 0
  123224. };
  123225. static long _vq_quantlist__16c0_s_p8_0[] = {
  123226. 6,
  123227. 5,
  123228. 7,
  123229. 4,
  123230. 8,
  123231. 3,
  123232. 9,
  123233. 2,
  123234. 10,
  123235. 1,
  123236. 11,
  123237. 0,
  123238. 12,
  123239. };
  123240. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123241. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123242. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123243. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123244. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123245. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123246. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123247. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123248. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123249. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123250. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123251. 0,12,13,13,12,13,14,14,14,
  123252. };
  123253. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123254. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123255. 12.5, 17.5, 22.5, 27.5,
  123256. };
  123257. static long _vq_quantmap__16c0_s_p8_0[] = {
  123258. 11, 9, 7, 5, 3, 1, 0, 2,
  123259. 4, 6, 8, 10, 12,
  123260. };
  123261. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123262. _vq_quantthresh__16c0_s_p8_0,
  123263. _vq_quantmap__16c0_s_p8_0,
  123264. 13,
  123265. 13
  123266. };
  123267. static static_codebook _16c0_s_p8_0 = {
  123268. 2, 169,
  123269. _vq_lengthlist__16c0_s_p8_0,
  123270. 1, -526516224, 1616117760, 4, 0,
  123271. _vq_quantlist__16c0_s_p8_0,
  123272. NULL,
  123273. &_vq_auxt__16c0_s_p8_0,
  123274. NULL,
  123275. 0
  123276. };
  123277. static long _vq_quantlist__16c0_s_p8_1[] = {
  123278. 2,
  123279. 1,
  123280. 3,
  123281. 0,
  123282. 4,
  123283. };
  123284. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123285. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123286. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123287. };
  123288. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123289. -1.5, -0.5, 0.5, 1.5,
  123290. };
  123291. static long _vq_quantmap__16c0_s_p8_1[] = {
  123292. 3, 1, 0, 2, 4,
  123293. };
  123294. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123295. _vq_quantthresh__16c0_s_p8_1,
  123296. _vq_quantmap__16c0_s_p8_1,
  123297. 5,
  123298. 5
  123299. };
  123300. static static_codebook _16c0_s_p8_1 = {
  123301. 2, 25,
  123302. _vq_lengthlist__16c0_s_p8_1,
  123303. 1, -533725184, 1611661312, 3, 0,
  123304. _vq_quantlist__16c0_s_p8_1,
  123305. NULL,
  123306. &_vq_auxt__16c0_s_p8_1,
  123307. NULL,
  123308. 0
  123309. };
  123310. static long _vq_quantlist__16c0_s_p9_0[] = {
  123311. 1,
  123312. 0,
  123313. 2,
  123314. };
  123315. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123316. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123317. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123318. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123319. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123320. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123321. 7,
  123322. };
  123323. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123324. -157.5, 157.5,
  123325. };
  123326. static long _vq_quantmap__16c0_s_p9_0[] = {
  123327. 1, 0, 2,
  123328. };
  123329. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123330. _vq_quantthresh__16c0_s_p9_0,
  123331. _vq_quantmap__16c0_s_p9_0,
  123332. 3,
  123333. 3
  123334. };
  123335. static static_codebook _16c0_s_p9_0 = {
  123336. 4, 81,
  123337. _vq_lengthlist__16c0_s_p9_0,
  123338. 1, -518803456, 1628680192, 2, 0,
  123339. _vq_quantlist__16c0_s_p9_0,
  123340. NULL,
  123341. &_vq_auxt__16c0_s_p9_0,
  123342. NULL,
  123343. 0
  123344. };
  123345. static long _vq_quantlist__16c0_s_p9_1[] = {
  123346. 7,
  123347. 6,
  123348. 8,
  123349. 5,
  123350. 9,
  123351. 4,
  123352. 10,
  123353. 3,
  123354. 11,
  123355. 2,
  123356. 12,
  123357. 1,
  123358. 13,
  123359. 0,
  123360. 14,
  123361. };
  123362. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123363. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123364. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123365. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123366. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123367. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123368. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123369. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123370. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123371. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123372. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123373. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123374. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123375. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123376. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123377. 10,
  123378. };
  123379. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123380. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123381. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123382. };
  123383. static long _vq_quantmap__16c0_s_p9_1[] = {
  123384. 13, 11, 9, 7, 5, 3, 1, 0,
  123385. 2, 4, 6, 8, 10, 12, 14,
  123386. };
  123387. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123388. _vq_quantthresh__16c0_s_p9_1,
  123389. _vq_quantmap__16c0_s_p9_1,
  123390. 15,
  123391. 15
  123392. };
  123393. static static_codebook _16c0_s_p9_1 = {
  123394. 2, 225,
  123395. _vq_lengthlist__16c0_s_p9_1,
  123396. 1, -520986624, 1620377600, 4, 0,
  123397. _vq_quantlist__16c0_s_p9_1,
  123398. NULL,
  123399. &_vq_auxt__16c0_s_p9_1,
  123400. NULL,
  123401. 0
  123402. };
  123403. static long _vq_quantlist__16c0_s_p9_2[] = {
  123404. 10,
  123405. 9,
  123406. 11,
  123407. 8,
  123408. 12,
  123409. 7,
  123410. 13,
  123411. 6,
  123412. 14,
  123413. 5,
  123414. 15,
  123415. 4,
  123416. 16,
  123417. 3,
  123418. 17,
  123419. 2,
  123420. 18,
  123421. 1,
  123422. 19,
  123423. 0,
  123424. 20,
  123425. };
  123426. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123427. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123428. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123429. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123430. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123431. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123432. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123433. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123434. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123435. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123436. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123437. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123438. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123439. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123440. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123441. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123442. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123443. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123444. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123445. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123446. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123447. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123448. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123449. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123450. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123451. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123452. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123453. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123454. 10,11,10,10,11, 9,10,10,10,
  123455. };
  123456. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123457. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123458. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123459. 6.5, 7.5, 8.5, 9.5,
  123460. };
  123461. static long _vq_quantmap__16c0_s_p9_2[] = {
  123462. 19, 17, 15, 13, 11, 9, 7, 5,
  123463. 3, 1, 0, 2, 4, 6, 8, 10,
  123464. 12, 14, 16, 18, 20,
  123465. };
  123466. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123467. _vq_quantthresh__16c0_s_p9_2,
  123468. _vq_quantmap__16c0_s_p9_2,
  123469. 21,
  123470. 21
  123471. };
  123472. static static_codebook _16c0_s_p9_2 = {
  123473. 2, 441,
  123474. _vq_lengthlist__16c0_s_p9_2,
  123475. 1, -529268736, 1611661312, 5, 0,
  123476. _vq_quantlist__16c0_s_p9_2,
  123477. NULL,
  123478. &_vq_auxt__16c0_s_p9_2,
  123479. NULL,
  123480. 0
  123481. };
  123482. static long _huff_lengthlist__16c0_s_single[] = {
  123483. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123484. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123485. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123486. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123487. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123488. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123489. 16,16,18,18,
  123490. };
  123491. static static_codebook _huff_book__16c0_s_single = {
  123492. 2, 100,
  123493. _huff_lengthlist__16c0_s_single,
  123494. 0, 0, 0, 0, 0,
  123495. NULL,
  123496. NULL,
  123497. NULL,
  123498. NULL,
  123499. 0
  123500. };
  123501. static long _huff_lengthlist__16c1_s_long[] = {
  123502. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123503. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123504. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123505. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123506. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123507. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123508. 12,11,11,13,
  123509. };
  123510. static static_codebook _huff_book__16c1_s_long = {
  123511. 2, 100,
  123512. _huff_lengthlist__16c1_s_long,
  123513. 0, 0, 0, 0, 0,
  123514. NULL,
  123515. NULL,
  123516. NULL,
  123517. NULL,
  123518. 0
  123519. };
  123520. static long _vq_quantlist__16c1_s_p1_0[] = {
  123521. 1,
  123522. 0,
  123523. 2,
  123524. };
  123525. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123526. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123527. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123532. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123537. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123572. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123577. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123582. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123618. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123623. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123628. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0,
  123937. };
  123938. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123939. -0.5, 0.5,
  123940. };
  123941. static long _vq_quantmap__16c1_s_p1_0[] = {
  123942. 1, 0, 2,
  123943. };
  123944. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123945. _vq_quantthresh__16c1_s_p1_0,
  123946. _vq_quantmap__16c1_s_p1_0,
  123947. 3,
  123948. 3
  123949. };
  123950. static static_codebook _16c1_s_p1_0 = {
  123951. 8, 6561,
  123952. _vq_lengthlist__16c1_s_p1_0,
  123953. 1, -535822336, 1611661312, 2, 0,
  123954. _vq_quantlist__16c1_s_p1_0,
  123955. NULL,
  123956. &_vq_auxt__16c1_s_p1_0,
  123957. NULL,
  123958. 0
  123959. };
  123960. static long _vq_quantlist__16c1_s_p2_0[] = {
  123961. 2,
  123962. 1,
  123963. 3,
  123964. 0,
  123965. 4,
  123966. };
  123967. static long _vq_lengthlist__16c1_s_p2_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,
  124008. };
  124009. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124010. -1.5, -0.5, 0.5, 1.5,
  124011. };
  124012. static long _vq_quantmap__16c1_s_p2_0[] = {
  124013. 3, 1, 0, 2, 4,
  124014. };
  124015. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124016. _vq_quantthresh__16c1_s_p2_0,
  124017. _vq_quantmap__16c1_s_p2_0,
  124018. 5,
  124019. 5
  124020. };
  124021. static static_codebook _16c1_s_p2_0 = {
  124022. 4, 625,
  124023. _vq_lengthlist__16c1_s_p2_0,
  124024. 1, -533725184, 1611661312, 3, 0,
  124025. _vq_quantlist__16c1_s_p2_0,
  124026. NULL,
  124027. &_vq_auxt__16c1_s_p2_0,
  124028. NULL,
  124029. 0
  124030. };
  124031. static long _vq_quantlist__16c1_s_p3_0[] = {
  124032. 2,
  124033. 1,
  124034. 3,
  124035. 0,
  124036. 4,
  124037. };
  124038. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124039. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  124079. };
  124080. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124081. -1.5, -0.5, 0.5, 1.5,
  124082. };
  124083. static long _vq_quantmap__16c1_s_p3_0[] = {
  124084. 3, 1, 0, 2, 4,
  124085. };
  124086. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124087. _vq_quantthresh__16c1_s_p3_0,
  124088. _vq_quantmap__16c1_s_p3_0,
  124089. 5,
  124090. 5
  124091. };
  124092. static static_codebook _16c1_s_p3_0 = {
  124093. 4, 625,
  124094. _vq_lengthlist__16c1_s_p3_0,
  124095. 1, -533725184, 1611661312, 3, 0,
  124096. _vq_quantlist__16c1_s_p3_0,
  124097. NULL,
  124098. &_vq_auxt__16c1_s_p3_0,
  124099. NULL,
  124100. 0
  124101. };
  124102. static long _vq_quantlist__16c1_s_p4_0[] = {
  124103. 4,
  124104. 3,
  124105. 5,
  124106. 2,
  124107. 6,
  124108. 1,
  124109. 7,
  124110. 0,
  124111. 8,
  124112. };
  124113. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124114. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124115. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124116. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124117. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124118. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0,
  124120. };
  124121. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124122. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124123. };
  124124. static long _vq_quantmap__16c1_s_p4_0[] = {
  124125. 7, 5, 3, 1, 0, 2, 4, 6,
  124126. 8,
  124127. };
  124128. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124129. _vq_quantthresh__16c1_s_p4_0,
  124130. _vq_quantmap__16c1_s_p4_0,
  124131. 9,
  124132. 9
  124133. };
  124134. static static_codebook _16c1_s_p4_0 = {
  124135. 2, 81,
  124136. _vq_lengthlist__16c1_s_p4_0,
  124137. 1, -531628032, 1611661312, 4, 0,
  124138. _vq_quantlist__16c1_s_p4_0,
  124139. NULL,
  124140. &_vq_auxt__16c1_s_p4_0,
  124141. NULL,
  124142. 0
  124143. };
  124144. static long _vq_quantlist__16c1_s_p5_0[] = {
  124145. 4,
  124146. 3,
  124147. 5,
  124148. 2,
  124149. 6,
  124150. 1,
  124151. 7,
  124152. 0,
  124153. 8,
  124154. };
  124155. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124156. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124157. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124158. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124159. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124160. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124161. 10,
  124162. };
  124163. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124164. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124165. };
  124166. static long _vq_quantmap__16c1_s_p5_0[] = {
  124167. 7, 5, 3, 1, 0, 2, 4, 6,
  124168. 8,
  124169. };
  124170. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124171. _vq_quantthresh__16c1_s_p5_0,
  124172. _vq_quantmap__16c1_s_p5_0,
  124173. 9,
  124174. 9
  124175. };
  124176. static static_codebook _16c1_s_p5_0 = {
  124177. 2, 81,
  124178. _vq_lengthlist__16c1_s_p5_0,
  124179. 1, -531628032, 1611661312, 4, 0,
  124180. _vq_quantlist__16c1_s_p5_0,
  124181. NULL,
  124182. &_vq_auxt__16c1_s_p5_0,
  124183. NULL,
  124184. 0
  124185. };
  124186. static long _vq_quantlist__16c1_s_p6_0[] = {
  124187. 8,
  124188. 7,
  124189. 9,
  124190. 6,
  124191. 10,
  124192. 5,
  124193. 11,
  124194. 4,
  124195. 12,
  124196. 3,
  124197. 13,
  124198. 2,
  124199. 14,
  124200. 1,
  124201. 15,
  124202. 0,
  124203. 16,
  124204. };
  124205. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124206. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124207. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124208. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124209. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124210. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124211. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124212. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124213. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124214. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124215. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124216. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124217. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124218. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124219. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124220. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124221. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124222. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124224. 14,
  124225. };
  124226. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124227. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124228. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124229. };
  124230. static long _vq_quantmap__16c1_s_p6_0[] = {
  124231. 15, 13, 11, 9, 7, 5, 3, 1,
  124232. 0, 2, 4, 6, 8, 10, 12, 14,
  124233. 16,
  124234. };
  124235. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124236. _vq_quantthresh__16c1_s_p6_0,
  124237. _vq_quantmap__16c1_s_p6_0,
  124238. 17,
  124239. 17
  124240. };
  124241. static static_codebook _16c1_s_p6_0 = {
  124242. 2, 289,
  124243. _vq_lengthlist__16c1_s_p6_0,
  124244. 1, -529530880, 1611661312, 5, 0,
  124245. _vq_quantlist__16c1_s_p6_0,
  124246. NULL,
  124247. &_vq_auxt__16c1_s_p6_0,
  124248. NULL,
  124249. 0
  124250. };
  124251. static long _vq_quantlist__16c1_s_p7_0[] = {
  124252. 1,
  124253. 0,
  124254. 2,
  124255. };
  124256. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124257. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124258. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124259. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124260. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124261. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124262. 11,
  124263. };
  124264. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124265. -5.5, 5.5,
  124266. };
  124267. static long _vq_quantmap__16c1_s_p7_0[] = {
  124268. 1, 0, 2,
  124269. };
  124270. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124271. _vq_quantthresh__16c1_s_p7_0,
  124272. _vq_quantmap__16c1_s_p7_0,
  124273. 3,
  124274. 3
  124275. };
  124276. static static_codebook _16c1_s_p7_0 = {
  124277. 4, 81,
  124278. _vq_lengthlist__16c1_s_p7_0,
  124279. 1, -529137664, 1618345984, 2, 0,
  124280. _vq_quantlist__16c1_s_p7_0,
  124281. NULL,
  124282. &_vq_auxt__16c1_s_p7_0,
  124283. NULL,
  124284. 0
  124285. };
  124286. static long _vq_quantlist__16c1_s_p7_1[] = {
  124287. 5,
  124288. 4,
  124289. 6,
  124290. 3,
  124291. 7,
  124292. 2,
  124293. 8,
  124294. 1,
  124295. 9,
  124296. 0,
  124297. 10,
  124298. };
  124299. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124300. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124301. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124302. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124303. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124304. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124305. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124306. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124307. 10,10,10, 8, 8, 8, 8, 9, 9,
  124308. };
  124309. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124310. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124311. 3.5, 4.5,
  124312. };
  124313. static long _vq_quantmap__16c1_s_p7_1[] = {
  124314. 9, 7, 5, 3, 1, 0, 2, 4,
  124315. 6, 8, 10,
  124316. };
  124317. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124318. _vq_quantthresh__16c1_s_p7_1,
  124319. _vq_quantmap__16c1_s_p7_1,
  124320. 11,
  124321. 11
  124322. };
  124323. static static_codebook _16c1_s_p7_1 = {
  124324. 2, 121,
  124325. _vq_lengthlist__16c1_s_p7_1,
  124326. 1, -531365888, 1611661312, 4, 0,
  124327. _vq_quantlist__16c1_s_p7_1,
  124328. NULL,
  124329. &_vq_auxt__16c1_s_p7_1,
  124330. NULL,
  124331. 0
  124332. };
  124333. static long _vq_quantlist__16c1_s_p8_0[] = {
  124334. 6,
  124335. 5,
  124336. 7,
  124337. 4,
  124338. 8,
  124339. 3,
  124340. 9,
  124341. 2,
  124342. 10,
  124343. 1,
  124344. 11,
  124345. 0,
  124346. 12,
  124347. };
  124348. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124349. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124350. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124351. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124352. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124353. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124354. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124355. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124356. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124357. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124358. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124359. 0,12,12,12,12,13,13,14,15,
  124360. };
  124361. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124362. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124363. 12.5, 17.5, 22.5, 27.5,
  124364. };
  124365. static long _vq_quantmap__16c1_s_p8_0[] = {
  124366. 11, 9, 7, 5, 3, 1, 0, 2,
  124367. 4, 6, 8, 10, 12,
  124368. };
  124369. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124370. _vq_quantthresh__16c1_s_p8_0,
  124371. _vq_quantmap__16c1_s_p8_0,
  124372. 13,
  124373. 13
  124374. };
  124375. static static_codebook _16c1_s_p8_0 = {
  124376. 2, 169,
  124377. _vq_lengthlist__16c1_s_p8_0,
  124378. 1, -526516224, 1616117760, 4, 0,
  124379. _vq_quantlist__16c1_s_p8_0,
  124380. NULL,
  124381. &_vq_auxt__16c1_s_p8_0,
  124382. NULL,
  124383. 0
  124384. };
  124385. static long _vq_quantlist__16c1_s_p8_1[] = {
  124386. 2,
  124387. 1,
  124388. 3,
  124389. 0,
  124390. 4,
  124391. };
  124392. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124393. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124394. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124395. };
  124396. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124397. -1.5, -0.5, 0.5, 1.5,
  124398. };
  124399. static long _vq_quantmap__16c1_s_p8_1[] = {
  124400. 3, 1, 0, 2, 4,
  124401. };
  124402. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124403. _vq_quantthresh__16c1_s_p8_1,
  124404. _vq_quantmap__16c1_s_p8_1,
  124405. 5,
  124406. 5
  124407. };
  124408. static static_codebook _16c1_s_p8_1 = {
  124409. 2, 25,
  124410. _vq_lengthlist__16c1_s_p8_1,
  124411. 1, -533725184, 1611661312, 3, 0,
  124412. _vq_quantlist__16c1_s_p8_1,
  124413. NULL,
  124414. &_vq_auxt__16c1_s_p8_1,
  124415. NULL,
  124416. 0
  124417. };
  124418. static long _vq_quantlist__16c1_s_p9_0[] = {
  124419. 6,
  124420. 5,
  124421. 7,
  124422. 4,
  124423. 8,
  124424. 3,
  124425. 9,
  124426. 2,
  124427. 10,
  124428. 1,
  124429. 11,
  124430. 0,
  124431. 12,
  124432. };
  124433. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124434. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124435. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124436. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124437. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124438. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124439. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124440. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124441. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124442. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124443. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124444. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124445. };
  124446. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124447. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124448. 787.5, 1102.5, 1417.5, 1732.5,
  124449. };
  124450. static long _vq_quantmap__16c1_s_p9_0[] = {
  124451. 11, 9, 7, 5, 3, 1, 0, 2,
  124452. 4, 6, 8, 10, 12,
  124453. };
  124454. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124455. _vq_quantthresh__16c1_s_p9_0,
  124456. _vq_quantmap__16c1_s_p9_0,
  124457. 13,
  124458. 13
  124459. };
  124460. static static_codebook _16c1_s_p9_0 = {
  124461. 2, 169,
  124462. _vq_lengthlist__16c1_s_p9_0,
  124463. 1, -513964032, 1628680192, 4, 0,
  124464. _vq_quantlist__16c1_s_p9_0,
  124465. NULL,
  124466. &_vq_auxt__16c1_s_p9_0,
  124467. NULL,
  124468. 0
  124469. };
  124470. static long _vq_quantlist__16c1_s_p9_1[] = {
  124471. 7,
  124472. 6,
  124473. 8,
  124474. 5,
  124475. 9,
  124476. 4,
  124477. 10,
  124478. 3,
  124479. 11,
  124480. 2,
  124481. 12,
  124482. 1,
  124483. 13,
  124484. 0,
  124485. 14,
  124486. };
  124487. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124488. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124489. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124490. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124491. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124492. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124493. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124494. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124495. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124496. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124497. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124498. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124499. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124500. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124501. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124502. 13,
  124503. };
  124504. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124505. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124506. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124507. };
  124508. static long _vq_quantmap__16c1_s_p9_1[] = {
  124509. 13, 11, 9, 7, 5, 3, 1, 0,
  124510. 2, 4, 6, 8, 10, 12, 14,
  124511. };
  124512. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124513. _vq_quantthresh__16c1_s_p9_1,
  124514. _vq_quantmap__16c1_s_p9_1,
  124515. 15,
  124516. 15
  124517. };
  124518. static static_codebook _16c1_s_p9_1 = {
  124519. 2, 225,
  124520. _vq_lengthlist__16c1_s_p9_1,
  124521. 1, -520986624, 1620377600, 4, 0,
  124522. _vq_quantlist__16c1_s_p9_1,
  124523. NULL,
  124524. &_vq_auxt__16c1_s_p9_1,
  124525. NULL,
  124526. 0
  124527. };
  124528. static long _vq_quantlist__16c1_s_p9_2[] = {
  124529. 10,
  124530. 9,
  124531. 11,
  124532. 8,
  124533. 12,
  124534. 7,
  124535. 13,
  124536. 6,
  124537. 14,
  124538. 5,
  124539. 15,
  124540. 4,
  124541. 16,
  124542. 3,
  124543. 17,
  124544. 2,
  124545. 18,
  124546. 1,
  124547. 19,
  124548. 0,
  124549. 20,
  124550. };
  124551. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124552. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124553. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124554. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124555. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124556. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124557. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124558. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124559. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124560. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124561. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124562. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124563. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124564. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124565. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124566. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124567. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124568. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124569. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124570. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124571. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124572. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124573. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124574. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124575. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124576. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124577. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124578. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124579. 11,11,11,11,12,11,11,12,11,
  124580. };
  124581. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124582. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124583. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124584. 6.5, 7.5, 8.5, 9.5,
  124585. };
  124586. static long _vq_quantmap__16c1_s_p9_2[] = {
  124587. 19, 17, 15, 13, 11, 9, 7, 5,
  124588. 3, 1, 0, 2, 4, 6, 8, 10,
  124589. 12, 14, 16, 18, 20,
  124590. };
  124591. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124592. _vq_quantthresh__16c1_s_p9_2,
  124593. _vq_quantmap__16c1_s_p9_2,
  124594. 21,
  124595. 21
  124596. };
  124597. static static_codebook _16c1_s_p9_2 = {
  124598. 2, 441,
  124599. _vq_lengthlist__16c1_s_p9_2,
  124600. 1, -529268736, 1611661312, 5, 0,
  124601. _vq_quantlist__16c1_s_p9_2,
  124602. NULL,
  124603. &_vq_auxt__16c1_s_p9_2,
  124604. NULL,
  124605. 0
  124606. };
  124607. static long _huff_lengthlist__16c1_s_short[] = {
  124608. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124609. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124610. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124611. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124612. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124613. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124614. 9, 9,10,13,
  124615. };
  124616. static static_codebook _huff_book__16c1_s_short = {
  124617. 2, 100,
  124618. _huff_lengthlist__16c1_s_short,
  124619. 0, 0, 0, 0, 0,
  124620. NULL,
  124621. NULL,
  124622. NULL,
  124623. NULL,
  124624. 0
  124625. };
  124626. static long _huff_lengthlist__16c2_s_long[] = {
  124627. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124628. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124629. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124630. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124631. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124632. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124633. 14,14,16,18,
  124634. };
  124635. static static_codebook _huff_book__16c2_s_long = {
  124636. 2, 100,
  124637. _huff_lengthlist__16c2_s_long,
  124638. 0, 0, 0, 0, 0,
  124639. NULL,
  124640. NULL,
  124641. NULL,
  124642. NULL,
  124643. 0
  124644. };
  124645. static long _vq_quantlist__16c2_s_p1_0[] = {
  124646. 1,
  124647. 0,
  124648. 2,
  124649. };
  124650. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124651. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124652. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124656. 0,
  124657. };
  124658. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124659. -0.5, 0.5,
  124660. };
  124661. static long _vq_quantmap__16c2_s_p1_0[] = {
  124662. 1, 0, 2,
  124663. };
  124664. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124665. _vq_quantthresh__16c2_s_p1_0,
  124666. _vq_quantmap__16c2_s_p1_0,
  124667. 3,
  124668. 3
  124669. };
  124670. static static_codebook _16c2_s_p1_0 = {
  124671. 4, 81,
  124672. _vq_lengthlist__16c2_s_p1_0,
  124673. 1, -535822336, 1611661312, 2, 0,
  124674. _vq_quantlist__16c2_s_p1_0,
  124675. NULL,
  124676. &_vq_auxt__16c2_s_p1_0,
  124677. NULL,
  124678. 0
  124679. };
  124680. static long _vq_quantlist__16c2_s_p2_0[] = {
  124681. 2,
  124682. 1,
  124683. 3,
  124684. 0,
  124685. 4,
  124686. };
  124687. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124688. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124689. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124690. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124691. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124692. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124693. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124694. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124695. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124700. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124701. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124702. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124703. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124708. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124709. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124710. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124711. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124716. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124717. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124718. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124719. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124724. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124725. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124726. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124727. 13,
  124728. };
  124729. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124730. -1.5, -0.5, 0.5, 1.5,
  124731. };
  124732. static long _vq_quantmap__16c2_s_p2_0[] = {
  124733. 3, 1, 0, 2, 4,
  124734. };
  124735. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124736. _vq_quantthresh__16c2_s_p2_0,
  124737. _vq_quantmap__16c2_s_p2_0,
  124738. 5,
  124739. 5
  124740. };
  124741. static static_codebook _16c2_s_p2_0 = {
  124742. 4, 625,
  124743. _vq_lengthlist__16c2_s_p2_0,
  124744. 1, -533725184, 1611661312, 3, 0,
  124745. _vq_quantlist__16c2_s_p2_0,
  124746. NULL,
  124747. &_vq_auxt__16c2_s_p2_0,
  124748. NULL,
  124749. 0
  124750. };
  124751. static long _vq_quantlist__16c2_s_p3_0[] = {
  124752. 4,
  124753. 3,
  124754. 5,
  124755. 2,
  124756. 6,
  124757. 1,
  124758. 7,
  124759. 0,
  124760. 8,
  124761. };
  124762. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124763. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124764. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124765. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124766. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124768. 0,
  124769. };
  124770. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124771. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124772. };
  124773. static long _vq_quantmap__16c2_s_p3_0[] = {
  124774. 7, 5, 3, 1, 0, 2, 4, 6,
  124775. 8,
  124776. };
  124777. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124778. _vq_quantthresh__16c2_s_p3_0,
  124779. _vq_quantmap__16c2_s_p3_0,
  124780. 9,
  124781. 9
  124782. };
  124783. static static_codebook _16c2_s_p3_0 = {
  124784. 2, 81,
  124785. _vq_lengthlist__16c2_s_p3_0,
  124786. 1, -531628032, 1611661312, 4, 0,
  124787. _vq_quantlist__16c2_s_p3_0,
  124788. NULL,
  124789. &_vq_auxt__16c2_s_p3_0,
  124790. NULL,
  124791. 0
  124792. };
  124793. static long _vq_quantlist__16c2_s_p4_0[] = {
  124794. 8,
  124795. 7,
  124796. 9,
  124797. 6,
  124798. 10,
  124799. 5,
  124800. 11,
  124801. 4,
  124802. 12,
  124803. 3,
  124804. 13,
  124805. 2,
  124806. 14,
  124807. 1,
  124808. 15,
  124809. 0,
  124810. 16,
  124811. };
  124812. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124813. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124814. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124815. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124816. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124817. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124818. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124819. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124820. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124821. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124822. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124831. 0,
  124832. };
  124833. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124834. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124835. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124836. };
  124837. static long _vq_quantmap__16c2_s_p4_0[] = {
  124838. 15, 13, 11, 9, 7, 5, 3, 1,
  124839. 0, 2, 4, 6, 8, 10, 12, 14,
  124840. 16,
  124841. };
  124842. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124843. _vq_quantthresh__16c2_s_p4_0,
  124844. _vq_quantmap__16c2_s_p4_0,
  124845. 17,
  124846. 17
  124847. };
  124848. static static_codebook _16c2_s_p4_0 = {
  124849. 2, 289,
  124850. _vq_lengthlist__16c2_s_p4_0,
  124851. 1, -529530880, 1611661312, 5, 0,
  124852. _vq_quantlist__16c2_s_p4_0,
  124853. NULL,
  124854. &_vq_auxt__16c2_s_p4_0,
  124855. NULL,
  124856. 0
  124857. };
  124858. static long _vq_quantlist__16c2_s_p5_0[] = {
  124859. 1,
  124860. 0,
  124861. 2,
  124862. };
  124863. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124864. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124865. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124866. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124867. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124868. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124869. 12,
  124870. };
  124871. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124872. -5.5, 5.5,
  124873. };
  124874. static long _vq_quantmap__16c2_s_p5_0[] = {
  124875. 1, 0, 2,
  124876. };
  124877. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124878. _vq_quantthresh__16c2_s_p5_0,
  124879. _vq_quantmap__16c2_s_p5_0,
  124880. 3,
  124881. 3
  124882. };
  124883. static static_codebook _16c2_s_p5_0 = {
  124884. 4, 81,
  124885. _vq_lengthlist__16c2_s_p5_0,
  124886. 1, -529137664, 1618345984, 2, 0,
  124887. _vq_quantlist__16c2_s_p5_0,
  124888. NULL,
  124889. &_vq_auxt__16c2_s_p5_0,
  124890. NULL,
  124891. 0
  124892. };
  124893. static long _vq_quantlist__16c2_s_p5_1[] = {
  124894. 5,
  124895. 4,
  124896. 6,
  124897. 3,
  124898. 7,
  124899. 2,
  124900. 8,
  124901. 1,
  124902. 9,
  124903. 0,
  124904. 10,
  124905. };
  124906. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124907. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124908. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124909. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124910. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124911. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124912. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124913. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124914. 11,11,11, 7, 7, 8, 8, 8, 8,
  124915. };
  124916. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124917. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124918. 3.5, 4.5,
  124919. };
  124920. static long _vq_quantmap__16c2_s_p5_1[] = {
  124921. 9, 7, 5, 3, 1, 0, 2, 4,
  124922. 6, 8, 10,
  124923. };
  124924. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124925. _vq_quantthresh__16c2_s_p5_1,
  124926. _vq_quantmap__16c2_s_p5_1,
  124927. 11,
  124928. 11
  124929. };
  124930. static static_codebook _16c2_s_p5_1 = {
  124931. 2, 121,
  124932. _vq_lengthlist__16c2_s_p5_1,
  124933. 1, -531365888, 1611661312, 4, 0,
  124934. _vq_quantlist__16c2_s_p5_1,
  124935. NULL,
  124936. &_vq_auxt__16c2_s_p5_1,
  124937. NULL,
  124938. 0
  124939. };
  124940. static long _vq_quantlist__16c2_s_p6_0[] = {
  124941. 6,
  124942. 5,
  124943. 7,
  124944. 4,
  124945. 8,
  124946. 3,
  124947. 9,
  124948. 2,
  124949. 10,
  124950. 1,
  124951. 11,
  124952. 0,
  124953. 12,
  124954. };
  124955. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124956. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124957. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124958. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124959. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124960. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124961. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124966. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124967. };
  124968. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124969. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124970. 12.5, 17.5, 22.5, 27.5,
  124971. };
  124972. static long _vq_quantmap__16c2_s_p6_0[] = {
  124973. 11, 9, 7, 5, 3, 1, 0, 2,
  124974. 4, 6, 8, 10, 12,
  124975. };
  124976. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124977. _vq_quantthresh__16c2_s_p6_0,
  124978. _vq_quantmap__16c2_s_p6_0,
  124979. 13,
  124980. 13
  124981. };
  124982. static static_codebook _16c2_s_p6_0 = {
  124983. 2, 169,
  124984. _vq_lengthlist__16c2_s_p6_0,
  124985. 1, -526516224, 1616117760, 4, 0,
  124986. _vq_quantlist__16c2_s_p6_0,
  124987. NULL,
  124988. &_vq_auxt__16c2_s_p6_0,
  124989. NULL,
  124990. 0
  124991. };
  124992. static long _vq_quantlist__16c2_s_p6_1[] = {
  124993. 2,
  124994. 1,
  124995. 3,
  124996. 0,
  124997. 4,
  124998. };
  124999. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125000. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125001. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125002. };
  125003. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125004. -1.5, -0.5, 0.5, 1.5,
  125005. };
  125006. static long _vq_quantmap__16c2_s_p6_1[] = {
  125007. 3, 1, 0, 2, 4,
  125008. };
  125009. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125010. _vq_quantthresh__16c2_s_p6_1,
  125011. _vq_quantmap__16c2_s_p6_1,
  125012. 5,
  125013. 5
  125014. };
  125015. static static_codebook _16c2_s_p6_1 = {
  125016. 2, 25,
  125017. _vq_lengthlist__16c2_s_p6_1,
  125018. 1, -533725184, 1611661312, 3, 0,
  125019. _vq_quantlist__16c2_s_p6_1,
  125020. NULL,
  125021. &_vq_auxt__16c2_s_p6_1,
  125022. NULL,
  125023. 0
  125024. };
  125025. static long _vq_quantlist__16c2_s_p7_0[] = {
  125026. 6,
  125027. 5,
  125028. 7,
  125029. 4,
  125030. 8,
  125031. 3,
  125032. 9,
  125033. 2,
  125034. 10,
  125035. 1,
  125036. 11,
  125037. 0,
  125038. 12,
  125039. };
  125040. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125041. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125042. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125043. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125044. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125045. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125046. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125047. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125048. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125049. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125050. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125051. 18,13,14,13,13,14,13,15,14,
  125052. };
  125053. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125054. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125055. 27.5, 38.5, 49.5, 60.5,
  125056. };
  125057. static long _vq_quantmap__16c2_s_p7_0[] = {
  125058. 11, 9, 7, 5, 3, 1, 0, 2,
  125059. 4, 6, 8, 10, 12,
  125060. };
  125061. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125062. _vq_quantthresh__16c2_s_p7_0,
  125063. _vq_quantmap__16c2_s_p7_0,
  125064. 13,
  125065. 13
  125066. };
  125067. static static_codebook _16c2_s_p7_0 = {
  125068. 2, 169,
  125069. _vq_lengthlist__16c2_s_p7_0,
  125070. 1, -523206656, 1618345984, 4, 0,
  125071. _vq_quantlist__16c2_s_p7_0,
  125072. NULL,
  125073. &_vq_auxt__16c2_s_p7_0,
  125074. NULL,
  125075. 0
  125076. };
  125077. static long _vq_quantlist__16c2_s_p7_1[] = {
  125078. 5,
  125079. 4,
  125080. 6,
  125081. 3,
  125082. 7,
  125083. 2,
  125084. 8,
  125085. 1,
  125086. 9,
  125087. 0,
  125088. 10,
  125089. };
  125090. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125091. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125092. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125093. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125094. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125095. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125096. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125097. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125098. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125099. };
  125100. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125101. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125102. 3.5, 4.5,
  125103. };
  125104. static long _vq_quantmap__16c2_s_p7_1[] = {
  125105. 9, 7, 5, 3, 1, 0, 2, 4,
  125106. 6, 8, 10,
  125107. };
  125108. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125109. _vq_quantthresh__16c2_s_p7_1,
  125110. _vq_quantmap__16c2_s_p7_1,
  125111. 11,
  125112. 11
  125113. };
  125114. static static_codebook _16c2_s_p7_1 = {
  125115. 2, 121,
  125116. _vq_lengthlist__16c2_s_p7_1,
  125117. 1, -531365888, 1611661312, 4, 0,
  125118. _vq_quantlist__16c2_s_p7_1,
  125119. NULL,
  125120. &_vq_auxt__16c2_s_p7_1,
  125121. NULL,
  125122. 0
  125123. };
  125124. static long _vq_quantlist__16c2_s_p8_0[] = {
  125125. 7,
  125126. 6,
  125127. 8,
  125128. 5,
  125129. 9,
  125130. 4,
  125131. 10,
  125132. 3,
  125133. 11,
  125134. 2,
  125135. 12,
  125136. 1,
  125137. 13,
  125138. 0,
  125139. 14,
  125140. };
  125141. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125142. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125143. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125144. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125145. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125146. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125147. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125148. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125149. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125150. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125151. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125152. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125153. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125154. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125155. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125156. 13,
  125157. };
  125158. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125159. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125160. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125161. };
  125162. static long _vq_quantmap__16c2_s_p8_0[] = {
  125163. 13, 11, 9, 7, 5, 3, 1, 0,
  125164. 2, 4, 6, 8, 10, 12, 14,
  125165. };
  125166. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125167. _vq_quantthresh__16c2_s_p8_0,
  125168. _vq_quantmap__16c2_s_p8_0,
  125169. 15,
  125170. 15
  125171. };
  125172. static static_codebook _16c2_s_p8_0 = {
  125173. 2, 225,
  125174. _vq_lengthlist__16c2_s_p8_0,
  125175. 1, -520986624, 1620377600, 4, 0,
  125176. _vq_quantlist__16c2_s_p8_0,
  125177. NULL,
  125178. &_vq_auxt__16c2_s_p8_0,
  125179. NULL,
  125180. 0
  125181. };
  125182. static long _vq_quantlist__16c2_s_p8_1[] = {
  125183. 10,
  125184. 9,
  125185. 11,
  125186. 8,
  125187. 12,
  125188. 7,
  125189. 13,
  125190. 6,
  125191. 14,
  125192. 5,
  125193. 15,
  125194. 4,
  125195. 16,
  125196. 3,
  125197. 17,
  125198. 2,
  125199. 18,
  125200. 1,
  125201. 19,
  125202. 0,
  125203. 20,
  125204. };
  125205. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125206. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125207. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125208. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125209. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125210. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125211. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125212. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125213. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125214. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125215. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125216. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125217. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125218. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125219. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125220. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125221. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125222. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125223. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125224. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125225. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125226. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125227. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125228. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125229. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125230. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125231. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125232. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125233. 10,11,10,10,10,10,10,10,10,
  125234. };
  125235. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125236. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125237. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125238. 6.5, 7.5, 8.5, 9.5,
  125239. };
  125240. static long _vq_quantmap__16c2_s_p8_1[] = {
  125241. 19, 17, 15, 13, 11, 9, 7, 5,
  125242. 3, 1, 0, 2, 4, 6, 8, 10,
  125243. 12, 14, 16, 18, 20,
  125244. };
  125245. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125246. _vq_quantthresh__16c2_s_p8_1,
  125247. _vq_quantmap__16c2_s_p8_1,
  125248. 21,
  125249. 21
  125250. };
  125251. static static_codebook _16c2_s_p8_1 = {
  125252. 2, 441,
  125253. _vq_lengthlist__16c2_s_p8_1,
  125254. 1, -529268736, 1611661312, 5, 0,
  125255. _vq_quantlist__16c2_s_p8_1,
  125256. NULL,
  125257. &_vq_auxt__16c2_s_p8_1,
  125258. NULL,
  125259. 0
  125260. };
  125261. static long _vq_quantlist__16c2_s_p9_0[] = {
  125262. 6,
  125263. 5,
  125264. 7,
  125265. 4,
  125266. 8,
  125267. 3,
  125268. 9,
  125269. 2,
  125270. 10,
  125271. 1,
  125272. 11,
  125273. 0,
  125274. 12,
  125275. };
  125276. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125277. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125278. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125279. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125280. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125281. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125282. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125283. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125284. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125285. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125286. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125287. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125288. };
  125289. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125290. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125291. 2327.5, 3258.5, 4189.5, 5120.5,
  125292. };
  125293. static long _vq_quantmap__16c2_s_p9_0[] = {
  125294. 11, 9, 7, 5, 3, 1, 0, 2,
  125295. 4, 6, 8, 10, 12,
  125296. };
  125297. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125298. _vq_quantthresh__16c2_s_p9_0,
  125299. _vq_quantmap__16c2_s_p9_0,
  125300. 13,
  125301. 13
  125302. };
  125303. static static_codebook _16c2_s_p9_0 = {
  125304. 2, 169,
  125305. _vq_lengthlist__16c2_s_p9_0,
  125306. 1, -510275072, 1631393792, 4, 0,
  125307. _vq_quantlist__16c2_s_p9_0,
  125308. NULL,
  125309. &_vq_auxt__16c2_s_p9_0,
  125310. NULL,
  125311. 0
  125312. };
  125313. static long _vq_quantlist__16c2_s_p9_1[] = {
  125314. 8,
  125315. 7,
  125316. 9,
  125317. 6,
  125318. 10,
  125319. 5,
  125320. 11,
  125321. 4,
  125322. 12,
  125323. 3,
  125324. 13,
  125325. 2,
  125326. 14,
  125327. 1,
  125328. 15,
  125329. 0,
  125330. 16,
  125331. };
  125332. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125333. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125334. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125335. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125336. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125337. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125338. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125339. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125340. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125341. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125342. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125343. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125344. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125345. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125346. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125347. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125348. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125349. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125350. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125351. 10,
  125352. };
  125353. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125354. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125355. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125356. };
  125357. static long _vq_quantmap__16c2_s_p9_1[] = {
  125358. 15, 13, 11, 9, 7, 5, 3, 1,
  125359. 0, 2, 4, 6, 8, 10, 12, 14,
  125360. 16,
  125361. };
  125362. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125363. _vq_quantthresh__16c2_s_p9_1,
  125364. _vq_quantmap__16c2_s_p9_1,
  125365. 17,
  125366. 17
  125367. };
  125368. static static_codebook _16c2_s_p9_1 = {
  125369. 2, 289,
  125370. _vq_lengthlist__16c2_s_p9_1,
  125371. 1, -518488064, 1622704128, 5, 0,
  125372. _vq_quantlist__16c2_s_p9_1,
  125373. NULL,
  125374. &_vq_auxt__16c2_s_p9_1,
  125375. NULL,
  125376. 0
  125377. };
  125378. static long _vq_quantlist__16c2_s_p9_2[] = {
  125379. 13,
  125380. 12,
  125381. 14,
  125382. 11,
  125383. 15,
  125384. 10,
  125385. 16,
  125386. 9,
  125387. 17,
  125388. 8,
  125389. 18,
  125390. 7,
  125391. 19,
  125392. 6,
  125393. 20,
  125394. 5,
  125395. 21,
  125396. 4,
  125397. 22,
  125398. 3,
  125399. 23,
  125400. 2,
  125401. 24,
  125402. 1,
  125403. 25,
  125404. 0,
  125405. 26,
  125406. };
  125407. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125408. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125409. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125410. };
  125411. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125412. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125413. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125414. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125415. 11.5, 12.5,
  125416. };
  125417. static long _vq_quantmap__16c2_s_p9_2[] = {
  125418. 25, 23, 21, 19, 17, 15, 13, 11,
  125419. 9, 7, 5, 3, 1, 0, 2, 4,
  125420. 6, 8, 10, 12, 14, 16, 18, 20,
  125421. 22, 24, 26,
  125422. };
  125423. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125424. _vq_quantthresh__16c2_s_p9_2,
  125425. _vq_quantmap__16c2_s_p9_2,
  125426. 27,
  125427. 27
  125428. };
  125429. static static_codebook _16c2_s_p9_2 = {
  125430. 1, 27,
  125431. _vq_lengthlist__16c2_s_p9_2,
  125432. 1, -528875520, 1611661312, 5, 0,
  125433. _vq_quantlist__16c2_s_p9_2,
  125434. NULL,
  125435. &_vq_auxt__16c2_s_p9_2,
  125436. NULL,
  125437. 0
  125438. };
  125439. static long _huff_lengthlist__16c2_s_short[] = {
  125440. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125441. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125442. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125443. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125444. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125445. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125446. 15,12,14,14,
  125447. };
  125448. static static_codebook _huff_book__16c2_s_short = {
  125449. 2, 100,
  125450. _huff_lengthlist__16c2_s_short,
  125451. 0, 0, 0, 0, 0,
  125452. NULL,
  125453. NULL,
  125454. NULL,
  125455. NULL,
  125456. 0
  125457. };
  125458. static long _vq_quantlist__8c0_s_p1_0[] = {
  125459. 1,
  125460. 0,
  125461. 2,
  125462. };
  125463. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125464. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125465. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125470. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125475. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125510. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125515. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125520. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125555. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125556. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125560. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125561. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125565. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125566. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0,
  125875. };
  125876. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125877. -0.5, 0.5,
  125878. };
  125879. static long _vq_quantmap__8c0_s_p1_0[] = {
  125880. 1, 0, 2,
  125881. };
  125882. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125883. _vq_quantthresh__8c0_s_p1_0,
  125884. _vq_quantmap__8c0_s_p1_0,
  125885. 3,
  125886. 3
  125887. };
  125888. static static_codebook _8c0_s_p1_0 = {
  125889. 8, 6561,
  125890. _vq_lengthlist__8c0_s_p1_0,
  125891. 1, -535822336, 1611661312, 2, 0,
  125892. _vq_quantlist__8c0_s_p1_0,
  125893. NULL,
  125894. &_vq_auxt__8c0_s_p1_0,
  125895. NULL,
  125896. 0
  125897. };
  125898. static long _vq_quantlist__8c0_s_p2_0[] = {
  125899. 2,
  125900. 1,
  125901. 3,
  125902. 0,
  125903. 4,
  125904. };
  125905. static long _vq_lengthlist__8c0_s_p2_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,
  125946. };
  125947. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125948. -1.5, -0.5, 0.5, 1.5,
  125949. };
  125950. static long _vq_quantmap__8c0_s_p2_0[] = {
  125951. 3, 1, 0, 2, 4,
  125952. };
  125953. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125954. _vq_quantthresh__8c0_s_p2_0,
  125955. _vq_quantmap__8c0_s_p2_0,
  125956. 5,
  125957. 5
  125958. };
  125959. static static_codebook _8c0_s_p2_0 = {
  125960. 4, 625,
  125961. _vq_lengthlist__8c0_s_p2_0,
  125962. 1, -533725184, 1611661312, 3, 0,
  125963. _vq_quantlist__8c0_s_p2_0,
  125964. NULL,
  125965. &_vq_auxt__8c0_s_p2_0,
  125966. NULL,
  125967. 0
  125968. };
  125969. static long _vq_quantlist__8c0_s_p3_0[] = {
  125970. 2,
  125971. 1,
  125972. 3,
  125973. 0,
  125974. 4,
  125975. };
  125976. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125977. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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,
  126017. };
  126018. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126019. -1.5, -0.5, 0.5, 1.5,
  126020. };
  126021. static long _vq_quantmap__8c0_s_p3_0[] = {
  126022. 3, 1, 0, 2, 4,
  126023. };
  126024. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126025. _vq_quantthresh__8c0_s_p3_0,
  126026. _vq_quantmap__8c0_s_p3_0,
  126027. 5,
  126028. 5
  126029. };
  126030. static static_codebook _8c0_s_p3_0 = {
  126031. 4, 625,
  126032. _vq_lengthlist__8c0_s_p3_0,
  126033. 1, -533725184, 1611661312, 3, 0,
  126034. _vq_quantlist__8c0_s_p3_0,
  126035. NULL,
  126036. &_vq_auxt__8c0_s_p3_0,
  126037. NULL,
  126038. 0
  126039. };
  126040. static long _vq_quantlist__8c0_s_p4_0[] = {
  126041. 4,
  126042. 3,
  126043. 5,
  126044. 2,
  126045. 6,
  126046. 1,
  126047. 7,
  126048. 0,
  126049. 8,
  126050. };
  126051. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126052. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126053. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126054. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126055. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126056. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0,
  126058. };
  126059. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126060. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126061. };
  126062. static long _vq_quantmap__8c0_s_p4_0[] = {
  126063. 7, 5, 3, 1, 0, 2, 4, 6,
  126064. 8,
  126065. };
  126066. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126067. _vq_quantthresh__8c0_s_p4_0,
  126068. _vq_quantmap__8c0_s_p4_0,
  126069. 9,
  126070. 9
  126071. };
  126072. static static_codebook _8c0_s_p4_0 = {
  126073. 2, 81,
  126074. _vq_lengthlist__8c0_s_p4_0,
  126075. 1, -531628032, 1611661312, 4, 0,
  126076. _vq_quantlist__8c0_s_p4_0,
  126077. NULL,
  126078. &_vq_auxt__8c0_s_p4_0,
  126079. NULL,
  126080. 0
  126081. };
  126082. static long _vq_quantlist__8c0_s_p5_0[] = {
  126083. 4,
  126084. 3,
  126085. 5,
  126086. 2,
  126087. 6,
  126088. 1,
  126089. 7,
  126090. 0,
  126091. 8,
  126092. };
  126093. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126094. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126095. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126096. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126097. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126098. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126099. 10,
  126100. };
  126101. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126102. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126103. };
  126104. static long _vq_quantmap__8c0_s_p5_0[] = {
  126105. 7, 5, 3, 1, 0, 2, 4, 6,
  126106. 8,
  126107. };
  126108. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126109. _vq_quantthresh__8c0_s_p5_0,
  126110. _vq_quantmap__8c0_s_p5_0,
  126111. 9,
  126112. 9
  126113. };
  126114. static static_codebook _8c0_s_p5_0 = {
  126115. 2, 81,
  126116. _vq_lengthlist__8c0_s_p5_0,
  126117. 1, -531628032, 1611661312, 4, 0,
  126118. _vq_quantlist__8c0_s_p5_0,
  126119. NULL,
  126120. &_vq_auxt__8c0_s_p5_0,
  126121. NULL,
  126122. 0
  126123. };
  126124. static long _vq_quantlist__8c0_s_p6_0[] = {
  126125. 8,
  126126. 7,
  126127. 9,
  126128. 6,
  126129. 10,
  126130. 5,
  126131. 11,
  126132. 4,
  126133. 12,
  126134. 3,
  126135. 13,
  126136. 2,
  126137. 14,
  126138. 1,
  126139. 15,
  126140. 0,
  126141. 16,
  126142. };
  126143. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126144. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126145. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126146. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126147. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126148. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126149. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126150. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126151. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126152. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126153. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126154. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126155. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126156. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126157. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126158. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126159. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126160. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126162. 14,
  126163. };
  126164. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126165. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126166. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126167. };
  126168. static long _vq_quantmap__8c0_s_p6_0[] = {
  126169. 15, 13, 11, 9, 7, 5, 3, 1,
  126170. 0, 2, 4, 6, 8, 10, 12, 14,
  126171. 16,
  126172. };
  126173. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126174. _vq_quantthresh__8c0_s_p6_0,
  126175. _vq_quantmap__8c0_s_p6_0,
  126176. 17,
  126177. 17
  126178. };
  126179. static static_codebook _8c0_s_p6_0 = {
  126180. 2, 289,
  126181. _vq_lengthlist__8c0_s_p6_0,
  126182. 1, -529530880, 1611661312, 5, 0,
  126183. _vq_quantlist__8c0_s_p6_0,
  126184. NULL,
  126185. &_vq_auxt__8c0_s_p6_0,
  126186. NULL,
  126187. 0
  126188. };
  126189. static long _vq_quantlist__8c0_s_p7_0[] = {
  126190. 1,
  126191. 0,
  126192. 2,
  126193. };
  126194. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126195. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126196. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126197. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126198. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126199. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126200. 10,
  126201. };
  126202. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126203. -5.5, 5.5,
  126204. };
  126205. static long _vq_quantmap__8c0_s_p7_0[] = {
  126206. 1, 0, 2,
  126207. };
  126208. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126209. _vq_quantthresh__8c0_s_p7_0,
  126210. _vq_quantmap__8c0_s_p7_0,
  126211. 3,
  126212. 3
  126213. };
  126214. static static_codebook _8c0_s_p7_0 = {
  126215. 4, 81,
  126216. _vq_lengthlist__8c0_s_p7_0,
  126217. 1, -529137664, 1618345984, 2, 0,
  126218. _vq_quantlist__8c0_s_p7_0,
  126219. NULL,
  126220. &_vq_auxt__8c0_s_p7_0,
  126221. NULL,
  126222. 0
  126223. };
  126224. static long _vq_quantlist__8c0_s_p7_1[] = {
  126225. 5,
  126226. 4,
  126227. 6,
  126228. 3,
  126229. 7,
  126230. 2,
  126231. 8,
  126232. 1,
  126233. 9,
  126234. 0,
  126235. 10,
  126236. };
  126237. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126238. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126239. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126240. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126241. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126242. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126243. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126244. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126245. 10,10,10, 9, 9, 9,10,10,10,
  126246. };
  126247. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126248. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126249. 3.5, 4.5,
  126250. };
  126251. static long _vq_quantmap__8c0_s_p7_1[] = {
  126252. 9, 7, 5, 3, 1, 0, 2, 4,
  126253. 6, 8, 10,
  126254. };
  126255. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126256. _vq_quantthresh__8c0_s_p7_1,
  126257. _vq_quantmap__8c0_s_p7_1,
  126258. 11,
  126259. 11
  126260. };
  126261. static static_codebook _8c0_s_p7_1 = {
  126262. 2, 121,
  126263. _vq_lengthlist__8c0_s_p7_1,
  126264. 1, -531365888, 1611661312, 4, 0,
  126265. _vq_quantlist__8c0_s_p7_1,
  126266. NULL,
  126267. &_vq_auxt__8c0_s_p7_1,
  126268. NULL,
  126269. 0
  126270. };
  126271. static long _vq_quantlist__8c0_s_p8_0[] = {
  126272. 6,
  126273. 5,
  126274. 7,
  126275. 4,
  126276. 8,
  126277. 3,
  126278. 9,
  126279. 2,
  126280. 10,
  126281. 1,
  126282. 11,
  126283. 0,
  126284. 12,
  126285. };
  126286. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126287. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126288. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126289. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126290. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126291. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126292. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126293. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126294. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126295. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126296. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126297. 0, 0,13,13,11,13,13,11,12,
  126298. };
  126299. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126300. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126301. 12.5, 17.5, 22.5, 27.5,
  126302. };
  126303. static long _vq_quantmap__8c0_s_p8_0[] = {
  126304. 11, 9, 7, 5, 3, 1, 0, 2,
  126305. 4, 6, 8, 10, 12,
  126306. };
  126307. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126308. _vq_quantthresh__8c0_s_p8_0,
  126309. _vq_quantmap__8c0_s_p8_0,
  126310. 13,
  126311. 13
  126312. };
  126313. static static_codebook _8c0_s_p8_0 = {
  126314. 2, 169,
  126315. _vq_lengthlist__8c0_s_p8_0,
  126316. 1, -526516224, 1616117760, 4, 0,
  126317. _vq_quantlist__8c0_s_p8_0,
  126318. NULL,
  126319. &_vq_auxt__8c0_s_p8_0,
  126320. NULL,
  126321. 0
  126322. };
  126323. static long _vq_quantlist__8c0_s_p8_1[] = {
  126324. 2,
  126325. 1,
  126326. 3,
  126327. 0,
  126328. 4,
  126329. };
  126330. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126331. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126332. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126333. };
  126334. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126335. -1.5, -0.5, 0.5, 1.5,
  126336. };
  126337. static long _vq_quantmap__8c0_s_p8_1[] = {
  126338. 3, 1, 0, 2, 4,
  126339. };
  126340. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126341. _vq_quantthresh__8c0_s_p8_1,
  126342. _vq_quantmap__8c0_s_p8_1,
  126343. 5,
  126344. 5
  126345. };
  126346. static static_codebook _8c0_s_p8_1 = {
  126347. 2, 25,
  126348. _vq_lengthlist__8c0_s_p8_1,
  126349. 1, -533725184, 1611661312, 3, 0,
  126350. _vq_quantlist__8c0_s_p8_1,
  126351. NULL,
  126352. &_vq_auxt__8c0_s_p8_1,
  126353. NULL,
  126354. 0
  126355. };
  126356. static long _vq_quantlist__8c0_s_p9_0[] = {
  126357. 1,
  126358. 0,
  126359. 2,
  126360. };
  126361. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126362. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126363. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126364. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126365. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126366. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126367. 7,
  126368. };
  126369. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126370. -157.5, 157.5,
  126371. };
  126372. static long _vq_quantmap__8c0_s_p9_0[] = {
  126373. 1, 0, 2,
  126374. };
  126375. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126376. _vq_quantthresh__8c0_s_p9_0,
  126377. _vq_quantmap__8c0_s_p9_0,
  126378. 3,
  126379. 3
  126380. };
  126381. static static_codebook _8c0_s_p9_0 = {
  126382. 4, 81,
  126383. _vq_lengthlist__8c0_s_p9_0,
  126384. 1, -518803456, 1628680192, 2, 0,
  126385. _vq_quantlist__8c0_s_p9_0,
  126386. NULL,
  126387. &_vq_auxt__8c0_s_p9_0,
  126388. NULL,
  126389. 0
  126390. };
  126391. static long _vq_quantlist__8c0_s_p9_1[] = {
  126392. 7,
  126393. 6,
  126394. 8,
  126395. 5,
  126396. 9,
  126397. 4,
  126398. 10,
  126399. 3,
  126400. 11,
  126401. 2,
  126402. 12,
  126403. 1,
  126404. 13,
  126405. 0,
  126406. 14,
  126407. };
  126408. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126409. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126410. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126411. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126412. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126413. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126414. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126415. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126416. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126417. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126418. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126419. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126420. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126421. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126422. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126423. 11,
  126424. };
  126425. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126426. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126427. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126428. };
  126429. static long _vq_quantmap__8c0_s_p9_1[] = {
  126430. 13, 11, 9, 7, 5, 3, 1, 0,
  126431. 2, 4, 6, 8, 10, 12, 14,
  126432. };
  126433. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126434. _vq_quantthresh__8c0_s_p9_1,
  126435. _vq_quantmap__8c0_s_p9_1,
  126436. 15,
  126437. 15
  126438. };
  126439. static static_codebook _8c0_s_p9_1 = {
  126440. 2, 225,
  126441. _vq_lengthlist__8c0_s_p9_1,
  126442. 1, -520986624, 1620377600, 4, 0,
  126443. _vq_quantlist__8c0_s_p9_1,
  126444. NULL,
  126445. &_vq_auxt__8c0_s_p9_1,
  126446. NULL,
  126447. 0
  126448. };
  126449. static long _vq_quantlist__8c0_s_p9_2[] = {
  126450. 10,
  126451. 9,
  126452. 11,
  126453. 8,
  126454. 12,
  126455. 7,
  126456. 13,
  126457. 6,
  126458. 14,
  126459. 5,
  126460. 15,
  126461. 4,
  126462. 16,
  126463. 3,
  126464. 17,
  126465. 2,
  126466. 18,
  126467. 1,
  126468. 19,
  126469. 0,
  126470. 20,
  126471. };
  126472. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126473. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126474. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126475. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126476. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126477. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126478. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126479. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126480. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126481. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126482. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126483. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126484. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126485. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126486. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126487. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126488. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126489. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126490. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126491. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126492. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126493. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126494. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126495. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126496. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126497. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126498. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126499. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126500. 10,11, 9,11,10, 9,10, 9,10,
  126501. };
  126502. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126503. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126504. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126505. 6.5, 7.5, 8.5, 9.5,
  126506. };
  126507. static long _vq_quantmap__8c0_s_p9_2[] = {
  126508. 19, 17, 15, 13, 11, 9, 7, 5,
  126509. 3, 1, 0, 2, 4, 6, 8, 10,
  126510. 12, 14, 16, 18, 20,
  126511. };
  126512. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126513. _vq_quantthresh__8c0_s_p9_2,
  126514. _vq_quantmap__8c0_s_p9_2,
  126515. 21,
  126516. 21
  126517. };
  126518. static static_codebook _8c0_s_p9_2 = {
  126519. 2, 441,
  126520. _vq_lengthlist__8c0_s_p9_2,
  126521. 1, -529268736, 1611661312, 5, 0,
  126522. _vq_quantlist__8c0_s_p9_2,
  126523. NULL,
  126524. &_vq_auxt__8c0_s_p9_2,
  126525. NULL,
  126526. 0
  126527. };
  126528. static long _huff_lengthlist__8c0_s_single[] = {
  126529. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126530. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126531. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126532. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126533. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126534. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126535. 17,16,17,17,
  126536. };
  126537. static static_codebook _huff_book__8c0_s_single = {
  126538. 2, 100,
  126539. _huff_lengthlist__8c0_s_single,
  126540. 0, 0, 0, 0, 0,
  126541. NULL,
  126542. NULL,
  126543. NULL,
  126544. NULL,
  126545. 0
  126546. };
  126547. static long _vq_quantlist__8c1_s_p1_0[] = {
  126548. 1,
  126549. 0,
  126550. 2,
  126551. };
  126552. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126553. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126554. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126558. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126559. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126563. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126564. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126599. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126604. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126609. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126644. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126645. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126649. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126650. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126654. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126655. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0,
  126964. };
  126965. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126966. -0.5, 0.5,
  126967. };
  126968. static long _vq_quantmap__8c1_s_p1_0[] = {
  126969. 1, 0, 2,
  126970. };
  126971. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126972. _vq_quantthresh__8c1_s_p1_0,
  126973. _vq_quantmap__8c1_s_p1_0,
  126974. 3,
  126975. 3
  126976. };
  126977. static static_codebook _8c1_s_p1_0 = {
  126978. 8, 6561,
  126979. _vq_lengthlist__8c1_s_p1_0,
  126980. 1, -535822336, 1611661312, 2, 0,
  126981. _vq_quantlist__8c1_s_p1_0,
  126982. NULL,
  126983. &_vq_auxt__8c1_s_p1_0,
  126984. NULL,
  126985. 0
  126986. };
  126987. static long _vq_quantlist__8c1_s_p2_0[] = {
  126988. 2,
  126989. 1,
  126990. 3,
  126991. 0,
  126992. 4,
  126993. };
  126994. static long _vq_lengthlist__8c1_s_p2_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,
  127035. };
  127036. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127037. -1.5, -0.5, 0.5, 1.5,
  127038. };
  127039. static long _vq_quantmap__8c1_s_p2_0[] = {
  127040. 3, 1, 0, 2, 4,
  127041. };
  127042. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127043. _vq_quantthresh__8c1_s_p2_0,
  127044. _vq_quantmap__8c1_s_p2_0,
  127045. 5,
  127046. 5
  127047. };
  127048. static static_codebook _8c1_s_p2_0 = {
  127049. 4, 625,
  127050. _vq_lengthlist__8c1_s_p2_0,
  127051. 1, -533725184, 1611661312, 3, 0,
  127052. _vq_quantlist__8c1_s_p2_0,
  127053. NULL,
  127054. &_vq_auxt__8c1_s_p2_0,
  127055. NULL,
  127056. 0
  127057. };
  127058. static long _vq_quantlist__8c1_s_p3_0[] = {
  127059. 2,
  127060. 1,
  127061. 3,
  127062. 0,
  127063. 4,
  127064. };
  127065. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127066. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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,
  127106. };
  127107. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127108. -1.5, -0.5, 0.5, 1.5,
  127109. };
  127110. static long _vq_quantmap__8c1_s_p3_0[] = {
  127111. 3, 1, 0, 2, 4,
  127112. };
  127113. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127114. _vq_quantthresh__8c1_s_p3_0,
  127115. _vq_quantmap__8c1_s_p3_0,
  127116. 5,
  127117. 5
  127118. };
  127119. static static_codebook _8c1_s_p3_0 = {
  127120. 4, 625,
  127121. _vq_lengthlist__8c1_s_p3_0,
  127122. 1, -533725184, 1611661312, 3, 0,
  127123. _vq_quantlist__8c1_s_p3_0,
  127124. NULL,
  127125. &_vq_auxt__8c1_s_p3_0,
  127126. NULL,
  127127. 0
  127128. };
  127129. static long _vq_quantlist__8c1_s_p4_0[] = {
  127130. 4,
  127131. 3,
  127132. 5,
  127133. 2,
  127134. 6,
  127135. 1,
  127136. 7,
  127137. 0,
  127138. 8,
  127139. };
  127140. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127141. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127142. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127143. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127144. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127145. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0,
  127147. };
  127148. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127149. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127150. };
  127151. static long _vq_quantmap__8c1_s_p4_0[] = {
  127152. 7, 5, 3, 1, 0, 2, 4, 6,
  127153. 8,
  127154. };
  127155. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127156. _vq_quantthresh__8c1_s_p4_0,
  127157. _vq_quantmap__8c1_s_p4_0,
  127158. 9,
  127159. 9
  127160. };
  127161. static static_codebook _8c1_s_p4_0 = {
  127162. 2, 81,
  127163. _vq_lengthlist__8c1_s_p4_0,
  127164. 1, -531628032, 1611661312, 4, 0,
  127165. _vq_quantlist__8c1_s_p4_0,
  127166. NULL,
  127167. &_vq_auxt__8c1_s_p4_0,
  127168. NULL,
  127169. 0
  127170. };
  127171. static long _vq_quantlist__8c1_s_p5_0[] = {
  127172. 4,
  127173. 3,
  127174. 5,
  127175. 2,
  127176. 6,
  127177. 1,
  127178. 7,
  127179. 0,
  127180. 8,
  127181. };
  127182. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127183. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127184. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127185. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127186. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127187. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127188. 10,
  127189. };
  127190. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127191. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127192. };
  127193. static long _vq_quantmap__8c1_s_p5_0[] = {
  127194. 7, 5, 3, 1, 0, 2, 4, 6,
  127195. 8,
  127196. };
  127197. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127198. _vq_quantthresh__8c1_s_p5_0,
  127199. _vq_quantmap__8c1_s_p5_0,
  127200. 9,
  127201. 9
  127202. };
  127203. static static_codebook _8c1_s_p5_0 = {
  127204. 2, 81,
  127205. _vq_lengthlist__8c1_s_p5_0,
  127206. 1, -531628032, 1611661312, 4, 0,
  127207. _vq_quantlist__8c1_s_p5_0,
  127208. NULL,
  127209. &_vq_auxt__8c1_s_p5_0,
  127210. NULL,
  127211. 0
  127212. };
  127213. static long _vq_quantlist__8c1_s_p6_0[] = {
  127214. 8,
  127215. 7,
  127216. 9,
  127217. 6,
  127218. 10,
  127219. 5,
  127220. 11,
  127221. 4,
  127222. 12,
  127223. 3,
  127224. 13,
  127225. 2,
  127226. 14,
  127227. 1,
  127228. 15,
  127229. 0,
  127230. 16,
  127231. };
  127232. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127233. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127234. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127235. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127236. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127237. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127238. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127239. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127240. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127241. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127242. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127243. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127244. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127245. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127246. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127247. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127248. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127249. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127251. 14,
  127252. };
  127253. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127254. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127255. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127256. };
  127257. static long _vq_quantmap__8c1_s_p6_0[] = {
  127258. 15, 13, 11, 9, 7, 5, 3, 1,
  127259. 0, 2, 4, 6, 8, 10, 12, 14,
  127260. 16,
  127261. };
  127262. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127263. _vq_quantthresh__8c1_s_p6_0,
  127264. _vq_quantmap__8c1_s_p6_0,
  127265. 17,
  127266. 17
  127267. };
  127268. static static_codebook _8c1_s_p6_0 = {
  127269. 2, 289,
  127270. _vq_lengthlist__8c1_s_p6_0,
  127271. 1, -529530880, 1611661312, 5, 0,
  127272. _vq_quantlist__8c1_s_p6_0,
  127273. NULL,
  127274. &_vq_auxt__8c1_s_p6_0,
  127275. NULL,
  127276. 0
  127277. };
  127278. static long _vq_quantlist__8c1_s_p7_0[] = {
  127279. 1,
  127280. 0,
  127281. 2,
  127282. };
  127283. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127284. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127285. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127286. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127287. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127288. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127289. 9,
  127290. };
  127291. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127292. -5.5, 5.5,
  127293. };
  127294. static long _vq_quantmap__8c1_s_p7_0[] = {
  127295. 1, 0, 2,
  127296. };
  127297. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127298. _vq_quantthresh__8c1_s_p7_0,
  127299. _vq_quantmap__8c1_s_p7_0,
  127300. 3,
  127301. 3
  127302. };
  127303. static static_codebook _8c1_s_p7_0 = {
  127304. 4, 81,
  127305. _vq_lengthlist__8c1_s_p7_0,
  127306. 1, -529137664, 1618345984, 2, 0,
  127307. _vq_quantlist__8c1_s_p7_0,
  127308. NULL,
  127309. &_vq_auxt__8c1_s_p7_0,
  127310. NULL,
  127311. 0
  127312. };
  127313. static long _vq_quantlist__8c1_s_p7_1[] = {
  127314. 5,
  127315. 4,
  127316. 6,
  127317. 3,
  127318. 7,
  127319. 2,
  127320. 8,
  127321. 1,
  127322. 9,
  127323. 0,
  127324. 10,
  127325. };
  127326. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127327. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127328. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127329. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127330. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127331. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127332. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127333. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127334. 10,10,10, 8, 8, 8, 8, 8, 8,
  127335. };
  127336. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127337. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127338. 3.5, 4.5,
  127339. };
  127340. static long _vq_quantmap__8c1_s_p7_1[] = {
  127341. 9, 7, 5, 3, 1, 0, 2, 4,
  127342. 6, 8, 10,
  127343. };
  127344. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127345. _vq_quantthresh__8c1_s_p7_1,
  127346. _vq_quantmap__8c1_s_p7_1,
  127347. 11,
  127348. 11
  127349. };
  127350. static static_codebook _8c1_s_p7_1 = {
  127351. 2, 121,
  127352. _vq_lengthlist__8c1_s_p7_1,
  127353. 1, -531365888, 1611661312, 4, 0,
  127354. _vq_quantlist__8c1_s_p7_1,
  127355. NULL,
  127356. &_vq_auxt__8c1_s_p7_1,
  127357. NULL,
  127358. 0
  127359. };
  127360. static long _vq_quantlist__8c1_s_p8_0[] = {
  127361. 6,
  127362. 5,
  127363. 7,
  127364. 4,
  127365. 8,
  127366. 3,
  127367. 9,
  127368. 2,
  127369. 10,
  127370. 1,
  127371. 11,
  127372. 0,
  127373. 12,
  127374. };
  127375. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127376. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127377. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127378. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127379. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127380. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127381. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127382. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127383. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127384. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127385. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127386. 0,12,12,11,10,12,11,13,12,
  127387. };
  127388. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127389. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127390. 12.5, 17.5, 22.5, 27.5,
  127391. };
  127392. static long _vq_quantmap__8c1_s_p8_0[] = {
  127393. 11, 9, 7, 5, 3, 1, 0, 2,
  127394. 4, 6, 8, 10, 12,
  127395. };
  127396. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127397. _vq_quantthresh__8c1_s_p8_0,
  127398. _vq_quantmap__8c1_s_p8_0,
  127399. 13,
  127400. 13
  127401. };
  127402. static static_codebook _8c1_s_p8_0 = {
  127403. 2, 169,
  127404. _vq_lengthlist__8c1_s_p8_0,
  127405. 1, -526516224, 1616117760, 4, 0,
  127406. _vq_quantlist__8c1_s_p8_0,
  127407. NULL,
  127408. &_vq_auxt__8c1_s_p8_0,
  127409. NULL,
  127410. 0
  127411. };
  127412. static long _vq_quantlist__8c1_s_p8_1[] = {
  127413. 2,
  127414. 1,
  127415. 3,
  127416. 0,
  127417. 4,
  127418. };
  127419. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127420. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127421. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127422. };
  127423. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127424. -1.5, -0.5, 0.5, 1.5,
  127425. };
  127426. static long _vq_quantmap__8c1_s_p8_1[] = {
  127427. 3, 1, 0, 2, 4,
  127428. };
  127429. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127430. _vq_quantthresh__8c1_s_p8_1,
  127431. _vq_quantmap__8c1_s_p8_1,
  127432. 5,
  127433. 5
  127434. };
  127435. static static_codebook _8c1_s_p8_1 = {
  127436. 2, 25,
  127437. _vq_lengthlist__8c1_s_p8_1,
  127438. 1, -533725184, 1611661312, 3, 0,
  127439. _vq_quantlist__8c1_s_p8_1,
  127440. NULL,
  127441. &_vq_auxt__8c1_s_p8_1,
  127442. NULL,
  127443. 0
  127444. };
  127445. static long _vq_quantlist__8c1_s_p9_0[] = {
  127446. 6,
  127447. 5,
  127448. 7,
  127449. 4,
  127450. 8,
  127451. 3,
  127452. 9,
  127453. 2,
  127454. 10,
  127455. 1,
  127456. 11,
  127457. 0,
  127458. 12,
  127459. };
  127460. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127461. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127462. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127463. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127464. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127465. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127466. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127467. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127468. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127469. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127470. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127471. 10,10,10,10,10, 9, 9, 9, 9,
  127472. };
  127473. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127474. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127475. 787.5, 1102.5, 1417.5, 1732.5,
  127476. };
  127477. static long _vq_quantmap__8c1_s_p9_0[] = {
  127478. 11, 9, 7, 5, 3, 1, 0, 2,
  127479. 4, 6, 8, 10, 12,
  127480. };
  127481. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127482. _vq_quantthresh__8c1_s_p9_0,
  127483. _vq_quantmap__8c1_s_p9_0,
  127484. 13,
  127485. 13
  127486. };
  127487. static static_codebook _8c1_s_p9_0 = {
  127488. 2, 169,
  127489. _vq_lengthlist__8c1_s_p9_0,
  127490. 1, -513964032, 1628680192, 4, 0,
  127491. _vq_quantlist__8c1_s_p9_0,
  127492. NULL,
  127493. &_vq_auxt__8c1_s_p9_0,
  127494. NULL,
  127495. 0
  127496. };
  127497. static long _vq_quantlist__8c1_s_p9_1[] = {
  127498. 7,
  127499. 6,
  127500. 8,
  127501. 5,
  127502. 9,
  127503. 4,
  127504. 10,
  127505. 3,
  127506. 11,
  127507. 2,
  127508. 12,
  127509. 1,
  127510. 13,
  127511. 0,
  127512. 14,
  127513. };
  127514. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127515. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127516. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127517. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127518. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127519. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127520. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127521. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127522. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127523. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127524. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127525. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127526. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127527. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127528. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127529. 15,
  127530. };
  127531. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127532. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127533. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127534. };
  127535. static long _vq_quantmap__8c1_s_p9_1[] = {
  127536. 13, 11, 9, 7, 5, 3, 1, 0,
  127537. 2, 4, 6, 8, 10, 12, 14,
  127538. };
  127539. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127540. _vq_quantthresh__8c1_s_p9_1,
  127541. _vq_quantmap__8c1_s_p9_1,
  127542. 15,
  127543. 15
  127544. };
  127545. static static_codebook _8c1_s_p9_1 = {
  127546. 2, 225,
  127547. _vq_lengthlist__8c1_s_p9_1,
  127548. 1, -520986624, 1620377600, 4, 0,
  127549. _vq_quantlist__8c1_s_p9_1,
  127550. NULL,
  127551. &_vq_auxt__8c1_s_p9_1,
  127552. NULL,
  127553. 0
  127554. };
  127555. static long _vq_quantlist__8c1_s_p9_2[] = {
  127556. 10,
  127557. 9,
  127558. 11,
  127559. 8,
  127560. 12,
  127561. 7,
  127562. 13,
  127563. 6,
  127564. 14,
  127565. 5,
  127566. 15,
  127567. 4,
  127568. 16,
  127569. 3,
  127570. 17,
  127571. 2,
  127572. 18,
  127573. 1,
  127574. 19,
  127575. 0,
  127576. 20,
  127577. };
  127578. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127579. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127580. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127581. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127582. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127583. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127584. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127585. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127586. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127587. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127588. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127589. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127590. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127591. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127592. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127593. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127594. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127595. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127596. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127597. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127598. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127599. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127600. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127601. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127602. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127603. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127604. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127605. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127606. 10,10,10,10,10,10,10,10,10,
  127607. };
  127608. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127609. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127610. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127611. 6.5, 7.5, 8.5, 9.5,
  127612. };
  127613. static long _vq_quantmap__8c1_s_p9_2[] = {
  127614. 19, 17, 15, 13, 11, 9, 7, 5,
  127615. 3, 1, 0, 2, 4, 6, 8, 10,
  127616. 12, 14, 16, 18, 20,
  127617. };
  127618. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127619. _vq_quantthresh__8c1_s_p9_2,
  127620. _vq_quantmap__8c1_s_p9_2,
  127621. 21,
  127622. 21
  127623. };
  127624. static static_codebook _8c1_s_p9_2 = {
  127625. 2, 441,
  127626. _vq_lengthlist__8c1_s_p9_2,
  127627. 1, -529268736, 1611661312, 5, 0,
  127628. _vq_quantlist__8c1_s_p9_2,
  127629. NULL,
  127630. &_vq_auxt__8c1_s_p9_2,
  127631. NULL,
  127632. 0
  127633. };
  127634. static long _huff_lengthlist__8c1_s_single[] = {
  127635. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127636. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127637. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127638. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127639. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127640. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127641. 9, 7, 7, 8,
  127642. };
  127643. static static_codebook _huff_book__8c1_s_single = {
  127644. 2, 100,
  127645. _huff_lengthlist__8c1_s_single,
  127646. 0, 0, 0, 0, 0,
  127647. NULL,
  127648. NULL,
  127649. NULL,
  127650. NULL,
  127651. 0
  127652. };
  127653. static long _huff_lengthlist__44c2_s_long[] = {
  127654. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127655. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127656. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127657. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127658. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127659. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127660. 10, 8, 8, 9,
  127661. };
  127662. static static_codebook _huff_book__44c2_s_long = {
  127663. 2, 100,
  127664. _huff_lengthlist__44c2_s_long,
  127665. 0, 0, 0, 0, 0,
  127666. NULL,
  127667. NULL,
  127668. NULL,
  127669. NULL,
  127670. 0
  127671. };
  127672. static long _vq_quantlist__44c2_s_p1_0[] = {
  127673. 1,
  127674. 0,
  127675. 2,
  127676. };
  127677. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127678. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127679. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127683. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127684. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127688. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127689. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127724. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127729. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127734. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127769. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127770. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127774. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127775. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127779. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127780. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0,
  128089. };
  128090. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128091. -0.5, 0.5,
  128092. };
  128093. static long _vq_quantmap__44c2_s_p1_0[] = {
  128094. 1, 0, 2,
  128095. };
  128096. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128097. _vq_quantthresh__44c2_s_p1_0,
  128098. _vq_quantmap__44c2_s_p1_0,
  128099. 3,
  128100. 3
  128101. };
  128102. static static_codebook _44c2_s_p1_0 = {
  128103. 8, 6561,
  128104. _vq_lengthlist__44c2_s_p1_0,
  128105. 1, -535822336, 1611661312, 2, 0,
  128106. _vq_quantlist__44c2_s_p1_0,
  128107. NULL,
  128108. &_vq_auxt__44c2_s_p1_0,
  128109. NULL,
  128110. 0
  128111. };
  128112. static long _vq_quantlist__44c2_s_p2_0[] = {
  128113. 2,
  128114. 1,
  128115. 3,
  128116. 0,
  128117. 4,
  128118. };
  128119. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128120. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128121. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128122. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128123. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128124. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128130. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128131. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128132. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128138. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128139. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128146. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128147. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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,
  128160. };
  128161. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128162. -1.5, -0.5, 0.5, 1.5,
  128163. };
  128164. static long _vq_quantmap__44c2_s_p2_0[] = {
  128165. 3, 1, 0, 2, 4,
  128166. };
  128167. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128168. _vq_quantthresh__44c2_s_p2_0,
  128169. _vq_quantmap__44c2_s_p2_0,
  128170. 5,
  128171. 5
  128172. };
  128173. static static_codebook _44c2_s_p2_0 = {
  128174. 4, 625,
  128175. _vq_lengthlist__44c2_s_p2_0,
  128176. 1, -533725184, 1611661312, 3, 0,
  128177. _vq_quantlist__44c2_s_p2_0,
  128178. NULL,
  128179. &_vq_auxt__44c2_s_p2_0,
  128180. NULL,
  128181. 0
  128182. };
  128183. static long _vq_quantlist__44c2_s_p3_0[] = {
  128184. 2,
  128185. 1,
  128186. 3,
  128187. 0,
  128188. 4,
  128189. };
  128190. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128191. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  128231. };
  128232. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128233. -1.5, -0.5, 0.5, 1.5,
  128234. };
  128235. static long _vq_quantmap__44c2_s_p3_0[] = {
  128236. 3, 1, 0, 2, 4,
  128237. };
  128238. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128239. _vq_quantthresh__44c2_s_p3_0,
  128240. _vq_quantmap__44c2_s_p3_0,
  128241. 5,
  128242. 5
  128243. };
  128244. static static_codebook _44c2_s_p3_0 = {
  128245. 4, 625,
  128246. _vq_lengthlist__44c2_s_p3_0,
  128247. 1, -533725184, 1611661312, 3, 0,
  128248. _vq_quantlist__44c2_s_p3_0,
  128249. NULL,
  128250. &_vq_auxt__44c2_s_p3_0,
  128251. NULL,
  128252. 0
  128253. };
  128254. static long _vq_quantlist__44c2_s_p4_0[] = {
  128255. 4,
  128256. 3,
  128257. 5,
  128258. 2,
  128259. 6,
  128260. 1,
  128261. 7,
  128262. 0,
  128263. 8,
  128264. };
  128265. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128266. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128267. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128268. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128269. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128270. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0,
  128272. };
  128273. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128274. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128275. };
  128276. static long _vq_quantmap__44c2_s_p4_0[] = {
  128277. 7, 5, 3, 1, 0, 2, 4, 6,
  128278. 8,
  128279. };
  128280. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128281. _vq_quantthresh__44c2_s_p4_0,
  128282. _vq_quantmap__44c2_s_p4_0,
  128283. 9,
  128284. 9
  128285. };
  128286. static static_codebook _44c2_s_p4_0 = {
  128287. 2, 81,
  128288. _vq_lengthlist__44c2_s_p4_0,
  128289. 1, -531628032, 1611661312, 4, 0,
  128290. _vq_quantlist__44c2_s_p4_0,
  128291. NULL,
  128292. &_vq_auxt__44c2_s_p4_0,
  128293. NULL,
  128294. 0
  128295. };
  128296. static long _vq_quantlist__44c2_s_p5_0[] = {
  128297. 4,
  128298. 3,
  128299. 5,
  128300. 2,
  128301. 6,
  128302. 1,
  128303. 7,
  128304. 0,
  128305. 8,
  128306. };
  128307. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128308. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128309. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128310. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128311. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128312. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128313. 11,
  128314. };
  128315. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128316. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128317. };
  128318. static long _vq_quantmap__44c2_s_p5_0[] = {
  128319. 7, 5, 3, 1, 0, 2, 4, 6,
  128320. 8,
  128321. };
  128322. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128323. _vq_quantthresh__44c2_s_p5_0,
  128324. _vq_quantmap__44c2_s_p5_0,
  128325. 9,
  128326. 9
  128327. };
  128328. static static_codebook _44c2_s_p5_0 = {
  128329. 2, 81,
  128330. _vq_lengthlist__44c2_s_p5_0,
  128331. 1, -531628032, 1611661312, 4, 0,
  128332. _vq_quantlist__44c2_s_p5_0,
  128333. NULL,
  128334. &_vq_auxt__44c2_s_p5_0,
  128335. NULL,
  128336. 0
  128337. };
  128338. static long _vq_quantlist__44c2_s_p6_0[] = {
  128339. 8,
  128340. 7,
  128341. 9,
  128342. 6,
  128343. 10,
  128344. 5,
  128345. 11,
  128346. 4,
  128347. 12,
  128348. 3,
  128349. 13,
  128350. 2,
  128351. 14,
  128352. 1,
  128353. 15,
  128354. 0,
  128355. 16,
  128356. };
  128357. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128358. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128359. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128360. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128361. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128362. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128363. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128364. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128365. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128366. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128367. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128368. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128369. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128370. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128371. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128372. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128373. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128374. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128376. 14,
  128377. };
  128378. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128379. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128380. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128381. };
  128382. static long _vq_quantmap__44c2_s_p6_0[] = {
  128383. 15, 13, 11, 9, 7, 5, 3, 1,
  128384. 0, 2, 4, 6, 8, 10, 12, 14,
  128385. 16,
  128386. };
  128387. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128388. _vq_quantthresh__44c2_s_p6_0,
  128389. _vq_quantmap__44c2_s_p6_0,
  128390. 17,
  128391. 17
  128392. };
  128393. static static_codebook _44c2_s_p6_0 = {
  128394. 2, 289,
  128395. _vq_lengthlist__44c2_s_p6_0,
  128396. 1, -529530880, 1611661312, 5, 0,
  128397. _vq_quantlist__44c2_s_p6_0,
  128398. NULL,
  128399. &_vq_auxt__44c2_s_p6_0,
  128400. NULL,
  128401. 0
  128402. };
  128403. static long _vq_quantlist__44c2_s_p7_0[] = {
  128404. 1,
  128405. 0,
  128406. 2,
  128407. };
  128408. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128409. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128410. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128411. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128412. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128413. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128414. 11,
  128415. };
  128416. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128417. -5.5, 5.5,
  128418. };
  128419. static long _vq_quantmap__44c2_s_p7_0[] = {
  128420. 1, 0, 2,
  128421. };
  128422. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128423. _vq_quantthresh__44c2_s_p7_0,
  128424. _vq_quantmap__44c2_s_p7_0,
  128425. 3,
  128426. 3
  128427. };
  128428. static static_codebook _44c2_s_p7_0 = {
  128429. 4, 81,
  128430. _vq_lengthlist__44c2_s_p7_0,
  128431. 1, -529137664, 1618345984, 2, 0,
  128432. _vq_quantlist__44c2_s_p7_0,
  128433. NULL,
  128434. &_vq_auxt__44c2_s_p7_0,
  128435. NULL,
  128436. 0
  128437. };
  128438. static long _vq_quantlist__44c2_s_p7_1[] = {
  128439. 5,
  128440. 4,
  128441. 6,
  128442. 3,
  128443. 7,
  128444. 2,
  128445. 8,
  128446. 1,
  128447. 9,
  128448. 0,
  128449. 10,
  128450. };
  128451. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128452. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128453. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128454. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128455. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128456. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128457. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128458. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128459. 10,10,10, 8, 8, 8, 8, 8, 8,
  128460. };
  128461. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128462. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128463. 3.5, 4.5,
  128464. };
  128465. static long _vq_quantmap__44c2_s_p7_1[] = {
  128466. 9, 7, 5, 3, 1, 0, 2, 4,
  128467. 6, 8, 10,
  128468. };
  128469. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128470. _vq_quantthresh__44c2_s_p7_1,
  128471. _vq_quantmap__44c2_s_p7_1,
  128472. 11,
  128473. 11
  128474. };
  128475. static static_codebook _44c2_s_p7_1 = {
  128476. 2, 121,
  128477. _vq_lengthlist__44c2_s_p7_1,
  128478. 1, -531365888, 1611661312, 4, 0,
  128479. _vq_quantlist__44c2_s_p7_1,
  128480. NULL,
  128481. &_vq_auxt__44c2_s_p7_1,
  128482. NULL,
  128483. 0
  128484. };
  128485. static long _vq_quantlist__44c2_s_p8_0[] = {
  128486. 6,
  128487. 5,
  128488. 7,
  128489. 4,
  128490. 8,
  128491. 3,
  128492. 9,
  128493. 2,
  128494. 10,
  128495. 1,
  128496. 11,
  128497. 0,
  128498. 12,
  128499. };
  128500. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128501. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128502. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128503. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128504. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128505. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128506. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128507. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128508. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128509. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128510. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128511. 0,12,12,12,12,13,12,14,14,
  128512. };
  128513. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128514. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128515. 12.5, 17.5, 22.5, 27.5,
  128516. };
  128517. static long _vq_quantmap__44c2_s_p8_0[] = {
  128518. 11, 9, 7, 5, 3, 1, 0, 2,
  128519. 4, 6, 8, 10, 12,
  128520. };
  128521. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128522. _vq_quantthresh__44c2_s_p8_0,
  128523. _vq_quantmap__44c2_s_p8_0,
  128524. 13,
  128525. 13
  128526. };
  128527. static static_codebook _44c2_s_p8_0 = {
  128528. 2, 169,
  128529. _vq_lengthlist__44c2_s_p8_0,
  128530. 1, -526516224, 1616117760, 4, 0,
  128531. _vq_quantlist__44c2_s_p8_0,
  128532. NULL,
  128533. &_vq_auxt__44c2_s_p8_0,
  128534. NULL,
  128535. 0
  128536. };
  128537. static long _vq_quantlist__44c2_s_p8_1[] = {
  128538. 2,
  128539. 1,
  128540. 3,
  128541. 0,
  128542. 4,
  128543. };
  128544. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128545. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128546. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128547. };
  128548. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128549. -1.5, -0.5, 0.5, 1.5,
  128550. };
  128551. static long _vq_quantmap__44c2_s_p8_1[] = {
  128552. 3, 1, 0, 2, 4,
  128553. };
  128554. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128555. _vq_quantthresh__44c2_s_p8_1,
  128556. _vq_quantmap__44c2_s_p8_1,
  128557. 5,
  128558. 5
  128559. };
  128560. static static_codebook _44c2_s_p8_1 = {
  128561. 2, 25,
  128562. _vq_lengthlist__44c2_s_p8_1,
  128563. 1, -533725184, 1611661312, 3, 0,
  128564. _vq_quantlist__44c2_s_p8_1,
  128565. NULL,
  128566. &_vq_auxt__44c2_s_p8_1,
  128567. NULL,
  128568. 0
  128569. };
  128570. static long _vq_quantlist__44c2_s_p9_0[] = {
  128571. 6,
  128572. 5,
  128573. 7,
  128574. 4,
  128575. 8,
  128576. 3,
  128577. 9,
  128578. 2,
  128579. 10,
  128580. 1,
  128581. 11,
  128582. 0,
  128583. 12,
  128584. };
  128585. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128586. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128587. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128588. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128589. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128590. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128592. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128596. 11,11,11,11,11,11,11,11,11,
  128597. };
  128598. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128599. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128600. 552.5, 773.5, 994.5, 1215.5,
  128601. };
  128602. static long _vq_quantmap__44c2_s_p9_0[] = {
  128603. 11, 9, 7, 5, 3, 1, 0, 2,
  128604. 4, 6, 8, 10, 12,
  128605. };
  128606. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128607. _vq_quantthresh__44c2_s_p9_0,
  128608. _vq_quantmap__44c2_s_p9_0,
  128609. 13,
  128610. 13
  128611. };
  128612. static static_codebook _44c2_s_p9_0 = {
  128613. 2, 169,
  128614. _vq_lengthlist__44c2_s_p9_0,
  128615. 1, -514541568, 1627103232, 4, 0,
  128616. _vq_quantlist__44c2_s_p9_0,
  128617. NULL,
  128618. &_vq_auxt__44c2_s_p9_0,
  128619. NULL,
  128620. 0
  128621. };
  128622. static long _vq_quantlist__44c2_s_p9_1[] = {
  128623. 6,
  128624. 5,
  128625. 7,
  128626. 4,
  128627. 8,
  128628. 3,
  128629. 9,
  128630. 2,
  128631. 10,
  128632. 1,
  128633. 11,
  128634. 0,
  128635. 12,
  128636. };
  128637. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128638. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128639. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128640. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128641. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128642. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128643. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128644. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128645. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128646. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128647. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128648. 17,13,12,12,10,13,11,14,14,
  128649. };
  128650. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128651. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128652. 42.5, 59.5, 76.5, 93.5,
  128653. };
  128654. static long _vq_quantmap__44c2_s_p9_1[] = {
  128655. 11, 9, 7, 5, 3, 1, 0, 2,
  128656. 4, 6, 8, 10, 12,
  128657. };
  128658. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128659. _vq_quantthresh__44c2_s_p9_1,
  128660. _vq_quantmap__44c2_s_p9_1,
  128661. 13,
  128662. 13
  128663. };
  128664. static static_codebook _44c2_s_p9_1 = {
  128665. 2, 169,
  128666. _vq_lengthlist__44c2_s_p9_1,
  128667. 1, -522616832, 1620115456, 4, 0,
  128668. _vq_quantlist__44c2_s_p9_1,
  128669. NULL,
  128670. &_vq_auxt__44c2_s_p9_1,
  128671. NULL,
  128672. 0
  128673. };
  128674. static long _vq_quantlist__44c2_s_p9_2[] = {
  128675. 8,
  128676. 7,
  128677. 9,
  128678. 6,
  128679. 10,
  128680. 5,
  128681. 11,
  128682. 4,
  128683. 12,
  128684. 3,
  128685. 13,
  128686. 2,
  128687. 14,
  128688. 1,
  128689. 15,
  128690. 0,
  128691. 16,
  128692. };
  128693. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128694. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128695. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128696. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128697. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128698. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128699. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128700. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128701. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128702. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128703. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128704. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128705. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128706. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128707. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128708. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128709. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128710. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128711. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128712. 10,
  128713. };
  128714. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128715. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128716. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128717. };
  128718. static long _vq_quantmap__44c2_s_p9_2[] = {
  128719. 15, 13, 11, 9, 7, 5, 3, 1,
  128720. 0, 2, 4, 6, 8, 10, 12, 14,
  128721. 16,
  128722. };
  128723. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128724. _vq_quantthresh__44c2_s_p9_2,
  128725. _vq_quantmap__44c2_s_p9_2,
  128726. 17,
  128727. 17
  128728. };
  128729. static static_codebook _44c2_s_p9_2 = {
  128730. 2, 289,
  128731. _vq_lengthlist__44c2_s_p9_2,
  128732. 1, -529530880, 1611661312, 5, 0,
  128733. _vq_quantlist__44c2_s_p9_2,
  128734. NULL,
  128735. &_vq_auxt__44c2_s_p9_2,
  128736. NULL,
  128737. 0
  128738. };
  128739. static long _huff_lengthlist__44c2_s_short[] = {
  128740. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128741. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128742. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128743. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128744. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128745. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128746. 6, 8, 9,12,
  128747. };
  128748. static static_codebook _huff_book__44c2_s_short = {
  128749. 2, 100,
  128750. _huff_lengthlist__44c2_s_short,
  128751. 0, 0, 0, 0, 0,
  128752. NULL,
  128753. NULL,
  128754. NULL,
  128755. NULL,
  128756. 0
  128757. };
  128758. static long _huff_lengthlist__44c3_s_long[] = {
  128759. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128760. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128761. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128762. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128763. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128764. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128765. 9, 8, 8, 8,
  128766. };
  128767. static static_codebook _huff_book__44c3_s_long = {
  128768. 2, 100,
  128769. _huff_lengthlist__44c3_s_long,
  128770. 0, 0, 0, 0, 0,
  128771. NULL,
  128772. NULL,
  128773. NULL,
  128774. NULL,
  128775. 0
  128776. };
  128777. static long _vq_quantlist__44c3_s_p1_0[] = {
  128778. 1,
  128779. 0,
  128780. 2,
  128781. };
  128782. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128783. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128784. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128788. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128789. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128793. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128794. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128829. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128834. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128839. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128874. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128875. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128879. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128880. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128884. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128885. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  128886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0,
  129194. };
  129195. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129196. -0.5, 0.5,
  129197. };
  129198. static long _vq_quantmap__44c3_s_p1_0[] = {
  129199. 1, 0, 2,
  129200. };
  129201. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129202. _vq_quantthresh__44c3_s_p1_0,
  129203. _vq_quantmap__44c3_s_p1_0,
  129204. 3,
  129205. 3
  129206. };
  129207. static static_codebook _44c3_s_p1_0 = {
  129208. 8, 6561,
  129209. _vq_lengthlist__44c3_s_p1_0,
  129210. 1, -535822336, 1611661312, 2, 0,
  129211. _vq_quantlist__44c3_s_p1_0,
  129212. NULL,
  129213. &_vq_auxt__44c3_s_p1_0,
  129214. NULL,
  129215. 0
  129216. };
  129217. static long _vq_quantlist__44c3_s_p2_0[] = {
  129218. 2,
  129219. 1,
  129220. 3,
  129221. 0,
  129222. 4,
  129223. };
  129224. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129225. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129226. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129227. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129228. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129229. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129235. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129236. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129237. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129243. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129244. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129251. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129252. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  129265. };
  129266. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129267. -1.5, -0.5, 0.5, 1.5,
  129268. };
  129269. static long _vq_quantmap__44c3_s_p2_0[] = {
  129270. 3, 1, 0, 2, 4,
  129271. };
  129272. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129273. _vq_quantthresh__44c3_s_p2_0,
  129274. _vq_quantmap__44c3_s_p2_0,
  129275. 5,
  129276. 5
  129277. };
  129278. static static_codebook _44c3_s_p2_0 = {
  129279. 4, 625,
  129280. _vq_lengthlist__44c3_s_p2_0,
  129281. 1, -533725184, 1611661312, 3, 0,
  129282. _vq_quantlist__44c3_s_p2_0,
  129283. NULL,
  129284. &_vq_auxt__44c3_s_p2_0,
  129285. NULL,
  129286. 0
  129287. };
  129288. static long _vq_quantlist__44c3_s_p3_0[] = {
  129289. 2,
  129290. 1,
  129291. 3,
  129292. 0,
  129293. 4,
  129294. };
  129295. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129296. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  129336. };
  129337. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129338. -1.5, -0.5, 0.5, 1.5,
  129339. };
  129340. static long _vq_quantmap__44c3_s_p3_0[] = {
  129341. 3, 1, 0, 2, 4,
  129342. };
  129343. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129344. _vq_quantthresh__44c3_s_p3_0,
  129345. _vq_quantmap__44c3_s_p3_0,
  129346. 5,
  129347. 5
  129348. };
  129349. static static_codebook _44c3_s_p3_0 = {
  129350. 4, 625,
  129351. _vq_lengthlist__44c3_s_p3_0,
  129352. 1, -533725184, 1611661312, 3, 0,
  129353. _vq_quantlist__44c3_s_p3_0,
  129354. NULL,
  129355. &_vq_auxt__44c3_s_p3_0,
  129356. NULL,
  129357. 0
  129358. };
  129359. static long _vq_quantlist__44c3_s_p4_0[] = {
  129360. 4,
  129361. 3,
  129362. 5,
  129363. 2,
  129364. 6,
  129365. 1,
  129366. 7,
  129367. 0,
  129368. 8,
  129369. };
  129370. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129371. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129372. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129373. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129374. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129375. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0,
  129377. };
  129378. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129379. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129380. };
  129381. static long _vq_quantmap__44c3_s_p4_0[] = {
  129382. 7, 5, 3, 1, 0, 2, 4, 6,
  129383. 8,
  129384. };
  129385. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129386. _vq_quantthresh__44c3_s_p4_0,
  129387. _vq_quantmap__44c3_s_p4_0,
  129388. 9,
  129389. 9
  129390. };
  129391. static static_codebook _44c3_s_p4_0 = {
  129392. 2, 81,
  129393. _vq_lengthlist__44c3_s_p4_0,
  129394. 1, -531628032, 1611661312, 4, 0,
  129395. _vq_quantlist__44c3_s_p4_0,
  129396. NULL,
  129397. &_vq_auxt__44c3_s_p4_0,
  129398. NULL,
  129399. 0
  129400. };
  129401. static long _vq_quantlist__44c3_s_p5_0[] = {
  129402. 4,
  129403. 3,
  129404. 5,
  129405. 2,
  129406. 6,
  129407. 1,
  129408. 7,
  129409. 0,
  129410. 8,
  129411. };
  129412. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129413. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129414. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129415. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129416. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129417. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129418. 11,
  129419. };
  129420. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129421. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129422. };
  129423. static long _vq_quantmap__44c3_s_p5_0[] = {
  129424. 7, 5, 3, 1, 0, 2, 4, 6,
  129425. 8,
  129426. };
  129427. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129428. _vq_quantthresh__44c3_s_p5_0,
  129429. _vq_quantmap__44c3_s_p5_0,
  129430. 9,
  129431. 9
  129432. };
  129433. static static_codebook _44c3_s_p5_0 = {
  129434. 2, 81,
  129435. _vq_lengthlist__44c3_s_p5_0,
  129436. 1, -531628032, 1611661312, 4, 0,
  129437. _vq_quantlist__44c3_s_p5_0,
  129438. NULL,
  129439. &_vq_auxt__44c3_s_p5_0,
  129440. NULL,
  129441. 0
  129442. };
  129443. static long _vq_quantlist__44c3_s_p6_0[] = {
  129444. 8,
  129445. 7,
  129446. 9,
  129447. 6,
  129448. 10,
  129449. 5,
  129450. 11,
  129451. 4,
  129452. 12,
  129453. 3,
  129454. 13,
  129455. 2,
  129456. 14,
  129457. 1,
  129458. 15,
  129459. 0,
  129460. 16,
  129461. };
  129462. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129463. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129464. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129465. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129466. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129467. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129468. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129469. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129470. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129471. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129472. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129473. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129474. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129475. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129476. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129477. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129478. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129479. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129481. 13,
  129482. };
  129483. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129484. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129485. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129486. };
  129487. static long _vq_quantmap__44c3_s_p6_0[] = {
  129488. 15, 13, 11, 9, 7, 5, 3, 1,
  129489. 0, 2, 4, 6, 8, 10, 12, 14,
  129490. 16,
  129491. };
  129492. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129493. _vq_quantthresh__44c3_s_p6_0,
  129494. _vq_quantmap__44c3_s_p6_0,
  129495. 17,
  129496. 17
  129497. };
  129498. static static_codebook _44c3_s_p6_0 = {
  129499. 2, 289,
  129500. _vq_lengthlist__44c3_s_p6_0,
  129501. 1, -529530880, 1611661312, 5, 0,
  129502. _vq_quantlist__44c3_s_p6_0,
  129503. NULL,
  129504. &_vq_auxt__44c3_s_p6_0,
  129505. NULL,
  129506. 0
  129507. };
  129508. static long _vq_quantlist__44c3_s_p7_0[] = {
  129509. 1,
  129510. 0,
  129511. 2,
  129512. };
  129513. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129514. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129515. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129516. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129517. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129518. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129519. 10,
  129520. };
  129521. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129522. -5.5, 5.5,
  129523. };
  129524. static long _vq_quantmap__44c3_s_p7_0[] = {
  129525. 1, 0, 2,
  129526. };
  129527. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129528. _vq_quantthresh__44c3_s_p7_0,
  129529. _vq_quantmap__44c3_s_p7_0,
  129530. 3,
  129531. 3
  129532. };
  129533. static static_codebook _44c3_s_p7_0 = {
  129534. 4, 81,
  129535. _vq_lengthlist__44c3_s_p7_0,
  129536. 1, -529137664, 1618345984, 2, 0,
  129537. _vq_quantlist__44c3_s_p7_0,
  129538. NULL,
  129539. &_vq_auxt__44c3_s_p7_0,
  129540. NULL,
  129541. 0
  129542. };
  129543. static long _vq_quantlist__44c3_s_p7_1[] = {
  129544. 5,
  129545. 4,
  129546. 6,
  129547. 3,
  129548. 7,
  129549. 2,
  129550. 8,
  129551. 1,
  129552. 9,
  129553. 0,
  129554. 10,
  129555. };
  129556. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129557. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129558. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129559. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129560. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129561. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129562. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129563. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129564. 10,10,10, 8, 8, 8, 8, 8, 8,
  129565. };
  129566. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129567. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129568. 3.5, 4.5,
  129569. };
  129570. static long _vq_quantmap__44c3_s_p7_1[] = {
  129571. 9, 7, 5, 3, 1, 0, 2, 4,
  129572. 6, 8, 10,
  129573. };
  129574. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129575. _vq_quantthresh__44c3_s_p7_1,
  129576. _vq_quantmap__44c3_s_p7_1,
  129577. 11,
  129578. 11
  129579. };
  129580. static static_codebook _44c3_s_p7_1 = {
  129581. 2, 121,
  129582. _vq_lengthlist__44c3_s_p7_1,
  129583. 1, -531365888, 1611661312, 4, 0,
  129584. _vq_quantlist__44c3_s_p7_1,
  129585. NULL,
  129586. &_vq_auxt__44c3_s_p7_1,
  129587. NULL,
  129588. 0
  129589. };
  129590. static long _vq_quantlist__44c3_s_p8_0[] = {
  129591. 6,
  129592. 5,
  129593. 7,
  129594. 4,
  129595. 8,
  129596. 3,
  129597. 9,
  129598. 2,
  129599. 10,
  129600. 1,
  129601. 11,
  129602. 0,
  129603. 12,
  129604. };
  129605. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129606. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129607. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129608. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129609. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129610. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129611. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129612. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129613. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129614. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129615. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129616. 0,13,13,12,12,13,12,14,13,
  129617. };
  129618. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129619. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129620. 12.5, 17.5, 22.5, 27.5,
  129621. };
  129622. static long _vq_quantmap__44c3_s_p8_0[] = {
  129623. 11, 9, 7, 5, 3, 1, 0, 2,
  129624. 4, 6, 8, 10, 12,
  129625. };
  129626. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129627. _vq_quantthresh__44c3_s_p8_0,
  129628. _vq_quantmap__44c3_s_p8_0,
  129629. 13,
  129630. 13
  129631. };
  129632. static static_codebook _44c3_s_p8_0 = {
  129633. 2, 169,
  129634. _vq_lengthlist__44c3_s_p8_0,
  129635. 1, -526516224, 1616117760, 4, 0,
  129636. _vq_quantlist__44c3_s_p8_0,
  129637. NULL,
  129638. &_vq_auxt__44c3_s_p8_0,
  129639. NULL,
  129640. 0
  129641. };
  129642. static long _vq_quantlist__44c3_s_p8_1[] = {
  129643. 2,
  129644. 1,
  129645. 3,
  129646. 0,
  129647. 4,
  129648. };
  129649. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129650. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129651. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129652. };
  129653. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129654. -1.5, -0.5, 0.5, 1.5,
  129655. };
  129656. static long _vq_quantmap__44c3_s_p8_1[] = {
  129657. 3, 1, 0, 2, 4,
  129658. };
  129659. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129660. _vq_quantthresh__44c3_s_p8_1,
  129661. _vq_quantmap__44c3_s_p8_1,
  129662. 5,
  129663. 5
  129664. };
  129665. static static_codebook _44c3_s_p8_1 = {
  129666. 2, 25,
  129667. _vq_lengthlist__44c3_s_p8_1,
  129668. 1, -533725184, 1611661312, 3, 0,
  129669. _vq_quantlist__44c3_s_p8_1,
  129670. NULL,
  129671. &_vq_auxt__44c3_s_p8_1,
  129672. NULL,
  129673. 0
  129674. };
  129675. static long _vq_quantlist__44c3_s_p9_0[] = {
  129676. 6,
  129677. 5,
  129678. 7,
  129679. 4,
  129680. 8,
  129681. 3,
  129682. 9,
  129683. 2,
  129684. 10,
  129685. 1,
  129686. 11,
  129687. 0,
  129688. 12,
  129689. };
  129690. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129691. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129692. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129693. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129694. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129695. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129696. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129697. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129698. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129699. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129700. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129701. 11,11,11,11,11,11,11,11,11,
  129702. };
  129703. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129704. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129705. 637.5, 892.5, 1147.5, 1402.5,
  129706. };
  129707. static long _vq_quantmap__44c3_s_p9_0[] = {
  129708. 11, 9, 7, 5, 3, 1, 0, 2,
  129709. 4, 6, 8, 10, 12,
  129710. };
  129711. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129712. _vq_quantthresh__44c3_s_p9_0,
  129713. _vq_quantmap__44c3_s_p9_0,
  129714. 13,
  129715. 13
  129716. };
  129717. static static_codebook _44c3_s_p9_0 = {
  129718. 2, 169,
  129719. _vq_lengthlist__44c3_s_p9_0,
  129720. 1, -514332672, 1627381760, 4, 0,
  129721. _vq_quantlist__44c3_s_p9_0,
  129722. NULL,
  129723. &_vq_auxt__44c3_s_p9_0,
  129724. NULL,
  129725. 0
  129726. };
  129727. static long _vq_quantlist__44c3_s_p9_1[] = {
  129728. 7,
  129729. 6,
  129730. 8,
  129731. 5,
  129732. 9,
  129733. 4,
  129734. 10,
  129735. 3,
  129736. 11,
  129737. 2,
  129738. 12,
  129739. 1,
  129740. 13,
  129741. 0,
  129742. 14,
  129743. };
  129744. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129745. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129746. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129747. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129748. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129749. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129750. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129751. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129752. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129753. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129754. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129755. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129756. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129757. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129758. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129759. 15,
  129760. };
  129761. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129762. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129763. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129764. };
  129765. static long _vq_quantmap__44c3_s_p9_1[] = {
  129766. 13, 11, 9, 7, 5, 3, 1, 0,
  129767. 2, 4, 6, 8, 10, 12, 14,
  129768. };
  129769. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129770. _vq_quantthresh__44c3_s_p9_1,
  129771. _vq_quantmap__44c3_s_p9_1,
  129772. 15,
  129773. 15
  129774. };
  129775. static static_codebook _44c3_s_p9_1 = {
  129776. 2, 225,
  129777. _vq_lengthlist__44c3_s_p9_1,
  129778. 1, -522338304, 1620115456, 4, 0,
  129779. _vq_quantlist__44c3_s_p9_1,
  129780. NULL,
  129781. &_vq_auxt__44c3_s_p9_1,
  129782. NULL,
  129783. 0
  129784. };
  129785. static long _vq_quantlist__44c3_s_p9_2[] = {
  129786. 8,
  129787. 7,
  129788. 9,
  129789. 6,
  129790. 10,
  129791. 5,
  129792. 11,
  129793. 4,
  129794. 12,
  129795. 3,
  129796. 13,
  129797. 2,
  129798. 14,
  129799. 1,
  129800. 15,
  129801. 0,
  129802. 16,
  129803. };
  129804. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129805. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129806. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129807. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129808. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129809. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129810. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129811. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129812. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129813. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129814. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129815. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129816. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129817. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129818. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129819. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129820. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129821. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129822. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129823. 10,
  129824. };
  129825. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129826. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129827. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129828. };
  129829. static long _vq_quantmap__44c3_s_p9_2[] = {
  129830. 15, 13, 11, 9, 7, 5, 3, 1,
  129831. 0, 2, 4, 6, 8, 10, 12, 14,
  129832. 16,
  129833. };
  129834. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129835. _vq_quantthresh__44c3_s_p9_2,
  129836. _vq_quantmap__44c3_s_p9_2,
  129837. 17,
  129838. 17
  129839. };
  129840. static static_codebook _44c3_s_p9_2 = {
  129841. 2, 289,
  129842. _vq_lengthlist__44c3_s_p9_2,
  129843. 1, -529530880, 1611661312, 5, 0,
  129844. _vq_quantlist__44c3_s_p9_2,
  129845. NULL,
  129846. &_vq_auxt__44c3_s_p9_2,
  129847. NULL,
  129848. 0
  129849. };
  129850. static long _huff_lengthlist__44c3_s_short[] = {
  129851. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129852. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129853. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129854. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129855. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129856. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129857. 6, 8, 9,11,
  129858. };
  129859. static static_codebook _huff_book__44c3_s_short = {
  129860. 2, 100,
  129861. _huff_lengthlist__44c3_s_short,
  129862. 0, 0, 0, 0, 0,
  129863. NULL,
  129864. NULL,
  129865. NULL,
  129866. NULL,
  129867. 0
  129868. };
  129869. static long _huff_lengthlist__44c4_s_long[] = {
  129870. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129871. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129872. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129873. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129874. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129875. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129876. 9, 8, 7, 7,
  129877. };
  129878. static static_codebook _huff_book__44c4_s_long = {
  129879. 2, 100,
  129880. _huff_lengthlist__44c4_s_long,
  129881. 0, 0, 0, 0, 0,
  129882. NULL,
  129883. NULL,
  129884. NULL,
  129885. NULL,
  129886. 0
  129887. };
  129888. static long _vq_quantlist__44c4_s_p1_0[] = {
  129889. 1,
  129890. 0,
  129891. 2,
  129892. };
  129893. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129894. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129895. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129899. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129900. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129904. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129905. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129940. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129945. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129950. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129985. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129986. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129990. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129991. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129995. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129996. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0,
  130305. };
  130306. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130307. -0.5, 0.5,
  130308. };
  130309. static long _vq_quantmap__44c4_s_p1_0[] = {
  130310. 1, 0, 2,
  130311. };
  130312. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130313. _vq_quantthresh__44c4_s_p1_0,
  130314. _vq_quantmap__44c4_s_p1_0,
  130315. 3,
  130316. 3
  130317. };
  130318. static static_codebook _44c4_s_p1_0 = {
  130319. 8, 6561,
  130320. _vq_lengthlist__44c4_s_p1_0,
  130321. 1, -535822336, 1611661312, 2, 0,
  130322. _vq_quantlist__44c4_s_p1_0,
  130323. NULL,
  130324. &_vq_auxt__44c4_s_p1_0,
  130325. NULL,
  130326. 0
  130327. };
  130328. static long _vq_quantlist__44c4_s_p2_0[] = {
  130329. 2,
  130330. 1,
  130331. 3,
  130332. 0,
  130333. 4,
  130334. };
  130335. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130336. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130337. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130338. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130339. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130340. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130346. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130347. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130348. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130354. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130355. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130362. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130363. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  130376. };
  130377. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130378. -1.5, -0.5, 0.5, 1.5,
  130379. };
  130380. static long _vq_quantmap__44c4_s_p2_0[] = {
  130381. 3, 1, 0, 2, 4,
  130382. };
  130383. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130384. _vq_quantthresh__44c4_s_p2_0,
  130385. _vq_quantmap__44c4_s_p2_0,
  130386. 5,
  130387. 5
  130388. };
  130389. static static_codebook _44c4_s_p2_0 = {
  130390. 4, 625,
  130391. _vq_lengthlist__44c4_s_p2_0,
  130392. 1, -533725184, 1611661312, 3, 0,
  130393. _vq_quantlist__44c4_s_p2_0,
  130394. NULL,
  130395. &_vq_auxt__44c4_s_p2_0,
  130396. NULL,
  130397. 0
  130398. };
  130399. static long _vq_quantlist__44c4_s_p3_0[] = {
  130400. 2,
  130401. 1,
  130402. 3,
  130403. 0,
  130404. 4,
  130405. };
  130406. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130407. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  130447. };
  130448. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130449. -1.5, -0.5, 0.5, 1.5,
  130450. };
  130451. static long _vq_quantmap__44c4_s_p3_0[] = {
  130452. 3, 1, 0, 2, 4,
  130453. };
  130454. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130455. _vq_quantthresh__44c4_s_p3_0,
  130456. _vq_quantmap__44c4_s_p3_0,
  130457. 5,
  130458. 5
  130459. };
  130460. static static_codebook _44c4_s_p3_0 = {
  130461. 4, 625,
  130462. _vq_lengthlist__44c4_s_p3_0,
  130463. 1, -533725184, 1611661312, 3, 0,
  130464. _vq_quantlist__44c4_s_p3_0,
  130465. NULL,
  130466. &_vq_auxt__44c4_s_p3_0,
  130467. NULL,
  130468. 0
  130469. };
  130470. static long _vq_quantlist__44c4_s_p4_0[] = {
  130471. 4,
  130472. 3,
  130473. 5,
  130474. 2,
  130475. 6,
  130476. 1,
  130477. 7,
  130478. 0,
  130479. 8,
  130480. };
  130481. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130482. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130483. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130484. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130485. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130486. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0,
  130488. };
  130489. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130490. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130491. };
  130492. static long _vq_quantmap__44c4_s_p4_0[] = {
  130493. 7, 5, 3, 1, 0, 2, 4, 6,
  130494. 8,
  130495. };
  130496. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130497. _vq_quantthresh__44c4_s_p4_0,
  130498. _vq_quantmap__44c4_s_p4_0,
  130499. 9,
  130500. 9
  130501. };
  130502. static static_codebook _44c4_s_p4_0 = {
  130503. 2, 81,
  130504. _vq_lengthlist__44c4_s_p4_0,
  130505. 1, -531628032, 1611661312, 4, 0,
  130506. _vq_quantlist__44c4_s_p4_0,
  130507. NULL,
  130508. &_vq_auxt__44c4_s_p4_0,
  130509. NULL,
  130510. 0
  130511. };
  130512. static long _vq_quantlist__44c4_s_p5_0[] = {
  130513. 4,
  130514. 3,
  130515. 5,
  130516. 2,
  130517. 6,
  130518. 1,
  130519. 7,
  130520. 0,
  130521. 8,
  130522. };
  130523. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130524. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130525. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130526. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130527. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130528. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130529. 10,
  130530. };
  130531. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130532. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130533. };
  130534. static long _vq_quantmap__44c4_s_p5_0[] = {
  130535. 7, 5, 3, 1, 0, 2, 4, 6,
  130536. 8,
  130537. };
  130538. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130539. _vq_quantthresh__44c4_s_p5_0,
  130540. _vq_quantmap__44c4_s_p5_0,
  130541. 9,
  130542. 9
  130543. };
  130544. static static_codebook _44c4_s_p5_0 = {
  130545. 2, 81,
  130546. _vq_lengthlist__44c4_s_p5_0,
  130547. 1, -531628032, 1611661312, 4, 0,
  130548. _vq_quantlist__44c4_s_p5_0,
  130549. NULL,
  130550. &_vq_auxt__44c4_s_p5_0,
  130551. NULL,
  130552. 0
  130553. };
  130554. static long _vq_quantlist__44c4_s_p6_0[] = {
  130555. 8,
  130556. 7,
  130557. 9,
  130558. 6,
  130559. 10,
  130560. 5,
  130561. 11,
  130562. 4,
  130563. 12,
  130564. 3,
  130565. 13,
  130566. 2,
  130567. 14,
  130568. 1,
  130569. 15,
  130570. 0,
  130571. 16,
  130572. };
  130573. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130574. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130575. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130576. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130577. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130578. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130579. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130580. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130581. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130582. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130583. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130584. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130585. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130586. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130587. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130588. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130589. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130590. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130592. 13,
  130593. };
  130594. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130595. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130596. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130597. };
  130598. static long _vq_quantmap__44c4_s_p6_0[] = {
  130599. 15, 13, 11, 9, 7, 5, 3, 1,
  130600. 0, 2, 4, 6, 8, 10, 12, 14,
  130601. 16,
  130602. };
  130603. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130604. _vq_quantthresh__44c4_s_p6_0,
  130605. _vq_quantmap__44c4_s_p6_0,
  130606. 17,
  130607. 17
  130608. };
  130609. static static_codebook _44c4_s_p6_0 = {
  130610. 2, 289,
  130611. _vq_lengthlist__44c4_s_p6_0,
  130612. 1, -529530880, 1611661312, 5, 0,
  130613. _vq_quantlist__44c4_s_p6_0,
  130614. NULL,
  130615. &_vq_auxt__44c4_s_p6_0,
  130616. NULL,
  130617. 0
  130618. };
  130619. static long _vq_quantlist__44c4_s_p7_0[] = {
  130620. 1,
  130621. 0,
  130622. 2,
  130623. };
  130624. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130625. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130626. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130627. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130628. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130629. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130630. 10,
  130631. };
  130632. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130633. -5.5, 5.5,
  130634. };
  130635. static long _vq_quantmap__44c4_s_p7_0[] = {
  130636. 1, 0, 2,
  130637. };
  130638. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130639. _vq_quantthresh__44c4_s_p7_0,
  130640. _vq_quantmap__44c4_s_p7_0,
  130641. 3,
  130642. 3
  130643. };
  130644. static static_codebook _44c4_s_p7_0 = {
  130645. 4, 81,
  130646. _vq_lengthlist__44c4_s_p7_0,
  130647. 1, -529137664, 1618345984, 2, 0,
  130648. _vq_quantlist__44c4_s_p7_0,
  130649. NULL,
  130650. &_vq_auxt__44c4_s_p7_0,
  130651. NULL,
  130652. 0
  130653. };
  130654. static long _vq_quantlist__44c4_s_p7_1[] = {
  130655. 5,
  130656. 4,
  130657. 6,
  130658. 3,
  130659. 7,
  130660. 2,
  130661. 8,
  130662. 1,
  130663. 9,
  130664. 0,
  130665. 10,
  130666. };
  130667. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130668. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130669. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130670. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130671. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130672. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130673. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130674. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130675. 10,10,10, 8, 8, 8, 8, 9, 9,
  130676. };
  130677. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130678. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130679. 3.5, 4.5,
  130680. };
  130681. static long _vq_quantmap__44c4_s_p7_1[] = {
  130682. 9, 7, 5, 3, 1, 0, 2, 4,
  130683. 6, 8, 10,
  130684. };
  130685. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130686. _vq_quantthresh__44c4_s_p7_1,
  130687. _vq_quantmap__44c4_s_p7_1,
  130688. 11,
  130689. 11
  130690. };
  130691. static static_codebook _44c4_s_p7_1 = {
  130692. 2, 121,
  130693. _vq_lengthlist__44c4_s_p7_1,
  130694. 1, -531365888, 1611661312, 4, 0,
  130695. _vq_quantlist__44c4_s_p7_1,
  130696. NULL,
  130697. &_vq_auxt__44c4_s_p7_1,
  130698. NULL,
  130699. 0
  130700. };
  130701. static long _vq_quantlist__44c4_s_p8_0[] = {
  130702. 6,
  130703. 5,
  130704. 7,
  130705. 4,
  130706. 8,
  130707. 3,
  130708. 9,
  130709. 2,
  130710. 10,
  130711. 1,
  130712. 11,
  130713. 0,
  130714. 12,
  130715. };
  130716. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130717. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130718. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130719. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130720. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130721. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130722. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130723. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130724. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130725. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130726. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130727. 0,13,12,12,12,12,12,13,13,
  130728. };
  130729. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130730. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130731. 12.5, 17.5, 22.5, 27.5,
  130732. };
  130733. static long _vq_quantmap__44c4_s_p8_0[] = {
  130734. 11, 9, 7, 5, 3, 1, 0, 2,
  130735. 4, 6, 8, 10, 12,
  130736. };
  130737. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130738. _vq_quantthresh__44c4_s_p8_0,
  130739. _vq_quantmap__44c4_s_p8_0,
  130740. 13,
  130741. 13
  130742. };
  130743. static static_codebook _44c4_s_p8_0 = {
  130744. 2, 169,
  130745. _vq_lengthlist__44c4_s_p8_0,
  130746. 1, -526516224, 1616117760, 4, 0,
  130747. _vq_quantlist__44c4_s_p8_0,
  130748. NULL,
  130749. &_vq_auxt__44c4_s_p8_0,
  130750. NULL,
  130751. 0
  130752. };
  130753. static long _vq_quantlist__44c4_s_p8_1[] = {
  130754. 2,
  130755. 1,
  130756. 3,
  130757. 0,
  130758. 4,
  130759. };
  130760. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130761. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130762. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130763. };
  130764. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130765. -1.5, -0.5, 0.5, 1.5,
  130766. };
  130767. static long _vq_quantmap__44c4_s_p8_1[] = {
  130768. 3, 1, 0, 2, 4,
  130769. };
  130770. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130771. _vq_quantthresh__44c4_s_p8_1,
  130772. _vq_quantmap__44c4_s_p8_1,
  130773. 5,
  130774. 5
  130775. };
  130776. static static_codebook _44c4_s_p8_1 = {
  130777. 2, 25,
  130778. _vq_lengthlist__44c4_s_p8_1,
  130779. 1, -533725184, 1611661312, 3, 0,
  130780. _vq_quantlist__44c4_s_p8_1,
  130781. NULL,
  130782. &_vq_auxt__44c4_s_p8_1,
  130783. NULL,
  130784. 0
  130785. };
  130786. static long _vq_quantlist__44c4_s_p9_0[] = {
  130787. 6,
  130788. 5,
  130789. 7,
  130790. 4,
  130791. 8,
  130792. 3,
  130793. 9,
  130794. 2,
  130795. 10,
  130796. 1,
  130797. 11,
  130798. 0,
  130799. 12,
  130800. };
  130801. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130802. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130803. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130804. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130805. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130806. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130807. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130808. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130809. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130810. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130811. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130812. 12,12,12,12,12,12,12,12,12,
  130813. };
  130814. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130815. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130816. 787.5, 1102.5, 1417.5, 1732.5,
  130817. };
  130818. static long _vq_quantmap__44c4_s_p9_0[] = {
  130819. 11, 9, 7, 5, 3, 1, 0, 2,
  130820. 4, 6, 8, 10, 12,
  130821. };
  130822. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130823. _vq_quantthresh__44c4_s_p9_0,
  130824. _vq_quantmap__44c4_s_p9_0,
  130825. 13,
  130826. 13
  130827. };
  130828. static static_codebook _44c4_s_p9_0 = {
  130829. 2, 169,
  130830. _vq_lengthlist__44c4_s_p9_0,
  130831. 1, -513964032, 1628680192, 4, 0,
  130832. _vq_quantlist__44c4_s_p9_0,
  130833. NULL,
  130834. &_vq_auxt__44c4_s_p9_0,
  130835. NULL,
  130836. 0
  130837. };
  130838. static long _vq_quantlist__44c4_s_p9_1[] = {
  130839. 7,
  130840. 6,
  130841. 8,
  130842. 5,
  130843. 9,
  130844. 4,
  130845. 10,
  130846. 3,
  130847. 11,
  130848. 2,
  130849. 12,
  130850. 1,
  130851. 13,
  130852. 0,
  130853. 14,
  130854. };
  130855. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130856. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130857. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130858. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130859. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130860. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130861. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130862. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130863. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130864. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130865. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130866. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130867. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130868. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130869. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130870. 15,
  130871. };
  130872. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130873. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130874. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130875. };
  130876. static long _vq_quantmap__44c4_s_p9_1[] = {
  130877. 13, 11, 9, 7, 5, 3, 1, 0,
  130878. 2, 4, 6, 8, 10, 12, 14,
  130879. };
  130880. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130881. _vq_quantthresh__44c4_s_p9_1,
  130882. _vq_quantmap__44c4_s_p9_1,
  130883. 15,
  130884. 15
  130885. };
  130886. static static_codebook _44c4_s_p9_1 = {
  130887. 2, 225,
  130888. _vq_lengthlist__44c4_s_p9_1,
  130889. 1, -520986624, 1620377600, 4, 0,
  130890. _vq_quantlist__44c4_s_p9_1,
  130891. NULL,
  130892. &_vq_auxt__44c4_s_p9_1,
  130893. NULL,
  130894. 0
  130895. };
  130896. static long _vq_quantlist__44c4_s_p9_2[] = {
  130897. 10,
  130898. 9,
  130899. 11,
  130900. 8,
  130901. 12,
  130902. 7,
  130903. 13,
  130904. 6,
  130905. 14,
  130906. 5,
  130907. 15,
  130908. 4,
  130909. 16,
  130910. 3,
  130911. 17,
  130912. 2,
  130913. 18,
  130914. 1,
  130915. 19,
  130916. 0,
  130917. 20,
  130918. };
  130919. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130920. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130921. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130922. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130923. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130924. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130925. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130926. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130927. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130928. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130929. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130930. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130931. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130932. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130933. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130934. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130935. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130936. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130937. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130938. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130939. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130940. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130941. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130942. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130943. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130944. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130945. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130946. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130947. 10,10,10,10,10,10,10,10,10,
  130948. };
  130949. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130950. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130951. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130952. 6.5, 7.5, 8.5, 9.5,
  130953. };
  130954. static long _vq_quantmap__44c4_s_p9_2[] = {
  130955. 19, 17, 15, 13, 11, 9, 7, 5,
  130956. 3, 1, 0, 2, 4, 6, 8, 10,
  130957. 12, 14, 16, 18, 20,
  130958. };
  130959. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130960. _vq_quantthresh__44c4_s_p9_2,
  130961. _vq_quantmap__44c4_s_p9_2,
  130962. 21,
  130963. 21
  130964. };
  130965. static static_codebook _44c4_s_p9_2 = {
  130966. 2, 441,
  130967. _vq_lengthlist__44c4_s_p9_2,
  130968. 1, -529268736, 1611661312, 5, 0,
  130969. _vq_quantlist__44c4_s_p9_2,
  130970. NULL,
  130971. &_vq_auxt__44c4_s_p9_2,
  130972. NULL,
  130973. 0
  130974. };
  130975. static long _huff_lengthlist__44c4_s_short[] = {
  130976. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130977. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130978. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130979. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130980. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130981. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130982. 7, 9,12,17,
  130983. };
  130984. static static_codebook _huff_book__44c4_s_short = {
  130985. 2, 100,
  130986. _huff_lengthlist__44c4_s_short,
  130987. 0, 0, 0, 0, 0,
  130988. NULL,
  130989. NULL,
  130990. NULL,
  130991. NULL,
  130992. 0
  130993. };
  130994. static long _huff_lengthlist__44c5_s_long[] = {
  130995. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130996. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130997. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130998. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130999. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131000. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131001. 9, 8, 7, 7,
  131002. };
  131003. static static_codebook _huff_book__44c5_s_long = {
  131004. 2, 100,
  131005. _huff_lengthlist__44c5_s_long,
  131006. 0, 0, 0, 0, 0,
  131007. NULL,
  131008. NULL,
  131009. NULL,
  131010. NULL,
  131011. 0
  131012. };
  131013. static long _vq_quantlist__44c5_s_p1_0[] = {
  131014. 1,
  131015. 0,
  131016. 2,
  131017. };
  131018. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131019. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131020. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131024. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131025. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131029. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131030. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131065. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131070. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131075. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131110. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131111. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131115. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131116. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131120. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131121. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0,
  131430. };
  131431. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131432. -0.5, 0.5,
  131433. };
  131434. static long _vq_quantmap__44c5_s_p1_0[] = {
  131435. 1, 0, 2,
  131436. };
  131437. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131438. _vq_quantthresh__44c5_s_p1_0,
  131439. _vq_quantmap__44c5_s_p1_0,
  131440. 3,
  131441. 3
  131442. };
  131443. static static_codebook _44c5_s_p1_0 = {
  131444. 8, 6561,
  131445. _vq_lengthlist__44c5_s_p1_0,
  131446. 1, -535822336, 1611661312, 2, 0,
  131447. _vq_quantlist__44c5_s_p1_0,
  131448. NULL,
  131449. &_vq_auxt__44c5_s_p1_0,
  131450. NULL,
  131451. 0
  131452. };
  131453. static long _vq_quantlist__44c5_s_p2_0[] = {
  131454. 2,
  131455. 1,
  131456. 3,
  131457. 0,
  131458. 4,
  131459. };
  131460. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131461. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131462. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131463. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131464. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131465. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131471. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131472. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131473. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131479. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131480. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131487. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131488. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  131501. };
  131502. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131503. -1.5, -0.5, 0.5, 1.5,
  131504. };
  131505. static long _vq_quantmap__44c5_s_p2_0[] = {
  131506. 3, 1, 0, 2, 4,
  131507. };
  131508. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131509. _vq_quantthresh__44c5_s_p2_0,
  131510. _vq_quantmap__44c5_s_p2_0,
  131511. 5,
  131512. 5
  131513. };
  131514. static static_codebook _44c5_s_p2_0 = {
  131515. 4, 625,
  131516. _vq_lengthlist__44c5_s_p2_0,
  131517. 1, -533725184, 1611661312, 3, 0,
  131518. _vq_quantlist__44c5_s_p2_0,
  131519. NULL,
  131520. &_vq_auxt__44c5_s_p2_0,
  131521. NULL,
  131522. 0
  131523. };
  131524. static long _vq_quantlist__44c5_s_p3_0[] = {
  131525. 2,
  131526. 1,
  131527. 3,
  131528. 0,
  131529. 4,
  131530. };
  131531. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131532. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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,
  131572. };
  131573. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131574. -1.5, -0.5, 0.5, 1.5,
  131575. };
  131576. static long _vq_quantmap__44c5_s_p3_0[] = {
  131577. 3, 1, 0, 2, 4,
  131578. };
  131579. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131580. _vq_quantthresh__44c5_s_p3_0,
  131581. _vq_quantmap__44c5_s_p3_0,
  131582. 5,
  131583. 5
  131584. };
  131585. static static_codebook _44c5_s_p3_0 = {
  131586. 4, 625,
  131587. _vq_lengthlist__44c5_s_p3_0,
  131588. 1, -533725184, 1611661312, 3, 0,
  131589. _vq_quantlist__44c5_s_p3_0,
  131590. NULL,
  131591. &_vq_auxt__44c5_s_p3_0,
  131592. NULL,
  131593. 0
  131594. };
  131595. static long _vq_quantlist__44c5_s_p4_0[] = {
  131596. 4,
  131597. 3,
  131598. 5,
  131599. 2,
  131600. 6,
  131601. 1,
  131602. 7,
  131603. 0,
  131604. 8,
  131605. };
  131606. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131607. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131608. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131609. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131610. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131611. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0,
  131613. };
  131614. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131615. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131616. };
  131617. static long _vq_quantmap__44c5_s_p4_0[] = {
  131618. 7, 5, 3, 1, 0, 2, 4, 6,
  131619. 8,
  131620. };
  131621. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131622. _vq_quantthresh__44c5_s_p4_0,
  131623. _vq_quantmap__44c5_s_p4_0,
  131624. 9,
  131625. 9
  131626. };
  131627. static static_codebook _44c5_s_p4_0 = {
  131628. 2, 81,
  131629. _vq_lengthlist__44c5_s_p4_0,
  131630. 1, -531628032, 1611661312, 4, 0,
  131631. _vq_quantlist__44c5_s_p4_0,
  131632. NULL,
  131633. &_vq_auxt__44c5_s_p4_0,
  131634. NULL,
  131635. 0
  131636. };
  131637. static long _vq_quantlist__44c5_s_p5_0[] = {
  131638. 4,
  131639. 3,
  131640. 5,
  131641. 2,
  131642. 6,
  131643. 1,
  131644. 7,
  131645. 0,
  131646. 8,
  131647. };
  131648. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131649. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131650. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131651. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131652. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131653. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131654. 10,
  131655. };
  131656. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131657. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131658. };
  131659. static long _vq_quantmap__44c5_s_p5_0[] = {
  131660. 7, 5, 3, 1, 0, 2, 4, 6,
  131661. 8,
  131662. };
  131663. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131664. _vq_quantthresh__44c5_s_p5_0,
  131665. _vq_quantmap__44c5_s_p5_0,
  131666. 9,
  131667. 9
  131668. };
  131669. static static_codebook _44c5_s_p5_0 = {
  131670. 2, 81,
  131671. _vq_lengthlist__44c5_s_p5_0,
  131672. 1, -531628032, 1611661312, 4, 0,
  131673. _vq_quantlist__44c5_s_p5_0,
  131674. NULL,
  131675. &_vq_auxt__44c5_s_p5_0,
  131676. NULL,
  131677. 0
  131678. };
  131679. static long _vq_quantlist__44c5_s_p6_0[] = {
  131680. 8,
  131681. 7,
  131682. 9,
  131683. 6,
  131684. 10,
  131685. 5,
  131686. 11,
  131687. 4,
  131688. 12,
  131689. 3,
  131690. 13,
  131691. 2,
  131692. 14,
  131693. 1,
  131694. 15,
  131695. 0,
  131696. 16,
  131697. };
  131698. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131699. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131700. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131701. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131702. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131703. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131704. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131705. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131706. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131707. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131708. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131709. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131710. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131711. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131712. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131713. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131714. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131715. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131716. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131717. 13,
  131718. };
  131719. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131720. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131721. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131722. };
  131723. static long _vq_quantmap__44c5_s_p6_0[] = {
  131724. 15, 13, 11, 9, 7, 5, 3, 1,
  131725. 0, 2, 4, 6, 8, 10, 12, 14,
  131726. 16,
  131727. };
  131728. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131729. _vq_quantthresh__44c5_s_p6_0,
  131730. _vq_quantmap__44c5_s_p6_0,
  131731. 17,
  131732. 17
  131733. };
  131734. static static_codebook _44c5_s_p6_0 = {
  131735. 2, 289,
  131736. _vq_lengthlist__44c5_s_p6_0,
  131737. 1, -529530880, 1611661312, 5, 0,
  131738. _vq_quantlist__44c5_s_p6_0,
  131739. NULL,
  131740. &_vq_auxt__44c5_s_p6_0,
  131741. NULL,
  131742. 0
  131743. };
  131744. static long _vq_quantlist__44c5_s_p7_0[] = {
  131745. 1,
  131746. 0,
  131747. 2,
  131748. };
  131749. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131750. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131751. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131752. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131753. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131754. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131755. 10,
  131756. };
  131757. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131758. -5.5, 5.5,
  131759. };
  131760. static long _vq_quantmap__44c5_s_p7_0[] = {
  131761. 1, 0, 2,
  131762. };
  131763. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131764. _vq_quantthresh__44c5_s_p7_0,
  131765. _vq_quantmap__44c5_s_p7_0,
  131766. 3,
  131767. 3
  131768. };
  131769. static static_codebook _44c5_s_p7_0 = {
  131770. 4, 81,
  131771. _vq_lengthlist__44c5_s_p7_0,
  131772. 1, -529137664, 1618345984, 2, 0,
  131773. _vq_quantlist__44c5_s_p7_0,
  131774. NULL,
  131775. &_vq_auxt__44c5_s_p7_0,
  131776. NULL,
  131777. 0
  131778. };
  131779. static long _vq_quantlist__44c5_s_p7_1[] = {
  131780. 5,
  131781. 4,
  131782. 6,
  131783. 3,
  131784. 7,
  131785. 2,
  131786. 8,
  131787. 1,
  131788. 9,
  131789. 0,
  131790. 10,
  131791. };
  131792. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131793. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131794. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131795. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131796. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131797. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131798. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131799. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131800. 10,10,10, 8, 8, 8, 8, 8, 8,
  131801. };
  131802. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131803. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131804. 3.5, 4.5,
  131805. };
  131806. static long _vq_quantmap__44c5_s_p7_1[] = {
  131807. 9, 7, 5, 3, 1, 0, 2, 4,
  131808. 6, 8, 10,
  131809. };
  131810. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131811. _vq_quantthresh__44c5_s_p7_1,
  131812. _vq_quantmap__44c5_s_p7_1,
  131813. 11,
  131814. 11
  131815. };
  131816. static static_codebook _44c5_s_p7_1 = {
  131817. 2, 121,
  131818. _vq_lengthlist__44c5_s_p7_1,
  131819. 1, -531365888, 1611661312, 4, 0,
  131820. _vq_quantlist__44c5_s_p7_1,
  131821. NULL,
  131822. &_vq_auxt__44c5_s_p7_1,
  131823. NULL,
  131824. 0
  131825. };
  131826. static long _vq_quantlist__44c5_s_p8_0[] = {
  131827. 6,
  131828. 5,
  131829. 7,
  131830. 4,
  131831. 8,
  131832. 3,
  131833. 9,
  131834. 2,
  131835. 10,
  131836. 1,
  131837. 11,
  131838. 0,
  131839. 12,
  131840. };
  131841. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131842. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131843. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131844. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131845. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131846. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131847. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131848. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131849. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131850. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131851. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131852. 0,12,12,12,12,12,12,13,13,
  131853. };
  131854. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131855. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131856. 12.5, 17.5, 22.5, 27.5,
  131857. };
  131858. static long _vq_quantmap__44c5_s_p8_0[] = {
  131859. 11, 9, 7, 5, 3, 1, 0, 2,
  131860. 4, 6, 8, 10, 12,
  131861. };
  131862. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131863. _vq_quantthresh__44c5_s_p8_0,
  131864. _vq_quantmap__44c5_s_p8_0,
  131865. 13,
  131866. 13
  131867. };
  131868. static static_codebook _44c5_s_p8_0 = {
  131869. 2, 169,
  131870. _vq_lengthlist__44c5_s_p8_0,
  131871. 1, -526516224, 1616117760, 4, 0,
  131872. _vq_quantlist__44c5_s_p8_0,
  131873. NULL,
  131874. &_vq_auxt__44c5_s_p8_0,
  131875. NULL,
  131876. 0
  131877. };
  131878. static long _vq_quantlist__44c5_s_p8_1[] = {
  131879. 2,
  131880. 1,
  131881. 3,
  131882. 0,
  131883. 4,
  131884. };
  131885. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131886. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131887. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131888. };
  131889. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131890. -1.5, -0.5, 0.5, 1.5,
  131891. };
  131892. static long _vq_quantmap__44c5_s_p8_1[] = {
  131893. 3, 1, 0, 2, 4,
  131894. };
  131895. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131896. _vq_quantthresh__44c5_s_p8_1,
  131897. _vq_quantmap__44c5_s_p8_1,
  131898. 5,
  131899. 5
  131900. };
  131901. static static_codebook _44c5_s_p8_1 = {
  131902. 2, 25,
  131903. _vq_lengthlist__44c5_s_p8_1,
  131904. 1, -533725184, 1611661312, 3, 0,
  131905. _vq_quantlist__44c5_s_p8_1,
  131906. NULL,
  131907. &_vq_auxt__44c5_s_p8_1,
  131908. NULL,
  131909. 0
  131910. };
  131911. static long _vq_quantlist__44c5_s_p9_0[] = {
  131912. 7,
  131913. 6,
  131914. 8,
  131915. 5,
  131916. 9,
  131917. 4,
  131918. 10,
  131919. 3,
  131920. 11,
  131921. 2,
  131922. 12,
  131923. 1,
  131924. 13,
  131925. 0,
  131926. 14,
  131927. };
  131928. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131929. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131930. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131931. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131932. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131933. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131934. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131935. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131936. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131937. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131938. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131939. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131940. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131941. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131942. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131943. 12,
  131944. };
  131945. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131946. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131947. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131948. };
  131949. static long _vq_quantmap__44c5_s_p9_0[] = {
  131950. 13, 11, 9, 7, 5, 3, 1, 0,
  131951. 2, 4, 6, 8, 10, 12, 14,
  131952. };
  131953. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131954. _vq_quantthresh__44c5_s_p9_0,
  131955. _vq_quantmap__44c5_s_p9_0,
  131956. 15,
  131957. 15
  131958. };
  131959. static static_codebook _44c5_s_p9_0 = {
  131960. 2, 225,
  131961. _vq_lengthlist__44c5_s_p9_0,
  131962. 1, -512522752, 1628852224, 4, 0,
  131963. _vq_quantlist__44c5_s_p9_0,
  131964. NULL,
  131965. &_vq_auxt__44c5_s_p9_0,
  131966. NULL,
  131967. 0
  131968. };
  131969. static long _vq_quantlist__44c5_s_p9_1[] = {
  131970. 8,
  131971. 7,
  131972. 9,
  131973. 6,
  131974. 10,
  131975. 5,
  131976. 11,
  131977. 4,
  131978. 12,
  131979. 3,
  131980. 13,
  131981. 2,
  131982. 14,
  131983. 1,
  131984. 15,
  131985. 0,
  131986. 16,
  131987. };
  131988. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131989. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131990. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131991. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131992. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131993. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131994. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131995. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131996. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131997. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131998. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131999. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132000. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132001. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132002. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132003. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132004. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132005. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132006. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132007. 15,
  132008. };
  132009. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132010. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132011. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132012. };
  132013. static long _vq_quantmap__44c5_s_p9_1[] = {
  132014. 15, 13, 11, 9, 7, 5, 3, 1,
  132015. 0, 2, 4, 6, 8, 10, 12, 14,
  132016. 16,
  132017. };
  132018. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132019. _vq_quantthresh__44c5_s_p9_1,
  132020. _vq_quantmap__44c5_s_p9_1,
  132021. 17,
  132022. 17
  132023. };
  132024. static static_codebook _44c5_s_p9_1 = {
  132025. 2, 289,
  132026. _vq_lengthlist__44c5_s_p9_1,
  132027. 1, -520814592, 1620377600, 5, 0,
  132028. _vq_quantlist__44c5_s_p9_1,
  132029. NULL,
  132030. &_vq_auxt__44c5_s_p9_1,
  132031. NULL,
  132032. 0
  132033. };
  132034. static long _vq_quantlist__44c5_s_p9_2[] = {
  132035. 10,
  132036. 9,
  132037. 11,
  132038. 8,
  132039. 12,
  132040. 7,
  132041. 13,
  132042. 6,
  132043. 14,
  132044. 5,
  132045. 15,
  132046. 4,
  132047. 16,
  132048. 3,
  132049. 17,
  132050. 2,
  132051. 18,
  132052. 1,
  132053. 19,
  132054. 0,
  132055. 20,
  132056. };
  132057. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132058. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132059. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132060. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132061. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132062. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132063. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132064. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132065. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132066. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132067. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132068. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132069. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132070. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132071. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132072. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132073. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132074. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132075. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132076. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132077. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132078. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132079. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132080. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132081. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132082. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132083. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132084. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132085. 10,10,10,10,10,10,10,10,10,
  132086. };
  132087. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132088. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132089. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132090. 6.5, 7.5, 8.5, 9.5,
  132091. };
  132092. static long _vq_quantmap__44c5_s_p9_2[] = {
  132093. 19, 17, 15, 13, 11, 9, 7, 5,
  132094. 3, 1, 0, 2, 4, 6, 8, 10,
  132095. 12, 14, 16, 18, 20,
  132096. };
  132097. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132098. _vq_quantthresh__44c5_s_p9_2,
  132099. _vq_quantmap__44c5_s_p9_2,
  132100. 21,
  132101. 21
  132102. };
  132103. static static_codebook _44c5_s_p9_2 = {
  132104. 2, 441,
  132105. _vq_lengthlist__44c5_s_p9_2,
  132106. 1, -529268736, 1611661312, 5, 0,
  132107. _vq_quantlist__44c5_s_p9_2,
  132108. NULL,
  132109. &_vq_auxt__44c5_s_p9_2,
  132110. NULL,
  132111. 0
  132112. };
  132113. static long _huff_lengthlist__44c5_s_short[] = {
  132114. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132115. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132116. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132117. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132118. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132119. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132120. 6, 8,11,16,
  132121. };
  132122. static static_codebook _huff_book__44c5_s_short = {
  132123. 2, 100,
  132124. _huff_lengthlist__44c5_s_short,
  132125. 0, 0, 0, 0, 0,
  132126. NULL,
  132127. NULL,
  132128. NULL,
  132129. NULL,
  132130. 0
  132131. };
  132132. static long _huff_lengthlist__44c6_s_long[] = {
  132133. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132134. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132135. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132136. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132137. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132138. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132139. 11,10,10,12,
  132140. };
  132141. static static_codebook _huff_book__44c6_s_long = {
  132142. 2, 100,
  132143. _huff_lengthlist__44c6_s_long,
  132144. 0, 0, 0, 0, 0,
  132145. NULL,
  132146. NULL,
  132147. NULL,
  132148. NULL,
  132149. 0
  132150. };
  132151. static long _vq_quantlist__44c6_s_p1_0[] = {
  132152. 1,
  132153. 0,
  132154. 2,
  132155. };
  132156. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132157. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132158. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132159. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132160. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132161. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132162. 8,
  132163. };
  132164. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132165. -0.5, 0.5,
  132166. };
  132167. static long _vq_quantmap__44c6_s_p1_0[] = {
  132168. 1, 0, 2,
  132169. };
  132170. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132171. _vq_quantthresh__44c6_s_p1_0,
  132172. _vq_quantmap__44c6_s_p1_0,
  132173. 3,
  132174. 3
  132175. };
  132176. static static_codebook _44c6_s_p1_0 = {
  132177. 4, 81,
  132178. _vq_lengthlist__44c6_s_p1_0,
  132179. 1, -535822336, 1611661312, 2, 0,
  132180. _vq_quantlist__44c6_s_p1_0,
  132181. NULL,
  132182. &_vq_auxt__44c6_s_p1_0,
  132183. NULL,
  132184. 0
  132185. };
  132186. static long _vq_quantlist__44c6_s_p2_0[] = {
  132187. 2,
  132188. 1,
  132189. 3,
  132190. 0,
  132191. 4,
  132192. };
  132193. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132194. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132195. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132196. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132197. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132198. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132199. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132200. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132201. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132203. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132204. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132205. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132206. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132207. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132208. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132209. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132211. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132212. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132213. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132214. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132215. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132216. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132217. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132219. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132220. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132221. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132222. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132223. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132224. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132225. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132230. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132231. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132232. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132233. 13,
  132234. };
  132235. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132236. -1.5, -0.5, 0.5, 1.5,
  132237. };
  132238. static long _vq_quantmap__44c6_s_p2_0[] = {
  132239. 3, 1, 0, 2, 4,
  132240. };
  132241. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132242. _vq_quantthresh__44c6_s_p2_0,
  132243. _vq_quantmap__44c6_s_p2_0,
  132244. 5,
  132245. 5
  132246. };
  132247. static static_codebook _44c6_s_p2_0 = {
  132248. 4, 625,
  132249. _vq_lengthlist__44c6_s_p2_0,
  132250. 1, -533725184, 1611661312, 3, 0,
  132251. _vq_quantlist__44c6_s_p2_0,
  132252. NULL,
  132253. &_vq_auxt__44c6_s_p2_0,
  132254. NULL,
  132255. 0
  132256. };
  132257. static long _vq_quantlist__44c6_s_p3_0[] = {
  132258. 4,
  132259. 3,
  132260. 5,
  132261. 2,
  132262. 6,
  132263. 1,
  132264. 7,
  132265. 0,
  132266. 8,
  132267. };
  132268. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132269. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132270. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132271. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132272. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132274. 0,
  132275. };
  132276. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132277. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132278. };
  132279. static long _vq_quantmap__44c6_s_p3_0[] = {
  132280. 7, 5, 3, 1, 0, 2, 4, 6,
  132281. 8,
  132282. };
  132283. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132284. _vq_quantthresh__44c6_s_p3_0,
  132285. _vq_quantmap__44c6_s_p3_0,
  132286. 9,
  132287. 9
  132288. };
  132289. static static_codebook _44c6_s_p3_0 = {
  132290. 2, 81,
  132291. _vq_lengthlist__44c6_s_p3_0,
  132292. 1, -531628032, 1611661312, 4, 0,
  132293. _vq_quantlist__44c6_s_p3_0,
  132294. NULL,
  132295. &_vq_auxt__44c6_s_p3_0,
  132296. NULL,
  132297. 0
  132298. };
  132299. static long _vq_quantlist__44c6_s_p4_0[] = {
  132300. 8,
  132301. 7,
  132302. 9,
  132303. 6,
  132304. 10,
  132305. 5,
  132306. 11,
  132307. 4,
  132308. 12,
  132309. 3,
  132310. 13,
  132311. 2,
  132312. 14,
  132313. 1,
  132314. 15,
  132315. 0,
  132316. 16,
  132317. };
  132318. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132319. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132320. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132321. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132322. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132323. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132324. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132325. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132326. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132327. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132328. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132337. 0,
  132338. };
  132339. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132340. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132341. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132342. };
  132343. static long _vq_quantmap__44c6_s_p4_0[] = {
  132344. 15, 13, 11, 9, 7, 5, 3, 1,
  132345. 0, 2, 4, 6, 8, 10, 12, 14,
  132346. 16,
  132347. };
  132348. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132349. _vq_quantthresh__44c6_s_p4_0,
  132350. _vq_quantmap__44c6_s_p4_0,
  132351. 17,
  132352. 17
  132353. };
  132354. static static_codebook _44c6_s_p4_0 = {
  132355. 2, 289,
  132356. _vq_lengthlist__44c6_s_p4_0,
  132357. 1, -529530880, 1611661312, 5, 0,
  132358. _vq_quantlist__44c6_s_p4_0,
  132359. NULL,
  132360. &_vq_auxt__44c6_s_p4_0,
  132361. NULL,
  132362. 0
  132363. };
  132364. static long _vq_quantlist__44c6_s_p5_0[] = {
  132365. 1,
  132366. 0,
  132367. 2,
  132368. };
  132369. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132370. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132371. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132372. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132373. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132374. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132375. 12,
  132376. };
  132377. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132378. -5.5, 5.5,
  132379. };
  132380. static long _vq_quantmap__44c6_s_p5_0[] = {
  132381. 1, 0, 2,
  132382. };
  132383. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132384. _vq_quantthresh__44c6_s_p5_0,
  132385. _vq_quantmap__44c6_s_p5_0,
  132386. 3,
  132387. 3
  132388. };
  132389. static static_codebook _44c6_s_p5_0 = {
  132390. 4, 81,
  132391. _vq_lengthlist__44c6_s_p5_0,
  132392. 1, -529137664, 1618345984, 2, 0,
  132393. _vq_quantlist__44c6_s_p5_0,
  132394. NULL,
  132395. &_vq_auxt__44c6_s_p5_0,
  132396. NULL,
  132397. 0
  132398. };
  132399. static long _vq_quantlist__44c6_s_p5_1[] = {
  132400. 5,
  132401. 4,
  132402. 6,
  132403. 3,
  132404. 7,
  132405. 2,
  132406. 8,
  132407. 1,
  132408. 9,
  132409. 0,
  132410. 10,
  132411. };
  132412. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132413. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132414. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132415. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132416. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132417. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132418. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132419. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132420. 11,10,10, 7, 7, 8, 8, 8, 8,
  132421. };
  132422. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132423. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132424. 3.5, 4.5,
  132425. };
  132426. static long _vq_quantmap__44c6_s_p5_1[] = {
  132427. 9, 7, 5, 3, 1, 0, 2, 4,
  132428. 6, 8, 10,
  132429. };
  132430. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132431. _vq_quantthresh__44c6_s_p5_1,
  132432. _vq_quantmap__44c6_s_p5_1,
  132433. 11,
  132434. 11
  132435. };
  132436. static static_codebook _44c6_s_p5_1 = {
  132437. 2, 121,
  132438. _vq_lengthlist__44c6_s_p5_1,
  132439. 1, -531365888, 1611661312, 4, 0,
  132440. _vq_quantlist__44c6_s_p5_1,
  132441. NULL,
  132442. &_vq_auxt__44c6_s_p5_1,
  132443. NULL,
  132444. 0
  132445. };
  132446. static long _vq_quantlist__44c6_s_p6_0[] = {
  132447. 6,
  132448. 5,
  132449. 7,
  132450. 4,
  132451. 8,
  132452. 3,
  132453. 9,
  132454. 2,
  132455. 10,
  132456. 1,
  132457. 11,
  132458. 0,
  132459. 12,
  132460. };
  132461. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132462. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132463. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132464. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132465. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132466. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132467. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132472. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132473. };
  132474. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132475. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132476. 12.5, 17.5, 22.5, 27.5,
  132477. };
  132478. static long _vq_quantmap__44c6_s_p6_0[] = {
  132479. 11, 9, 7, 5, 3, 1, 0, 2,
  132480. 4, 6, 8, 10, 12,
  132481. };
  132482. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132483. _vq_quantthresh__44c6_s_p6_0,
  132484. _vq_quantmap__44c6_s_p6_0,
  132485. 13,
  132486. 13
  132487. };
  132488. static static_codebook _44c6_s_p6_0 = {
  132489. 2, 169,
  132490. _vq_lengthlist__44c6_s_p6_0,
  132491. 1, -526516224, 1616117760, 4, 0,
  132492. _vq_quantlist__44c6_s_p6_0,
  132493. NULL,
  132494. &_vq_auxt__44c6_s_p6_0,
  132495. NULL,
  132496. 0
  132497. };
  132498. static long _vq_quantlist__44c6_s_p6_1[] = {
  132499. 2,
  132500. 1,
  132501. 3,
  132502. 0,
  132503. 4,
  132504. };
  132505. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132506. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132507. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132508. };
  132509. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132510. -1.5, -0.5, 0.5, 1.5,
  132511. };
  132512. static long _vq_quantmap__44c6_s_p6_1[] = {
  132513. 3, 1, 0, 2, 4,
  132514. };
  132515. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132516. _vq_quantthresh__44c6_s_p6_1,
  132517. _vq_quantmap__44c6_s_p6_1,
  132518. 5,
  132519. 5
  132520. };
  132521. static static_codebook _44c6_s_p6_1 = {
  132522. 2, 25,
  132523. _vq_lengthlist__44c6_s_p6_1,
  132524. 1, -533725184, 1611661312, 3, 0,
  132525. _vq_quantlist__44c6_s_p6_1,
  132526. NULL,
  132527. &_vq_auxt__44c6_s_p6_1,
  132528. NULL,
  132529. 0
  132530. };
  132531. static long _vq_quantlist__44c6_s_p7_0[] = {
  132532. 6,
  132533. 5,
  132534. 7,
  132535. 4,
  132536. 8,
  132537. 3,
  132538. 9,
  132539. 2,
  132540. 10,
  132541. 1,
  132542. 11,
  132543. 0,
  132544. 12,
  132545. };
  132546. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132547. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132548. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132549. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132550. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132551. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132552. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132553. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132554. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132555. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132556. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132557. 20,13,13,13,13,13,13,14,14,
  132558. };
  132559. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132560. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132561. 27.5, 38.5, 49.5, 60.5,
  132562. };
  132563. static long _vq_quantmap__44c6_s_p7_0[] = {
  132564. 11, 9, 7, 5, 3, 1, 0, 2,
  132565. 4, 6, 8, 10, 12,
  132566. };
  132567. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132568. _vq_quantthresh__44c6_s_p7_0,
  132569. _vq_quantmap__44c6_s_p7_0,
  132570. 13,
  132571. 13
  132572. };
  132573. static static_codebook _44c6_s_p7_0 = {
  132574. 2, 169,
  132575. _vq_lengthlist__44c6_s_p7_0,
  132576. 1, -523206656, 1618345984, 4, 0,
  132577. _vq_quantlist__44c6_s_p7_0,
  132578. NULL,
  132579. &_vq_auxt__44c6_s_p7_0,
  132580. NULL,
  132581. 0
  132582. };
  132583. static long _vq_quantlist__44c6_s_p7_1[] = {
  132584. 5,
  132585. 4,
  132586. 6,
  132587. 3,
  132588. 7,
  132589. 2,
  132590. 8,
  132591. 1,
  132592. 9,
  132593. 0,
  132594. 10,
  132595. };
  132596. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132597. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132598. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132599. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132600. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132601. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132602. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132603. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132604. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132605. };
  132606. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132607. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132608. 3.5, 4.5,
  132609. };
  132610. static long _vq_quantmap__44c6_s_p7_1[] = {
  132611. 9, 7, 5, 3, 1, 0, 2, 4,
  132612. 6, 8, 10,
  132613. };
  132614. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132615. _vq_quantthresh__44c6_s_p7_1,
  132616. _vq_quantmap__44c6_s_p7_1,
  132617. 11,
  132618. 11
  132619. };
  132620. static static_codebook _44c6_s_p7_1 = {
  132621. 2, 121,
  132622. _vq_lengthlist__44c6_s_p7_1,
  132623. 1, -531365888, 1611661312, 4, 0,
  132624. _vq_quantlist__44c6_s_p7_1,
  132625. NULL,
  132626. &_vq_auxt__44c6_s_p7_1,
  132627. NULL,
  132628. 0
  132629. };
  132630. static long _vq_quantlist__44c6_s_p8_0[] = {
  132631. 7,
  132632. 6,
  132633. 8,
  132634. 5,
  132635. 9,
  132636. 4,
  132637. 10,
  132638. 3,
  132639. 11,
  132640. 2,
  132641. 12,
  132642. 1,
  132643. 13,
  132644. 0,
  132645. 14,
  132646. };
  132647. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132648. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132649. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132650. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132651. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132652. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132653. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132654. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132655. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132656. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132657. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132658. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132659. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132660. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132661. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132662. 14,
  132663. };
  132664. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132665. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132666. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132667. };
  132668. static long _vq_quantmap__44c6_s_p8_0[] = {
  132669. 13, 11, 9, 7, 5, 3, 1, 0,
  132670. 2, 4, 6, 8, 10, 12, 14,
  132671. };
  132672. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132673. _vq_quantthresh__44c6_s_p8_0,
  132674. _vq_quantmap__44c6_s_p8_0,
  132675. 15,
  132676. 15
  132677. };
  132678. static static_codebook _44c6_s_p8_0 = {
  132679. 2, 225,
  132680. _vq_lengthlist__44c6_s_p8_0,
  132681. 1, -520986624, 1620377600, 4, 0,
  132682. _vq_quantlist__44c6_s_p8_0,
  132683. NULL,
  132684. &_vq_auxt__44c6_s_p8_0,
  132685. NULL,
  132686. 0
  132687. };
  132688. static long _vq_quantlist__44c6_s_p8_1[] = {
  132689. 10,
  132690. 9,
  132691. 11,
  132692. 8,
  132693. 12,
  132694. 7,
  132695. 13,
  132696. 6,
  132697. 14,
  132698. 5,
  132699. 15,
  132700. 4,
  132701. 16,
  132702. 3,
  132703. 17,
  132704. 2,
  132705. 18,
  132706. 1,
  132707. 19,
  132708. 0,
  132709. 20,
  132710. };
  132711. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132712. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132713. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132714. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132715. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132716. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132717. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132718. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132719. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132720. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132721. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132722. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132723. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132724. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132725. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132726. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132727. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132728. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132729. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132730. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132731. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132732. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132733. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132734. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132735. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132736. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132737. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132738. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132739. 10,10,10,10,10,10,10,10,10,
  132740. };
  132741. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132742. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132743. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132744. 6.5, 7.5, 8.5, 9.5,
  132745. };
  132746. static long _vq_quantmap__44c6_s_p8_1[] = {
  132747. 19, 17, 15, 13, 11, 9, 7, 5,
  132748. 3, 1, 0, 2, 4, 6, 8, 10,
  132749. 12, 14, 16, 18, 20,
  132750. };
  132751. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132752. _vq_quantthresh__44c6_s_p8_1,
  132753. _vq_quantmap__44c6_s_p8_1,
  132754. 21,
  132755. 21
  132756. };
  132757. static static_codebook _44c6_s_p8_1 = {
  132758. 2, 441,
  132759. _vq_lengthlist__44c6_s_p8_1,
  132760. 1, -529268736, 1611661312, 5, 0,
  132761. _vq_quantlist__44c6_s_p8_1,
  132762. NULL,
  132763. &_vq_auxt__44c6_s_p8_1,
  132764. NULL,
  132765. 0
  132766. };
  132767. static long _vq_quantlist__44c6_s_p9_0[] = {
  132768. 6,
  132769. 5,
  132770. 7,
  132771. 4,
  132772. 8,
  132773. 3,
  132774. 9,
  132775. 2,
  132776. 10,
  132777. 1,
  132778. 11,
  132779. 0,
  132780. 12,
  132781. };
  132782. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132783. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132784. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132786. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132787. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132788. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132789. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132790. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132791. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132792. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132793. 10,10,10,10,10,10,10,10,10,
  132794. };
  132795. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132796. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132797. 1592.5, 2229.5, 2866.5, 3503.5,
  132798. };
  132799. static long _vq_quantmap__44c6_s_p9_0[] = {
  132800. 11, 9, 7, 5, 3, 1, 0, 2,
  132801. 4, 6, 8, 10, 12,
  132802. };
  132803. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132804. _vq_quantthresh__44c6_s_p9_0,
  132805. _vq_quantmap__44c6_s_p9_0,
  132806. 13,
  132807. 13
  132808. };
  132809. static static_codebook _44c6_s_p9_0 = {
  132810. 2, 169,
  132811. _vq_lengthlist__44c6_s_p9_0,
  132812. 1, -511845376, 1630791680, 4, 0,
  132813. _vq_quantlist__44c6_s_p9_0,
  132814. NULL,
  132815. &_vq_auxt__44c6_s_p9_0,
  132816. NULL,
  132817. 0
  132818. };
  132819. static long _vq_quantlist__44c6_s_p9_1[] = {
  132820. 6,
  132821. 5,
  132822. 7,
  132823. 4,
  132824. 8,
  132825. 3,
  132826. 9,
  132827. 2,
  132828. 10,
  132829. 1,
  132830. 11,
  132831. 0,
  132832. 12,
  132833. };
  132834. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132835. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132836. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132837. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132838. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132839. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132840. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132841. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132842. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132843. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132844. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132845. 15,12,10,11,11,13,11,12,13,
  132846. };
  132847. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132848. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132849. 122.5, 171.5, 220.5, 269.5,
  132850. };
  132851. static long _vq_quantmap__44c6_s_p9_1[] = {
  132852. 11, 9, 7, 5, 3, 1, 0, 2,
  132853. 4, 6, 8, 10, 12,
  132854. };
  132855. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132856. _vq_quantthresh__44c6_s_p9_1,
  132857. _vq_quantmap__44c6_s_p9_1,
  132858. 13,
  132859. 13
  132860. };
  132861. static static_codebook _44c6_s_p9_1 = {
  132862. 2, 169,
  132863. _vq_lengthlist__44c6_s_p9_1,
  132864. 1, -518889472, 1622704128, 4, 0,
  132865. _vq_quantlist__44c6_s_p9_1,
  132866. NULL,
  132867. &_vq_auxt__44c6_s_p9_1,
  132868. NULL,
  132869. 0
  132870. };
  132871. static long _vq_quantlist__44c6_s_p9_2[] = {
  132872. 24,
  132873. 23,
  132874. 25,
  132875. 22,
  132876. 26,
  132877. 21,
  132878. 27,
  132879. 20,
  132880. 28,
  132881. 19,
  132882. 29,
  132883. 18,
  132884. 30,
  132885. 17,
  132886. 31,
  132887. 16,
  132888. 32,
  132889. 15,
  132890. 33,
  132891. 14,
  132892. 34,
  132893. 13,
  132894. 35,
  132895. 12,
  132896. 36,
  132897. 11,
  132898. 37,
  132899. 10,
  132900. 38,
  132901. 9,
  132902. 39,
  132903. 8,
  132904. 40,
  132905. 7,
  132906. 41,
  132907. 6,
  132908. 42,
  132909. 5,
  132910. 43,
  132911. 4,
  132912. 44,
  132913. 3,
  132914. 45,
  132915. 2,
  132916. 46,
  132917. 1,
  132918. 47,
  132919. 0,
  132920. 48,
  132921. };
  132922. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132923. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132924. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132925. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132926. 7,
  132927. };
  132928. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132929. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132930. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132931. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132932. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132933. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132934. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132935. };
  132936. static long _vq_quantmap__44c6_s_p9_2[] = {
  132937. 47, 45, 43, 41, 39, 37, 35, 33,
  132938. 31, 29, 27, 25, 23, 21, 19, 17,
  132939. 15, 13, 11, 9, 7, 5, 3, 1,
  132940. 0, 2, 4, 6, 8, 10, 12, 14,
  132941. 16, 18, 20, 22, 24, 26, 28, 30,
  132942. 32, 34, 36, 38, 40, 42, 44, 46,
  132943. 48,
  132944. };
  132945. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132946. _vq_quantthresh__44c6_s_p9_2,
  132947. _vq_quantmap__44c6_s_p9_2,
  132948. 49,
  132949. 49
  132950. };
  132951. static static_codebook _44c6_s_p9_2 = {
  132952. 1, 49,
  132953. _vq_lengthlist__44c6_s_p9_2,
  132954. 1, -526909440, 1611661312, 6, 0,
  132955. _vq_quantlist__44c6_s_p9_2,
  132956. NULL,
  132957. &_vq_auxt__44c6_s_p9_2,
  132958. NULL,
  132959. 0
  132960. };
  132961. static long _huff_lengthlist__44c6_s_short[] = {
  132962. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132963. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132964. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132965. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132966. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132967. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132968. 9,10,17,18,
  132969. };
  132970. static static_codebook _huff_book__44c6_s_short = {
  132971. 2, 100,
  132972. _huff_lengthlist__44c6_s_short,
  132973. 0, 0, 0, 0, 0,
  132974. NULL,
  132975. NULL,
  132976. NULL,
  132977. NULL,
  132978. 0
  132979. };
  132980. static long _huff_lengthlist__44c7_s_long[] = {
  132981. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132982. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132983. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132984. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132985. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132986. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132987. 11,10,10,12,
  132988. };
  132989. static static_codebook _huff_book__44c7_s_long = {
  132990. 2, 100,
  132991. _huff_lengthlist__44c7_s_long,
  132992. 0, 0, 0, 0, 0,
  132993. NULL,
  132994. NULL,
  132995. NULL,
  132996. NULL,
  132997. 0
  132998. };
  132999. static long _vq_quantlist__44c7_s_p1_0[] = {
  133000. 1,
  133001. 0,
  133002. 2,
  133003. };
  133004. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133005. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133006. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133007. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133008. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133009. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133010. 8,
  133011. };
  133012. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133013. -0.5, 0.5,
  133014. };
  133015. static long _vq_quantmap__44c7_s_p1_0[] = {
  133016. 1, 0, 2,
  133017. };
  133018. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133019. _vq_quantthresh__44c7_s_p1_0,
  133020. _vq_quantmap__44c7_s_p1_0,
  133021. 3,
  133022. 3
  133023. };
  133024. static static_codebook _44c7_s_p1_0 = {
  133025. 4, 81,
  133026. _vq_lengthlist__44c7_s_p1_0,
  133027. 1, -535822336, 1611661312, 2, 0,
  133028. _vq_quantlist__44c7_s_p1_0,
  133029. NULL,
  133030. &_vq_auxt__44c7_s_p1_0,
  133031. NULL,
  133032. 0
  133033. };
  133034. static long _vq_quantlist__44c7_s_p2_0[] = {
  133035. 2,
  133036. 1,
  133037. 3,
  133038. 0,
  133039. 4,
  133040. };
  133041. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133042. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133043. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133044. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133045. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133046. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133047. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133048. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133049. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133051. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133052. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133053. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133054. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133055. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133056. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133057. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133059. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133060. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133061. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133062. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133063. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133064. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133065. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133067. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133068. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133069. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133070. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133071. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133072. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133073. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133078. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133079. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133080. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133081. 13,
  133082. };
  133083. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133084. -1.5, -0.5, 0.5, 1.5,
  133085. };
  133086. static long _vq_quantmap__44c7_s_p2_0[] = {
  133087. 3, 1, 0, 2, 4,
  133088. };
  133089. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133090. _vq_quantthresh__44c7_s_p2_0,
  133091. _vq_quantmap__44c7_s_p2_0,
  133092. 5,
  133093. 5
  133094. };
  133095. static static_codebook _44c7_s_p2_0 = {
  133096. 4, 625,
  133097. _vq_lengthlist__44c7_s_p2_0,
  133098. 1, -533725184, 1611661312, 3, 0,
  133099. _vq_quantlist__44c7_s_p2_0,
  133100. NULL,
  133101. &_vq_auxt__44c7_s_p2_0,
  133102. NULL,
  133103. 0
  133104. };
  133105. static long _vq_quantlist__44c7_s_p3_0[] = {
  133106. 4,
  133107. 3,
  133108. 5,
  133109. 2,
  133110. 6,
  133111. 1,
  133112. 7,
  133113. 0,
  133114. 8,
  133115. };
  133116. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133117. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133118. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133119. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133120. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133122. 0,
  133123. };
  133124. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133125. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133126. };
  133127. static long _vq_quantmap__44c7_s_p3_0[] = {
  133128. 7, 5, 3, 1, 0, 2, 4, 6,
  133129. 8,
  133130. };
  133131. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133132. _vq_quantthresh__44c7_s_p3_0,
  133133. _vq_quantmap__44c7_s_p3_0,
  133134. 9,
  133135. 9
  133136. };
  133137. static static_codebook _44c7_s_p3_0 = {
  133138. 2, 81,
  133139. _vq_lengthlist__44c7_s_p3_0,
  133140. 1, -531628032, 1611661312, 4, 0,
  133141. _vq_quantlist__44c7_s_p3_0,
  133142. NULL,
  133143. &_vq_auxt__44c7_s_p3_0,
  133144. NULL,
  133145. 0
  133146. };
  133147. static long _vq_quantlist__44c7_s_p4_0[] = {
  133148. 8,
  133149. 7,
  133150. 9,
  133151. 6,
  133152. 10,
  133153. 5,
  133154. 11,
  133155. 4,
  133156. 12,
  133157. 3,
  133158. 13,
  133159. 2,
  133160. 14,
  133161. 1,
  133162. 15,
  133163. 0,
  133164. 16,
  133165. };
  133166. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133167. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133168. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133169. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133170. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133171. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133172. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133173. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133174. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133175. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133176. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133185. 0,
  133186. };
  133187. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133188. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133189. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133190. };
  133191. static long _vq_quantmap__44c7_s_p4_0[] = {
  133192. 15, 13, 11, 9, 7, 5, 3, 1,
  133193. 0, 2, 4, 6, 8, 10, 12, 14,
  133194. 16,
  133195. };
  133196. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133197. _vq_quantthresh__44c7_s_p4_0,
  133198. _vq_quantmap__44c7_s_p4_0,
  133199. 17,
  133200. 17
  133201. };
  133202. static static_codebook _44c7_s_p4_0 = {
  133203. 2, 289,
  133204. _vq_lengthlist__44c7_s_p4_0,
  133205. 1, -529530880, 1611661312, 5, 0,
  133206. _vq_quantlist__44c7_s_p4_0,
  133207. NULL,
  133208. &_vq_auxt__44c7_s_p4_0,
  133209. NULL,
  133210. 0
  133211. };
  133212. static long _vq_quantlist__44c7_s_p5_0[] = {
  133213. 1,
  133214. 0,
  133215. 2,
  133216. };
  133217. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133218. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133219. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133220. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133221. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133222. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133223. 12,
  133224. };
  133225. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133226. -5.5, 5.5,
  133227. };
  133228. static long _vq_quantmap__44c7_s_p5_0[] = {
  133229. 1, 0, 2,
  133230. };
  133231. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133232. _vq_quantthresh__44c7_s_p5_0,
  133233. _vq_quantmap__44c7_s_p5_0,
  133234. 3,
  133235. 3
  133236. };
  133237. static static_codebook _44c7_s_p5_0 = {
  133238. 4, 81,
  133239. _vq_lengthlist__44c7_s_p5_0,
  133240. 1, -529137664, 1618345984, 2, 0,
  133241. _vq_quantlist__44c7_s_p5_0,
  133242. NULL,
  133243. &_vq_auxt__44c7_s_p5_0,
  133244. NULL,
  133245. 0
  133246. };
  133247. static long _vq_quantlist__44c7_s_p5_1[] = {
  133248. 5,
  133249. 4,
  133250. 6,
  133251. 3,
  133252. 7,
  133253. 2,
  133254. 8,
  133255. 1,
  133256. 9,
  133257. 0,
  133258. 10,
  133259. };
  133260. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133261. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133262. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133263. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133264. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133265. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133266. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133267. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133268. 11,11,11, 7, 7, 8, 8, 8, 8,
  133269. };
  133270. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133271. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133272. 3.5, 4.5,
  133273. };
  133274. static long _vq_quantmap__44c7_s_p5_1[] = {
  133275. 9, 7, 5, 3, 1, 0, 2, 4,
  133276. 6, 8, 10,
  133277. };
  133278. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133279. _vq_quantthresh__44c7_s_p5_1,
  133280. _vq_quantmap__44c7_s_p5_1,
  133281. 11,
  133282. 11
  133283. };
  133284. static static_codebook _44c7_s_p5_1 = {
  133285. 2, 121,
  133286. _vq_lengthlist__44c7_s_p5_1,
  133287. 1, -531365888, 1611661312, 4, 0,
  133288. _vq_quantlist__44c7_s_p5_1,
  133289. NULL,
  133290. &_vq_auxt__44c7_s_p5_1,
  133291. NULL,
  133292. 0
  133293. };
  133294. static long _vq_quantlist__44c7_s_p6_0[] = {
  133295. 6,
  133296. 5,
  133297. 7,
  133298. 4,
  133299. 8,
  133300. 3,
  133301. 9,
  133302. 2,
  133303. 10,
  133304. 1,
  133305. 11,
  133306. 0,
  133307. 12,
  133308. };
  133309. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133310. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133311. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133312. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133313. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133314. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133315. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133320. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133321. };
  133322. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133323. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133324. 12.5, 17.5, 22.5, 27.5,
  133325. };
  133326. static long _vq_quantmap__44c7_s_p6_0[] = {
  133327. 11, 9, 7, 5, 3, 1, 0, 2,
  133328. 4, 6, 8, 10, 12,
  133329. };
  133330. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133331. _vq_quantthresh__44c7_s_p6_0,
  133332. _vq_quantmap__44c7_s_p6_0,
  133333. 13,
  133334. 13
  133335. };
  133336. static static_codebook _44c7_s_p6_0 = {
  133337. 2, 169,
  133338. _vq_lengthlist__44c7_s_p6_0,
  133339. 1, -526516224, 1616117760, 4, 0,
  133340. _vq_quantlist__44c7_s_p6_0,
  133341. NULL,
  133342. &_vq_auxt__44c7_s_p6_0,
  133343. NULL,
  133344. 0
  133345. };
  133346. static long _vq_quantlist__44c7_s_p6_1[] = {
  133347. 2,
  133348. 1,
  133349. 3,
  133350. 0,
  133351. 4,
  133352. };
  133353. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133354. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133355. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133356. };
  133357. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133358. -1.5, -0.5, 0.5, 1.5,
  133359. };
  133360. static long _vq_quantmap__44c7_s_p6_1[] = {
  133361. 3, 1, 0, 2, 4,
  133362. };
  133363. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133364. _vq_quantthresh__44c7_s_p6_1,
  133365. _vq_quantmap__44c7_s_p6_1,
  133366. 5,
  133367. 5
  133368. };
  133369. static static_codebook _44c7_s_p6_1 = {
  133370. 2, 25,
  133371. _vq_lengthlist__44c7_s_p6_1,
  133372. 1, -533725184, 1611661312, 3, 0,
  133373. _vq_quantlist__44c7_s_p6_1,
  133374. NULL,
  133375. &_vq_auxt__44c7_s_p6_1,
  133376. NULL,
  133377. 0
  133378. };
  133379. static long _vq_quantlist__44c7_s_p7_0[] = {
  133380. 6,
  133381. 5,
  133382. 7,
  133383. 4,
  133384. 8,
  133385. 3,
  133386. 9,
  133387. 2,
  133388. 10,
  133389. 1,
  133390. 11,
  133391. 0,
  133392. 12,
  133393. };
  133394. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133395. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133396. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133397. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133398. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133399. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133400. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133401. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133402. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133403. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133404. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133405. 19,13,13,13,13,14,14,15,15,
  133406. };
  133407. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133408. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133409. 27.5, 38.5, 49.5, 60.5,
  133410. };
  133411. static long _vq_quantmap__44c7_s_p7_0[] = {
  133412. 11, 9, 7, 5, 3, 1, 0, 2,
  133413. 4, 6, 8, 10, 12,
  133414. };
  133415. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133416. _vq_quantthresh__44c7_s_p7_0,
  133417. _vq_quantmap__44c7_s_p7_0,
  133418. 13,
  133419. 13
  133420. };
  133421. static static_codebook _44c7_s_p7_0 = {
  133422. 2, 169,
  133423. _vq_lengthlist__44c7_s_p7_0,
  133424. 1, -523206656, 1618345984, 4, 0,
  133425. _vq_quantlist__44c7_s_p7_0,
  133426. NULL,
  133427. &_vq_auxt__44c7_s_p7_0,
  133428. NULL,
  133429. 0
  133430. };
  133431. static long _vq_quantlist__44c7_s_p7_1[] = {
  133432. 5,
  133433. 4,
  133434. 6,
  133435. 3,
  133436. 7,
  133437. 2,
  133438. 8,
  133439. 1,
  133440. 9,
  133441. 0,
  133442. 10,
  133443. };
  133444. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133445. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133446. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133447. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133448. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133449. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133450. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133451. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133452. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133453. };
  133454. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133455. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133456. 3.5, 4.5,
  133457. };
  133458. static long _vq_quantmap__44c7_s_p7_1[] = {
  133459. 9, 7, 5, 3, 1, 0, 2, 4,
  133460. 6, 8, 10,
  133461. };
  133462. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133463. _vq_quantthresh__44c7_s_p7_1,
  133464. _vq_quantmap__44c7_s_p7_1,
  133465. 11,
  133466. 11
  133467. };
  133468. static static_codebook _44c7_s_p7_1 = {
  133469. 2, 121,
  133470. _vq_lengthlist__44c7_s_p7_1,
  133471. 1, -531365888, 1611661312, 4, 0,
  133472. _vq_quantlist__44c7_s_p7_1,
  133473. NULL,
  133474. &_vq_auxt__44c7_s_p7_1,
  133475. NULL,
  133476. 0
  133477. };
  133478. static long _vq_quantlist__44c7_s_p8_0[] = {
  133479. 7,
  133480. 6,
  133481. 8,
  133482. 5,
  133483. 9,
  133484. 4,
  133485. 10,
  133486. 3,
  133487. 11,
  133488. 2,
  133489. 12,
  133490. 1,
  133491. 13,
  133492. 0,
  133493. 14,
  133494. };
  133495. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133496. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133497. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133498. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133499. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133500. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133501. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133502. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133503. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133504. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133505. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133506. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133507. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133508. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133509. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133510. 14,
  133511. };
  133512. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133513. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133514. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133515. };
  133516. static long _vq_quantmap__44c7_s_p8_0[] = {
  133517. 13, 11, 9, 7, 5, 3, 1, 0,
  133518. 2, 4, 6, 8, 10, 12, 14,
  133519. };
  133520. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133521. _vq_quantthresh__44c7_s_p8_0,
  133522. _vq_quantmap__44c7_s_p8_0,
  133523. 15,
  133524. 15
  133525. };
  133526. static static_codebook _44c7_s_p8_0 = {
  133527. 2, 225,
  133528. _vq_lengthlist__44c7_s_p8_0,
  133529. 1, -520986624, 1620377600, 4, 0,
  133530. _vq_quantlist__44c7_s_p8_0,
  133531. NULL,
  133532. &_vq_auxt__44c7_s_p8_0,
  133533. NULL,
  133534. 0
  133535. };
  133536. static long _vq_quantlist__44c7_s_p8_1[] = {
  133537. 10,
  133538. 9,
  133539. 11,
  133540. 8,
  133541. 12,
  133542. 7,
  133543. 13,
  133544. 6,
  133545. 14,
  133546. 5,
  133547. 15,
  133548. 4,
  133549. 16,
  133550. 3,
  133551. 17,
  133552. 2,
  133553. 18,
  133554. 1,
  133555. 19,
  133556. 0,
  133557. 20,
  133558. };
  133559. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133560. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133561. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133562. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133563. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133564. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133565. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133566. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133567. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133568. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133569. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133570. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133571. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133572. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133573. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133574. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133575. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133576. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133577. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133578. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133579. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133580. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133581. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133582. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133583. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133584. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133585. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133586. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133587. 10,10,10,10,10,10,10,10,10,
  133588. };
  133589. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133590. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133591. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133592. 6.5, 7.5, 8.5, 9.5,
  133593. };
  133594. static long _vq_quantmap__44c7_s_p8_1[] = {
  133595. 19, 17, 15, 13, 11, 9, 7, 5,
  133596. 3, 1, 0, 2, 4, 6, 8, 10,
  133597. 12, 14, 16, 18, 20,
  133598. };
  133599. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133600. _vq_quantthresh__44c7_s_p8_1,
  133601. _vq_quantmap__44c7_s_p8_1,
  133602. 21,
  133603. 21
  133604. };
  133605. static static_codebook _44c7_s_p8_1 = {
  133606. 2, 441,
  133607. _vq_lengthlist__44c7_s_p8_1,
  133608. 1, -529268736, 1611661312, 5, 0,
  133609. _vq_quantlist__44c7_s_p8_1,
  133610. NULL,
  133611. &_vq_auxt__44c7_s_p8_1,
  133612. NULL,
  133613. 0
  133614. };
  133615. static long _vq_quantlist__44c7_s_p9_0[] = {
  133616. 6,
  133617. 5,
  133618. 7,
  133619. 4,
  133620. 8,
  133621. 3,
  133622. 9,
  133623. 2,
  133624. 10,
  133625. 1,
  133626. 11,
  133627. 0,
  133628. 12,
  133629. };
  133630. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133631. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133632. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133641. 11,11,11,11,11,11,11,11,11,
  133642. };
  133643. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133644. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133645. 1592.5, 2229.5, 2866.5, 3503.5,
  133646. };
  133647. static long _vq_quantmap__44c7_s_p9_0[] = {
  133648. 11, 9, 7, 5, 3, 1, 0, 2,
  133649. 4, 6, 8, 10, 12,
  133650. };
  133651. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133652. _vq_quantthresh__44c7_s_p9_0,
  133653. _vq_quantmap__44c7_s_p9_0,
  133654. 13,
  133655. 13
  133656. };
  133657. static static_codebook _44c7_s_p9_0 = {
  133658. 2, 169,
  133659. _vq_lengthlist__44c7_s_p9_0,
  133660. 1, -511845376, 1630791680, 4, 0,
  133661. _vq_quantlist__44c7_s_p9_0,
  133662. NULL,
  133663. &_vq_auxt__44c7_s_p9_0,
  133664. NULL,
  133665. 0
  133666. };
  133667. static long _vq_quantlist__44c7_s_p9_1[] = {
  133668. 6,
  133669. 5,
  133670. 7,
  133671. 4,
  133672. 8,
  133673. 3,
  133674. 9,
  133675. 2,
  133676. 10,
  133677. 1,
  133678. 11,
  133679. 0,
  133680. 12,
  133681. };
  133682. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133683. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133684. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133685. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133686. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133687. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133688. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133689. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133690. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133691. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133692. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133693. 15,11,11,10,10,12,12,12,12,
  133694. };
  133695. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133696. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133697. 122.5, 171.5, 220.5, 269.5,
  133698. };
  133699. static long _vq_quantmap__44c7_s_p9_1[] = {
  133700. 11, 9, 7, 5, 3, 1, 0, 2,
  133701. 4, 6, 8, 10, 12,
  133702. };
  133703. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133704. _vq_quantthresh__44c7_s_p9_1,
  133705. _vq_quantmap__44c7_s_p9_1,
  133706. 13,
  133707. 13
  133708. };
  133709. static static_codebook _44c7_s_p9_1 = {
  133710. 2, 169,
  133711. _vq_lengthlist__44c7_s_p9_1,
  133712. 1, -518889472, 1622704128, 4, 0,
  133713. _vq_quantlist__44c7_s_p9_1,
  133714. NULL,
  133715. &_vq_auxt__44c7_s_p9_1,
  133716. NULL,
  133717. 0
  133718. };
  133719. static long _vq_quantlist__44c7_s_p9_2[] = {
  133720. 24,
  133721. 23,
  133722. 25,
  133723. 22,
  133724. 26,
  133725. 21,
  133726. 27,
  133727. 20,
  133728. 28,
  133729. 19,
  133730. 29,
  133731. 18,
  133732. 30,
  133733. 17,
  133734. 31,
  133735. 16,
  133736. 32,
  133737. 15,
  133738. 33,
  133739. 14,
  133740. 34,
  133741. 13,
  133742. 35,
  133743. 12,
  133744. 36,
  133745. 11,
  133746. 37,
  133747. 10,
  133748. 38,
  133749. 9,
  133750. 39,
  133751. 8,
  133752. 40,
  133753. 7,
  133754. 41,
  133755. 6,
  133756. 42,
  133757. 5,
  133758. 43,
  133759. 4,
  133760. 44,
  133761. 3,
  133762. 45,
  133763. 2,
  133764. 46,
  133765. 1,
  133766. 47,
  133767. 0,
  133768. 48,
  133769. };
  133770. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133771. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133772. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133773. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133774. 7,
  133775. };
  133776. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133777. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133778. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133779. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133780. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133781. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133782. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133783. };
  133784. static long _vq_quantmap__44c7_s_p9_2[] = {
  133785. 47, 45, 43, 41, 39, 37, 35, 33,
  133786. 31, 29, 27, 25, 23, 21, 19, 17,
  133787. 15, 13, 11, 9, 7, 5, 3, 1,
  133788. 0, 2, 4, 6, 8, 10, 12, 14,
  133789. 16, 18, 20, 22, 24, 26, 28, 30,
  133790. 32, 34, 36, 38, 40, 42, 44, 46,
  133791. 48,
  133792. };
  133793. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133794. _vq_quantthresh__44c7_s_p9_2,
  133795. _vq_quantmap__44c7_s_p9_2,
  133796. 49,
  133797. 49
  133798. };
  133799. static static_codebook _44c7_s_p9_2 = {
  133800. 1, 49,
  133801. _vq_lengthlist__44c7_s_p9_2,
  133802. 1, -526909440, 1611661312, 6, 0,
  133803. _vq_quantlist__44c7_s_p9_2,
  133804. NULL,
  133805. &_vq_auxt__44c7_s_p9_2,
  133806. NULL,
  133807. 0
  133808. };
  133809. static long _huff_lengthlist__44c7_s_short[] = {
  133810. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133811. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133812. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133813. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133814. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133815. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133816. 10, 9,11,14,
  133817. };
  133818. static static_codebook _huff_book__44c7_s_short = {
  133819. 2, 100,
  133820. _huff_lengthlist__44c7_s_short,
  133821. 0, 0, 0, 0, 0,
  133822. NULL,
  133823. NULL,
  133824. NULL,
  133825. NULL,
  133826. 0
  133827. };
  133828. static long _huff_lengthlist__44c8_s_long[] = {
  133829. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133830. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133831. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133832. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133833. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133834. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133835. 11, 9, 9,10,
  133836. };
  133837. static static_codebook _huff_book__44c8_s_long = {
  133838. 2, 100,
  133839. _huff_lengthlist__44c8_s_long,
  133840. 0, 0, 0, 0, 0,
  133841. NULL,
  133842. NULL,
  133843. NULL,
  133844. NULL,
  133845. 0
  133846. };
  133847. static long _vq_quantlist__44c8_s_p1_0[] = {
  133848. 1,
  133849. 0,
  133850. 2,
  133851. };
  133852. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133853. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133854. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133855. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133856. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133857. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133858. 8,
  133859. };
  133860. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133861. -0.5, 0.5,
  133862. };
  133863. static long _vq_quantmap__44c8_s_p1_0[] = {
  133864. 1, 0, 2,
  133865. };
  133866. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133867. _vq_quantthresh__44c8_s_p1_0,
  133868. _vq_quantmap__44c8_s_p1_0,
  133869. 3,
  133870. 3
  133871. };
  133872. static static_codebook _44c8_s_p1_0 = {
  133873. 4, 81,
  133874. _vq_lengthlist__44c8_s_p1_0,
  133875. 1, -535822336, 1611661312, 2, 0,
  133876. _vq_quantlist__44c8_s_p1_0,
  133877. NULL,
  133878. &_vq_auxt__44c8_s_p1_0,
  133879. NULL,
  133880. 0
  133881. };
  133882. static long _vq_quantlist__44c8_s_p2_0[] = {
  133883. 2,
  133884. 1,
  133885. 3,
  133886. 0,
  133887. 4,
  133888. };
  133889. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133890. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133891. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133892. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133893. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133894. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133895. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133896. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133897. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133899. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133900. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133901. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133902. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133903. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133904. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133905. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133907. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133908. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133909. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133910. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133911. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133912. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133913. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133915. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133916. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133917. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133918. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133919. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133920. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133921. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133926. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133927. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133928. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133929. 13,
  133930. };
  133931. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133932. -1.5, -0.5, 0.5, 1.5,
  133933. };
  133934. static long _vq_quantmap__44c8_s_p2_0[] = {
  133935. 3, 1, 0, 2, 4,
  133936. };
  133937. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133938. _vq_quantthresh__44c8_s_p2_0,
  133939. _vq_quantmap__44c8_s_p2_0,
  133940. 5,
  133941. 5
  133942. };
  133943. static static_codebook _44c8_s_p2_0 = {
  133944. 4, 625,
  133945. _vq_lengthlist__44c8_s_p2_0,
  133946. 1, -533725184, 1611661312, 3, 0,
  133947. _vq_quantlist__44c8_s_p2_0,
  133948. NULL,
  133949. &_vq_auxt__44c8_s_p2_0,
  133950. NULL,
  133951. 0
  133952. };
  133953. static long _vq_quantlist__44c8_s_p3_0[] = {
  133954. 4,
  133955. 3,
  133956. 5,
  133957. 2,
  133958. 6,
  133959. 1,
  133960. 7,
  133961. 0,
  133962. 8,
  133963. };
  133964. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133965. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133966. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133967. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133968. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133970. 0,
  133971. };
  133972. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133973. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133974. };
  133975. static long _vq_quantmap__44c8_s_p3_0[] = {
  133976. 7, 5, 3, 1, 0, 2, 4, 6,
  133977. 8,
  133978. };
  133979. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133980. _vq_quantthresh__44c8_s_p3_0,
  133981. _vq_quantmap__44c8_s_p3_0,
  133982. 9,
  133983. 9
  133984. };
  133985. static static_codebook _44c8_s_p3_0 = {
  133986. 2, 81,
  133987. _vq_lengthlist__44c8_s_p3_0,
  133988. 1, -531628032, 1611661312, 4, 0,
  133989. _vq_quantlist__44c8_s_p3_0,
  133990. NULL,
  133991. &_vq_auxt__44c8_s_p3_0,
  133992. NULL,
  133993. 0
  133994. };
  133995. static long _vq_quantlist__44c8_s_p4_0[] = {
  133996. 8,
  133997. 7,
  133998. 9,
  133999. 6,
  134000. 10,
  134001. 5,
  134002. 11,
  134003. 4,
  134004. 12,
  134005. 3,
  134006. 13,
  134007. 2,
  134008. 14,
  134009. 1,
  134010. 15,
  134011. 0,
  134012. 16,
  134013. };
  134014. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134015. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134016. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134017. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134018. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134019. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134020. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134021. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134022. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134023. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134024. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134033. 0,
  134034. };
  134035. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134036. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134037. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134038. };
  134039. static long _vq_quantmap__44c8_s_p4_0[] = {
  134040. 15, 13, 11, 9, 7, 5, 3, 1,
  134041. 0, 2, 4, 6, 8, 10, 12, 14,
  134042. 16,
  134043. };
  134044. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134045. _vq_quantthresh__44c8_s_p4_0,
  134046. _vq_quantmap__44c8_s_p4_0,
  134047. 17,
  134048. 17
  134049. };
  134050. static static_codebook _44c8_s_p4_0 = {
  134051. 2, 289,
  134052. _vq_lengthlist__44c8_s_p4_0,
  134053. 1, -529530880, 1611661312, 5, 0,
  134054. _vq_quantlist__44c8_s_p4_0,
  134055. NULL,
  134056. &_vq_auxt__44c8_s_p4_0,
  134057. NULL,
  134058. 0
  134059. };
  134060. static long _vq_quantlist__44c8_s_p5_0[] = {
  134061. 1,
  134062. 0,
  134063. 2,
  134064. };
  134065. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134066. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134067. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134068. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134069. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134070. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134071. 12,
  134072. };
  134073. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134074. -5.5, 5.5,
  134075. };
  134076. static long _vq_quantmap__44c8_s_p5_0[] = {
  134077. 1, 0, 2,
  134078. };
  134079. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134080. _vq_quantthresh__44c8_s_p5_0,
  134081. _vq_quantmap__44c8_s_p5_0,
  134082. 3,
  134083. 3
  134084. };
  134085. static static_codebook _44c8_s_p5_0 = {
  134086. 4, 81,
  134087. _vq_lengthlist__44c8_s_p5_0,
  134088. 1, -529137664, 1618345984, 2, 0,
  134089. _vq_quantlist__44c8_s_p5_0,
  134090. NULL,
  134091. &_vq_auxt__44c8_s_p5_0,
  134092. NULL,
  134093. 0
  134094. };
  134095. static long _vq_quantlist__44c8_s_p5_1[] = {
  134096. 5,
  134097. 4,
  134098. 6,
  134099. 3,
  134100. 7,
  134101. 2,
  134102. 8,
  134103. 1,
  134104. 9,
  134105. 0,
  134106. 10,
  134107. };
  134108. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134109. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134110. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134111. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134112. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134113. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134114. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134115. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134116. 11,11,11, 7, 7, 7, 7, 8, 8,
  134117. };
  134118. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134119. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134120. 3.5, 4.5,
  134121. };
  134122. static long _vq_quantmap__44c8_s_p5_1[] = {
  134123. 9, 7, 5, 3, 1, 0, 2, 4,
  134124. 6, 8, 10,
  134125. };
  134126. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134127. _vq_quantthresh__44c8_s_p5_1,
  134128. _vq_quantmap__44c8_s_p5_1,
  134129. 11,
  134130. 11
  134131. };
  134132. static static_codebook _44c8_s_p5_1 = {
  134133. 2, 121,
  134134. _vq_lengthlist__44c8_s_p5_1,
  134135. 1, -531365888, 1611661312, 4, 0,
  134136. _vq_quantlist__44c8_s_p5_1,
  134137. NULL,
  134138. &_vq_auxt__44c8_s_p5_1,
  134139. NULL,
  134140. 0
  134141. };
  134142. static long _vq_quantlist__44c8_s_p6_0[] = {
  134143. 6,
  134144. 5,
  134145. 7,
  134146. 4,
  134147. 8,
  134148. 3,
  134149. 9,
  134150. 2,
  134151. 10,
  134152. 1,
  134153. 11,
  134154. 0,
  134155. 12,
  134156. };
  134157. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134158. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134159. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134160. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134161. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134162. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134163. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134168. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134169. };
  134170. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134171. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134172. 12.5, 17.5, 22.5, 27.5,
  134173. };
  134174. static long _vq_quantmap__44c8_s_p6_0[] = {
  134175. 11, 9, 7, 5, 3, 1, 0, 2,
  134176. 4, 6, 8, 10, 12,
  134177. };
  134178. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134179. _vq_quantthresh__44c8_s_p6_0,
  134180. _vq_quantmap__44c8_s_p6_0,
  134181. 13,
  134182. 13
  134183. };
  134184. static static_codebook _44c8_s_p6_0 = {
  134185. 2, 169,
  134186. _vq_lengthlist__44c8_s_p6_0,
  134187. 1, -526516224, 1616117760, 4, 0,
  134188. _vq_quantlist__44c8_s_p6_0,
  134189. NULL,
  134190. &_vq_auxt__44c8_s_p6_0,
  134191. NULL,
  134192. 0
  134193. };
  134194. static long _vq_quantlist__44c8_s_p6_1[] = {
  134195. 2,
  134196. 1,
  134197. 3,
  134198. 0,
  134199. 4,
  134200. };
  134201. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134202. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134203. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134204. };
  134205. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134206. -1.5, -0.5, 0.5, 1.5,
  134207. };
  134208. static long _vq_quantmap__44c8_s_p6_1[] = {
  134209. 3, 1, 0, 2, 4,
  134210. };
  134211. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134212. _vq_quantthresh__44c8_s_p6_1,
  134213. _vq_quantmap__44c8_s_p6_1,
  134214. 5,
  134215. 5
  134216. };
  134217. static static_codebook _44c8_s_p6_1 = {
  134218. 2, 25,
  134219. _vq_lengthlist__44c8_s_p6_1,
  134220. 1, -533725184, 1611661312, 3, 0,
  134221. _vq_quantlist__44c8_s_p6_1,
  134222. NULL,
  134223. &_vq_auxt__44c8_s_p6_1,
  134224. NULL,
  134225. 0
  134226. };
  134227. static long _vq_quantlist__44c8_s_p7_0[] = {
  134228. 6,
  134229. 5,
  134230. 7,
  134231. 4,
  134232. 8,
  134233. 3,
  134234. 9,
  134235. 2,
  134236. 10,
  134237. 1,
  134238. 11,
  134239. 0,
  134240. 12,
  134241. };
  134242. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134243. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134244. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134245. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134246. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134247. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134248. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134249. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134250. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134251. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134252. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134253. 20,13,13,13,13,14,13,15,15,
  134254. };
  134255. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134256. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134257. 27.5, 38.5, 49.5, 60.5,
  134258. };
  134259. static long _vq_quantmap__44c8_s_p7_0[] = {
  134260. 11, 9, 7, 5, 3, 1, 0, 2,
  134261. 4, 6, 8, 10, 12,
  134262. };
  134263. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134264. _vq_quantthresh__44c8_s_p7_0,
  134265. _vq_quantmap__44c8_s_p7_0,
  134266. 13,
  134267. 13
  134268. };
  134269. static static_codebook _44c8_s_p7_0 = {
  134270. 2, 169,
  134271. _vq_lengthlist__44c8_s_p7_0,
  134272. 1, -523206656, 1618345984, 4, 0,
  134273. _vq_quantlist__44c8_s_p7_0,
  134274. NULL,
  134275. &_vq_auxt__44c8_s_p7_0,
  134276. NULL,
  134277. 0
  134278. };
  134279. static long _vq_quantlist__44c8_s_p7_1[] = {
  134280. 5,
  134281. 4,
  134282. 6,
  134283. 3,
  134284. 7,
  134285. 2,
  134286. 8,
  134287. 1,
  134288. 9,
  134289. 0,
  134290. 10,
  134291. };
  134292. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134293. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134294. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134295. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134296. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134297. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134298. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134299. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134300. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134301. };
  134302. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134303. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134304. 3.5, 4.5,
  134305. };
  134306. static long _vq_quantmap__44c8_s_p7_1[] = {
  134307. 9, 7, 5, 3, 1, 0, 2, 4,
  134308. 6, 8, 10,
  134309. };
  134310. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134311. _vq_quantthresh__44c8_s_p7_1,
  134312. _vq_quantmap__44c8_s_p7_1,
  134313. 11,
  134314. 11
  134315. };
  134316. static static_codebook _44c8_s_p7_1 = {
  134317. 2, 121,
  134318. _vq_lengthlist__44c8_s_p7_1,
  134319. 1, -531365888, 1611661312, 4, 0,
  134320. _vq_quantlist__44c8_s_p7_1,
  134321. NULL,
  134322. &_vq_auxt__44c8_s_p7_1,
  134323. NULL,
  134324. 0
  134325. };
  134326. static long _vq_quantlist__44c8_s_p8_0[] = {
  134327. 7,
  134328. 6,
  134329. 8,
  134330. 5,
  134331. 9,
  134332. 4,
  134333. 10,
  134334. 3,
  134335. 11,
  134336. 2,
  134337. 12,
  134338. 1,
  134339. 13,
  134340. 0,
  134341. 14,
  134342. };
  134343. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134344. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134345. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134346. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134347. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134348. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134349. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134350. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134351. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134352. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134353. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134354. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134355. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134356. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134357. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134358. 15,
  134359. };
  134360. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134361. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134362. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134363. };
  134364. static long _vq_quantmap__44c8_s_p8_0[] = {
  134365. 13, 11, 9, 7, 5, 3, 1, 0,
  134366. 2, 4, 6, 8, 10, 12, 14,
  134367. };
  134368. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134369. _vq_quantthresh__44c8_s_p8_0,
  134370. _vq_quantmap__44c8_s_p8_0,
  134371. 15,
  134372. 15
  134373. };
  134374. static static_codebook _44c8_s_p8_0 = {
  134375. 2, 225,
  134376. _vq_lengthlist__44c8_s_p8_0,
  134377. 1, -520986624, 1620377600, 4, 0,
  134378. _vq_quantlist__44c8_s_p8_0,
  134379. NULL,
  134380. &_vq_auxt__44c8_s_p8_0,
  134381. NULL,
  134382. 0
  134383. };
  134384. static long _vq_quantlist__44c8_s_p8_1[] = {
  134385. 10,
  134386. 9,
  134387. 11,
  134388. 8,
  134389. 12,
  134390. 7,
  134391. 13,
  134392. 6,
  134393. 14,
  134394. 5,
  134395. 15,
  134396. 4,
  134397. 16,
  134398. 3,
  134399. 17,
  134400. 2,
  134401. 18,
  134402. 1,
  134403. 19,
  134404. 0,
  134405. 20,
  134406. };
  134407. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134408. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134409. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134410. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134411. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134412. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134413. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134414. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134415. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134416. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134417. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134418. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134419. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134420. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134421. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134422. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134423. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134424. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134425. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134426. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134427. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134428. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134429. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134430. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134431. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134432. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134433. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134434. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134435. 10, 9, 9,10,10, 9,10, 9, 9,
  134436. };
  134437. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134438. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134439. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134440. 6.5, 7.5, 8.5, 9.5,
  134441. };
  134442. static long _vq_quantmap__44c8_s_p8_1[] = {
  134443. 19, 17, 15, 13, 11, 9, 7, 5,
  134444. 3, 1, 0, 2, 4, 6, 8, 10,
  134445. 12, 14, 16, 18, 20,
  134446. };
  134447. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134448. _vq_quantthresh__44c8_s_p8_1,
  134449. _vq_quantmap__44c8_s_p8_1,
  134450. 21,
  134451. 21
  134452. };
  134453. static static_codebook _44c8_s_p8_1 = {
  134454. 2, 441,
  134455. _vq_lengthlist__44c8_s_p8_1,
  134456. 1, -529268736, 1611661312, 5, 0,
  134457. _vq_quantlist__44c8_s_p8_1,
  134458. NULL,
  134459. &_vq_auxt__44c8_s_p8_1,
  134460. NULL,
  134461. 0
  134462. };
  134463. static long _vq_quantlist__44c8_s_p9_0[] = {
  134464. 8,
  134465. 7,
  134466. 9,
  134467. 6,
  134468. 10,
  134469. 5,
  134470. 11,
  134471. 4,
  134472. 12,
  134473. 3,
  134474. 13,
  134475. 2,
  134476. 14,
  134477. 1,
  134478. 15,
  134479. 0,
  134480. 16,
  134481. };
  134482. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134483. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134484. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134485. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134497. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134498. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134499. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134500. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134501. 10,
  134502. };
  134503. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134504. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134505. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134506. };
  134507. static long _vq_quantmap__44c8_s_p9_0[] = {
  134508. 15, 13, 11, 9, 7, 5, 3, 1,
  134509. 0, 2, 4, 6, 8, 10, 12, 14,
  134510. 16,
  134511. };
  134512. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134513. _vq_quantthresh__44c8_s_p9_0,
  134514. _vq_quantmap__44c8_s_p9_0,
  134515. 17,
  134516. 17
  134517. };
  134518. static static_codebook _44c8_s_p9_0 = {
  134519. 2, 289,
  134520. _vq_lengthlist__44c8_s_p9_0,
  134521. 1, -509798400, 1631393792, 5, 0,
  134522. _vq_quantlist__44c8_s_p9_0,
  134523. NULL,
  134524. &_vq_auxt__44c8_s_p9_0,
  134525. NULL,
  134526. 0
  134527. };
  134528. static long _vq_quantlist__44c8_s_p9_1[] = {
  134529. 9,
  134530. 8,
  134531. 10,
  134532. 7,
  134533. 11,
  134534. 6,
  134535. 12,
  134536. 5,
  134537. 13,
  134538. 4,
  134539. 14,
  134540. 3,
  134541. 15,
  134542. 2,
  134543. 16,
  134544. 1,
  134545. 17,
  134546. 0,
  134547. 18,
  134548. };
  134549. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134550. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134551. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134552. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134553. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134554. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134555. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134556. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134557. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134558. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134559. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134560. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134561. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134562. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134563. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134564. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134565. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134566. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134567. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134568. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134569. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134570. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134571. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134572. 14,13,13,14,14,15,14,15,14,
  134573. };
  134574. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134575. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134576. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134577. 367.5, 416.5,
  134578. };
  134579. static long _vq_quantmap__44c8_s_p9_1[] = {
  134580. 17, 15, 13, 11, 9, 7, 5, 3,
  134581. 1, 0, 2, 4, 6, 8, 10, 12,
  134582. 14, 16, 18,
  134583. };
  134584. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134585. _vq_quantthresh__44c8_s_p9_1,
  134586. _vq_quantmap__44c8_s_p9_1,
  134587. 19,
  134588. 19
  134589. };
  134590. static static_codebook _44c8_s_p9_1 = {
  134591. 2, 361,
  134592. _vq_lengthlist__44c8_s_p9_1,
  134593. 1, -518287360, 1622704128, 5, 0,
  134594. _vq_quantlist__44c8_s_p9_1,
  134595. NULL,
  134596. &_vq_auxt__44c8_s_p9_1,
  134597. NULL,
  134598. 0
  134599. };
  134600. static long _vq_quantlist__44c8_s_p9_2[] = {
  134601. 24,
  134602. 23,
  134603. 25,
  134604. 22,
  134605. 26,
  134606. 21,
  134607. 27,
  134608. 20,
  134609. 28,
  134610. 19,
  134611. 29,
  134612. 18,
  134613. 30,
  134614. 17,
  134615. 31,
  134616. 16,
  134617. 32,
  134618. 15,
  134619. 33,
  134620. 14,
  134621. 34,
  134622. 13,
  134623. 35,
  134624. 12,
  134625. 36,
  134626. 11,
  134627. 37,
  134628. 10,
  134629. 38,
  134630. 9,
  134631. 39,
  134632. 8,
  134633. 40,
  134634. 7,
  134635. 41,
  134636. 6,
  134637. 42,
  134638. 5,
  134639. 43,
  134640. 4,
  134641. 44,
  134642. 3,
  134643. 45,
  134644. 2,
  134645. 46,
  134646. 1,
  134647. 47,
  134648. 0,
  134649. 48,
  134650. };
  134651. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134652. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134653. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134654. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134655. 7,
  134656. };
  134657. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134658. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134659. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134660. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134661. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134662. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134663. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134664. };
  134665. static long _vq_quantmap__44c8_s_p9_2[] = {
  134666. 47, 45, 43, 41, 39, 37, 35, 33,
  134667. 31, 29, 27, 25, 23, 21, 19, 17,
  134668. 15, 13, 11, 9, 7, 5, 3, 1,
  134669. 0, 2, 4, 6, 8, 10, 12, 14,
  134670. 16, 18, 20, 22, 24, 26, 28, 30,
  134671. 32, 34, 36, 38, 40, 42, 44, 46,
  134672. 48,
  134673. };
  134674. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134675. _vq_quantthresh__44c8_s_p9_2,
  134676. _vq_quantmap__44c8_s_p9_2,
  134677. 49,
  134678. 49
  134679. };
  134680. static static_codebook _44c8_s_p9_2 = {
  134681. 1, 49,
  134682. _vq_lengthlist__44c8_s_p9_2,
  134683. 1, -526909440, 1611661312, 6, 0,
  134684. _vq_quantlist__44c8_s_p9_2,
  134685. NULL,
  134686. &_vq_auxt__44c8_s_p9_2,
  134687. NULL,
  134688. 0
  134689. };
  134690. static long _huff_lengthlist__44c8_s_short[] = {
  134691. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134692. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134693. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134694. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134695. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134696. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134697. 10, 9,11,14,
  134698. };
  134699. static static_codebook _huff_book__44c8_s_short = {
  134700. 2, 100,
  134701. _huff_lengthlist__44c8_s_short,
  134702. 0, 0, 0, 0, 0,
  134703. NULL,
  134704. NULL,
  134705. NULL,
  134706. NULL,
  134707. 0
  134708. };
  134709. static long _huff_lengthlist__44c9_s_long[] = {
  134710. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134711. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134712. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134713. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134714. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134715. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134716. 10, 9, 8, 9,
  134717. };
  134718. static static_codebook _huff_book__44c9_s_long = {
  134719. 2, 100,
  134720. _huff_lengthlist__44c9_s_long,
  134721. 0, 0, 0, 0, 0,
  134722. NULL,
  134723. NULL,
  134724. NULL,
  134725. NULL,
  134726. 0
  134727. };
  134728. static long _vq_quantlist__44c9_s_p1_0[] = {
  134729. 1,
  134730. 0,
  134731. 2,
  134732. };
  134733. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134734. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134735. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134736. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134737. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134738. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134739. 7,
  134740. };
  134741. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134742. -0.5, 0.5,
  134743. };
  134744. static long _vq_quantmap__44c9_s_p1_0[] = {
  134745. 1, 0, 2,
  134746. };
  134747. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134748. _vq_quantthresh__44c9_s_p1_0,
  134749. _vq_quantmap__44c9_s_p1_0,
  134750. 3,
  134751. 3
  134752. };
  134753. static static_codebook _44c9_s_p1_0 = {
  134754. 4, 81,
  134755. _vq_lengthlist__44c9_s_p1_0,
  134756. 1, -535822336, 1611661312, 2, 0,
  134757. _vq_quantlist__44c9_s_p1_0,
  134758. NULL,
  134759. &_vq_auxt__44c9_s_p1_0,
  134760. NULL,
  134761. 0
  134762. };
  134763. static long _vq_quantlist__44c9_s_p2_0[] = {
  134764. 2,
  134765. 1,
  134766. 3,
  134767. 0,
  134768. 4,
  134769. };
  134770. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134771. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134772. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134773. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134774. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134775. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134776. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134777. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134778. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134780. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134781. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134782. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134783. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134784. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134785. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134786. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134788. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134789. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134790. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134791. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134792. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134793. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134794. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134796. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134797. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134798. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134799. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134800. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134801. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134802. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134807. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134808. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134809. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134810. 12,
  134811. };
  134812. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134813. -1.5, -0.5, 0.5, 1.5,
  134814. };
  134815. static long _vq_quantmap__44c9_s_p2_0[] = {
  134816. 3, 1, 0, 2, 4,
  134817. };
  134818. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134819. _vq_quantthresh__44c9_s_p2_0,
  134820. _vq_quantmap__44c9_s_p2_0,
  134821. 5,
  134822. 5
  134823. };
  134824. static static_codebook _44c9_s_p2_0 = {
  134825. 4, 625,
  134826. _vq_lengthlist__44c9_s_p2_0,
  134827. 1, -533725184, 1611661312, 3, 0,
  134828. _vq_quantlist__44c9_s_p2_0,
  134829. NULL,
  134830. &_vq_auxt__44c9_s_p2_0,
  134831. NULL,
  134832. 0
  134833. };
  134834. static long _vq_quantlist__44c9_s_p3_0[] = {
  134835. 4,
  134836. 3,
  134837. 5,
  134838. 2,
  134839. 6,
  134840. 1,
  134841. 7,
  134842. 0,
  134843. 8,
  134844. };
  134845. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134846. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134847. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134848. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134849. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134851. 0,
  134852. };
  134853. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134854. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134855. };
  134856. static long _vq_quantmap__44c9_s_p3_0[] = {
  134857. 7, 5, 3, 1, 0, 2, 4, 6,
  134858. 8,
  134859. };
  134860. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134861. _vq_quantthresh__44c9_s_p3_0,
  134862. _vq_quantmap__44c9_s_p3_0,
  134863. 9,
  134864. 9
  134865. };
  134866. static static_codebook _44c9_s_p3_0 = {
  134867. 2, 81,
  134868. _vq_lengthlist__44c9_s_p3_0,
  134869. 1, -531628032, 1611661312, 4, 0,
  134870. _vq_quantlist__44c9_s_p3_0,
  134871. NULL,
  134872. &_vq_auxt__44c9_s_p3_0,
  134873. NULL,
  134874. 0
  134875. };
  134876. static long _vq_quantlist__44c9_s_p4_0[] = {
  134877. 8,
  134878. 7,
  134879. 9,
  134880. 6,
  134881. 10,
  134882. 5,
  134883. 11,
  134884. 4,
  134885. 12,
  134886. 3,
  134887. 13,
  134888. 2,
  134889. 14,
  134890. 1,
  134891. 15,
  134892. 0,
  134893. 16,
  134894. };
  134895. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134896. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134897. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134898. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134899. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134900. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134901. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134902. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134903. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134904. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134905. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134914. 0,
  134915. };
  134916. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134917. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134918. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134919. };
  134920. static long _vq_quantmap__44c9_s_p4_0[] = {
  134921. 15, 13, 11, 9, 7, 5, 3, 1,
  134922. 0, 2, 4, 6, 8, 10, 12, 14,
  134923. 16,
  134924. };
  134925. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134926. _vq_quantthresh__44c9_s_p4_0,
  134927. _vq_quantmap__44c9_s_p4_0,
  134928. 17,
  134929. 17
  134930. };
  134931. static static_codebook _44c9_s_p4_0 = {
  134932. 2, 289,
  134933. _vq_lengthlist__44c9_s_p4_0,
  134934. 1, -529530880, 1611661312, 5, 0,
  134935. _vq_quantlist__44c9_s_p4_0,
  134936. NULL,
  134937. &_vq_auxt__44c9_s_p4_0,
  134938. NULL,
  134939. 0
  134940. };
  134941. static long _vq_quantlist__44c9_s_p5_0[] = {
  134942. 1,
  134943. 0,
  134944. 2,
  134945. };
  134946. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134947. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134948. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134949. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134950. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134951. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134952. 12,
  134953. };
  134954. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134955. -5.5, 5.5,
  134956. };
  134957. static long _vq_quantmap__44c9_s_p5_0[] = {
  134958. 1, 0, 2,
  134959. };
  134960. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134961. _vq_quantthresh__44c9_s_p5_0,
  134962. _vq_quantmap__44c9_s_p5_0,
  134963. 3,
  134964. 3
  134965. };
  134966. static static_codebook _44c9_s_p5_0 = {
  134967. 4, 81,
  134968. _vq_lengthlist__44c9_s_p5_0,
  134969. 1, -529137664, 1618345984, 2, 0,
  134970. _vq_quantlist__44c9_s_p5_0,
  134971. NULL,
  134972. &_vq_auxt__44c9_s_p5_0,
  134973. NULL,
  134974. 0
  134975. };
  134976. static long _vq_quantlist__44c9_s_p5_1[] = {
  134977. 5,
  134978. 4,
  134979. 6,
  134980. 3,
  134981. 7,
  134982. 2,
  134983. 8,
  134984. 1,
  134985. 9,
  134986. 0,
  134987. 10,
  134988. };
  134989. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134990. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134991. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134992. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134993. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134994. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134995. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134996. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134997. 11,11,11, 7, 7, 7, 7, 7, 7,
  134998. };
  134999. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135000. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135001. 3.5, 4.5,
  135002. };
  135003. static long _vq_quantmap__44c9_s_p5_1[] = {
  135004. 9, 7, 5, 3, 1, 0, 2, 4,
  135005. 6, 8, 10,
  135006. };
  135007. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135008. _vq_quantthresh__44c9_s_p5_1,
  135009. _vq_quantmap__44c9_s_p5_1,
  135010. 11,
  135011. 11
  135012. };
  135013. static static_codebook _44c9_s_p5_1 = {
  135014. 2, 121,
  135015. _vq_lengthlist__44c9_s_p5_1,
  135016. 1, -531365888, 1611661312, 4, 0,
  135017. _vq_quantlist__44c9_s_p5_1,
  135018. NULL,
  135019. &_vq_auxt__44c9_s_p5_1,
  135020. NULL,
  135021. 0
  135022. };
  135023. static long _vq_quantlist__44c9_s_p6_0[] = {
  135024. 6,
  135025. 5,
  135026. 7,
  135027. 4,
  135028. 8,
  135029. 3,
  135030. 9,
  135031. 2,
  135032. 10,
  135033. 1,
  135034. 11,
  135035. 0,
  135036. 12,
  135037. };
  135038. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135039. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135040. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135041. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135042. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135043. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135044. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135049. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135050. };
  135051. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135052. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135053. 12.5, 17.5, 22.5, 27.5,
  135054. };
  135055. static long _vq_quantmap__44c9_s_p6_0[] = {
  135056. 11, 9, 7, 5, 3, 1, 0, 2,
  135057. 4, 6, 8, 10, 12,
  135058. };
  135059. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135060. _vq_quantthresh__44c9_s_p6_0,
  135061. _vq_quantmap__44c9_s_p6_0,
  135062. 13,
  135063. 13
  135064. };
  135065. static static_codebook _44c9_s_p6_0 = {
  135066. 2, 169,
  135067. _vq_lengthlist__44c9_s_p6_0,
  135068. 1, -526516224, 1616117760, 4, 0,
  135069. _vq_quantlist__44c9_s_p6_0,
  135070. NULL,
  135071. &_vq_auxt__44c9_s_p6_0,
  135072. NULL,
  135073. 0
  135074. };
  135075. static long _vq_quantlist__44c9_s_p6_1[] = {
  135076. 2,
  135077. 1,
  135078. 3,
  135079. 0,
  135080. 4,
  135081. };
  135082. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135083. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135084. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135085. };
  135086. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135087. -1.5, -0.5, 0.5, 1.5,
  135088. };
  135089. static long _vq_quantmap__44c9_s_p6_1[] = {
  135090. 3, 1, 0, 2, 4,
  135091. };
  135092. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135093. _vq_quantthresh__44c9_s_p6_1,
  135094. _vq_quantmap__44c9_s_p6_1,
  135095. 5,
  135096. 5
  135097. };
  135098. static static_codebook _44c9_s_p6_1 = {
  135099. 2, 25,
  135100. _vq_lengthlist__44c9_s_p6_1,
  135101. 1, -533725184, 1611661312, 3, 0,
  135102. _vq_quantlist__44c9_s_p6_1,
  135103. NULL,
  135104. &_vq_auxt__44c9_s_p6_1,
  135105. NULL,
  135106. 0
  135107. };
  135108. static long _vq_quantlist__44c9_s_p7_0[] = {
  135109. 6,
  135110. 5,
  135111. 7,
  135112. 4,
  135113. 8,
  135114. 3,
  135115. 9,
  135116. 2,
  135117. 10,
  135118. 1,
  135119. 11,
  135120. 0,
  135121. 12,
  135122. };
  135123. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135124. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135125. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135126. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135127. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135128. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135129. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135130. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135131. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135132. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135133. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135134. 19,12,12,12,12,13,13,14,14,
  135135. };
  135136. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135137. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135138. 27.5, 38.5, 49.5, 60.5,
  135139. };
  135140. static long _vq_quantmap__44c9_s_p7_0[] = {
  135141. 11, 9, 7, 5, 3, 1, 0, 2,
  135142. 4, 6, 8, 10, 12,
  135143. };
  135144. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135145. _vq_quantthresh__44c9_s_p7_0,
  135146. _vq_quantmap__44c9_s_p7_0,
  135147. 13,
  135148. 13
  135149. };
  135150. static static_codebook _44c9_s_p7_0 = {
  135151. 2, 169,
  135152. _vq_lengthlist__44c9_s_p7_0,
  135153. 1, -523206656, 1618345984, 4, 0,
  135154. _vq_quantlist__44c9_s_p7_0,
  135155. NULL,
  135156. &_vq_auxt__44c9_s_p7_0,
  135157. NULL,
  135158. 0
  135159. };
  135160. static long _vq_quantlist__44c9_s_p7_1[] = {
  135161. 5,
  135162. 4,
  135163. 6,
  135164. 3,
  135165. 7,
  135166. 2,
  135167. 8,
  135168. 1,
  135169. 9,
  135170. 0,
  135171. 10,
  135172. };
  135173. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135174. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135175. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135176. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135177. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135178. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135179. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135180. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135181. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135182. };
  135183. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135184. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135185. 3.5, 4.5,
  135186. };
  135187. static long _vq_quantmap__44c9_s_p7_1[] = {
  135188. 9, 7, 5, 3, 1, 0, 2, 4,
  135189. 6, 8, 10,
  135190. };
  135191. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135192. _vq_quantthresh__44c9_s_p7_1,
  135193. _vq_quantmap__44c9_s_p7_1,
  135194. 11,
  135195. 11
  135196. };
  135197. static static_codebook _44c9_s_p7_1 = {
  135198. 2, 121,
  135199. _vq_lengthlist__44c9_s_p7_1,
  135200. 1, -531365888, 1611661312, 4, 0,
  135201. _vq_quantlist__44c9_s_p7_1,
  135202. NULL,
  135203. &_vq_auxt__44c9_s_p7_1,
  135204. NULL,
  135205. 0
  135206. };
  135207. static long _vq_quantlist__44c9_s_p8_0[] = {
  135208. 7,
  135209. 6,
  135210. 8,
  135211. 5,
  135212. 9,
  135213. 4,
  135214. 10,
  135215. 3,
  135216. 11,
  135217. 2,
  135218. 12,
  135219. 1,
  135220. 13,
  135221. 0,
  135222. 14,
  135223. };
  135224. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135225. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135226. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135227. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135228. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135229. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135230. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135231. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135232. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135233. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135234. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135235. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135236. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135237. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135238. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135239. 14,
  135240. };
  135241. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135242. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135243. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135244. };
  135245. static long _vq_quantmap__44c9_s_p8_0[] = {
  135246. 13, 11, 9, 7, 5, 3, 1, 0,
  135247. 2, 4, 6, 8, 10, 12, 14,
  135248. };
  135249. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135250. _vq_quantthresh__44c9_s_p8_0,
  135251. _vq_quantmap__44c9_s_p8_0,
  135252. 15,
  135253. 15
  135254. };
  135255. static static_codebook _44c9_s_p8_0 = {
  135256. 2, 225,
  135257. _vq_lengthlist__44c9_s_p8_0,
  135258. 1, -520986624, 1620377600, 4, 0,
  135259. _vq_quantlist__44c9_s_p8_0,
  135260. NULL,
  135261. &_vq_auxt__44c9_s_p8_0,
  135262. NULL,
  135263. 0
  135264. };
  135265. static long _vq_quantlist__44c9_s_p8_1[] = {
  135266. 10,
  135267. 9,
  135268. 11,
  135269. 8,
  135270. 12,
  135271. 7,
  135272. 13,
  135273. 6,
  135274. 14,
  135275. 5,
  135276. 15,
  135277. 4,
  135278. 16,
  135279. 3,
  135280. 17,
  135281. 2,
  135282. 18,
  135283. 1,
  135284. 19,
  135285. 0,
  135286. 20,
  135287. };
  135288. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135289. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135290. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135291. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135292. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135293. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135294. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135295. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135296. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135297. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135298. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135299. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135300. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135301. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135302. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135303. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135304. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135305. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135306. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135307. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135308. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135309. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135310. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135311. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135312. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135313. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135314. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135315. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135316. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135317. };
  135318. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135319. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135320. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135321. 6.5, 7.5, 8.5, 9.5,
  135322. };
  135323. static long _vq_quantmap__44c9_s_p8_1[] = {
  135324. 19, 17, 15, 13, 11, 9, 7, 5,
  135325. 3, 1, 0, 2, 4, 6, 8, 10,
  135326. 12, 14, 16, 18, 20,
  135327. };
  135328. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135329. _vq_quantthresh__44c9_s_p8_1,
  135330. _vq_quantmap__44c9_s_p8_1,
  135331. 21,
  135332. 21
  135333. };
  135334. static static_codebook _44c9_s_p8_1 = {
  135335. 2, 441,
  135336. _vq_lengthlist__44c9_s_p8_1,
  135337. 1, -529268736, 1611661312, 5, 0,
  135338. _vq_quantlist__44c9_s_p8_1,
  135339. NULL,
  135340. &_vq_auxt__44c9_s_p8_1,
  135341. NULL,
  135342. 0
  135343. };
  135344. static long _vq_quantlist__44c9_s_p9_0[] = {
  135345. 9,
  135346. 8,
  135347. 10,
  135348. 7,
  135349. 11,
  135350. 6,
  135351. 12,
  135352. 5,
  135353. 13,
  135354. 4,
  135355. 14,
  135356. 3,
  135357. 15,
  135358. 2,
  135359. 16,
  135360. 1,
  135361. 17,
  135362. 0,
  135363. 18,
  135364. };
  135365. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135366. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135367. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135368. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135369. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135370. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135371. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135372. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135373. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135374. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135375. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135376. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135377. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135378. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135379. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135380. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135381. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135382. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135383. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135384. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135385. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135387. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135388. 11,11,11,11,11,11,11,11,11,
  135389. };
  135390. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135391. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135392. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135393. 6982.5, 7913.5,
  135394. };
  135395. static long _vq_quantmap__44c9_s_p9_0[] = {
  135396. 17, 15, 13, 11, 9, 7, 5, 3,
  135397. 1, 0, 2, 4, 6, 8, 10, 12,
  135398. 14, 16, 18,
  135399. };
  135400. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135401. _vq_quantthresh__44c9_s_p9_0,
  135402. _vq_quantmap__44c9_s_p9_0,
  135403. 19,
  135404. 19
  135405. };
  135406. static static_codebook _44c9_s_p9_0 = {
  135407. 2, 361,
  135408. _vq_lengthlist__44c9_s_p9_0,
  135409. 1, -508535424, 1631393792, 5, 0,
  135410. _vq_quantlist__44c9_s_p9_0,
  135411. NULL,
  135412. &_vq_auxt__44c9_s_p9_0,
  135413. NULL,
  135414. 0
  135415. };
  135416. static long _vq_quantlist__44c9_s_p9_1[] = {
  135417. 9,
  135418. 8,
  135419. 10,
  135420. 7,
  135421. 11,
  135422. 6,
  135423. 12,
  135424. 5,
  135425. 13,
  135426. 4,
  135427. 14,
  135428. 3,
  135429. 15,
  135430. 2,
  135431. 16,
  135432. 1,
  135433. 17,
  135434. 0,
  135435. 18,
  135436. };
  135437. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135438. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135439. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135440. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135441. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135442. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135443. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135444. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135445. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135446. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135447. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135448. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135449. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135450. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135451. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135452. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135453. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135454. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135455. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135456. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135457. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135458. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135459. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135460. 13,13,13,14,13,14,15,15,15,
  135461. };
  135462. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135463. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135464. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135465. 367.5, 416.5,
  135466. };
  135467. static long _vq_quantmap__44c9_s_p9_1[] = {
  135468. 17, 15, 13, 11, 9, 7, 5, 3,
  135469. 1, 0, 2, 4, 6, 8, 10, 12,
  135470. 14, 16, 18,
  135471. };
  135472. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135473. _vq_quantthresh__44c9_s_p9_1,
  135474. _vq_quantmap__44c9_s_p9_1,
  135475. 19,
  135476. 19
  135477. };
  135478. static static_codebook _44c9_s_p9_1 = {
  135479. 2, 361,
  135480. _vq_lengthlist__44c9_s_p9_1,
  135481. 1, -518287360, 1622704128, 5, 0,
  135482. _vq_quantlist__44c9_s_p9_1,
  135483. NULL,
  135484. &_vq_auxt__44c9_s_p9_1,
  135485. NULL,
  135486. 0
  135487. };
  135488. static long _vq_quantlist__44c9_s_p9_2[] = {
  135489. 24,
  135490. 23,
  135491. 25,
  135492. 22,
  135493. 26,
  135494. 21,
  135495. 27,
  135496. 20,
  135497. 28,
  135498. 19,
  135499. 29,
  135500. 18,
  135501. 30,
  135502. 17,
  135503. 31,
  135504. 16,
  135505. 32,
  135506. 15,
  135507. 33,
  135508. 14,
  135509. 34,
  135510. 13,
  135511. 35,
  135512. 12,
  135513. 36,
  135514. 11,
  135515. 37,
  135516. 10,
  135517. 38,
  135518. 9,
  135519. 39,
  135520. 8,
  135521. 40,
  135522. 7,
  135523. 41,
  135524. 6,
  135525. 42,
  135526. 5,
  135527. 43,
  135528. 4,
  135529. 44,
  135530. 3,
  135531. 45,
  135532. 2,
  135533. 46,
  135534. 1,
  135535. 47,
  135536. 0,
  135537. 48,
  135538. };
  135539. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135540. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135541. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135542. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135543. 7,
  135544. };
  135545. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135546. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135547. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135548. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135549. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135550. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135551. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135552. };
  135553. static long _vq_quantmap__44c9_s_p9_2[] = {
  135554. 47, 45, 43, 41, 39, 37, 35, 33,
  135555. 31, 29, 27, 25, 23, 21, 19, 17,
  135556. 15, 13, 11, 9, 7, 5, 3, 1,
  135557. 0, 2, 4, 6, 8, 10, 12, 14,
  135558. 16, 18, 20, 22, 24, 26, 28, 30,
  135559. 32, 34, 36, 38, 40, 42, 44, 46,
  135560. 48,
  135561. };
  135562. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135563. _vq_quantthresh__44c9_s_p9_2,
  135564. _vq_quantmap__44c9_s_p9_2,
  135565. 49,
  135566. 49
  135567. };
  135568. static static_codebook _44c9_s_p9_2 = {
  135569. 1, 49,
  135570. _vq_lengthlist__44c9_s_p9_2,
  135571. 1, -526909440, 1611661312, 6, 0,
  135572. _vq_quantlist__44c9_s_p9_2,
  135573. NULL,
  135574. &_vq_auxt__44c9_s_p9_2,
  135575. NULL,
  135576. 0
  135577. };
  135578. static long _huff_lengthlist__44c9_s_short[] = {
  135579. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135580. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135581. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135582. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135583. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135584. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135585. 9, 8,10,13,
  135586. };
  135587. static static_codebook _huff_book__44c9_s_short = {
  135588. 2, 100,
  135589. _huff_lengthlist__44c9_s_short,
  135590. 0, 0, 0, 0, 0,
  135591. NULL,
  135592. NULL,
  135593. NULL,
  135594. NULL,
  135595. 0
  135596. };
  135597. static long _huff_lengthlist__44c0_s_long[] = {
  135598. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135599. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135600. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135601. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135602. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135603. 12,
  135604. };
  135605. static static_codebook _huff_book__44c0_s_long = {
  135606. 2, 81,
  135607. _huff_lengthlist__44c0_s_long,
  135608. 0, 0, 0, 0, 0,
  135609. NULL,
  135610. NULL,
  135611. NULL,
  135612. NULL,
  135613. 0
  135614. };
  135615. static long _vq_quantlist__44c0_s_p1_0[] = {
  135616. 1,
  135617. 0,
  135618. 2,
  135619. };
  135620. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135621. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135622. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135626. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135627. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135631. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135632. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135667. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135672. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135677. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135712. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135713. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135717. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135718. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135722. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135723. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0,
  136032. };
  136033. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136034. -0.5, 0.5,
  136035. };
  136036. static long _vq_quantmap__44c0_s_p1_0[] = {
  136037. 1, 0, 2,
  136038. };
  136039. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136040. _vq_quantthresh__44c0_s_p1_0,
  136041. _vq_quantmap__44c0_s_p1_0,
  136042. 3,
  136043. 3
  136044. };
  136045. static static_codebook _44c0_s_p1_0 = {
  136046. 8, 6561,
  136047. _vq_lengthlist__44c0_s_p1_0,
  136048. 1, -535822336, 1611661312, 2, 0,
  136049. _vq_quantlist__44c0_s_p1_0,
  136050. NULL,
  136051. &_vq_auxt__44c0_s_p1_0,
  136052. NULL,
  136053. 0
  136054. };
  136055. static long _vq_quantlist__44c0_s_p2_0[] = {
  136056. 2,
  136057. 1,
  136058. 3,
  136059. 0,
  136060. 4,
  136061. };
  136062. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136063. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  136103. };
  136104. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136105. -1.5, -0.5, 0.5, 1.5,
  136106. };
  136107. static long _vq_quantmap__44c0_s_p2_0[] = {
  136108. 3, 1, 0, 2, 4,
  136109. };
  136110. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136111. _vq_quantthresh__44c0_s_p2_0,
  136112. _vq_quantmap__44c0_s_p2_0,
  136113. 5,
  136114. 5
  136115. };
  136116. static static_codebook _44c0_s_p2_0 = {
  136117. 4, 625,
  136118. _vq_lengthlist__44c0_s_p2_0,
  136119. 1, -533725184, 1611661312, 3, 0,
  136120. _vq_quantlist__44c0_s_p2_0,
  136121. NULL,
  136122. &_vq_auxt__44c0_s_p2_0,
  136123. NULL,
  136124. 0
  136125. };
  136126. static long _vq_quantlist__44c0_s_p3_0[] = {
  136127. 4,
  136128. 3,
  136129. 5,
  136130. 2,
  136131. 6,
  136132. 1,
  136133. 7,
  136134. 0,
  136135. 8,
  136136. };
  136137. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136138. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136139. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136140. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136141. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136142. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0,
  136144. };
  136145. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136146. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136147. };
  136148. static long _vq_quantmap__44c0_s_p3_0[] = {
  136149. 7, 5, 3, 1, 0, 2, 4, 6,
  136150. 8,
  136151. };
  136152. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136153. _vq_quantthresh__44c0_s_p3_0,
  136154. _vq_quantmap__44c0_s_p3_0,
  136155. 9,
  136156. 9
  136157. };
  136158. static static_codebook _44c0_s_p3_0 = {
  136159. 2, 81,
  136160. _vq_lengthlist__44c0_s_p3_0,
  136161. 1, -531628032, 1611661312, 4, 0,
  136162. _vq_quantlist__44c0_s_p3_0,
  136163. NULL,
  136164. &_vq_auxt__44c0_s_p3_0,
  136165. NULL,
  136166. 0
  136167. };
  136168. static long _vq_quantlist__44c0_s_p4_0[] = {
  136169. 4,
  136170. 3,
  136171. 5,
  136172. 2,
  136173. 6,
  136174. 1,
  136175. 7,
  136176. 0,
  136177. 8,
  136178. };
  136179. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136180. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136181. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136182. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136183. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136184. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136185. 10,
  136186. };
  136187. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136188. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136189. };
  136190. static long _vq_quantmap__44c0_s_p4_0[] = {
  136191. 7, 5, 3, 1, 0, 2, 4, 6,
  136192. 8,
  136193. };
  136194. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136195. _vq_quantthresh__44c0_s_p4_0,
  136196. _vq_quantmap__44c0_s_p4_0,
  136197. 9,
  136198. 9
  136199. };
  136200. static static_codebook _44c0_s_p4_0 = {
  136201. 2, 81,
  136202. _vq_lengthlist__44c0_s_p4_0,
  136203. 1, -531628032, 1611661312, 4, 0,
  136204. _vq_quantlist__44c0_s_p4_0,
  136205. NULL,
  136206. &_vq_auxt__44c0_s_p4_0,
  136207. NULL,
  136208. 0
  136209. };
  136210. static long _vq_quantlist__44c0_s_p5_0[] = {
  136211. 8,
  136212. 7,
  136213. 9,
  136214. 6,
  136215. 10,
  136216. 5,
  136217. 11,
  136218. 4,
  136219. 12,
  136220. 3,
  136221. 13,
  136222. 2,
  136223. 14,
  136224. 1,
  136225. 15,
  136226. 0,
  136227. 16,
  136228. };
  136229. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136230. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136231. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136232. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136233. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136234. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136235. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136236. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136237. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136238. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136239. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136240. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136241. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136242. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136243. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136244. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136245. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136246. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136248. 14,
  136249. };
  136250. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136251. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136252. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136253. };
  136254. static long _vq_quantmap__44c0_s_p5_0[] = {
  136255. 15, 13, 11, 9, 7, 5, 3, 1,
  136256. 0, 2, 4, 6, 8, 10, 12, 14,
  136257. 16,
  136258. };
  136259. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136260. _vq_quantthresh__44c0_s_p5_0,
  136261. _vq_quantmap__44c0_s_p5_0,
  136262. 17,
  136263. 17
  136264. };
  136265. static static_codebook _44c0_s_p5_0 = {
  136266. 2, 289,
  136267. _vq_lengthlist__44c0_s_p5_0,
  136268. 1, -529530880, 1611661312, 5, 0,
  136269. _vq_quantlist__44c0_s_p5_0,
  136270. NULL,
  136271. &_vq_auxt__44c0_s_p5_0,
  136272. NULL,
  136273. 0
  136274. };
  136275. static long _vq_quantlist__44c0_s_p6_0[] = {
  136276. 1,
  136277. 0,
  136278. 2,
  136279. };
  136280. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136281. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136282. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136283. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136284. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136285. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136286. 10,
  136287. };
  136288. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136289. -5.5, 5.5,
  136290. };
  136291. static long _vq_quantmap__44c0_s_p6_0[] = {
  136292. 1, 0, 2,
  136293. };
  136294. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136295. _vq_quantthresh__44c0_s_p6_0,
  136296. _vq_quantmap__44c0_s_p6_0,
  136297. 3,
  136298. 3
  136299. };
  136300. static static_codebook _44c0_s_p6_0 = {
  136301. 4, 81,
  136302. _vq_lengthlist__44c0_s_p6_0,
  136303. 1, -529137664, 1618345984, 2, 0,
  136304. _vq_quantlist__44c0_s_p6_0,
  136305. NULL,
  136306. &_vq_auxt__44c0_s_p6_0,
  136307. NULL,
  136308. 0
  136309. };
  136310. static long _vq_quantlist__44c0_s_p6_1[] = {
  136311. 5,
  136312. 4,
  136313. 6,
  136314. 3,
  136315. 7,
  136316. 2,
  136317. 8,
  136318. 1,
  136319. 9,
  136320. 0,
  136321. 10,
  136322. };
  136323. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136324. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136325. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136326. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136327. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136328. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136329. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136330. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136331. 10,10,10, 8, 8, 8, 8, 8, 8,
  136332. };
  136333. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136334. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136335. 3.5, 4.5,
  136336. };
  136337. static long _vq_quantmap__44c0_s_p6_1[] = {
  136338. 9, 7, 5, 3, 1, 0, 2, 4,
  136339. 6, 8, 10,
  136340. };
  136341. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136342. _vq_quantthresh__44c0_s_p6_1,
  136343. _vq_quantmap__44c0_s_p6_1,
  136344. 11,
  136345. 11
  136346. };
  136347. static static_codebook _44c0_s_p6_1 = {
  136348. 2, 121,
  136349. _vq_lengthlist__44c0_s_p6_1,
  136350. 1, -531365888, 1611661312, 4, 0,
  136351. _vq_quantlist__44c0_s_p6_1,
  136352. NULL,
  136353. &_vq_auxt__44c0_s_p6_1,
  136354. NULL,
  136355. 0
  136356. };
  136357. static long _vq_quantlist__44c0_s_p7_0[] = {
  136358. 6,
  136359. 5,
  136360. 7,
  136361. 4,
  136362. 8,
  136363. 3,
  136364. 9,
  136365. 2,
  136366. 10,
  136367. 1,
  136368. 11,
  136369. 0,
  136370. 12,
  136371. };
  136372. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136373. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136374. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136375. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136376. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136377. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136378. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136379. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136380. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136381. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136382. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136383. 0,12,12,11,11,12,12,13,13,
  136384. };
  136385. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136386. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136387. 12.5, 17.5, 22.5, 27.5,
  136388. };
  136389. static long _vq_quantmap__44c0_s_p7_0[] = {
  136390. 11, 9, 7, 5, 3, 1, 0, 2,
  136391. 4, 6, 8, 10, 12,
  136392. };
  136393. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136394. _vq_quantthresh__44c0_s_p7_0,
  136395. _vq_quantmap__44c0_s_p7_0,
  136396. 13,
  136397. 13
  136398. };
  136399. static static_codebook _44c0_s_p7_0 = {
  136400. 2, 169,
  136401. _vq_lengthlist__44c0_s_p7_0,
  136402. 1, -526516224, 1616117760, 4, 0,
  136403. _vq_quantlist__44c0_s_p7_0,
  136404. NULL,
  136405. &_vq_auxt__44c0_s_p7_0,
  136406. NULL,
  136407. 0
  136408. };
  136409. static long _vq_quantlist__44c0_s_p7_1[] = {
  136410. 2,
  136411. 1,
  136412. 3,
  136413. 0,
  136414. 4,
  136415. };
  136416. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136417. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136418. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136419. };
  136420. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136421. -1.5, -0.5, 0.5, 1.5,
  136422. };
  136423. static long _vq_quantmap__44c0_s_p7_1[] = {
  136424. 3, 1, 0, 2, 4,
  136425. };
  136426. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136427. _vq_quantthresh__44c0_s_p7_1,
  136428. _vq_quantmap__44c0_s_p7_1,
  136429. 5,
  136430. 5
  136431. };
  136432. static static_codebook _44c0_s_p7_1 = {
  136433. 2, 25,
  136434. _vq_lengthlist__44c0_s_p7_1,
  136435. 1, -533725184, 1611661312, 3, 0,
  136436. _vq_quantlist__44c0_s_p7_1,
  136437. NULL,
  136438. &_vq_auxt__44c0_s_p7_1,
  136439. NULL,
  136440. 0
  136441. };
  136442. static long _vq_quantlist__44c0_s_p8_0[] = {
  136443. 2,
  136444. 1,
  136445. 3,
  136446. 0,
  136447. 4,
  136448. };
  136449. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136450. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136451. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136452. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136453. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136454. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136455. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136456. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136457. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136458. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136459. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136460. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136461. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136462. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136463. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136464. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136465. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136467. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136470. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136471. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136472. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136473. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136474. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136475. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136476. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136477. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136478. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136479. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136480. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136481. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136482. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136483. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136489. 11,
  136490. };
  136491. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136492. -331.5, -110.5, 110.5, 331.5,
  136493. };
  136494. static long _vq_quantmap__44c0_s_p8_0[] = {
  136495. 3, 1, 0, 2, 4,
  136496. };
  136497. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136498. _vq_quantthresh__44c0_s_p8_0,
  136499. _vq_quantmap__44c0_s_p8_0,
  136500. 5,
  136501. 5
  136502. };
  136503. static static_codebook _44c0_s_p8_0 = {
  136504. 4, 625,
  136505. _vq_lengthlist__44c0_s_p8_0,
  136506. 1, -518283264, 1627103232, 3, 0,
  136507. _vq_quantlist__44c0_s_p8_0,
  136508. NULL,
  136509. &_vq_auxt__44c0_s_p8_0,
  136510. NULL,
  136511. 0
  136512. };
  136513. static long _vq_quantlist__44c0_s_p8_1[] = {
  136514. 6,
  136515. 5,
  136516. 7,
  136517. 4,
  136518. 8,
  136519. 3,
  136520. 9,
  136521. 2,
  136522. 10,
  136523. 1,
  136524. 11,
  136525. 0,
  136526. 12,
  136527. };
  136528. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136529. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136530. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136531. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136532. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136533. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136534. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136535. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136536. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136537. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136538. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136539. 16,13,13,12,12,14,14,15,13,
  136540. };
  136541. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136542. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136543. 42.5, 59.5, 76.5, 93.5,
  136544. };
  136545. static long _vq_quantmap__44c0_s_p8_1[] = {
  136546. 11, 9, 7, 5, 3, 1, 0, 2,
  136547. 4, 6, 8, 10, 12,
  136548. };
  136549. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136550. _vq_quantthresh__44c0_s_p8_1,
  136551. _vq_quantmap__44c0_s_p8_1,
  136552. 13,
  136553. 13
  136554. };
  136555. static static_codebook _44c0_s_p8_1 = {
  136556. 2, 169,
  136557. _vq_lengthlist__44c0_s_p8_1,
  136558. 1, -522616832, 1620115456, 4, 0,
  136559. _vq_quantlist__44c0_s_p8_1,
  136560. NULL,
  136561. &_vq_auxt__44c0_s_p8_1,
  136562. NULL,
  136563. 0
  136564. };
  136565. static long _vq_quantlist__44c0_s_p8_2[] = {
  136566. 8,
  136567. 7,
  136568. 9,
  136569. 6,
  136570. 10,
  136571. 5,
  136572. 11,
  136573. 4,
  136574. 12,
  136575. 3,
  136576. 13,
  136577. 2,
  136578. 14,
  136579. 1,
  136580. 15,
  136581. 0,
  136582. 16,
  136583. };
  136584. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136585. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136586. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136587. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136588. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136589. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136590. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136591. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136592. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136593. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136594. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136595. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136596. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136597. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136598. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136599. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136600. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136601. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136602. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136603. 10,
  136604. };
  136605. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136606. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136607. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136608. };
  136609. static long _vq_quantmap__44c0_s_p8_2[] = {
  136610. 15, 13, 11, 9, 7, 5, 3, 1,
  136611. 0, 2, 4, 6, 8, 10, 12, 14,
  136612. 16,
  136613. };
  136614. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136615. _vq_quantthresh__44c0_s_p8_2,
  136616. _vq_quantmap__44c0_s_p8_2,
  136617. 17,
  136618. 17
  136619. };
  136620. static static_codebook _44c0_s_p8_2 = {
  136621. 2, 289,
  136622. _vq_lengthlist__44c0_s_p8_2,
  136623. 1, -529530880, 1611661312, 5, 0,
  136624. _vq_quantlist__44c0_s_p8_2,
  136625. NULL,
  136626. &_vq_auxt__44c0_s_p8_2,
  136627. NULL,
  136628. 0
  136629. };
  136630. static long _huff_lengthlist__44c0_s_short[] = {
  136631. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136632. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136633. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136634. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136635. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136636. 12,
  136637. };
  136638. static static_codebook _huff_book__44c0_s_short = {
  136639. 2, 81,
  136640. _huff_lengthlist__44c0_s_short,
  136641. 0, 0, 0, 0, 0,
  136642. NULL,
  136643. NULL,
  136644. NULL,
  136645. NULL,
  136646. 0
  136647. };
  136648. static long _huff_lengthlist__44c0_sm_long[] = {
  136649. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136650. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136651. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136652. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136653. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136654. 13,
  136655. };
  136656. static static_codebook _huff_book__44c0_sm_long = {
  136657. 2, 81,
  136658. _huff_lengthlist__44c0_sm_long,
  136659. 0, 0, 0, 0, 0,
  136660. NULL,
  136661. NULL,
  136662. NULL,
  136663. NULL,
  136664. 0
  136665. };
  136666. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136667. 1,
  136668. 0,
  136669. 2,
  136670. };
  136671. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136672. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136673. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136677. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136678. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136682. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136683. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136718. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136723. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136728. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136763. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136764. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136768. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136769. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136773. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136774. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0,
  137083. };
  137084. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137085. -0.5, 0.5,
  137086. };
  137087. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137088. 1, 0, 2,
  137089. };
  137090. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137091. _vq_quantthresh__44c0_sm_p1_0,
  137092. _vq_quantmap__44c0_sm_p1_0,
  137093. 3,
  137094. 3
  137095. };
  137096. static static_codebook _44c0_sm_p1_0 = {
  137097. 8, 6561,
  137098. _vq_lengthlist__44c0_sm_p1_0,
  137099. 1, -535822336, 1611661312, 2, 0,
  137100. _vq_quantlist__44c0_sm_p1_0,
  137101. NULL,
  137102. &_vq_auxt__44c0_sm_p1_0,
  137103. NULL,
  137104. 0
  137105. };
  137106. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137107. 2,
  137108. 1,
  137109. 3,
  137110. 0,
  137111. 4,
  137112. };
  137113. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137114. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  137154. };
  137155. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137156. -1.5, -0.5, 0.5, 1.5,
  137157. };
  137158. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137159. 3, 1, 0, 2, 4,
  137160. };
  137161. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137162. _vq_quantthresh__44c0_sm_p2_0,
  137163. _vq_quantmap__44c0_sm_p2_0,
  137164. 5,
  137165. 5
  137166. };
  137167. static static_codebook _44c0_sm_p2_0 = {
  137168. 4, 625,
  137169. _vq_lengthlist__44c0_sm_p2_0,
  137170. 1, -533725184, 1611661312, 3, 0,
  137171. _vq_quantlist__44c0_sm_p2_0,
  137172. NULL,
  137173. &_vq_auxt__44c0_sm_p2_0,
  137174. NULL,
  137175. 0
  137176. };
  137177. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137178. 4,
  137179. 3,
  137180. 5,
  137181. 2,
  137182. 6,
  137183. 1,
  137184. 7,
  137185. 0,
  137186. 8,
  137187. };
  137188. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137189. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137190. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137191. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137192. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137193. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0,
  137195. };
  137196. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137197. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137198. };
  137199. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137200. 7, 5, 3, 1, 0, 2, 4, 6,
  137201. 8,
  137202. };
  137203. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137204. _vq_quantthresh__44c0_sm_p3_0,
  137205. _vq_quantmap__44c0_sm_p3_0,
  137206. 9,
  137207. 9
  137208. };
  137209. static static_codebook _44c0_sm_p3_0 = {
  137210. 2, 81,
  137211. _vq_lengthlist__44c0_sm_p3_0,
  137212. 1, -531628032, 1611661312, 4, 0,
  137213. _vq_quantlist__44c0_sm_p3_0,
  137214. NULL,
  137215. &_vq_auxt__44c0_sm_p3_0,
  137216. NULL,
  137217. 0
  137218. };
  137219. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137220. 4,
  137221. 3,
  137222. 5,
  137223. 2,
  137224. 6,
  137225. 1,
  137226. 7,
  137227. 0,
  137228. 8,
  137229. };
  137230. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137231. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137232. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137233. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137234. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137235. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137236. 11,
  137237. };
  137238. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137239. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137240. };
  137241. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137242. 7, 5, 3, 1, 0, 2, 4, 6,
  137243. 8,
  137244. };
  137245. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137246. _vq_quantthresh__44c0_sm_p4_0,
  137247. _vq_quantmap__44c0_sm_p4_0,
  137248. 9,
  137249. 9
  137250. };
  137251. static static_codebook _44c0_sm_p4_0 = {
  137252. 2, 81,
  137253. _vq_lengthlist__44c0_sm_p4_0,
  137254. 1, -531628032, 1611661312, 4, 0,
  137255. _vq_quantlist__44c0_sm_p4_0,
  137256. NULL,
  137257. &_vq_auxt__44c0_sm_p4_0,
  137258. NULL,
  137259. 0
  137260. };
  137261. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137262. 8,
  137263. 7,
  137264. 9,
  137265. 6,
  137266. 10,
  137267. 5,
  137268. 11,
  137269. 4,
  137270. 12,
  137271. 3,
  137272. 13,
  137273. 2,
  137274. 14,
  137275. 1,
  137276. 15,
  137277. 0,
  137278. 16,
  137279. };
  137280. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137281. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137282. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137283. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137284. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137285. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137286. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137287. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137288. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137289. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137290. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137291. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137292. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137293. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137294. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137295. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137296. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137297. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137299. 14,
  137300. };
  137301. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137302. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137303. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137304. };
  137305. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137306. 15, 13, 11, 9, 7, 5, 3, 1,
  137307. 0, 2, 4, 6, 8, 10, 12, 14,
  137308. 16,
  137309. };
  137310. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137311. _vq_quantthresh__44c0_sm_p5_0,
  137312. _vq_quantmap__44c0_sm_p5_0,
  137313. 17,
  137314. 17
  137315. };
  137316. static static_codebook _44c0_sm_p5_0 = {
  137317. 2, 289,
  137318. _vq_lengthlist__44c0_sm_p5_0,
  137319. 1, -529530880, 1611661312, 5, 0,
  137320. _vq_quantlist__44c0_sm_p5_0,
  137321. NULL,
  137322. &_vq_auxt__44c0_sm_p5_0,
  137323. NULL,
  137324. 0
  137325. };
  137326. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137327. 1,
  137328. 0,
  137329. 2,
  137330. };
  137331. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137332. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137333. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137334. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137335. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137336. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137337. 11,
  137338. };
  137339. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137340. -5.5, 5.5,
  137341. };
  137342. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137343. 1, 0, 2,
  137344. };
  137345. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137346. _vq_quantthresh__44c0_sm_p6_0,
  137347. _vq_quantmap__44c0_sm_p6_0,
  137348. 3,
  137349. 3
  137350. };
  137351. static static_codebook _44c0_sm_p6_0 = {
  137352. 4, 81,
  137353. _vq_lengthlist__44c0_sm_p6_0,
  137354. 1, -529137664, 1618345984, 2, 0,
  137355. _vq_quantlist__44c0_sm_p6_0,
  137356. NULL,
  137357. &_vq_auxt__44c0_sm_p6_0,
  137358. NULL,
  137359. 0
  137360. };
  137361. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137362. 5,
  137363. 4,
  137364. 6,
  137365. 3,
  137366. 7,
  137367. 2,
  137368. 8,
  137369. 1,
  137370. 9,
  137371. 0,
  137372. 10,
  137373. };
  137374. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137375. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137376. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137377. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137378. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137379. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137380. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137381. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137382. 10,10,10, 8, 8, 8, 8, 8, 8,
  137383. };
  137384. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137385. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137386. 3.5, 4.5,
  137387. };
  137388. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137389. 9, 7, 5, 3, 1, 0, 2, 4,
  137390. 6, 8, 10,
  137391. };
  137392. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137393. _vq_quantthresh__44c0_sm_p6_1,
  137394. _vq_quantmap__44c0_sm_p6_1,
  137395. 11,
  137396. 11
  137397. };
  137398. static static_codebook _44c0_sm_p6_1 = {
  137399. 2, 121,
  137400. _vq_lengthlist__44c0_sm_p6_1,
  137401. 1, -531365888, 1611661312, 4, 0,
  137402. _vq_quantlist__44c0_sm_p6_1,
  137403. NULL,
  137404. &_vq_auxt__44c0_sm_p6_1,
  137405. NULL,
  137406. 0
  137407. };
  137408. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137409. 6,
  137410. 5,
  137411. 7,
  137412. 4,
  137413. 8,
  137414. 3,
  137415. 9,
  137416. 2,
  137417. 10,
  137418. 1,
  137419. 11,
  137420. 0,
  137421. 12,
  137422. };
  137423. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137424. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137425. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137426. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137427. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137428. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137429. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137430. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137431. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137432. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137433. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137434. 0,12,12,11,11,13,12,14,14,
  137435. };
  137436. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137437. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137438. 12.5, 17.5, 22.5, 27.5,
  137439. };
  137440. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137441. 11, 9, 7, 5, 3, 1, 0, 2,
  137442. 4, 6, 8, 10, 12,
  137443. };
  137444. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137445. _vq_quantthresh__44c0_sm_p7_0,
  137446. _vq_quantmap__44c0_sm_p7_0,
  137447. 13,
  137448. 13
  137449. };
  137450. static static_codebook _44c0_sm_p7_0 = {
  137451. 2, 169,
  137452. _vq_lengthlist__44c0_sm_p7_0,
  137453. 1, -526516224, 1616117760, 4, 0,
  137454. _vq_quantlist__44c0_sm_p7_0,
  137455. NULL,
  137456. &_vq_auxt__44c0_sm_p7_0,
  137457. NULL,
  137458. 0
  137459. };
  137460. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137461. 2,
  137462. 1,
  137463. 3,
  137464. 0,
  137465. 4,
  137466. };
  137467. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137468. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137469. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137470. };
  137471. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137472. -1.5, -0.5, 0.5, 1.5,
  137473. };
  137474. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137475. 3, 1, 0, 2, 4,
  137476. };
  137477. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137478. _vq_quantthresh__44c0_sm_p7_1,
  137479. _vq_quantmap__44c0_sm_p7_1,
  137480. 5,
  137481. 5
  137482. };
  137483. static static_codebook _44c0_sm_p7_1 = {
  137484. 2, 25,
  137485. _vq_lengthlist__44c0_sm_p7_1,
  137486. 1, -533725184, 1611661312, 3, 0,
  137487. _vq_quantlist__44c0_sm_p7_1,
  137488. NULL,
  137489. &_vq_auxt__44c0_sm_p7_1,
  137490. NULL,
  137491. 0
  137492. };
  137493. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137494. 4,
  137495. 3,
  137496. 5,
  137497. 2,
  137498. 6,
  137499. 1,
  137500. 7,
  137501. 0,
  137502. 8,
  137503. };
  137504. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137505. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137506. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137508. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137509. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137510. 12,
  137511. };
  137512. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137513. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137514. };
  137515. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137516. 7, 5, 3, 1, 0, 2, 4, 6,
  137517. 8,
  137518. };
  137519. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137520. _vq_quantthresh__44c0_sm_p8_0,
  137521. _vq_quantmap__44c0_sm_p8_0,
  137522. 9,
  137523. 9
  137524. };
  137525. static static_codebook _44c0_sm_p8_0 = {
  137526. 2, 81,
  137527. _vq_lengthlist__44c0_sm_p8_0,
  137528. 1, -516186112, 1627103232, 4, 0,
  137529. _vq_quantlist__44c0_sm_p8_0,
  137530. NULL,
  137531. &_vq_auxt__44c0_sm_p8_0,
  137532. NULL,
  137533. 0
  137534. };
  137535. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137536. 6,
  137537. 5,
  137538. 7,
  137539. 4,
  137540. 8,
  137541. 3,
  137542. 9,
  137543. 2,
  137544. 10,
  137545. 1,
  137546. 11,
  137547. 0,
  137548. 12,
  137549. };
  137550. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137551. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137552. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137553. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137554. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137555. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137556. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137557. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137558. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137559. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137560. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137561. 20,13,13,12,12,16,13,15,13,
  137562. };
  137563. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137564. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137565. 42.5, 59.5, 76.5, 93.5,
  137566. };
  137567. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137568. 11, 9, 7, 5, 3, 1, 0, 2,
  137569. 4, 6, 8, 10, 12,
  137570. };
  137571. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137572. _vq_quantthresh__44c0_sm_p8_1,
  137573. _vq_quantmap__44c0_sm_p8_1,
  137574. 13,
  137575. 13
  137576. };
  137577. static static_codebook _44c0_sm_p8_1 = {
  137578. 2, 169,
  137579. _vq_lengthlist__44c0_sm_p8_1,
  137580. 1, -522616832, 1620115456, 4, 0,
  137581. _vq_quantlist__44c0_sm_p8_1,
  137582. NULL,
  137583. &_vq_auxt__44c0_sm_p8_1,
  137584. NULL,
  137585. 0
  137586. };
  137587. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137588. 8,
  137589. 7,
  137590. 9,
  137591. 6,
  137592. 10,
  137593. 5,
  137594. 11,
  137595. 4,
  137596. 12,
  137597. 3,
  137598. 13,
  137599. 2,
  137600. 14,
  137601. 1,
  137602. 15,
  137603. 0,
  137604. 16,
  137605. };
  137606. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137607. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137608. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137609. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137610. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137611. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137612. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137613. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137614. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137615. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137616. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137617. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137618. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137619. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137620. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137621. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137622. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137623. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137624. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137625. 9,
  137626. };
  137627. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137628. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137629. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137630. };
  137631. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137632. 15, 13, 11, 9, 7, 5, 3, 1,
  137633. 0, 2, 4, 6, 8, 10, 12, 14,
  137634. 16,
  137635. };
  137636. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137637. _vq_quantthresh__44c0_sm_p8_2,
  137638. _vq_quantmap__44c0_sm_p8_2,
  137639. 17,
  137640. 17
  137641. };
  137642. static static_codebook _44c0_sm_p8_2 = {
  137643. 2, 289,
  137644. _vq_lengthlist__44c0_sm_p8_2,
  137645. 1, -529530880, 1611661312, 5, 0,
  137646. _vq_quantlist__44c0_sm_p8_2,
  137647. NULL,
  137648. &_vq_auxt__44c0_sm_p8_2,
  137649. NULL,
  137650. 0
  137651. };
  137652. static long _huff_lengthlist__44c0_sm_short[] = {
  137653. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137654. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137655. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137656. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137657. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137658. 12,
  137659. };
  137660. static static_codebook _huff_book__44c0_sm_short = {
  137661. 2, 81,
  137662. _huff_lengthlist__44c0_sm_short,
  137663. 0, 0, 0, 0, 0,
  137664. NULL,
  137665. NULL,
  137666. NULL,
  137667. NULL,
  137668. 0
  137669. };
  137670. static long _huff_lengthlist__44c1_s_long[] = {
  137671. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137672. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137673. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137674. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137675. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137676. 11,
  137677. };
  137678. static static_codebook _huff_book__44c1_s_long = {
  137679. 2, 81,
  137680. _huff_lengthlist__44c1_s_long,
  137681. 0, 0, 0, 0, 0,
  137682. NULL,
  137683. NULL,
  137684. NULL,
  137685. NULL,
  137686. 0
  137687. };
  137688. static long _vq_quantlist__44c1_s_p1_0[] = {
  137689. 1,
  137690. 0,
  137691. 2,
  137692. };
  137693. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137694. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137695. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137699. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137700. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137704. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137705. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137740. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137745. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137750. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137785. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137786. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137790. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137791. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137795. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137796. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0,
  138105. };
  138106. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138107. -0.5, 0.5,
  138108. };
  138109. static long _vq_quantmap__44c1_s_p1_0[] = {
  138110. 1, 0, 2,
  138111. };
  138112. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138113. _vq_quantthresh__44c1_s_p1_0,
  138114. _vq_quantmap__44c1_s_p1_0,
  138115. 3,
  138116. 3
  138117. };
  138118. static static_codebook _44c1_s_p1_0 = {
  138119. 8, 6561,
  138120. _vq_lengthlist__44c1_s_p1_0,
  138121. 1, -535822336, 1611661312, 2, 0,
  138122. _vq_quantlist__44c1_s_p1_0,
  138123. NULL,
  138124. &_vq_auxt__44c1_s_p1_0,
  138125. NULL,
  138126. 0
  138127. };
  138128. static long _vq_quantlist__44c1_s_p2_0[] = {
  138129. 2,
  138130. 1,
  138131. 3,
  138132. 0,
  138133. 4,
  138134. };
  138135. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138136. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  138176. };
  138177. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138178. -1.5, -0.5, 0.5, 1.5,
  138179. };
  138180. static long _vq_quantmap__44c1_s_p2_0[] = {
  138181. 3, 1, 0, 2, 4,
  138182. };
  138183. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138184. _vq_quantthresh__44c1_s_p2_0,
  138185. _vq_quantmap__44c1_s_p2_0,
  138186. 5,
  138187. 5
  138188. };
  138189. static static_codebook _44c1_s_p2_0 = {
  138190. 4, 625,
  138191. _vq_lengthlist__44c1_s_p2_0,
  138192. 1, -533725184, 1611661312, 3, 0,
  138193. _vq_quantlist__44c1_s_p2_0,
  138194. NULL,
  138195. &_vq_auxt__44c1_s_p2_0,
  138196. NULL,
  138197. 0
  138198. };
  138199. static long _vq_quantlist__44c1_s_p3_0[] = {
  138200. 4,
  138201. 3,
  138202. 5,
  138203. 2,
  138204. 6,
  138205. 1,
  138206. 7,
  138207. 0,
  138208. 8,
  138209. };
  138210. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138211. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138212. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138213. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138214. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138215. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0,
  138217. };
  138218. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138219. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138220. };
  138221. static long _vq_quantmap__44c1_s_p3_0[] = {
  138222. 7, 5, 3, 1, 0, 2, 4, 6,
  138223. 8,
  138224. };
  138225. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138226. _vq_quantthresh__44c1_s_p3_0,
  138227. _vq_quantmap__44c1_s_p3_0,
  138228. 9,
  138229. 9
  138230. };
  138231. static static_codebook _44c1_s_p3_0 = {
  138232. 2, 81,
  138233. _vq_lengthlist__44c1_s_p3_0,
  138234. 1, -531628032, 1611661312, 4, 0,
  138235. _vq_quantlist__44c1_s_p3_0,
  138236. NULL,
  138237. &_vq_auxt__44c1_s_p3_0,
  138238. NULL,
  138239. 0
  138240. };
  138241. static long _vq_quantlist__44c1_s_p4_0[] = {
  138242. 4,
  138243. 3,
  138244. 5,
  138245. 2,
  138246. 6,
  138247. 1,
  138248. 7,
  138249. 0,
  138250. 8,
  138251. };
  138252. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138253. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138254. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138255. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138256. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138257. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138258. 11,
  138259. };
  138260. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138261. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138262. };
  138263. static long _vq_quantmap__44c1_s_p4_0[] = {
  138264. 7, 5, 3, 1, 0, 2, 4, 6,
  138265. 8,
  138266. };
  138267. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138268. _vq_quantthresh__44c1_s_p4_0,
  138269. _vq_quantmap__44c1_s_p4_0,
  138270. 9,
  138271. 9
  138272. };
  138273. static static_codebook _44c1_s_p4_0 = {
  138274. 2, 81,
  138275. _vq_lengthlist__44c1_s_p4_0,
  138276. 1, -531628032, 1611661312, 4, 0,
  138277. _vq_quantlist__44c1_s_p4_0,
  138278. NULL,
  138279. &_vq_auxt__44c1_s_p4_0,
  138280. NULL,
  138281. 0
  138282. };
  138283. static long _vq_quantlist__44c1_s_p5_0[] = {
  138284. 8,
  138285. 7,
  138286. 9,
  138287. 6,
  138288. 10,
  138289. 5,
  138290. 11,
  138291. 4,
  138292. 12,
  138293. 3,
  138294. 13,
  138295. 2,
  138296. 14,
  138297. 1,
  138298. 15,
  138299. 0,
  138300. 16,
  138301. };
  138302. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138303. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138304. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138305. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138306. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138307. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138308. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138309. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138310. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138311. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138312. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138313. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138314. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138315. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138316. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138317. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138318. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138319. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138321. 14,
  138322. };
  138323. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138324. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138325. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138326. };
  138327. static long _vq_quantmap__44c1_s_p5_0[] = {
  138328. 15, 13, 11, 9, 7, 5, 3, 1,
  138329. 0, 2, 4, 6, 8, 10, 12, 14,
  138330. 16,
  138331. };
  138332. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138333. _vq_quantthresh__44c1_s_p5_0,
  138334. _vq_quantmap__44c1_s_p5_0,
  138335. 17,
  138336. 17
  138337. };
  138338. static static_codebook _44c1_s_p5_0 = {
  138339. 2, 289,
  138340. _vq_lengthlist__44c1_s_p5_0,
  138341. 1, -529530880, 1611661312, 5, 0,
  138342. _vq_quantlist__44c1_s_p5_0,
  138343. NULL,
  138344. &_vq_auxt__44c1_s_p5_0,
  138345. NULL,
  138346. 0
  138347. };
  138348. static long _vq_quantlist__44c1_s_p6_0[] = {
  138349. 1,
  138350. 0,
  138351. 2,
  138352. };
  138353. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138354. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138355. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138356. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138357. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138358. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138359. 11,
  138360. };
  138361. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138362. -5.5, 5.5,
  138363. };
  138364. static long _vq_quantmap__44c1_s_p6_0[] = {
  138365. 1, 0, 2,
  138366. };
  138367. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138368. _vq_quantthresh__44c1_s_p6_0,
  138369. _vq_quantmap__44c1_s_p6_0,
  138370. 3,
  138371. 3
  138372. };
  138373. static static_codebook _44c1_s_p6_0 = {
  138374. 4, 81,
  138375. _vq_lengthlist__44c1_s_p6_0,
  138376. 1, -529137664, 1618345984, 2, 0,
  138377. _vq_quantlist__44c1_s_p6_0,
  138378. NULL,
  138379. &_vq_auxt__44c1_s_p6_0,
  138380. NULL,
  138381. 0
  138382. };
  138383. static long _vq_quantlist__44c1_s_p6_1[] = {
  138384. 5,
  138385. 4,
  138386. 6,
  138387. 3,
  138388. 7,
  138389. 2,
  138390. 8,
  138391. 1,
  138392. 9,
  138393. 0,
  138394. 10,
  138395. };
  138396. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138397. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138398. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138399. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138400. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138401. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138402. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138403. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138404. 10,10,10, 8, 8, 8, 8, 8, 8,
  138405. };
  138406. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138407. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138408. 3.5, 4.5,
  138409. };
  138410. static long _vq_quantmap__44c1_s_p6_1[] = {
  138411. 9, 7, 5, 3, 1, 0, 2, 4,
  138412. 6, 8, 10,
  138413. };
  138414. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138415. _vq_quantthresh__44c1_s_p6_1,
  138416. _vq_quantmap__44c1_s_p6_1,
  138417. 11,
  138418. 11
  138419. };
  138420. static static_codebook _44c1_s_p6_1 = {
  138421. 2, 121,
  138422. _vq_lengthlist__44c1_s_p6_1,
  138423. 1, -531365888, 1611661312, 4, 0,
  138424. _vq_quantlist__44c1_s_p6_1,
  138425. NULL,
  138426. &_vq_auxt__44c1_s_p6_1,
  138427. NULL,
  138428. 0
  138429. };
  138430. static long _vq_quantlist__44c1_s_p7_0[] = {
  138431. 6,
  138432. 5,
  138433. 7,
  138434. 4,
  138435. 8,
  138436. 3,
  138437. 9,
  138438. 2,
  138439. 10,
  138440. 1,
  138441. 11,
  138442. 0,
  138443. 12,
  138444. };
  138445. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138446. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138447. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138448. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138449. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138450. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138451. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138452. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138453. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138454. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138455. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138456. 0,12,11,11,11,13,10,14,13,
  138457. };
  138458. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138459. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138460. 12.5, 17.5, 22.5, 27.5,
  138461. };
  138462. static long _vq_quantmap__44c1_s_p7_0[] = {
  138463. 11, 9, 7, 5, 3, 1, 0, 2,
  138464. 4, 6, 8, 10, 12,
  138465. };
  138466. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138467. _vq_quantthresh__44c1_s_p7_0,
  138468. _vq_quantmap__44c1_s_p7_0,
  138469. 13,
  138470. 13
  138471. };
  138472. static static_codebook _44c1_s_p7_0 = {
  138473. 2, 169,
  138474. _vq_lengthlist__44c1_s_p7_0,
  138475. 1, -526516224, 1616117760, 4, 0,
  138476. _vq_quantlist__44c1_s_p7_0,
  138477. NULL,
  138478. &_vq_auxt__44c1_s_p7_0,
  138479. NULL,
  138480. 0
  138481. };
  138482. static long _vq_quantlist__44c1_s_p7_1[] = {
  138483. 2,
  138484. 1,
  138485. 3,
  138486. 0,
  138487. 4,
  138488. };
  138489. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138490. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138491. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138492. };
  138493. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138494. -1.5, -0.5, 0.5, 1.5,
  138495. };
  138496. static long _vq_quantmap__44c1_s_p7_1[] = {
  138497. 3, 1, 0, 2, 4,
  138498. };
  138499. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138500. _vq_quantthresh__44c1_s_p7_1,
  138501. _vq_quantmap__44c1_s_p7_1,
  138502. 5,
  138503. 5
  138504. };
  138505. static static_codebook _44c1_s_p7_1 = {
  138506. 2, 25,
  138507. _vq_lengthlist__44c1_s_p7_1,
  138508. 1, -533725184, 1611661312, 3, 0,
  138509. _vq_quantlist__44c1_s_p7_1,
  138510. NULL,
  138511. &_vq_auxt__44c1_s_p7_1,
  138512. NULL,
  138513. 0
  138514. };
  138515. static long _vq_quantlist__44c1_s_p8_0[] = {
  138516. 6,
  138517. 5,
  138518. 7,
  138519. 4,
  138520. 8,
  138521. 3,
  138522. 9,
  138523. 2,
  138524. 10,
  138525. 1,
  138526. 11,
  138527. 0,
  138528. 12,
  138529. };
  138530. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138531. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138532. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138533. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138534. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138535. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138536. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138537. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138538. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138539. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138540. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138541. 10,10,10,10,10,10,10,10,10,
  138542. };
  138543. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138544. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138545. 552.5, 773.5, 994.5, 1215.5,
  138546. };
  138547. static long _vq_quantmap__44c1_s_p8_0[] = {
  138548. 11, 9, 7, 5, 3, 1, 0, 2,
  138549. 4, 6, 8, 10, 12,
  138550. };
  138551. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138552. _vq_quantthresh__44c1_s_p8_0,
  138553. _vq_quantmap__44c1_s_p8_0,
  138554. 13,
  138555. 13
  138556. };
  138557. static static_codebook _44c1_s_p8_0 = {
  138558. 2, 169,
  138559. _vq_lengthlist__44c1_s_p8_0,
  138560. 1, -514541568, 1627103232, 4, 0,
  138561. _vq_quantlist__44c1_s_p8_0,
  138562. NULL,
  138563. &_vq_auxt__44c1_s_p8_0,
  138564. NULL,
  138565. 0
  138566. };
  138567. static long _vq_quantlist__44c1_s_p8_1[] = {
  138568. 6,
  138569. 5,
  138570. 7,
  138571. 4,
  138572. 8,
  138573. 3,
  138574. 9,
  138575. 2,
  138576. 10,
  138577. 1,
  138578. 11,
  138579. 0,
  138580. 12,
  138581. };
  138582. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138583. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138584. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138585. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138586. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138587. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138588. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138589. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138590. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138591. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138592. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138593. 16,13,12,12,11,14,12,15,13,
  138594. };
  138595. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138596. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138597. 42.5, 59.5, 76.5, 93.5,
  138598. };
  138599. static long _vq_quantmap__44c1_s_p8_1[] = {
  138600. 11, 9, 7, 5, 3, 1, 0, 2,
  138601. 4, 6, 8, 10, 12,
  138602. };
  138603. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138604. _vq_quantthresh__44c1_s_p8_1,
  138605. _vq_quantmap__44c1_s_p8_1,
  138606. 13,
  138607. 13
  138608. };
  138609. static static_codebook _44c1_s_p8_1 = {
  138610. 2, 169,
  138611. _vq_lengthlist__44c1_s_p8_1,
  138612. 1, -522616832, 1620115456, 4, 0,
  138613. _vq_quantlist__44c1_s_p8_1,
  138614. NULL,
  138615. &_vq_auxt__44c1_s_p8_1,
  138616. NULL,
  138617. 0
  138618. };
  138619. static long _vq_quantlist__44c1_s_p8_2[] = {
  138620. 8,
  138621. 7,
  138622. 9,
  138623. 6,
  138624. 10,
  138625. 5,
  138626. 11,
  138627. 4,
  138628. 12,
  138629. 3,
  138630. 13,
  138631. 2,
  138632. 14,
  138633. 1,
  138634. 15,
  138635. 0,
  138636. 16,
  138637. };
  138638. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138639. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138640. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138641. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138642. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138643. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138644. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138645. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138646. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138647. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138648. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138649. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138650. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138651. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138652. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138653. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138654. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138655. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138656. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138657. 9,
  138658. };
  138659. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138660. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138661. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138662. };
  138663. static long _vq_quantmap__44c1_s_p8_2[] = {
  138664. 15, 13, 11, 9, 7, 5, 3, 1,
  138665. 0, 2, 4, 6, 8, 10, 12, 14,
  138666. 16,
  138667. };
  138668. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138669. _vq_quantthresh__44c1_s_p8_2,
  138670. _vq_quantmap__44c1_s_p8_2,
  138671. 17,
  138672. 17
  138673. };
  138674. static static_codebook _44c1_s_p8_2 = {
  138675. 2, 289,
  138676. _vq_lengthlist__44c1_s_p8_2,
  138677. 1, -529530880, 1611661312, 5, 0,
  138678. _vq_quantlist__44c1_s_p8_2,
  138679. NULL,
  138680. &_vq_auxt__44c1_s_p8_2,
  138681. NULL,
  138682. 0
  138683. };
  138684. static long _huff_lengthlist__44c1_s_short[] = {
  138685. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138686. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138687. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138688. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138689. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138690. 11,
  138691. };
  138692. static static_codebook _huff_book__44c1_s_short = {
  138693. 2, 81,
  138694. _huff_lengthlist__44c1_s_short,
  138695. 0, 0, 0, 0, 0,
  138696. NULL,
  138697. NULL,
  138698. NULL,
  138699. NULL,
  138700. 0
  138701. };
  138702. static long _huff_lengthlist__44c1_sm_long[] = {
  138703. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138704. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138705. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138706. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138707. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138708. 11,
  138709. };
  138710. static static_codebook _huff_book__44c1_sm_long = {
  138711. 2, 81,
  138712. _huff_lengthlist__44c1_sm_long,
  138713. 0, 0, 0, 0, 0,
  138714. NULL,
  138715. NULL,
  138716. NULL,
  138717. NULL,
  138718. 0
  138719. };
  138720. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138721. 1,
  138722. 0,
  138723. 2,
  138724. };
  138725. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138726. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138727. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138731. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138732. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138736. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138737. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138772. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138777. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138782. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138817. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138818. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138822. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138823. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138827. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138828. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0,
  139137. };
  139138. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139139. -0.5, 0.5,
  139140. };
  139141. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139142. 1, 0, 2,
  139143. };
  139144. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139145. _vq_quantthresh__44c1_sm_p1_0,
  139146. _vq_quantmap__44c1_sm_p1_0,
  139147. 3,
  139148. 3
  139149. };
  139150. static static_codebook _44c1_sm_p1_0 = {
  139151. 8, 6561,
  139152. _vq_lengthlist__44c1_sm_p1_0,
  139153. 1, -535822336, 1611661312, 2, 0,
  139154. _vq_quantlist__44c1_sm_p1_0,
  139155. NULL,
  139156. &_vq_auxt__44c1_sm_p1_0,
  139157. NULL,
  139158. 0
  139159. };
  139160. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139161. 2,
  139162. 1,
  139163. 3,
  139164. 0,
  139165. 4,
  139166. };
  139167. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139168. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  139208. };
  139209. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139210. -1.5, -0.5, 0.5, 1.5,
  139211. };
  139212. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139213. 3, 1, 0, 2, 4,
  139214. };
  139215. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139216. _vq_quantthresh__44c1_sm_p2_0,
  139217. _vq_quantmap__44c1_sm_p2_0,
  139218. 5,
  139219. 5
  139220. };
  139221. static static_codebook _44c1_sm_p2_0 = {
  139222. 4, 625,
  139223. _vq_lengthlist__44c1_sm_p2_0,
  139224. 1, -533725184, 1611661312, 3, 0,
  139225. _vq_quantlist__44c1_sm_p2_0,
  139226. NULL,
  139227. &_vq_auxt__44c1_sm_p2_0,
  139228. NULL,
  139229. 0
  139230. };
  139231. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139232. 4,
  139233. 3,
  139234. 5,
  139235. 2,
  139236. 6,
  139237. 1,
  139238. 7,
  139239. 0,
  139240. 8,
  139241. };
  139242. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139243. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139244. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139245. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139246. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139247. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0,
  139249. };
  139250. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139251. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139252. };
  139253. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139254. 7, 5, 3, 1, 0, 2, 4, 6,
  139255. 8,
  139256. };
  139257. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139258. _vq_quantthresh__44c1_sm_p3_0,
  139259. _vq_quantmap__44c1_sm_p3_0,
  139260. 9,
  139261. 9
  139262. };
  139263. static static_codebook _44c1_sm_p3_0 = {
  139264. 2, 81,
  139265. _vq_lengthlist__44c1_sm_p3_0,
  139266. 1, -531628032, 1611661312, 4, 0,
  139267. _vq_quantlist__44c1_sm_p3_0,
  139268. NULL,
  139269. &_vq_auxt__44c1_sm_p3_0,
  139270. NULL,
  139271. 0
  139272. };
  139273. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139274. 4,
  139275. 3,
  139276. 5,
  139277. 2,
  139278. 6,
  139279. 1,
  139280. 7,
  139281. 0,
  139282. 8,
  139283. };
  139284. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139285. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139286. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139287. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139288. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139289. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139290. 11,
  139291. };
  139292. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139293. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139294. };
  139295. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139296. 7, 5, 3, 1, 0, 2, 4, 6,
  139297. 8,
  139298. };
  139299. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139300. _vq_quantthresh__44c1_sm_p4_0,
  139301. _vq_quantmap__44c1_sm_p4_0,
  139302. 9,
  139303. 9
  139304. };
  139305. static static_codebook _44c1_sm_p4_0 = {
  139306. 2, 81,
  139307. _vq_lengthlist__44c1_sm_p4_0,
  139308. 1, -531628032, 1611661312, 4, 0,
  139309. _vq_quantlist__44c1_sm_p4_0,
  139310. NULL,
  139311. &_vq_auxt__44c1_sm_p4_0,
  139312. NULL,
  139313. 0
  139314. };
  139315. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139316. 8,
  139317. 7,
  139318. 9,
  139319. 6,
  139320. 10,
  139321. 5,
  139322. 11,
  139323. 4,
  139324. 12,
  139325. 3,
  139326. 13,
  139327. 2,
  139328. 14,
  139329. 1,
  139330. 15,
  139331. 0,
  139332. 16,
  139333. };
  139334. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139335. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139336. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139337. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139338. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139339. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139340. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139341. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139342. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139343. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139344. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139345. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139346. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139347. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139348. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139349. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139350. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139351. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139353. 14,
  139354. };
  139355. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139356. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139357. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139358. };
  139359. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139360. 15, 13, 11, 9, 7, 5, 3, 1,
  139361. 0, 2, 4, 6, 8, 10, 12, 14,
  139362. 16,
  139363. };
  139364. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139365. _vq_quantthresh__44c1_sm_p5_0,
  139366. _vq_quantmap__44c1_sm_p5_0,
  139367. 17,
  139368. 17
  139369. };
  139370. static static_codebook _44c1_sm_p5_0 = {
  139371. 2, 289,
  139372. _vq_lengthlist__44c1_sm_p5_0,
  139373. 1, -529530880, 1611661312, 5, 0,
  139374. _vq_quantlist__44c1_sm_p5_0,
  139375. NULL,
  139376. &_vq_auxt__44c1_sm_p5_0,
  139377. NULL,
  139378. 0
  139379. };
  139380. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139381. 1,
  139382. 0,
  139383. 2,
  139384. };
  139385. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139386. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139387. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139388. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139389. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139390. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139391. 11,
  139392. };
  139393. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139394. -5.5, 5.5,
  139395. };
  139396. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139397. 1, 0, 2,
  139398. };
  139399. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139400. _vq_quantthresh__44c1_sm_p6_0,
  139401. _vq_quantmap__44c1_sm_p6_0,
  139402. 3,
  139403. 3
  139404. };
  139405. static static_codebook _44c1_sm_p6_0 = {
  139406. 4, 81,
  139407. _vq_lengthlist__44c1_sm_p6_0,
  139408. 1, -529137664, 1618345984, 2, 0,
  139409. _vq_quantlist__44c1_sm_p6_0,
  139410. NULL,
  139411. &_vq_auxt__44c1_sm_p6_0,
  139412. NULL,
  139413. 0
  139414. };
  139415. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139416. 5,
  139417. 4,
  139418. 6,
  139419. 3,
  139420. 7,
  139421. 2,
  139422. 8,
  139423. 1,
  139424. 9,
  139425. 0,
  139426. 10,
  139427. };
  139428. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139429. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139430. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139431. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139432. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139433. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139434. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139435. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139436. 10,10,10, 8, 8, 8, 8, 8, 8,
  139437. };
  139438. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139439. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139440. 3.5, 4.5,
  139441. };
  139442. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139443. 9, 7, 5, 3, 1, 0, 2, 4,
  139444. 6, 8, 10,
  139445. };
  139446. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139447. _vq_quantthresh__44c1_sm_p6_1,
  139448. _vq_quantmap__44c1_sm_p6_1,
  139449. 11,
  139450. 11
  139451. };
  139452. static static_codebook _44c1_sm_p6_1 = {
  139453. 2, 121,
  139454. _vq_lengthlist__44c1_sm_p6_1,
  139455. 1, -531365888, 1611661312, 4, 0,
  139456. _vq_quantlist__44c1_sm_p6_1,
  139457. NULL,
  139458. &_vq_auxt__44c1_sm_p6_1,
  139459. NULL,
  139460. 0
  139461. };
  139462. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139463. 6,
  139464. 5,
  139465. 7,
  139466. 4,
  139467. 8,
  139468. 3,
  139469. 9,
  139470. 2,
  139471. 10,
  139472. 1,
  139473. 11,
  139474. 0,
  139475. 12,
  139476. };
  139477. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139478. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139479. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139480. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139481. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139482. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139483. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139484. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139485. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139486. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139487. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139488. 0,12,12,11,11,13,12,14,13,
  139489. };
  139490. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139491. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139492. 12.5, 17.5, 22.5, 27.5,
  139493. };
  139494. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139495. 11, 9, 7, 5, 3, 1, 0, 2,
  139496. 4, 6, 8, 10, 12,
  139497. };
  139498. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139499. _vq_quantthresh__44c1_sm_p7_0,
  139500. _vq_quantmap__44c1_sm_p7_0,
  139501. 13,
  139502. 13
  139503. };
  139504. static static_codebook _44c1_sm_p7_0 = {
  139505. 2, 169,
  139506. _vq_lengthlist__44c1_sm_p7_0,
  139507. 1, -526516224, 1616117760, 4, 0,
  139508. _vq_quantlist__44c1_sm_p7_0,
  139509. NULL,
  139510. &_vq_auxt__44c1_sm_p7_0,
  139511. NULL,
  139512. 0
  139513. };
  139514. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139515. 2,
  139516. 1,
  139517. 3,
  139518. 0,
  139519. 4,
  139520. };
  139521. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139522. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139523. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139524. };
  139525. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139526. -1.5, -0.5, 0.5, 1.5,
  139527. };
  139528. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139529. 3, 1, 0, 2, 4,
  139530. };
  139531. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139532. _vq_quantthresh__44c1_sm_p7_1,
  139533. _vq_quantmap__44c1_sm_p7_1,
  139534. 5,
  139535. 5
  139536. };
  139537. static static_codebook _44c1_sm_p7_1 = {
  139538. 2, 25,
  139539. _vq_lengthlist__44c1_sm_p7_1,
  139540. 1, -533725184, 1611661312, 3, 0,
  139541. _vq_quantlist__44c1_sm_p7_1,
  139542. NULL,
  139543. &_vq_auxt__44c1_sm_p7_1,
  139544. NULL,
  139545. 0
  139546. };
  139547. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139548. 6,
  139549. 5,
  139550. 7,
  139551. 4,
  139552. 8,
  139553. 3,
  139554. 9,
  139555. 2,
  139556. 10,
  139557. 1,
  139558. 11,
  139559. 0,
  139560. 12,
  139561. };
  139562. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139563. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139564. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139565. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139566. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139567. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139568. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139569. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139570. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139571. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139572. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139573. 13,13,13,13,13,13,13,13,13,
  139574. };
  139575. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139576. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139577. 552.5, 773.5, 994.5, 1215.5,
  139578. };
  139579. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139580. 11, 9, 7, 5, 3, 1, 0, 2,
  139581. 4, 6, 8, 10, 12,
  139582. };
  139583. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139584. _vq_quantthresh__44c1_sm_p8_0,
  139585. _vq_quantmap__44c1_sm_p8_0,
  139586. 13,
  139587. 13
  139588. };
  139589. static static_codebook _44c1_sm_p8_0 = {
  139590. 2, 169,
  139591. _vq_lengthlist__44c1_sm_p8_0,
  139592. 1, -514541568, 1627103232, 4, 0,
  139593. _vq_quantlist__44c1_sm_p8_0,
  139594. NULL,
  139595. &_vq_auxt__44c1_sm_p8_0,
  139596. NULL,
  139597. 0
  139598. };
  139599. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139600. 6,
  139601. 5,
  139602. 7,
  139603. 4,
  139604. 8,
  139605. 3,
  139606. 9,
  139607. 2,
  139608. 10,
  139609. 1,
  139610. 11,
  139611. 0,
  139612. 12,
  139613. };
  139614. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139615. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139616. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139617. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139618. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139619. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139620. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139621. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139622. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139623. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139624. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139625. 20,13,12,12,12,14,12,14,13,
  139626. };
  139627. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139628. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139629. 42.5, 59.5, 76.5, 93.5,
  139630. };
  139631. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139632. 11, 9, 7, 5, 3, 1, 0, 2,
  139633. 4, 6, 8, 10, 12,
  139634. };
  139635. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139636. _vq_quantthresh__44c1_sm_p8_1,
  139637. _vq_quantmap__44c1_sm_p8_1,
  139638. 13,
  139639. 13
  139640. };
  139641. static static_codebook _44c1_sm_p8_1 = {
  139642. 2, 169,
  139643. _vq_lengthlist__44c1_sm_p8_1,
  139644. 1, -522616832, 1620115456, 4, 0,
  139645. _vq_quantlist__44c1_sm_p8_1,
  139646. NULL,
  139647. &_vq_auxt__44c1_sm_p8_1,
  139648. NULL,
  139649. 0
  139650. };
  139651. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139652. 8,
  139653. 7,
  139654. 9,
  139655. 6,
  139656. 10,
  139657. 5,
  139658. 11,
  139659. 4,
  139660. 12,
  139661. 3,
  139662. 13,
  139663. 2,
  139664. 14,
  139665. 1,
  139666. 15,
  139667. 0,
  139668. 16,
  139669. };
  139670. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139671. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139672. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139673. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139674. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139675. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139676. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139677. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139678. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139679. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139680. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139681. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139682. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139683. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139684. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139685. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139686. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139687. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139688. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139689. 9,
  139690. };
  139691. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139692. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139693. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139694. };
  139695. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139696. 15, 13, 11, 9, 7, 5, 3, 1,
  139697. 0, 2, 4, 6, 8, 10, 12, 14,
  139698. 16,
  139699. };
  139700. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139701. _vq_quantthresh__44c1_sm_p8_2,
  139702. _vq_quantmap__44c1_sm_p8_2,
  139703. 17,
  139704. 17
  139705. };
  139706. static static_codebook _44c1_sm_p8_2 = {
  139707. 2, 289,
  139708. _vq_lengthlist__44c1_sm_p8_2,
  139709. 1, -529530880, 1611661312, 5, 0,
  139710. _vq_quantlist__44c1_sm_p8_2,
  139711. NULL,
  139712. &_vq_auxt__44c1_sm_p8_2,
  139713. NULL,
  139714. 0
  139715. };
  139716. static long _huff_lengthlist__44c1_sm_short[] = {
  139717. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139718. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139719. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139720. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139721. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139722. 11,
  139723. };
  139724. static static_codebook _huff_book__44c1_sm_short = {
  139725. 2, 81,
  139726. _huff_lengthlist__44c1_sm_short,
  139727. 0, 0, 0, 0, 0,
  139728. NULL,
  139729. NULL,
  139730. NULL,
  139731. NULL,
  139732. 0
  139733. };
  139734. static long _huff_lengthlist__44cn1_s_long[] = {
  139735. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139736. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139737. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139738. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139739. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139740. 20,
  139741. };
  139742. static static_codebook _huff_book__44cn1_s_long = {
  139743. 2, 81,
  139744. _huff_lengthlist__44cn1_s_long,
  139745. 0, 0, 0, 0, 0,
  139746. NULL,
  139747. NULL,
  139748. NULL,
  139749. NULL,
  139750. 0
  139751. };
  139752. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139753. 1,
  139754. 0,
  139755. 2,
  139756. };
  139757. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139758. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139759. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139763. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139764. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139768. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139769. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139804. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139809. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139814. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139849. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139850. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139854. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139855. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139859. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139860. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0,
  140169. };
  140170. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140171. -0.5, 0.5,
  140172. };
  140173. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140174. 1, 0, 2,
  140175. };
  140176. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140177. _vq_quantthresh__44cn1_s_p1_0,
  140178. _vq_quantmap__44cn1_s_p1_0,
  140179. 3,
  140180. 3
  140181. };
  140182. static static_codebook _44cn1_s_p1_0 = {
  140183. 8, 6561,
  140184. _vq_lengthlist__44cn1_s_p1_0,
  140185. 1, -535822336, 1611661312, 2, 0,
  140186. _vq_quantlist__44cn1_s_p1_0,
  140187. NULL,
  140188. &_vq_auxt__44cn1_s_p1_0,
  140189. NULL,
  140190. 0
  140191. };
  140192. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140193. 2,
  140194. 1,
  140195. 3,
  140196. 0,
  140197. 4,
  140198. };
  140199. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140200. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  140240. };
  140241. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140242. -1.5, -0.5, 0.5, 1.5,
  140243. };
  140244. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140245. 3, 1, 0, 2, 4,
  140246. };
  140247. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140248. _vq_quantthresh__44cn1_s_p2_0,
  140249. _vq_quantmap__44cn1_s_p2_0,
  140250. 5,
  140251. 5
  140252. };
  140253. static static_codebook _44cn1_s_p2_0 = {
  140254. 4, 625,
  140255. _vq_lengthlist__44cn1_s_p2_0,
  140256. 1, -533725184, 1611661312, 3, 0,
  140257. _vq_quantlist__44cn1_s_p2_0,
  140258. NULL,
  140259. &_vq_auxt__44cn1_s_p2_0,
  140260. NULL,
  140261. 0
  140262. };
  140263. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140264. 4,
  140265. 3,
  140266. 5,
  140267. 2,
  140268. 6,
  140269. 1,
  140270. 7,
  140271. 0,
  140272. 8,
  140273. };
  140274. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140275. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140276. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140277. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140278. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140279. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0,
  140281. };
  140282. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140283. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140284. };
  140285. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140286. 7, 5, 3, 1, 0, 2, 4, 6,
  140287. 8,
  140288. };
  140289. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140290. _vq_quantthresh__44cn1_s_p3_0,
  140291. _vq_quantmap__44cn1_s_p3_0,
  140292. 9,
  140293. 9
  140294. };
  140295. static static_codebook _44cn1_s_p3_0 = {
  140296. 2, 81,
  140297. _vq_lengthlist__44cn1_s_p3_0,
  140298. 1, -531628032, 1611661312, 4, 0,
  140299. _vq_quantlist__44cn1_s_p3_0,
  140300. NULL,
  140301. &_vq_auxt__44cn1_s_p3_0,
  140302. NULL,
  140303. 0
  140304. };
  140305. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140306. 4,
  140307. 3,
  140308. 5,
  140309. 2,
  140310. 6,
  140311. 1,
  140312. 7,
  140313. 0,
  140314. 8,
  140315. };
  140316. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140317. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140318. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140319. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140320. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140321. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140322. 11,
  140323. };
  140324. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140325. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140326. };
  140327. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140328. 7, 5, 3, 1, 0, 2, 4, 6,
  140329. 8,
  140330. };
  140331. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140332. _vq_quantthresh__44cn1_s_p4_0,
  140333. _vq_quantmap__44cn1_s_p4_0,
  140334. 9,
  140335. 9
  140336. };
  140337. static static_codebook _44cn1_s_p4_0 = {
  140338. 2, 81,
  140339. _vq_lengthlist__44cn1_s_p4_0,
  140340. 1, -531628032, 1611661312, 4, 0,
  140341. _vq_quantlist__44cn1_s_p4_0,
  140342. NULL,
  140343. &_vq_auxt__44cn1_s_p4_0,
  140344. NULL,
  140345. 0
  140346. };
  140347. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140348. 8,
  140349. 7,
  140350. 9,
  140351. 6,
  140352. 10,
  140353. 5,
  140354. 11,
  140355. 4,
  140356. 12,
  140357. 3,
  140358. 13,
  140359. 2,
  140360. 14,
  140361. 1,
  140362. 15,
  140363. 0,
  140364. 16,
  140365. };
  140366. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140367. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140368. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140369. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140370. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140371. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140372. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140373. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140374. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140375. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140376. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140377. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140378. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140379. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140380. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140381. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140382. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140383. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140385. 14,
  140386. };
  140387. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140388. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140389. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140390. };
  140391. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140392. 15, 13, 11, 9, 7, 5, 3, 1,
  140393. 0, 2, 4, 6, 8, 10, 12, 14,
  140394. 16,
  140395. };
  140396. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140397. _vq_quantthresh__44cn1_s_p5_0,
  140398. _vq_quantmap__44cn1_s_p5_0,
  140399. 17,
  140400. 17
  140401. };
  140402. static static_codebook _44cn1_s_p5_0 = {
  140403. 2, 289,
  140404. _vq_lengthlist__44cn1_s_p5_0,
  140405. 1, -529530880, 1611661312, 5, 0,
  140406. _vq_quantlist__44cn1_s_p5_0,
  140407. NULL,
  140408. &_vq_auxt__44cn1_s_p5_0,
  140409. NULL,
  140410. 0
  140411. };
  140412. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140413. 1,
  140414. 0,
  140415. 2,
  140416. };
  140417. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140418. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140419. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140420. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140421. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140422. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140423. 10,
  140424. };
  140425. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140426. -5.5, 5.5,
  140427. };
  140428. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140429. 1, 0, 2,
  140430. };
  140431. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140432. _vq_quantthresh__44cn1_s_p6_0,
  140433. _vq_quantmap__44cn1_s_p6_0,
  140434. 3,
  140435. 3
  140436. };
  140437. static static_codebook _44cn1_s_p6_0 = {
  140438. 4, 81,
  140439. _vq_lengthlist__44cn1_s_p6_0,
  140440. 1, -529137664, 1618345984, 2, 0,
  140441. _vq_quantlist__44cn1_s_p6_0,
  140442. NULL,
  140443. &_vq_auxt__44cn1_s_p6_0,
  140444. NULL,
  140445. 0
  140446. };
  140447. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140448. 5,
  140449. 4,
  140450. 6,
  140451. 3,
  140452. 7,
  140453. 2,
  140454. 8,
  140455. 1,
  140456. 9,
  140457. 0,
  140458. 10,
  140459. };
  140460. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140461. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140462. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140463. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140464. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140465. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140466. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140467. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140468. 10,10,10, 9, 9, 9, 9, 9, 9,
  140469. };
  140470. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140471. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140472. 3.5, 4.5,
  140473. };
  140474. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140475. 9, 7, 5, 3, 1, 0, 2, 4,
  140476. 6, 8, 10,
  140477. };
  140478. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140479. _vq_quantthresh__44cn1_s_p6_1,
  140480. _vq_quantmap__44cn1_s_p6_1,
  140481. 11,
  140482. 11
  140483. };
  140484. static static_codebook _44cn1_s_p6_1 = {
  140485. 2, 121,
  140486. _vq_lengthlist__44cn1_s_p6_1,
  140487. 1, -531365888, 1611661312, 4, 0,
  140488. _vq_quantlist__44cn1_s_p6_1,
  140489. NULL,
  140490. &_vq_auxt__44cn1_s_p6_1,
  140491. NULL,
  140492. 0
  140493. };
  140494. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140495. 6,
  140496. 5,
  140497. 7,
  140498. 4,
  140499. 8,
  140500. 3,
  140501. 9,
  140502. 2,
  140503. 10,
  140504. 1,
  140505. 11,
  140506. 0,
  140507. 12,
  140508. };
  140509. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140510. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140511. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140512. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140513. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140514. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140515. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140516. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140517. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140518. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140519. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140520. 0,13,13,12,12,13,13,13,14,
  140521. };
  140522. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140523. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140524. 12.5, 17.5, 22.5, 27.5,
  140525. };
  140526. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140527. 11, 9, 7, 5, 3, 1, 0, 2,
  140528. 4, 6, 8, 10, 12,
  140529. };
  140530. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140531. _vq_quantthresh__44cn1_s_p7_0,
  140532. _vq_quantmap__44cn1_s_p7_0,
  140533. 13,
  140534. 13
  140535. };
  140536. static static_codebook _44cn1_s_p7_0 = {
  140537. 2, 169,
  140538. _vq_lengthlist__44cn1_s_p7_0,
  140539. 1, -526516224, 1616117760, 4, 0,
  140540. _vq_quantlist__44cn1_s_p7_0,
  140541. NULL,
  140542. &_vq_auxt__44cn1_s_p7_0,
  140543. NULL,
  140544. 0
  140545. };
  140546. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140547. 2,
  140548. 1,
  140549. 3,
  140550. 0,
  140551. 4,
  140552. };
  140553. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140554. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140555. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140556. };
  140557. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140558. -1.5, -0.5, 0.5, 1.5,
  140559. };
  140560. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140561. 3, 1, 0, 2, 4,
  140562. };
  140563. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140564. _vq_quantthresh__44cn1_s_p7_1,
  140565. _vq_quantmap__44cn1_s_p7_1,
  140566. 5,
  140567. 5
  140568. };
  140569. static static_codebook _44cn1_s_p7_1 = {
  140570. 2, 25,
  140571. _vq_lengthlist__44cn1_s_p7_1,
  140572. 1, -533725184, 1611661312, 3, 0,
  140573. _vq_quantlist__44cn1_s_p7_1,
  140574. NULL,
  140575. &_vq_auxt__44cn1_s_p7_1,
  140576. NULL,
  140577. 0
  140578. };
  140579. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140580. 2,
  140581. 1,
  140582. 3,
  140583. 0,
  140584. 4,
  140585. };
  140586. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140587. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140588. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140589. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140590. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140592. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140594. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140596. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140602. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140604. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140611. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140612. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140613. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140614. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140615. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140616. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140617. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140618. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140620. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140621. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140622. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140623. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140624. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140625. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140626. 12,
  140627. };
  140628. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140629. -331.5, -110.5, 110.5, 331.5,
  140630. };
  140631. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140632. 3, 1, 0, 2, 4,
  140633. };
  140634. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140635. _vq_quantthresh__44cn1_s_p8_0,
  140636. _vq_quantmap__44cn1_s_p8_0,
  140637. 5,
  140638. 5
  140639. };
  140640. static static_codebook _44cn1_s_p8_0 = {
  140641. 4, 625,
  140642. _vq_lengthlist__44cn1_s_p8_0,
  140643. 1, -518283264, 1627103232, 3, 0,
  140644. _vq_quantlist__44cn1_s_p8_0,
  140645. NULL,
  140646. &_vq_auxt__44cn1_s_p8_0,
  140647. NULL,
  140648. 0
  140649. };
  140650. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140651. 6,
  140652. 5,
  140653. 7,
  140654. 4,
  140655. 8,
  140656. 3,
  140657. 9,
  140658. 2,
  140659. 10,
  140660. 1,
  140661. 11,
  140662. 0,
  140663. 12,
  140664. };
  140665. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140666. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140667. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140668. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140669. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140670. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140671. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140672. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140673. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140674. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140675. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140676. 15,12,12,11,11,14,12,13,14,
  140677. };
  140678. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140679. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140680. 42.5, 59.5, 76.5, 93.5,
  140681. };
  140682. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140683. 11, 9, 7, 5, 3, 1, 0, 2,
  140684. 4, 6, 8, 10, 12,
  140685. };
  140686. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140687. _vq_quantthresh__44cn1_s_p8_1,
  140688. _vq_quantmap__44cn1_s_p8_1,
  140689. 13,
  140690. 13
  140691. };
  140692. static static_codebook _44cn1_s_p8_1 = {
  140693. 2, 169,
  140694. _vq_lengthlist__44cn1_s_p8_1,
  140695. 1, -522616832, 1620115456, 4, 0,
  140696. _vq_quantlist__44cn1_s_p8_1,
  140697. NULL,
  140698. &_vq_auxt__44cn1_s_p8_1,
  140699. NULL,
  140700. 0
  140701. };
  140702. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140703. 8,
  140704. 7,
  140705. 9,
  140706. 6,
  140707. 10,
  140708. 5,
  140709. 11,
  140710. 4,
  140711. 12,
  140712. 3,
  140713. 13,
  140714. 2,
  140715. 14,
  140716. 1,
  140717. 15,
  140718. 0,
  140719. 16,
  140720. };
  140721. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140722. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140723. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140724. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140725. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140726. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140727. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140728. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140729. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140730. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140731. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140732. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140733. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140734. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140735. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140736. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140737. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140738. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140739. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140740. 9,
  140741. };
  140742. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140743. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140744. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140745. };
  140746. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140747. 15, 13, 11, 9, 7, 5, 3, 1,
  140748. 0, 2, 4, 6, 8, 10, 12, 14,
  140749. 16,
  140750. };
  140751. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140752. _vq_quantthresh__44cn1_s_p8_2,
  140753. _vq_quantmap__44cn1_s_p8_2,
  140754. 17,
  140755. 17
  140756. };
  140757. static static_codebook _44cn1_s_p8_2 = {
  140758. 2, 289,
  140759. _vq_lengthlist__44cn1_s_p8_2,
  140760. 1, -529530880, 1611661312, 5, 0,
  140761. _vq_quantlist__44cn1_s_p8_2,
  140762. NULL,
  140763. &_vq_auxt__44cn1_s_p8_2,
  140764. NULL,
  140765. 0
  140766. };
  140767. static long _huff_lengthlist__44cn1_s_short[] = {
  140768. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140769. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140770. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140771. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140772. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140773. 10,
  140774. };
  140775. static static_codebook _huff_book__44cn1_s_short = {
  140776. 2, 81,
  140777. _huff_lengthlist__44cn1_s_short,
  140778. 0, 0, 0, 0, 0,
  140779. NULL,
  140780. NULL,
  140781. NULL,
  140782. NULL,
  140783. 0
  140784. };
  140785. static long _huff_lengthlist__44cn1_sm_long[] = {
  140786. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140787. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140788. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140789. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140790. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140791. 17,
  140792. };
  140793. static static_codebook _huff_book__44cn1_sm_long = {
  140794. 2, 81,
  140795. _huff_lengthlist__44cn1_sm_long,
  140796. 0, 0, 0, 0, 0,
  140797. NULL,
  140798. NULL,
  140799. NULL,
  140800. NULL,
  140801. 0
  140802. };
  140803. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140804. 1,
  140805. 0,
  140806. 2,
  140807. };
  140808. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140809. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140810. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140814. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140815. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140819. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140820. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140855. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140860. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140865. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140900. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140901. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140905. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140906. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140910. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140911. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0,
  141220. };
  141221. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141222. -0.5, 0.5,
  141223. };
  141224. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141225. 1, 0, 2,
  141226. };
  141227. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141228. _vq_quantthresh__44cn1_sm_p1_0,
  141229. _vq_quantmap__44cn1_sm_p1_0,
  141230. 3,
  141231. 3
  141232. };
  141233. static static_codebook _44cn1_sm_p1_0 = {
  141234. 8, 6561,
  141235. _vq_lengthlist__44cn1_sm_p1_0,
  141236. 1, -535822336, 1611661312, 2, 0,
  141237. _vq_quantlist__44cn1_sm_p1_0,
  141238. NULL,
  141239. &_vq_auxt__44cn1_sm_p1_0,
  141240. NULL,
  141241. 0
  141242. };
  141243. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141244. 2,
  141245. 1,
  141246. 3,
  141247. 0,
  141248. 4,
  141249. };
  141250. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141251. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  141291. };
  141292. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141293. -1.5, -0.5, 0.5, 1.5,
  141294. };
  141295. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141296. 3, 1, 0, 2, 4,
  141297. };
  141298. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141299. _vq_quantthresh__44cn1_sm_p2_0,
  141300. _vq_quantmap__44cn1_sm_p2_0,
  141301. 5,
  141302. 5
  141303. };
  141304. static static_codebook _44cn1_sm_p2_0 = {
  141305. 4, 625,
  141306. _vq_lengthlist__44cn1_sm_p2_0,
  141307. 1, -533725184, 1611661312, 3, 0,
  141308. _vq_quantlist__44cn1_sm_p2_0,
  141309. NULL,
  141310. &_vq_auxt__44cn1_sm_p2_0,
  141311. NULL,
  141312. 0
  141313. };
  141314. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141315. 4,
  141316. 3,
  141317. 5,
  141318. 2,
  141319. 6,
  141320. 1,
  141321. 7,
  141322. 0,
  141323. 8,
  141324. };
  141325. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141326. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141327. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141328. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141329. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141330. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0,
  141332. };
  141333. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141334. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141335. };
  141336. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141337. 7, 5, 3, 1, 0, 2, 4, 6,
  141338. 8,
  141339. };
  141340. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141341. _vq_quantthresh__44cn1_sm_p3_0,
  141342. _vq_quantmap__44cn1_sm_p3_0,
  141343. 9,
  141344. 9
  141345. };
  141346. static static_codebook _44cn1_sm_p3_0 = {
  141347. 2, 81,
  141348. _vq_lengthlist__44cn1_sm_p3_0,
  141349. 1, -531628032, 1611661312, 4, 0,
  141350. _vq_quantlist__44cn1_sm_p3_0,
  141351. NULL,
  141352. &_vq_auxt__44cn1_sm_p3_0,
  141353. NULL,
  141354. 0
  141355. };
  141356. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141357. 4,
  141358. 3,
  141359. 5,
  141360. 2,
  141361. 6,
  141362. 1,
  141363. 7,
  141364. 0,
  141365. 8,
  141366. };
  141367. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141368. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141369. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141370. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141371. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141372. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141373. 11,
  141374. };
  141375. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141376. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141377. };
  141378. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141379. 7, 5, 3, 1, 0, 2, 4, 6,
  141380. 8,
  141381. };
  141382. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141383. _vq_quantthresh__44cn1_sm_p4_0,
  141384. _vq_quantmap__44cn1_sm_p4_0,
  141385. 9,
  141386. 9
  141387. };
  141388. static static_codebook _44cn1_sm_p4_0 = {
  141389. 2, 81,
  141390. _vq_lengthlist__44cn1_sm_p4_0,
  141391. 1, -531628032, 1611661312, 4, 0,
  141392. _vq_quantlist__44cn1_sm_p4_0,
  141393. NULL,
  141394. &_vq_auxt__44cn1_sm_p4_0,
  141395. NULL,
  141396. 0
  141397. };
  141398. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141399. 8,
  141400. 7,
  141401. 9,
  141402. 6,
  141403. 10,
  141404. 5,
  141405. 11,
  141406. 4,
  141407. 12,
  141408. 3,
  141409. 13,
  141410. 2,
  141411. 14,
  141412. 1,
  141413. 15,
  141414. 0,
  141415. 16,
  141416. };
  141417. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141418. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141419. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141420. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141421. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141422. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141423. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141424. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141425. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141426. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141427. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141428. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141429. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141430. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141431. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141432. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141433. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141434. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141435. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141436. 14,
  141437. };
  141438. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141439. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141440. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141441. };
  141442. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141443. 15, 13, 11, 9, 7, 5, 3, 1,
  141444. 0, 2, 4, 6, 8, 10, 12, 14,
  141445. 16,
  141446. };
  141447. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141448. _vq_quantthresh__44cn1_sm_p5_0,
  141449. _vq_quantmap__44cn1_sm_p5_0,
  141450. 17,
  141451. 17
  141452. };
  141453. static static_codebook _44cn1_sm_p5_0 = {
  141454. 2, 289,
  141455. _vq_lengthlist__44cn1_sm_p5_0,
  141456. 1, -529530880, 1611661312, 5, 0,
  141457. _vq_quantlist__44cn1_sm_p5_0,
  141458. NULL,
  141459. &_vq_auxt__44cn1_sm_p5_0,
  141460. NULL,
  141461. 0
  141462. };
  141463. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141464. 1,
  141465. 0,
  141466. 2,
  141467. };
  141468. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141469. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141470. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141471. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141472. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141473. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141474. 10,
  141475. };
  141476. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141477. -5.5, 5.5,
  141478. };
  141479. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141480. 1, 0, 2,
  141481. };
  141482. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141483. _vq_quantthresh__44cn1_sm_p6_0,
  141484. _vq_quantmap__44cn1_sm_p6_0,
  141485. 3,
  141486. 3
  141487. };
  141488. static static_codebook _44cn1_sm_p6_0 = {
  141489. 4, 81,
  141490. _vq_lengthlist__44cn1_sm_p6_0,
  141491. 1, -529137664, 1618345984, 2, 0,
  141492. _vq_quantlist__44cn1_sm_p6_0,
  141493. NULL,
  141494. &_vq_auxt__44cn1_sm_p6_0,
  141495. NULL,
  141496. 0
  141497. };
  141498. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141499. 5,
  141500. 4,
  141501. 6,
  141502. 3,
  141503. 7,
  141504. 2,
  141505. 8,
  141506. 1,
  141507. 9,
  141508. 0,
  141509. 10,
  141510. };
  141511. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141512. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141513. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141514. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141515. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141516. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141517. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141518. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141519. 10,10,10, 8, 9, 8, 8, 9, 8,
  141520. };
  141521. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141522. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141523. 3.5, 4.5,
  141524. };
  141525. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141526. 9, 7, 5, 3, 1, 0, 2, 4,
  141527. 6, 8, 10,
  141528. };
  141529. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141530. _vq_quantthresh__44cn1_sm_p6_1,
  141531. _vq_quantmap__44cn1_sm_p6_1,
  141532. 11,
  141533. 11
  141534. };
  141535. static static_codebook _44cn1_sm_p6_1 = {
  141536. 2, 121,
  141537. _vq_lengthlist__44cn1_sm_p6_1,
  141538. 1, -531365888, 1611661312, 4, 0,
  141539. _vq_quantlist__44cn1_sm_p6_1,
  141540. NULL,
  141541. &_vq_auxt__44cn1_sm_p6_1,
  141542. NULL,
  141543. 0
  141544. };
  141545. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141546. 6,
  141547. 5,
  141548. 7,
  141549. 4,
  141550. 8,
  141551. 3,
  141552. 9,
  141553. 2,
  141554. 10,
  141555. 1,
  141556. 11,
  141557. 0,
  141558. 12,
  141559. };
  141560. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141561. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141562. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141563. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141564. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141565. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141566. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141567. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141568. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141569. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141570. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141571. 0,13,12,12,12,13,13,13,14,
  141572. };
  141573. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141574. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141575. 12.5, 17.5, 22.5, 27.5,
  141576. };
  141577. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141578. 11, 9, 7, 5, 3, 1, 0, 2,
  141579. 4, 6, 8, 10, 12,
  141580. };
  141581. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141582. _vq_quantthresh__44cn1_sm_p7_0,
  141583. _vq_quantmap__44cn1_sm_p7_0,
  141584. 13,
  141585. 13
  141586. };
  141587. static static_codebook _44cn1_sm_p7_0 = {
  141588. 2, 169,
  141589. _vq_lengthlist__44cn1_sm_p7_0,
  141590. 1, -526516224, 1616117760, 4, 0,
  141591. _vq_quantlist__44cn1_sm_p7_0,
  141592. NULL,
  141593. &_vq_auxt__44cn1_sm_p7_0,
  141594. NULL,
  141595. 0
  141596. };
  141597. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141598. 2,
  141599. 1,
  141600. 3,
  141601. 0,
  141602. 4,
  141603. };
  141604. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141605. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141606. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141607. };
  141608. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141609. -1.5, -0.5, 0.5, 1.5,
  141610. };
  141611. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141612. 3, 1, 0, 2, 4,
  141613. };
  141614. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141615. _vq_quantthresh__44cn1_sm_p7_1,
  141616. _vq_quantmap__44cn1_sm_p7_1,
  141617. 5,
  141618. 5
  141619. };
  141620. static static_codebook _44cn1_sm_p7_1 = {
  141621. 2, 25,
  141622. _vq_lengthlist__44cn1_sm_p7_1,
  141623. 1, -533725184, 1611661312, 3, 0,
  141624. _vq_quantlist__44cn1_sm_p7_1,
  141625. NULL,
  141626. &_vq_auxt__44cn1_sm_p7_1,
  141627. NULL,
  141628. 0
  141629. };
  141630. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141631. 4,
  141632. 3,
  141633. 5,
  141634. 2,
  141635. 6,
  141636. 1,
  141637. 7,
  141638. 0,
  141639. 8,
  141640. };
  141641. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141642. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141643. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141644. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141645. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141646. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141647. 14,
  141648. };
  141649. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141650. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141651. };
  141652. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141653. 7, 5, 3, 1, 0, 2, 4, 6,
  141654. 8,
  141655. };
  141656. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141657. _vq_quantthresh__44cn1_sm_p8_0,
  141658. _vq_quantmap__44cn1_sm_p8_0,
  141659. 9,
  141660. 9
  141661. };
  141662. static static_codebook _44cn1_sm_p8_0 = {
  141663. 2, 81,
  141664. _vq_lengthlist__44cn1_sm_p8_0,
  141665. 1, -516186112, 1627103232, 4, 0,
  141666. _vq_quantlist__44cn1_sm_p8_0,
  141667. NULL,
  141668. &_vq_auxt__44cn1_sm_p8_0,
  141669. NULL,
  141670. 0
  141671. };
  141672. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141673. 6,
  141674. 5,
  141675. 7,
  141676. 4,
  141677. 8,
  141678. 3,
  141679. 9,
  141680. 2,
  141681. 10,
  141682. 1,
  141683. 11,
  141684. 0,
  141685. 12,
  141686. };
  141687. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141688. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141689. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141690. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141691. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141692. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141693. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141694. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141695. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141696. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141697. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141698. 17,12,12,11,10,13,11,13,13,
  141699. };
  141700. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141701. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141702. 42.5, 59.5, 76.5, 93.5,
  141703. };
  141704. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141705. 11, 9, 7, 5, 3, 1, 0, 2,
  141706. 4, 6, 8, 10, 12,
  141707. };
  141708. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141709. _vq_quantthresh__44cn1_sm_p8_1,
  141710. _vq_quantmap__44cn1_sm_p8_1,
  141711. 13,
  141712. 13
  141713. };
  141714. static static_codebook _44cn1_sm_p8_1 = {
  141715. 2, 169,
  141716. _vq_lengthlist__44cn1_sm_p8_1,
  141717. 1, -522616832, 1620115456, 4, 0,
  141718. _vq_quantlist__44cn1_sm_p8_1,
  141719. NULL,
  141720. &_vq_auxt__44cn1_sm_p8_1,
  141721. NULL,
  141722. 0
  141723. };
  141724. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141725. 8,
  141726. 7,
  141727. 9,
  141728. 6,
  141729. 10,
  141730. 5,
  141731. 11,
  141732. 4,
  141733. 12,
  141734. 3,
  141735. 13,
  141736. 2,
  141737. 14,
  141738. 1,
  141739. 15,
  141740. 0,
  141741. 16,
  141742. };
  141743. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141744. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141745. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141746. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141747. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141748. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141749. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141750. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141751. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141752. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141753. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141754. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141755. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141756. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141757. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141758. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141759. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141760. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141761. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141762. 9,
  141763. };
  141764. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141765. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141766. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141767. };
  141768. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141769. 15, 13, 11, 9, 7, 5, 3, 1,
  141770. 0, 2, 4, 6, 8, 10, 12, 14,
  141771. 16,
  141772. };
  141773. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141774. _vq_quantthresh__44cn1_sm_p8_2,
  141775. _vq_quantmap__44cn1_sm_p8_2,
  141776. 17,
  141777. 17
  141778. };
  141779. static static_codebook _44cn1_sm_p8_2 = {
  141780. 2, 289,
  141781. _vq_lengthlist__44cn1_sm_p8_2,
  141782. 1, -529530880, 1611661312, 5, 0,
  141783. _vq_quantlist__44cn1_sm_p8_2,
  141784. NULL,
  141785. &_vq_auxt__44cn1_sm_p8_2,
  141786. NULL,
  141787. 0
  141788. };
  141789. static long _huff_lengthlist__44cn1_sm_short[] = {
  141790. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141791. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141792. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141793. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141794. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141795. 9,
  141796. };
  141797. static static_codebook _huff_book__44cn1_sm_short = {
  141798. 2, 81,
  141799. _huff_lengthlist__44cn1_sm_short,
  141800. 0, 0, 0, 0, 0,
  141801. NULL,
  141802. NULL,
  141803. NULL,
  141804. NULL,
  141805. 0
  141806. };
  141807. /*** End of inlined file: res_books_stereo.h ***/
  141808. /***** residue backends *********************************************/
  141809. static vorbis_info_residue0 _residue_44_low={
  141810. 0,-1, -1, 9,-1,
  141811. /* 0 1 2 3 4 5 6 7 */
  141812. {0},
  141813. {-1},
  141814. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141815. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141816. };
  141817. static vorbis_info_residue0 _residue_44_mid={
  141818. 0,-1, -1, 10,-1,
  141819. /* 0 1 2 3 4 5 6 7 8 */
  141820. {0},
  141821. {-1},
  141822. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141823. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141824. };
  141825. static vorbis_info_residue0 _residue_44_high={
  141826. 0,-1, -1, 10,-1,
  141827. /* 0 1 2 3 4 5 6 7 8 */
  141828. {0},
  141829. {-1},
  141830. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141831. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141832. };
  141833. static static_bookblock _resbook_44s_n1={
  141834. {
  141835. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141836. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141837. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141838. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141839. }
  141840. };
  141841. static static_bookblock _resbook_44sm_n1={
  141842. {
  141843. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141844. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141845. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141846. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141847. }
  141848. };
  141849. static static_bookblock _resbook_44s_0={
  141850. {
  141851. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141852. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141853. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141854. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141855. }
  141856. };
  141857. static static_bookblock _resbook_44sm_0={
  141858. {
  141859. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141860. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141861. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141862. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141863. }
  141864. };
  141865. static static_bookblock _resbook_44s_1={
  141866. {
  141867. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141868. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141869. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141870. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141871. }
  141872. };
  141873. static static_bookblock _resbook_44sm_1={
  141874. {
  141875. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141876. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141877. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141878. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141879. }
  141880. };
  141881. static static_bookblock _resbook_44s_2={
  141882. {
  141883. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141884. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141885. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141886. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141887. }
  141888. };
  141889. static static_bookblock _resbook_44s_3={
  141890. {
  141891. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141892. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141893. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141894. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141895. }
  141896. };
  141897. static static_bookblock _resbook_44s_4={
  141898. {
  141899. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141900. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141901. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141902. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141903. }
  141904. };
  141905. static static_bookblock _resbook_44s_5={
  141906. {
  141907. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141908. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141909. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141910. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141911. }
  141912. };
  141913. static static_bookblock _resbook_44s_6={
  141914. {
  141915. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141916. {0,0,&_44c6_s_p4_0},
  141917. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141918. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141919. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141920. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141921. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141922. }
  141923. };
  141924. static static_bookblock _resbook_44s_7={
  141925. {
  141926. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141927. {0,0,&_44c7_s_p4_0},
  141928. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141929. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141930. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141931. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141932. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141933. }
  141934. };
  141935. static static_bookblock _resbook_44s_8={
  141936. {
  141937. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141938. {0,0,&_44c8_s_p4_0},
  141939. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141940. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141941. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141942. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141943. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141944. }
  141945. };
  141946. static static_bookblock _resbook_44s_9={
  141947. {
  141948. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141949. {0,0,&_44c9_s_p4_0},
  141950. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141951. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141952. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141953. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141954. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141955. }
  141956. };
  141957. static vorbis_residue_template _res_44s_n1[]={
  141958. {2,0, &_residue_44_low,
  141959. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141960. &_resbook_44s_n1,&_resbook_44sm_n1},
  141961. {2,0, &_residue_44_low,
  141962. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141963. &_resbook_44s_n1,&_resbook_44sm_n1}
  141964. };
  141965. static vorbis_residue_template _res_44s_0[]={
  141966. {2,0, &_residue_44_low,
  141967. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141968. &_resbook_44s_0,&_resbook_44sm_0},
  141969. {2,0, &_residue_44_low,
  141970. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141971. &_resbook_44s_0,&_resbook_44sm_0}
  141972. };
  141973. static vorbis_residue_template _res_44s_1[]={
  141974. {2,0, &_residue_44_low,
  141975. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141976. &_resbook_44s_1,&_resbook_44sm_1},
  141977. {2,0, &_residue_44_low,
  141978. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141979. &_resbook_44s_1,&_resbook_44sm_1}
  141980. };
  141981. static vorbis_residue_template _res_44s_2[]={
  141982. {2,0, &_residue_44_mid,
  141983. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141984. &_resbook_44s_2,&_resbook_44s_2},
  141985. {2,0, &_residue_44_mid,
  141986. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141987. &_resbook_44s_2,&_resbook_44s_2}
  141988. };
  141989. static vorbis_residue_template _res_44s_3[]={
  141990. {2,0, &_residue_44_mid,
  141991. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141992. &_resbook_44s_3,&_resbook_44s_3},
  141993. {2,0, &_residue_44_mid,
  141994. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141995. &_resbook_44s_3,&_resbook_44s_3}
  141996. };
  141997. static vorbis_residue_template _res_44s_4[]={
  141998. {2,0, &_residue_44_mid,
  141999. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142000. &_resbook_44s_4,&_resbook_44s_4},
  142001. {2,0, &_residue_44_mid,
  142002. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142003. &_resbook_44s_4,&_resbook_44s_4}
  142004. };
  142005. static vorbis_residue_template _res_44s_5[]={
  142006. {2,0, &_residue_44_mid,
  142007. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142008. &_resbook_44s_5,&_resbook_44s_5},
  142009. {2,0, &_residue_44_mid,
  142010. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142011. &_resbook_44s_5,&_resbook_44s_5}
  142012. };
  142013. static vorbis_residue_template _res_44s_6[]={
  142014. {2,0, &_residue_44_high,
  142015. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142016. &_resbook_44s_6,&_resbook_44s_6},
  142017. {2,0, &_residue_44_high,
  142018. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142019. &_resbook_44s_6,&_resbook_44s_6}
  142020. };
  142021. static vorbis_residue_template _res_44s_7[]={
  142022. {2,0, &_residue_44_high,
  142023. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142024. &_resbook_44s_7,&_resbook_44s_7},
  142025. {2,0, &_residue_44_high,
  142026. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142027. &_resbook_44s_7,&_resbook_44s_7}
  142028. };
  142029. static vorbis_residue_template _res_44s_8[]={
  142030. {2,0, &_residue_44_high,
  142031. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142032. &_resbook_44s_8,&_resbook_44s_8},
  142033. {2,0, &_residue_44_high,
  142034. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142035. &_resbook_44s_8,&_resbook_44s_8}
  142036. };
  142037. static vorbis_residue_template _res_44s_9[]={
  142038. {2,0, &_residue_44_high,
  142039. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142040. &_resbook_44s_9,&_resbook_44s_9},
  142041. {2,0, &_residue_44_high,
  142042. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142043. &_resbook_44s_9,&_resbook_44s_9}
  142044. };
  142045. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142046. { _map_nominal, _res_44s_n1 }, /* -1 */
  142047. { _map_nominal, _res_44s_0 }, /* 0 */
  142048. { _map_nominal, _res_44s_1 }, /* 1 */
  142049. { _map_nominal, _res_44s_2 }, /* 2 */
  142050. { _map_nominal, _res_44s_3 }, /* 3 */
  142051. { _map_nominal, _res_44s_4 }, /* 4 */
  142052. { _map_nominal, _res_44s_5 }, /* 5 */
  142053. { _map_nominal, _res_44s_6 }, /* 6 */
  142054. { _map_nominal, _res_44s_7 }, /* 7 */
  142055. { _map_nominal, _res_44s_8 }, /* 8 */
  142056. { _map_nominal, _res_44s_9 }, /* 9 */
  142057. };
  142058. /*** End of inlined file: residue_44.h ***/
  142059. /*** Start of inlined file: psych_44.h ***/
  142060. /* preecho trigger settings *****************************************/
  142061. static vorbis_info_psy_global _psy_global_44[5]={
  142062. {8, /* lines per eighth octave */
  142063. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142064. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142065. -6.f,
  142066. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142067. },
  142068. {8, /* lines per eighth octave */
  142069. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142070. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142071. -6.f,
  142072. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142073. },
  142074. {8, /* lines per eighth octave */
  142075. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142076. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142077. -6.f,
  142078. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142079. },
  142080. {8, /* lines per eighth octave */
  142081. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142082. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142083. -6.f,
  142084. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142085. },
  142086. {8, /* lines per eighth octave */
  142087. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142088. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142089. -6.f,
  142090. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142091. },
  142092. };
  142093. /* noise compander lookups * low, mid, high quality ****************/
  142094. static compandblock _psy_compand_44[6]={
  142095. /* sub-mode Z short */
  142096. {{
  142097. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142098. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142099. 16,17,18,19,20,21,22, 23, /* 23dB */
  142100. 24,25,26,27,28,29,30, 31, /* 31dB */
  142101. 32,33,34,35,36,37,38, 39, /* 39dB */
  142102. }},
  142103. /* mode_Z nominal short */
  142104. {{
  142105. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142106. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142107. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142108. 15,16,17,17,17,18,18, 19, /* 31dB */
  142109. 19,19,20,21,22,23,24, 25, /* 39dB */
  142110. }},
  142111. /* mode A short */
  142112. {{
  142113. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142114. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142115. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142116. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142117. 11,12,13,14,15,16,17, 18, /* 39dB */
  142118. }},
  142119. /* sub-mode Z long */
  142120. {{
  142121. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142122. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142123. 16,17,18,19,20,21,22, 23, /* 23dB */
  142124. 24,25,26,27,28,29,30, 31, /* 31dB */
  142125. 32,33,34,35,36,37,38, 39, /* 39dB */
  142126. }},
  142127. /* mode_Z nominal long */
  142128. {{
  142129. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142130. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142131. 13,14,14,14,15,15,15, 15, /* 23dB */
  142132. 16,16,17,17,17,18,18, 19, /* 31dB */
  142133. 19,19,20,21,22,23,24, 25, /* 39dB */
  142134. }},
  142135. /* mode A long */
  142136. {{
  142137. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142138. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142139. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142140. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142141. 11,12,13,14,15,16,17, 18, /* 39dB */
  142142. }}
  142143. };
  142144. /* tonal masking curve level adjustments *************************/
  142145. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142146. /* 63 125 250 500 1 2 4 8 16 */
  142147. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142148. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142149. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142150. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142151. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142152. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142153. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142154. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142155. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142156. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142157. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142158. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142159. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142160. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142161. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142162. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142163. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142164. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142165. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142166. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142167. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142168. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142169. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142170. };
  142171. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142172. /* 63 125 250 500 1 2 4 8 16 */
  142173. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142174. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142175. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142176. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142177. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142178. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142179. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142180. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142181. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142182. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142183. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142184. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142185. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142186. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142187. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142188. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142189. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142190. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142191. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142192. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142193. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142194. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142195. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142196. };
  142197. /* noise bias (transition block) */
  142198. static noise3 _psy_noisebias_trans[12]={
  142199. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142200. /* -1 */
  142201. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142202. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142203. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142204. /* 0
  142205. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142206. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142207. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142208. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142209. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142210. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142211. /* 1
  142212. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142213. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142214. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142215. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142216. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142217. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142218. /* 2
  142219. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142220. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142221. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142222. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142223. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142224. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142225. /* 3
  142226. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142227. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142228. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142229. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142230. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142231. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142232. /* 4
  142233. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142234. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142235. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142236. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142237. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142238. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142239. /* 5
  142240. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142241. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142242. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142243. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142244. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142245. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142246. /* 6
  142247. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142248. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142249. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142250. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142251. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142252. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142253. /* 7
  142254. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142255. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142256. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142257. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142258. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142259. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142260. /* 8
  142261. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142262. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142263. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142264. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142265. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142266. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142267. /* 9
  142268. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142269. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142270. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142271. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142272. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142273. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142274. /* 10 */
  142275. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142276. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142277. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142278. };
  142279. /* noise bias (long block) */
  142280. static noise3 _psy_noisebias_long[12]={
  142281. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142282. /* -1 */
  142283. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142284. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142285. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142286. /* 0 */
  142287. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142288. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142289. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142290. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142291. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142292. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142293. /* 1 */
  142294. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142295. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142296. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142297. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142298. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142299. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142300. /* 2 */
  142301. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142302. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142303. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142304. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142305. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142306. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142307. /* 3 */
  142308. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142309. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142310. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142311. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142312. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142313. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142314. /* 4 */
  142315. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142316. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142317. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142318. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142319. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142320. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142321. /* 5 */
  142322. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142323. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142324. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142325. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142326. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142327. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142328. /* 6 */
  142329. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142330. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142331. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142332. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142333. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142334. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142335. /* 7 */
  142336. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142337. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142338. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142339. /* 8 */
  142340. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142341. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142342. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142343. /* 9 */
  142344. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142345. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142346. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142347. /* 10 */
  142348. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142349. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142350. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142351. };
  142352. /* noise bias (impulse block) */
  142353. static noise3 _psy_noisebias_impulse[12]={
  142354. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142355. /* -1 */
  142356. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142357. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142358. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142359. /* 0 */
  142360. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142361. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142362. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142363. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142364. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142365. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142366. /* 1 */
  142367. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142368. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142369. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142370. /* 2 */
  142371. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142372. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142373. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142374. /* 3 */
  142375. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142376. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142377. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142378. /* 4 */
  142379. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142380. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142381. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142382. /* 5 */
  142383. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142384. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142385. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142386. /* 6
  142387. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142388. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142389. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142390. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142391. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142392. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142393. /* 7 */
  142394. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142395. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142396. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142397. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142398. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142399. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142400. /* 8 */
  142401. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142402. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142403. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142404. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142405. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142406. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142407. /* 9 */
  142408. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142409. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142410. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142411. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142412. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142413. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142414. /* 10 */
  142415. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142416. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142417. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142418. };
  142419. /* noise bias (padding block) */
  142420. static noise3 _psy_noisebias_padding[12]={
  142421. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142422. /* -1 */
  142423. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142424. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142425. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142426. /* 0 */
  142427. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142428. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142429. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142430. /* 1 */
  142431. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142432. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142433. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142434. /* 2 */
  142435. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142436. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142437. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142438. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142439. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142440. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142441. /* 3 */
  142442. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142443. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142444. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142445. /* 4 */
  142446. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142447. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142448. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142449. /* 5 */
  142450. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142451. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142452. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142453. /* 6 */
  142454. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142455. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142456. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142457. /* 7 */
  142458. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142459. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142460. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142461. /* 8 */
  142462. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142463. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142464. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142465. /* 9 */
  142466. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142467. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142468. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142469. /* 10 */
  142470. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142471. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142472. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142473. };
  142474. static noiseguard _psy_noiseguards_44[4]={
  142475. {3,3,15},
  142476. {3,3,15},
  142477. {10,10,100},
  142478. {10,10,100},
  142479. };
  142480. static int _psy_tone_suppress[12]={
  142481. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142482. };
  142483. static int _psy_tone_0dB[12]={
  142484. 90,90,95,95,95,95,105,105,105,105,105,105,
  142485. };
  142486. static int _psy_noise_suppress[12]={
  142487. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142488. };
  142489. static vorbis_info_psy _psy_info_template={
  142490. /* blockflag */
  142491. -1,
  142492. /* ath_adjatt, ath_maxatt */
  142493. -140.,-140.,
  142494. /* tonemask att boost/decay,suppr,curves */
  142495. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142496. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142497. 1, -0.f, .5f, .5f, 0,0,0,
  142498. /* noiseoffset*3, noisecompand, max_curve_dB */
  142499. {{-1},{-1},{-1}},{-1},105.f,
  142500. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142501. 0,0,-1,-1,0.,
  142502. };
  142503. /* ath ****************/
  142504. static int _psy_ath_floater[12]={
  142505. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142506. };
  142507. static int _psy_ath_abs[12]={
  142508. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142509. };
  142510. /* stereo setup. These don't map directly to quality level, there's
  142511. an additional indirection as several of the below may be used in a
  142512. single bitmanaged stream
  142513. ****************/
  142514. /* various stereo possibilities */
  142515. /* stereo mode by base quality level */
  142516. static adj_stereo _psy_stereo_modes_44[12]={
  142517. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142518. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142519. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142520. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142521. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142522. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142523. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142524. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142525. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142526. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142527. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142528. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142529. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142530. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142531. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142532. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142533. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142534. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142535. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142536. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142537. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142538. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142539. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142540. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142541. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142542. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142543. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142544. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142545. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142546. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142547. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142548. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142549. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142550. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142551. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142552. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142553. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142554. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142555. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142556. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142557. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142558. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142559. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142560. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142561. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142562. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142563. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142564. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142565. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142566. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142567. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142568. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142569. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142570. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142571. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142572. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142573. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142574. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142575. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142576. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142577. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142578. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142579. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142580. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142581. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142582. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142583. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142584. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142585. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142586. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142587. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142588. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142589. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142590. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142591. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142592. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142593. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142594. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142595. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142596. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142597. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142598. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142599. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142600. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142601. };
  142602. /* tone master attenuation by base quality mode and bitrate tweak */
  142603. static att3 _psy_tone_masteratt_44[12]={
  142604. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142605. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142606. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142607. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142608. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142609. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142610. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142611. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142612. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142613. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142614. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142615. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142616. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142617. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142618. };
  142619. /* lowpass by mode **************/
  142620. static double _psy_lowpass_44[12]={
  142621. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142622. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142623. };
  142624. /* noise normalization **********/
  142625. static int _noise_start_short_44[11]={
  142626. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142627. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142628. };
  142629. static int _noise_start_long_44[11]={
  142630. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142631. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142632. };
  142633. static int _noise_part_short_44[11]={
  142634. 8,8,8,8,8,8,8,8,8,8,8
  142635. };
  142636. static int _noise_part_long_44[11]={
  142637. 32,32,32,32,32,32,32,32,32,32,32
  142638. };
  142639. static double _noise_thresh_44[11]={
  142640. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142641. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142642. };
  142643. static double _noise_thresh_5only[2]={
  142644. .5,.5,
  142645. };
  142646. /*** End of inlined file: psych_44.h ***/
  142647. static double rate_mapping_44_stereo[12]={
  142648. 22500.,32000.,40000.,48000.,56000.,64000.,
  142649. 80000.,96000.,112000.,128000.,160000.,250001.
  142650. };
  142651. static double quality_mapping_44[12]={
  142652. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142653. };
  142654. static int blocksize_short_44[11]={
  142655. 512,256,256,256,256,256,256,256,256,256,256
  142656. };
  142657. static int blocksize_long_44[11]={
  142658. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142659. };
  142660. static double _psy_compand_short_mapping[12]={
  142661. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142662. };
  142663. static double _psy_compand_long_mapping[12]={
  142664. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142665. };
  142666. static double _global_mapping_44[12]={
  142667. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142668. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142669. };
  142670. static int _floor_short_mapping_44[11]={
  142671. 1,0,0,2,2,4,5,5,5,5,5
  142672. };
  142673. static int _floor_long_mapping_44[11]={
  142674. 8,7,7,7,7,7,7,7,7,7,7
  142675. };
  142676. ve_setup_data_template ve_setup_44_stereo={
  142677. 11,
  142678. rate_mapping_44_stereo,
  142679. quality_mapping_44,
  142680. 2,
  142681. 40000,
  142682. 50000,
  142683. blocksize_short_44,
  142684. blocksize_long_44,
  142685. _psy_tone_masteratt_44,
  142686. _psy_tone_0dB,
  142687. _psy_tone_suppress,
  142688. _vp_tonemask_adj_otherblock,
  142689. _vp_tonemask_adj_longblock,
  142690. _vp_tonemask_adj_otherblock,
  142691. _psy_noiseguards_44,
  142692. _psy_noisebias_impulse,
  142693. _psy_noisebias_padding,
  142694. _psy_noisebias_trans,
  142695. _psy_noisebias_long,
  142696. _psy_noise_suppress,
  142697. _psy_compand_44,
  142698. _psy_compand_short_mapping,
  142699. _psy_compand_long_mapping,
  142700. {_noise_start_short_44,_noise_start_long_44},
  142701. {_noise_part_short_44,_noise_part_long_44},
  142702. _noise_thresh_44,
  142703. _psy_ath_floater,
  142704. _psy_ath_abs,
  142705. _psy_lowpass_44,
  142706. _psy_global_44,
  142707. _global_mapping_44,
  142708. _psy_stereo_modes_44,
  142709. _floor_books,
  142710. _floor,
  142711. _floor_short_mapping_44,
  142712. _floor_long_mapping_44,
  142713. _mapres_template_44_stereo
  142714. };
  142715. /*** End of inlined file: setup_44.h ***/
  142716. /*** Start of inlined file: setup_44u.h ***/
  142717. /*** Start of inlined file: residue_44u.h ***/
  142718. /*** Start of inlined file: res_books_uncoupled.h ***/
  142719. static long _vq_quantlist__16u0__p1_0[] = {
  142720. 1,
  142721. 0,
  142722. 2,
  142723. };
  142724. static long _vq_lengthlist__16u0__p1_0[] = {
  142725. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142726. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142727. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142728. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142729. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142730. 12,
  142731. };
  142732. static float _vq_quantthresh__16u0__p1_0[] = {
  142733. -0.5, 0.5,
  142734. };
  142735. static long _vq_quantmap__16u0__p1_0[] = {
  142736. 1, 0, 2,
  142737. };
  142738. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142739. _vq_quantthresh__16u0__p1_0,
  142740. _vq_quantmap__16u0__p1_0,
  142741. 3,
  142742. 3
  142743. };
  142744. static static_codebook _16u0__p1_0 = {
  142745. 4, 81,
  142746. _vq_lengthlist__16u0__p1_0,
  142747. 1, -535822336, 1611661312, 2, 0,
  142748. _vq_quantlist__16u0__p1_0,
  142749. NULL,
  142750. &_vq_auxt__16u0__p1_0,
  142751. NULL,
  142752. 0
  142753. };
  142754. static long _vq_quantlist__16u0__p2_0[] = {
  142755. 1,
  142756. 0,
  142757. 2,
  142758. };
  142759. static long _vq_lengthlist__16u0__p2_0[] = {
  142760. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142761. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142762. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142763. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142764. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142765. 8,
  142766. };
  142767. static float _vq_quantthresh__16u0__p2_0[] = {
  142768. -0.5, 0.5,
  142769. };
  142770. static long _vq_quantmap__16u0__p2_0[] = {
  142771. 1, 0, 2,
  142772. };
  142773. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142774. _vq_quantthresh__16u0__p2_0,
  142775. _vq_quantmap__16u0__p2_0,
  142776. 3,
  142777. 3
  142778. };
  142779. static static_codebook _16u0__p2_0 = {
  142780. 4, 81,
  142781. _vq_lengthlist__16u0__p2_0,
  142782. 1, -535822336, 1611661312, 2, 0,
  142783. _vq_quantlist__16u0__p2_0,
  142784. NULL,
  142785. &_vq_auxt__16u0__p2_0,
  142786. NULL,
  142787. 0
  142788. };
  142789. static long _vq_quantlist__16u0__p3_0[] = {
  142790. 2,
  142791. 1,
  142792. 3,
  142793. 0,
  142794. 4,
  142795. };
  142796. static long _vq_lengthlist__16u0__p3_0[] = {
  142797. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142798. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142799. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142800. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142801. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142802. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142803. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142804. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142805. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142806. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142807. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142808. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142809. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142810. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142811. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142812. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142813. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142814. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142815. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142816. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142817. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142818. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142819. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142820. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142821. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142822. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142823. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142824. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142825. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142826. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142827. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142828. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142829. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142830. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142831. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142832. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142833. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142834. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142835. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142836. 18,
  142837. };
  142838. static float _vq_quantthresh__16u0__p3_0[] = {
  142839. -1.5, -0.5, 0.5, 1.5,
  142840. };
  142841. static long _vq_quantmap__16u0__p3_0[] = {
  142842. 3, 1, 0, 2, 4,
  142843. };
  142844. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142845. _vq_quantthresh__16u0__p3_0,
  142846. _vq_quantmap__16u0__p3_0,
  142847. 5,
  142848. 5
  142849. };
  142850. static static_codebook _16u0__p3_0 = {
  142851. 4, 625,
  142852. _vq_lengthlist__16u0__p3_0,
  142853. 1, -533725184, 1611661312, 3, 0,
  142854. _vq_quantlist__16u0__p3_0,
  142855. NULL,
  142856. &_vq_auxt__16u0__p3_0,
  142857. NULL,
  142858. 0
  142859. };
  142860. static long _vq_quantlist__16u0__p4_0[] = {
  142861. 2,
  142862. 1,
  142863. 3,
  142864. 0,
  142865. 4,
  142866. };
  142867. static long _vq_lengthlist__16u0__p4_0[] = {
  142868. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142869. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142870. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142871. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142872. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142873. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142874. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142875. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142876. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142877. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142878. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142879. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142880. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142881. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142882. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142883. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142884. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142885. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142886. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142887. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142888. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142889. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142890. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142891. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142892. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142893. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142894. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142895. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142896. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142897. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142898. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142899. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142900. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142901. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142902. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142903. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142904. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142905. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142906. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142907. 11,
  142908. };
  142909. static float _vq_quantthresh__16u0__p4_0[] = {
  142910. -1.5, -0.5, 0.5, 1.5,
  142911. };
  142912. static long _vq_quantmap__16u0__p4_0[] = {
  142913. 3, 1, 0, 2, 4,
  142914. };
  142915. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142916. _vq_quantthresh__16u0__p4_0,
  142917. _vq_quantmap__16u0__p4_0,
  142918. 5,
  142919. 5
  142920. };
  142921. static static_codebook _16u0__p4_0 = {
  142922. 4, 625,
  142923. _vq_lengthlist__16u0__p4_0,
  142924. 1, -533725184, 1611661312, 3, 0,
  142925. _vq_quantlist__16u0__p4_0,
  142926. NULL,
  142927. &_vq_auxt__16u0__p4_0,
  142928. NULL,
  142929. 0
  142930. };
  142931. static long _vq_quantlist__16u0__p5_0[] = {
  142932. 4,
  142933. 3,
  142934. 5,
  142935. 2,
  142936. 6,
  142937. 1,
  142938. 7,
  142939. 0,
  142940. 8,
  142941. };
  142942. static long _vq_lengthlist__16u0__p5_0[] = {
  142943. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142944. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142945. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142946. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142947. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142948. 12,
  142949. };
  142950. static float _vq_quantthresh__16u0__p5_0[] = {
  142951. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142952. };
  142953. static long _vq_quantmap__16u0__p5_0[] = {
  142954. 7, 5, 3, 1, 0, 2, 4, 6,
  142955. 8,
  142956. };
  142957. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142958. _vq_quantthresh__16u0__p5_0,
  142959. _vq_quantmap__16u0__p5_0,
  142960. 9,
  142961. 9
  142962. };
  142963. static static_codebook _16u0__p5_0 = {
  142964. 2, 81,
  142965. _vq_lengthlist__16u0__p5_0,
  142966. 1, -531628032, 1611661312, 4, 0,
  142967. _vq_quantlist__16u0__p5_0,
  142968. NULL,
  142969. &_vq_auxt__16u0__p5_0,
  142970. NULL,
  142971. 0
  142972. };
  142973. static long _vq_quantlist__16u0__p6_0[] = {
  142974. 6,
  142975. 5,
  142976. 7,
  142977. 4,
  142978. 8,
  142979. 3,
  142980. 9,
  142981. 2,
  142982. 10,
  142983. 1,
  142984. 11,
  142985. 0,
  142986. 12,
  142987. };
  142988. static long _vq_lengthlist__16u0__p6_0[] = {
  142989. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142990. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142991. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142992. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142993. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142994. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142995. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142996. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142997. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142998. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142999. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143000. };
  143001. static float _vq_quantthresh__16u0__p6_0[] = {
  143002. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143003. 12.5, 17.5, 22.5, 27.5,
  143004. };
  143005. static long _vq_quantmap__16u0__p6_0[] = {
  143006. 11, 9, 7, 5, 3, 1, 0, 2,
  143007. 4, 6, 8, 10, 12,
  143008. };
  143009. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143010. _vq_quantthresh__16u0__p6_0,
  143011. _vq_quantmap__16u0__p6_0,
  143012. 13,
  143013. 13
  143014. };
  143015. static static_codebook _16u0__p6_0 = {
  143016. 2, 169,
  143017. _vq_lengthlist__16u0__p6_0,
  143018. 1, -526516224, 1616117760, 4, 0,
  143019. _vq_quantlist__16u0__p6_0,
  143020. NULL,
  143021. &_vq_auxt__16u0__p6_0,
  143022. NULL,
  143023. 0
  143024. };
  143025. static long _vq_quantlist__16u0__p6_1[] = {
  143026. 2,
  143027. 1,
  143028. 3,
  143029. 0,
  143030. 4,
  143031. };
  143032. static long _vq_lengthlist__16u0__p6_1[] = {
  143033. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143034. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143035. };
  143036. static float _vq_quantthresh__16u0__p6_1[] = {
  143037. -1.5, -0.5, 0.5, 1.5,
  143038. };
  143039. static long _vq_quantmap__16u0__p6_1[] = {
  143040. 3, 1, 0, 2, 4,
  143041. };
  143042. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143043. _vq_quantthresh__16u0__p6_1,
  143044. _vq_quantmap__16u0__p6_1,
  143045. 5,
  143046. 5
  143047. };
  143048. static static_codebook _16u0__p6_1 = {
  143049. 2, 25,
  143050. _vq_lengthlist__16u0__p6_1,
  143051. 1, -533725184, 1611661312, 3, 0,
  143052. _vq_quantlist__16u0__p6_1,
  143053. NULL,
  143054. &_vq_auxt__16u0__p6_1,
  143055. NULL,
  143056. 0
  143057. };
  143058. static long _vq_quantlist__16u0__p7_0[] = {
  143059. 1,
  143060. 0,
  143061. 2,
  143062. };
  143063. static long _vq_lengthlist__16u0__p7_0[] = {
  143064. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143065. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143066. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143067. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143068. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143069. 7,
  143070. };
  143071. static float _vq_quantthresh__16u0__p7_0[] = {
  143072. -157.5, 157.5,
  143073. };
  143074. static long _vq_quantmap__16u0__p7_0[] = {
  143075. 1, 0, 2,
  143076. };
  143077. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143078. _vq_quantthresh__16u0__p7_0,
  143079. _vq_quantmap__16u0__p7_0,
  143080. 3,
  143081. 3
  143082. };
  143083. static static_codebook _16u0__p7_0 = {
  143084. 4, 81,
  143085. _vq_lengthlist__16u0__p7_0,
  143086. 1, -518803456, 1628680192, 2, 0,
  143087. _vq_quantlist__16u0__p7_0,
  143088. NULL,
  143089. &_vq_auxt__16u0__p7_0,
  143090. NULL,
  143091. 0
  143092. };
  143093. static long _vq_quantlist__16u0__p7_1[] = {
  143094. 7,
  143095. 6,
  143096. 8,
  143097. 5,
  143098. 9,
  143099. 4,
  143100. 10,
  143101. 3,
  143102. 11,
  143103. 2,
  143104. 12,
  143105. 1,
  143106. 13,
  143107. 0,
  143108. 14,
  143109. };
  143110. static long _vq_lengthlist__16u0__p7_1[] = {
  143111. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143112. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143113. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143114. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143115. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143116. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143117. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143118. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143119. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143120. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143121. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143122. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143123. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143124. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143125. 10,
  143126. };
  143127. static float _vq_quantthresh__16u0__p7_1[] = {
  143128. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143129. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143130. };
  143131. static long _vq_quantmap__16u0__p7_1[] = {
  143132. 13, 11, 9, 7, 5, 3, 1, 0,
  143133. 2, 4, 6, 8, 10, 12, 14,
  143134. };
  143135. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143136. _vq_quantthresh__16u0__p7_1,
  143137. _vq_quantmap__16u0__p7_1,
  143138. 15,
  143139. 15
  143140. };
  143141. static static_codebook _16u0__p7_1 = {
  143142. 2, 225,
  143143. _vq_lengthlist__16u0__p7_1,
  143144. 1, -520986624, 1620377600, 4, 0,
  143145. _vq_quantlist__16u0__p7_1,
  143146. NULL,
  143147. &_vq_auxt__16u0__p7_1,
  143148. NULL,
  143149. 0
  143150. };
  143151. static long _vq_quantlist__16u0__p7_2[] = {
  143152. 10,
  143153. 9,
  143154. 11,
  143155. 8,
  143156. 12,
  143157. 7,
  143158. 13,
  143159. 6,
  143160. 14,
  143161. 5,
  143162. 15,
  143163. 4,
  143164. 16,
  143165. 3,
  143166. 17,
  143167. 2,
  143168. 18,
  143169. 1,
  143170. 19,
  143171. 0,
  143172. 20,
  143173. };
  143174. static long _vq_lengthlist__16u0__p7_2[] = {
  143175. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143176. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143177. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143178. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143179. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143180. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143181. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143182. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143183. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143184. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143185. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143186. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143187. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143188. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143189. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143190. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143191. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143192. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143193. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143194. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143195. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143196. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143197. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143198. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143199. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143200. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143201. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143202. 10,10,12,11,10,11,11,11,10,
  143203. };
  143204. static float _vq_quantthresh__16u0__p7_2[] = {
  143205. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143206. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143207. 6.5, 7.5, 8.5, 9.5,
  143208. };
  143209. static long _vq_quantmap__16u0__p7_2[] = {
  143210. 19, 17, 15, 13, 11, 9, 7, 5,
  143211. 3, 1, 0, 2, 4, 6, 8, 10,
  143212. 12, 14, 16, 18, 20,
  143213. };
  143214. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143215. _vq_quantthresh__16u0__p7_2,
  143216. _vq_quantmap__16u0__p7_2,
  143217. 21,
  143218. 21
  143219. };
  143220. static static_codebook _16u0__p7_2 = {
  143221. 2, 441,
  143222. _vq_lengthlist__16u0__p7_2,
  143223. 1, -529268736, 1611661312, 5, 0,
  143224. _vq_quantlist__16u0__p7_2,
  143225. NULL,
  143226. &_vq_auxt__16u0__p7_2,
  143227. NULL,
  143228. 0
  143229. };
  143230. static long _huff_lengthlist__16u0__single[] = {
  143231. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143232. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143233. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143234. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143235. };
  143236. static static_codebook _huff_book__16u0__single = {
  143237. 2, 64,
  143238. _huff_lengthlist__16u0__single,
  143239. 0, 0, 0, 0, 0,
  143240. NULL,
  143241. NULL,
  143242. NULL,
  143243. NULL,
  143244. 0
  143245. };
  143246. static long _huff_lengthlist__16u1__long[] = {
  143247. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143248. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143249. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143250. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143251. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143252. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143253. 16,13,16,18,
  143254. };
  143255. static static_codebook _huff_book__16u1__long = {
  143256. 2, 100,
  143257. _huff_lengthlist__16u1__long,
  143258. 0, 0, 0, 0, 0,
  143259. NULL,
  143260. NULL,
  143261. NULL,
  143262. NULL,
  143263. 0
  143264. };
  143265. static long _vq_quantlist__16u1__p1_0[] = {
  143266. 1,
  143267. 0,
  143268. 2,
  143269. };
  143270. static long _vq_lengthlist__16u1__p1_0[] = {
  143271. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143272. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143273. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143274. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143275. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143276. 11,
  143277. };
  143278. static float _vq_quantthresh__16u1__p1_0[] = {
  143279. -0.5, 0.5,
  143280. };
  143281. static long _vq_quantmap__16u1__p1_0[] = {
  143282. 1, 0, 2,
  143283. };
  143284. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143285. _vq_quantthresh__16u1__p1_0,
  143286. _vq_quantmap__16u1__p1_0,
  143287. 3,
  143288. 3
  143289. };
  143290. static static_codebook _16u1__p1_0 = {
  143291. 4, 81,
  143292. _vq_lengthlist__16u1__p1_0,
  143293. 1, -535822336, 1611661312, 2, 0,
  143294. _vq_quantlist__16u1__p1_0,
  143295. NULL,
  143296. &_vq_auxt__16u1__p1_0,
  143297. NULL,
  143298. 0
  143299. };
  143300. static long _vq_quantlist__16u1__p2_0[] = {
  143301. 1,
  143302. 0,
  143303. 2,
  143304. };
  143305. static long _vq_lengthlist__16u1__p2_0[] = {
  143306. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143307. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143308. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143309. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143310. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143311. 8,
  143312. };
  143313. static float _vq_quantthresh__16u1__p2_0[] = {
  143314. -0.5, 0.5,
  143315. };
  143316. static long _vq_quantmap__16u1__p2_0[] = {
  143317. 1, 0, 2,
  143318. };
  143319. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143320. _vq_quantthresh__16u1__p2_0,
  143321. _vq_quantmap__16u1__p2_0,
  143322. 3,
  143323. 3
  143324. };
  143325. static static_codebook _16u1__p2_0 = {
  143326. 4, 81,
  143327. _vq_lengthlist__16u1__p2_0,
  143328. 1, -535822336, 1611661312, 2, 0,
  143329. _vq_quantlist__16u1__p2_0,
  143330. NULL,
  143331. &_vq_auxt__16u1__p2_0,
  143332. NULL,
  143333. 0
  143334. };
  143335. static long _vq_quantlist__16u1__p3_0[] = {
  143336. 2,
  143337. 1,
  143338. 3,
  143339. 0,
  143340. 4,
  143341. };
  143342. static long _vq_lengthlist__16u1__p3_0[] = {
  143343. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143344. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143345. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143346. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143347. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143348. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143349. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143350. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143351. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143352. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143353. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143354. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143355. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143356. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143357. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143358. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143359. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143360. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143361. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143362. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143363. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143364. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143365. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143366. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143367. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143368. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143369. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143370. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143371. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143372. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143373. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143374. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143375. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143376. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143377. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143378. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143379. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143380. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143381. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143382. 16,
  143383. };
  143384. static float _vq_quantthresh__16u1__p3_0[] = {
  143385. -1.5, -0.5, 0.5, 1.5,
  143386. };
  143387. static long _vq_quantmap__16u1__p3_0[] = {
  143388. 3, 1, 0, 2, 4,
  143389. };
  143390. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143391. _vq_quantthresh__16u1__p3_0,
  143392. _vq_quantmap__16u1__p3_0,
  143393. 5,
  143394. 5
  143395. };
  143396. static static_codebook _16u1__p3_0 = {
  143397. 4, 625,
  143398. _vq_lengthlist__16u1__p3_0,
  143399. 1, -533725184, 1611661312, 3, 0,
  143400. _vq_quantlist__16u1__p3_0,
  143401. NULL,
  143402. &_vq_auxt__16u1__p3_0,
  143403. NULL,
  143404. 0
  143405. };
  143406. static long _vq_quantlist__16u1__p4_0[] = {
  143407. 2,
  143408. 1,
  143409. 3,
  143410. 0,
  143411. 4,
  143412. };
  143413. static long _vq_lengthlist__16u1__p4_0[] = {
  143414. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143415. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143416. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143417. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143418. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143419. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143420. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143421. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143422. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143423. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143424. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143425. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143426. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143427. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143428. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143429. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143430. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143431. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143432. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143433. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143434. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143435. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143436. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143437. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143438. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143439. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143440. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143441. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143442. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143443. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143444. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143445. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143446. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143447. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143448. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143449. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143450. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143451. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143452. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143453. 11,
  143454. };
  143455. static float _vq_quantthresh__16u1__p4_0[] = {
  143456. -1.5, -0.5, 0.5, 1.5,
  143457. };
  143458. static long _vq_quantmap__16u1__p4_0[] = {
  143459. 3, 1, 0, 2, 4,
  143460. };
  143461. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143462. _vq_quantthresh__16u1__p4_0,
  143463. _vq_quantmap__16u1__p4_0,
  143464. 5,
  143465. 5
  143466. };
  143467. static static_codebook _16u1__p4_0 = {
  143468. 4, 625,
  143469. _vq_lengthlist__16u1__p4_0,
  143470. 1, -533725184, 1611661312, 3, 0,
  143471. _vq_quantlist__16u1__p4_0,
  143472. NULL,
  143473. &_vq_auxt__16u1__p4_0,
  143474. NULL,
  143475. 0
  143476. };
  143477. static long _vq_quantlist__16u1__p5_0[] = {
  143478. 4,
  143479. 3,
  143480. 5,
  143481. 2,
  143482. 6,
  143483. 1,
  143484. 7,
  143485. 0,
  143486. 8,
  143487. };
  143488. static long _vq_lengthlist__16u1__p5_0[] = {
  143489. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143490. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143491. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143492. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143493. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143494. 13,
  143495. };
  143496. static float _vq_quantthresh__16u1__p5_0[] = {
  143497. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143498. };
  143499. static long _vq_quantmap__16u1__p5_0[] = {
  143500. 7, 5, 3, 1, 0, 2, 4, 6,
  143501. 8,
  143502. };
  143503. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143504. _vq_quantthresh__16u1__p5_0,
  143505. _vq_quantmap__16u1__p5_0,
  143506. 9,
  143507. 9
  143508. };
  143509. static static_codebook _16u1__p5_0 = {
  143510. 2, 81,
  143511. _vq_lengthlist__16u1__p5_0,
  143512. 1, -531628032, 1611661312, 4, 0,
  143513. _vq_quantlist__16u1__p5_0,
  143514. NULL,
  143515. &_vq_auxt__16u1__p5_0,
  143516. NULL,
  143517. 0
  143518. };
  143519. static long _vq_quantlist__16u1__p6_0[] = {
  143520. 4,
  143521. 3,
  143522. 5,
  143523. 2,
  143524. 6,
  143525. 1,
  143526. 7,
  143527. 0,
  143528. 8,
  143529. };
  143530. static long _vq_lengthlist__16u1__p6_0[] = {
  143531. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143532. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143533. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143534. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143535. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143536. 11,
  143537. };
  143538. static float _vq_quantthresh__16u1__p6_0[] = {
  143539. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143540. };
  143541. static long _vq_quantmap__16u1__p6_0[] = {
  143542. 7, 5, 3, 1, 0, 2, 4, 6,
  143543. 8,
  143544. };
  143545. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143546. _vq_quantthresh__16u1__p6_0,
  143547. _vq_quantmap__16u1__p6_0,
  143548. 9,
  143549. 9
  143550. };
  143551. static static_codebook _16u1__p6_0 = {
  143552. 2, 81,
  143553. _vq_lengthlist__16u1__p6_0,
  143554. 1, -531628032, 1611661312, 4, 0,
  143555. _vq_quantlist__16u1__p6_0,
  143556. NULL,
  143557. &_vq_auxt__16u1__p6_0,
  143558. NULL,
  143559. 0
  143560. };
  143561. static long _vq_quantlist__16u1__p7_0[] = {
  143562. 1,
  143563. 0,
  143564. 2,
  143565. };
  143566. static long _vq_lengthlist__16u1__p7_0[] = {
  143567. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143568. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143569. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143570. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143571. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143572. 13,
  143573. };
  143574. static float _vq_quantthresh__16u1__p7_0[] = {
  143575. -5.5, 5.5,
  143576. };
  143577. static long _vq_quantmap__16u1__p7_0[] = {
  143578. 1, 0, 2,
  143579. };
  143580. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143581. _vq_quantthresh__16u1__p7_0,
  143582. _vq_quantmap__16u1__p7_0,
  143583. 3,
  143584. 3
  143585. };
  143586. static static_codebook _16u1__p7_0 = {
  143587. 4, 81,
  143588. _vq_lengthlist__16u1__p7_0,
  143589. 1, -529137664, 1618345984, 2, 0,
  143590. _vq_quantlist__16u1__p7_0,
  143591. NULL,
  143592. &_vq_auxt__16u1__p7_0,
  143593. NULL,
  143594. 0
  143595. };
  143596. static long _vq_quantlist__16u1__p7_1[] = {
  143597. 5,
  143598. 4,
  143599. 6,
  143600. 3,
  143601. 7,
  143602. 2,
  143603. 8,
  143604. 1,
  143605. 9,
  143606. 0,
  143607. 10,
  143608. };
  143609. static long _vq_lengthlist__16u1__p7_1[] = {
  143610. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143611. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143612. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143613. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143614. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143615. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143616. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143617. 8, 9, 9,10,10,10,10,10,10,
  143618. };
  143619. static float _vq_quantthresh__16u1__p7_1[] = {
  143620. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143621. 3.5, 4.5,
  143622. };
  143623. static long _vq_quantmap__16u1__p7_1[] = {
  143624. 9, 7, 5, 3, 1, 0, 2, 4,
  143625. 6, 8, 10,
  143626. };
  143627. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143628. _vq_quantthresh__16u1__p7_1,
  143629. _vq_quantmap__16u1__p7_1,
  143630. 11,
  143631. 11
  143632. };
  143633. static static_codebook _16u1__p7_1 = {
  143634. 2, 121,
  143635. _vq_lengthlist__16u1__p7_1,
  143636. 1, -531365888, 1611661312, 4, 0,
  143637. _vq_quantlist__16u1__p7_1,
  143638. NULL,
  143639. &_vq_auxt__16u1__p7_1,
  143640. NULL,
  143641. 0
  143642. };
  143643. static long _vq_quantlist__16u1__p8_0[] = {
  143644. 5,
  143645. 4,
  143646. 6,
  143647. 3,
  143648. 7,
  143649. 2,
  143650. 8,
  143651. 1,
  143652. 9,
  143653. 0,
  143654. 10,
  143655. };
  143656. static long _vq_lengthlist__16u1__p8_0[] = {
  143657. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143658. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143659. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143660. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143661. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143662. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143663. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143664. 13,14,14,15,15,16,16,15,16,
  143665. };
  143666. static float _vq_quantthresh__16u1__p8_0[] = {
  143667. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143668. 38.5, 49.5,
  143669. };
  143670. static long _vq_quantmap__16u1__p8_0[] = {
  143671. 9, 7, 5, 3, 1, 0, 2, 4,
  143672. 6, 8, 10,
  143673. };
  143674. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143675. _vq_quantthresh__16u1__p8_0,
  143676. _vq_quantmap__16u1__p8_0,
  143677. 11,
  143678. 11
  143679. };
  143680. static static_codebook _16u1__p8_0 = {
  143681. 2, 121,
  143682. _vq_lengthlist__16u1__p8_0,
  143683. 1, -524582912, 1618345984, 4, 0,
  143684. _vq_quantlist__16u1__p8_0,
  143685. NULL,
  143686. &_vq_auxt__16u1__p8_0,
  143687. NULL,
  143688. 0
  143689. };
  143690. static long _vq_quantlist__16u1__p8_1[] = {
  143691. 5,
  143692. 4,
  143693. 6,
  143694. 3,
  143695. 7,
  143696. 2,
  143697. 8,
  143698. 1,
  143699. 9,
  143700. 0,
  143701. 10,
  143702. };
  143703. static long _vq_lengthlist__16u1__p8_1[] = {
  143704. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143705. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143706. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143707. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143708. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143709. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143710. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143711. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143712. };
  143713. static float _vq_quantthresh__16u1__p8_1[] = {
  143714. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143715. 3.5, 4.5,
  143716. };
  143717. static long _vq_quantmap__16u1__p8_1[] = {
  143718. 9, 7, 5, 3, 1, 0, 2, 4,
  143719. 6, 8, 10,
  143720. };
  143721. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143722. _vq_quantthresh__16u1__p8_1,
  143723. _vq_quantmap__16u1__p8_1,
  143724. 11,
  143725. 11
  143726. };
  143727. static static_codebook _16u1__p8_1 = {
  143728. 2, 121,
  143729. _vq_lengthlist__16u1__p8_1,
  143730. 1, -531365888, 1611661312, 4, 0,
  143731. _vq_quantlist__16u1__p8_1,
  143732. NULL,
  143733. &_vq_auxt__16u1__p8_1,
  143734. NULL,
  143735. 0
  143736. };
  143737. static long _vq_quantlist__16u1__p9_0[] = {
  143738. 7,
  143739. 6,
  143740. 8,
  143741. 5,
  143742. 9,
  143743. 4,
  143744. 10,
  143745. 3,
  143746. 11,
  143747. 2,
  143748. 12,
  143749. 1,
  143750. 13,
  143751. 0,
  143752. 14,
  143753. };
  143754. static long _vq_lengthlist__16u1__p9_0[] = {
  143755. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143756. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143757. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143758. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143759. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143760. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143761. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143762. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143763. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143764. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143765. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143766. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143767. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143768. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143769. 8,
  143770. };
  143771. static float _vq_quantthresh__16u1__p9_0[] = {
  143772. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143773. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143774. };
  143775. static long _vq_quantmap__16u1__p9_0[] = {
  143776. 13, 11, 9, 7, 5, 3, 1, 0,
  143777. 2, 4, 6, 8, 10, 12, 14,
  143778. };
  143779. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143780. _vq_quantthresh__16u1__p9_0,
  143781. _vq_quantmap__16u1__p9_0,
  143782. 15,
  143783. 15
  143784. };
  143785. static static_codebook _16u1__p9_0 = {
  143786. 2, 225,
  143787. _vq_lengthlist__16u1__p9_0,
  143788. 1, -514071552, 1627381760, 4, 0,
  143789. _vq_quantlist__16u1__p9_0,
  143790. NULL,
  143791. &_vq_auxt__16u1__p9_0,
  143792. NULL,
  143793. 0
  143794. };
  143795. static long _vq_quantlist__16u1__p9_1[] = {
  143796. 7,
  143797. 6,
  143798. 8,
  143799. 5,
  143800. 9,
  143801. 4,
  143802. 10,
  143803. 3,
  143804. 11,
  143805. 2,
  143806. 12,
  143807. 1,
  143808. 13,
  143809. 0,
  143810. 14,
  143811. };
  143812. static long _vq_lengthlist__16u1__p9_1[] = {
  143813. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143814. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143815. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143816. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143817. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143818. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143819. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143820. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143821. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143822. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143823. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143824. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143825. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143826. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143827. 9,
  143828. };
  143829. static float _vq_quantthresh__16u1__p9_1[] = {
  143830. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143831. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143832. };
  143833. static long _vq_quantmap__16u1__p9_1[] = {
  143834. 13, 11, 9, 7, 5, 3, 1, 0,
  143835. 2, 4, 6, 8, 10, 12, 14,
  143836. };
  143837. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143838. _vq_quantthresh__16u1__p9_1,
  143839. _vq_quantmap__16u1__p9_1,
  143840. 15,
  143841. 15
  143842. };
  143843. static static_codebook _16u1__p9_1 = {
  143844. 2, 225,
  143845. _vq_lengthlist__16u1__p9_1,
  143846. 1, -522338304, 1620115456, 4, 0,
  143847. _vq_quantlist__16u1__p9_1,
  143848. NULL,
  143849. &_vq_auxt__16u1__p9_1,
  143850. NULL,
  143851. 0
  143852. };
  143853. static long _vq_quantlist__16u1__p9_2[] = {
  143854. 8,
  143855. 7,
  143856. 9,
  143857. 6,
  143858. 10,
  143859. 5,
  143860. 11,
  143861. 4,
  143862. 12,
  143863. 3,
  143864. 13,
  143865. 2,
  143866. 14,
  143867. 1,
  143868. 15,
  143869. 0,
  143870. 16,
  143871. };
  143872. static long _vq_lengthlist__16u1__p9_2[] = {
  143873. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143874. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143875. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143876. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143877. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143878. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143879. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143880. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143881. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143882. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143883. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143884. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143885. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143886. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143887. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143888. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143889. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143890. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143891. 10,
  143892. };
  143893. static float _vq_quantthresh__16u1__p9_2[] = {
  143894. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143895. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143896. };
  143897. static long _vq_quantmap__16u1__p9_2[] = {
  143898. 15, 13, 11, 9, 7, 5, 3, 1,
  143899. 0, 2, 4, 6, 8, 10, 12, 14,
  143900. 16,
  143901. };
  143902. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143903. _vq_quantthresh__16u1__p9_2,
  143904. _vq_quantmap__16u1__p9_2,
  143905. 17,
  143906. 17
  143907. };
  143908. static static_codebook _16u1__p9_2 = {
  143909. 2, 289,
  143910. _vq_lengthlist__16u1__p9_2,
  143911. 1, -529530880, 1611661312, 5, 0,
  143912. _vq_quantlist__16u1__p9_2,
  143913. NULL,
  143914. &_vq_auxt__16u1__p9_2,
  143915. NULL,
  143916. 0
  143917. };
  143918. static long _huff_lengthlist__16u1__short[] = {
  143919. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143920. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143921. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143922. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143923. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143924. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143925. 16,16,16,16,
  143926. };
  143927. static static_codebook _huff_book__16u1__short = {
  143928. 2, 100,
  143929. _huff_lengthlist__16u1__short,
  143930. 0, 0, 0, 0, 0,
  143931. NULL,
  143932. NULL,
  143933. NULL,
  143934. NULL,
  143935. 0
  143936. };
  143937. static long _huff_lengthlist__16u2__long[] = {
  143938. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143939. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143940. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143941. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143942. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143943. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143944. 13,14,18,18,
  143945. };
  143946. static static_codebook _huff_book__16u2__long = {
  143947. 2, 100,
  143948. _huff_lengthlist__16u2__long,
  143949. 0, 0, 0, 0, 0,
  143950. NULL,
  143951. NULL,
  143952. NULL,
  143953. NULL,
  143954. 0
  143955. };
  143956. static long _huff_lengthlist__16u2__short[] = {
  143957. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143958. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143959. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143960. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143961. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143962. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143963. 16,16,16,16,
  143964. };
  143965. static static_codebook _huff_book__16u2__short = {
  143966. 2, 100,
  143967. _huff_lengthlist__16u2__short,
  143968. 0, 0, 0, 0, 0,
  143969. NULL,
  143970. NULL,
  143971. NULL,
  143972. NULL,
  143973. 0
  143974. };
  143975. static long _vq_quantlist__16u2_p1_0[] = {
  143976. 1,
  143977. 0,
  143978. 2,
  143979. };
  143980. static long _vq_lengthlist__16u2_p1_0[] = {
  143981. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143982. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143983. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143984. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143985. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143986. 10,
  143987. };
  143988. static float _vq_quantthresh__16u2_p1_0[] = {
  143989. -0.5, 0.5,
  143990. };
  143991. static long _vq_quantmap__16u2_p1_0[] = {
  143992. 1, 0, 2,
  143993. };
  143994. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143995. _vq_quantthresh__16u2_p1_0,
  143996. _vq_quantmap__16u2_p1_0,
  143997. 3,
  143998. 3
  143999. };
  144000. static static_codebook _16u2_p1_0 = {
  144001. 4, 81,
  144002. _vq_lengthlist__16u2_p1_0,
  144003. 1, -535822336, 1611661312, 2, 0,
  144004. _vq_quantlist__16u2_p1_0,
  144005. NULL,
  144006. &_vq_auxt__16u2_p1_0,
  144007. NULL,
  144008. 0
  144009. };
  144010. static long _vq_quantlist__16u2_p2_0[] = {
  144011. 2,
  144012. 1,
  144013. 3,
  144014. 0,
  144015. 4,
  144016. };
  144017. static long _vq_lengthlist__16u2_p2_0[] = {
  144018. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144019. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144020. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144021. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144022. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144023. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144024. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144025. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144026. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144027. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144028. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144029. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144030. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144031. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144032. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144033. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144034. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144035. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144036. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144037. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144038. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144039. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144040. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144041. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144042. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144043. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144044. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144045. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144046. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144047. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144048. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144049. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144050. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144051. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144052. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144053. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144054. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144055. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144056. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144057. 13,
  144058. };
  144059. static float _vq_quantthresh__16u2_p2_0[] = {
  144060. -1.5, -0.5, 0.5, 1.5,
  144061. };
  144062. static long _vq_quantmap__16u2_p2_0[] = {
  144063. 3, 1, 0, 2, 4,
  144064. };
  144065. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144066. _vq_quantthresh__16u2_p2_0,
  144067. _vq_quantmap__16u2_p2_0,
  144068. 5,
  144069. 5
  144070. };
  144071. static static_codebook _16u2_p2_0 = {
  144072. 4, 625,
  144073. _vq_lengthlist__16u2_p2_0,
  144074. 1, -533725184, 1611661312, 3, 0,
  144075. _vq_quantlist__16u2_p2_0,
  144076. NULL,
  144077. &_vq_auxt__16u2_p2_0,
  144078. NULL,
  144079. 0
  144080. };
  144081. static long _vq_quantlist__16u2_p3_0[] = {
  144082. 4,
  144083. 3,
  144084. 5,
  144085. 2,
  144086. 6,
  144087. 1,
  144088. 7,
  144089. 0,
  144090. 8,
  144091. };
  144092. static long _vq_lengthlist__16u2_p3_0[] = {
  144093. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144094. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144095. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144096. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144097. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144098. 11,
  144099. };
  144100. static float _vq_quantthresh__16u2_p3_0[] = {
  144101. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144102. };
  144103. static long _vq_quantmap__16u2_p3_0[] = {
  144104. 7, 5, 3, 1, 0, 2, 4, 6,
  144105. 8,
  144106. };
  144107. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144108. _vq_quantthresh__16u2_p3_0,
  144109. _vq_quantmap__16u2_p3_0,
  144110. 9,
  144111. 9
  144112. };
  144113. static static_codebook _16u2_p3_0 = {
  144114. 2, 81,
  144115. _vq_lengthlist__16u2_p3_0,
  144116. 1, -531628032, 1611661312, 4, 0,
  144117. _vq_quantlist__16u2_p3_0,
  144118. NULL,
  144119. &_vq_auxt__16u2_p3_0,
  144120. NULL,
  144121. 0
  144122. };
  144123. static long _vq_quantlist__16u2_p4_0[] = {
  144124. 8,
  144125. 7,
  144126. 9,
  144127. 6,
  144128. 10,
  144129. 5,
  144130. 11,
  144131. 4,
  144132. 12,
  144133. 3,
  144134. 13,
  144135. 2,
  144136. 14,
  144137. 1,
  144138. 15,
  144139. 0,
  144140. 16,
  144141. };
  144142. static long _vq_lengthlist__16u2_p4_0[] = {
  144143. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144144. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144145. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144146. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144147. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144148. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144149. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144150. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144151. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144152. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144153. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144154. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144155. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144156. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144157. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144158. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144159. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144160. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144161. 14,
  144162. };
  144163. static float _vq_quantthresh__16u2_p4_0[] = {
  144164. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144165. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144166. };
  144167. static long _vq_quantmap__16u2_p4_0[] = {
  144168. 15, 13, 11, 9, 7, 5, 3, 1,
  144169. 0, 2, 4, 6, 8, 10, 12, 14,
  144170. 16,
  144171. };
  144172. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144173. _vq_quantthresh__16u2_p4_0,
  144174. _vq_quantmap__16u2_p4_0,
  144175. 17,
  144176. 17
  144177. };
  144178. static static_codebook _16u2_p4_0 = {
  144179. 2, 289,
  144180. _vq_lengthlist__16u2_p4_0,
  144181. 1, -529530880, 1611661312, 5, 0,
  144182. _vq_quantlist__16u2_p4_0,
  144183. NULL,
  144184. &_vq_auxt__16u2_p4_0,
  144185. NULL,
  144186. 0
  144187. };
  144188. static long _vq_quantlist__16u2_p5_0[] = {
  144189. 1,
  144190. 0,
  144191. 2,
  144192. };
  144193. static long _vq_lengthlist__16u2_p5_0[] = {
  144194. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144195. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144196. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144197. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144198. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144199. 10,
  144200. };
  144201. static float _vq_quantthresh__16u2_p5_0[] = {
  144202. -5.5, 5.5,
  144203. };
  144204. static long _vq_quantmap__16u2_p5_0[] = {
  144205. 1, 0, 2,
  144206. };
  144207. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144208. _vq_quantthresh__16u2_p5_0,
  144209. _vq_quantmap__16u2_p5_0,
  144210. 3,
  144211. 3
  144212. };
  144213. static static_codebook _16u2_p5_0 = {
  144214. 4, 81,
  144215. _vq_lengthlist__16u2_p5_0,
  144216. 1, -529137664, 1618345984, 2, 0,
  144217. _vq_quantlist__16u2_p5_0,
  144218. NULL,
  144219. &_vq_auxt__16u2_p5_0,
  144220. NULL,
  144221. 0
  144222. };
  144223. static long _vq_quantlist__16u2_p5_1[] = {
  144224. 5,
  144225. 4,
  144226. 6,
  144227. 3,
  144228. 7,
  144229. 2,
  144230. 8,
  144231. 1,
  144232. 9,
  144233. 0,
  144234. 10,
  144235. };
  144236. static long _vq_lengthlist__16u2_p5_1[] = {
  144237. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144238. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144239. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144240. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144241. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144242. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144243. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144244. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144245. };
  144246. static float _vq_quantthresh__16u2_p5_1[] = {
  144247. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144248. 3.5, 4.5,
  144249. };
  144250. static long _vq_quantmap__16u2_p5_1[] = {
  144251. 9, 7, 5, 3, 1, 0, 2, 4,
  144252. 6, 8, 10,
  144253. };
  144254. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144255. _vq_quantthresh__16u2_p5_1,
  144256. _vq_quantmap__16u2_p5_1,
  144257. 11,
  144258. 11
  144259. };
  144260. static static_codebook _16u2_p5_1 = {
  144261. 2, 121,
  144262. _vq_lengthlist__16u2_p5_1,
  144263. 1, -531365888, 1611661312, 4, 0,
  144264. _vq_quantlist__16u2_p5_1,
  144265. NULL,
  144266. &_vq_auxt__16u2_p5_1,
  144267. NULL,
  144268. 0
  144269. };
  144270. static long _vq_quantlist__16u2_p6_0[] = {
  144271. 6,
  144272. 5,
  144273. 7,
  144274. 4,
  144275. 8,
  144276. 3,
  144277. 9,
  144278. 2,
  144279. 10,
  144280. 1,
  144281. 11,
  144282. 0,
  144283. 12,
  144284. };
  144285. static long _vq_lengthlist__16u2_p6_0[] = {
  144286. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144287. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144288. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144289. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144290. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144291. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144292. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144293. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144294. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144295. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144296. 12,13,13,14,14,14,14,15,15,
  144297. };
  144298. static float _vq_quantthresh__16u2_p6_0[] = {
  144299. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144300. 12.5, 17.5, 22.5, 27.5,
  144301. };
  144302. static long _vq_quantmap__16u2_p6_0[] = {
  144303. 11, 9, 7, 5, 3, 1, 0, 2,
  144304. 4, 6, 8, 10, 12,
  144305. };
  144306. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144307. _vq_quantthresh__16u2_p6_0,
  144308. _vq_quantmap__16u2_p6_0,
  144309. 13,
  144310. 13
  144311. };
  144312. static static_codebook _16u2_p6_0 = {
  144313. 2, 169,
  144314. _vq_lengthlist__16u2_p6_0,
  144315. 1, -526516224, 1616117760, 4, 0,
  144316. _vq_quantlist__16u2_p6_0,
  144317. NULL,
  144318. &_vq_auxt__16u2_p6_0,
  144319. NULL,
  144320. 0
  144321. };
  144322. static long _vq_quantlist__16u2_p6_1[] = {
  144323. 2,
  144324. 1,
  144325. 3,
  144326. 0,
  144327. 4,
  144328. };
  144329. static long _vq_lengthlist__16u2_p6_1[] = {
  144330. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144331. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144332. };
  144333. static float _vq_quantthresh__16u2_p6_1[] = {
  144334. -1.5, -0.5, 0.5, 1.5,
  144335. };
  144336. static long _vq_quantmap__16u2_p6_1[] = {
  144337. 3, 1, 0, 2, 4,
  144338. };
  144339. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144340. _vq_quantthresh__16u2_p6_1,
  144341. _vq_quantmap__16u2_p6_1,
  144342. 5,
  144343. 5
  144344. };
  144345. static static_codebook _16u2_p6_1 = {
  144346. 2, 25,
  144347. _vq_lengthlist__16u2_p6_1,
  144348. 1, -533725184, 1611661312, 3, 0,
  144349. _vq_quantlist__16u2_p6_1,
  144350. NULL,
  144351. &_vq_auxt__16u2_p6_1,
  144352. NULL,
  144353. 0
  144354. };
  144355. static long _vq_quantlist__16u2_p7_0[] = {
  144356. 6,
  144357. 5,
  144358. 7,
  144359. 4,
  144360. 8,
  144361. 3,
  144362. 9,
  144363. 2,
  144364. 10,
  144365. 1,
  144366. 11,
  144367. 0,
  144368. 12,
  144369. };
  144370. static long _vq_lengthlist__16u2_p7_0[] = {
  144371. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144372. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144373. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144374. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144375. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144376. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144377. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144378. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144379. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144380. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144381. 12,13,13,13,14,14,14,15,14,
  144382. };
  144383. static float _vq_quantthresh__16u2_p7_0[] = {
  144384. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144385. 27.5, 38.5, 49.5, 60.5,
  144386. };
  144387. static long _vq_quantmap__16u2_p7_0[] = {
  144388. 11, 9, 7, 5, 3, 1, 0, 2,
  144389. 4, 6, 8, 10, 12,
  144390. };
  144391. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144392. _vq_quantthresh__16u2_p7_0,
  144393. _vq_quantmap__16u2_p7_0,
  144394. 13,
  144395. 13
  144396. };
  144397. static static_codebook _16u2_p7_0 = {
  144398. 2, 169,
  144399. _vq_lengthlist__16u2_p7_0,
  144400. 1, -523206656, 1618345984, 4, 0,
  144401. _vq_quantlist__16u2_p7_0,
  144402. NULL,
  144403. &_vq_auxt__16u2_p7_0,
  144404. NULL,
  144405. 0
  144406. };
  144407. static long _vq_quantlist__16u2_p7_1[] = {
  144408. 5,
  144409. 4,
  144410. 6,
  144411. 3,
  144412. 7,
  144413. 2,
  144414. 8,
  144415. 1,
  144416. 9,
  144417. 0,
  144418. 10,
  144419. };
  144420. static long _vq_lengthlist__16u2_p7_1[] = {
  144421. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144422. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144423. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144424. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144425. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144426. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144427. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144428. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144429. };
  144430. static float _vq_quantthresh__16u2_p7_1[] = {
  144431. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144432. 3.5, 4.5,
  144433. };
  144434. static long _vq_quantmap__16u2_p7_1[] = {
  144435. 9, 7, 5, 3, 1, 0, 2, 4,
  144436. 6, 8, 10,
  144437. };
  144438. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144439. _vq_quantthresh__16u2_p7_1,
  144440. _vq_quantmap__16u2_p7_1,
  144441. 11,
  144442. 11
  144443. };
  144444. static static_codebook _16u2_p7_1 = {
  144445. 2, 121,
  144446. _vq_lengthlist__16u2_p7_1,
  144447. 1, -531365888, 1611661312, 4, 0,
  144448. _vq_quantlist__16u2_p7_1,
  144449. NULL,
  144450. &_vq_auxt__16u2_p7_1,
  144451. NULL,
  144452. 0
  144453. };
  144454. static long _vq_quantlist__16u2_p8_0[] = {
  144455. 7,
  144456. 6,
  144457. 8,
  144458. 5,
  144459. 9,
  144460. 4,
  144461. 10,
  144462. 3,
  144463. 11,
  144464. 2,
  144465. 12,
  144466. 1,
  144467. 13,
  144468. 0,
  144469. 14,
  144470. };
  144471. static long _vq_lengthlist__16u2_p8_0[] = {
  144472. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144473. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144474. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144475. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144476. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144477. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144478. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144479. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144480. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144481. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144482. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144483. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144484. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144485. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144486. 14,
  144487. };
  144488. static float _vq_quantthresh__16u2_p8_0[] = {
  144489. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144490. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144491. };
  144492. static long _vq_quantmap__16u2_p8_0[] = {
  144493. 13, 11, 9, 7, 5, 3, 1, 0,
  144494. 2, 4, 6, 8, 10, 12, 14,
  144495. };
  144496. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144497. _vq_quantthresh__16u2_p8_0,
  144498. _vq_quantmap__16u2_p8_0,
  144499. 15,
  144500. 15
  144501. };
  144502. static static_codebook _16u2_p8_0 = {
  144503. 2, 225,
  144504. _vq_lengthlist__16u2_p8_0,
  144505. 1, -520986624, 1620377600, 4, 0,
  144506. _vq_quantlist__16u2_p8_0,
  144507. NULL,
  144508. &_vq_auxt__16u2_p8_0,
  144509. NULL,
  144510. 0
  144511. };
  144512. static long _vq_quantlist__16u2_p8_1[] = {
  144513. 10,
  144514. 9,
  144515. 11,
  144516. 8,
  144517. 12,
  144518. 7,
  144519. 13,
  144520. 6,
  144521. 14,
  144522. 5,
  144523. 15,
  144524. 4,
  144525. 16,
  144526. 3,
  144527. 17,
  144528. 2,
  144529. 18,
  144530. 1,
  144531. 19,
  144532. 0,
  144533. 20,
  144534. };
  144535. static long _vq_lengthlist__16u2_p8_1[] = {
  144536. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144537. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144538. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144539. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144540. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144541. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144542. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144543. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144544. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144545. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144546. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144547. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144548. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144549. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144550. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144551. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144552. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144553. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144554. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144555. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144556. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144557. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144558. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144559. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144560. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144561. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144562. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144563. 11,11,10,11,11,11,10,11,11,
  144564. };
  144565. static float _vq_quantthresh__16u2_p8_1[] = {
  144566. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144567. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144568. 6.5, 7.5, 8.5, 9.5,
  144569. };
  144570. static long _vq_quantmap__16u2_p8_1[] = {
  144571. 19, 17, 15, 13, 11, 9, 7, 5,
  144572. 3, 1, 0, 2, 4, 6, 8, 10,
  144573. 12, 14, 16, 18, 20,
  144574. };
  144575. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144576. _vq_quantthresh__16u2_p8_1,
  144577. _vq_quantmap__16u2_p8_1,
  144578. 21,
  144579. 21
  144580. };
  144581. static static_codebook _16u2_p8_1 = {
  144582. 2, 441,
  144583. _vq_lengthlist__16u2_p8_1,
  144584. 1, -529268736, 1611661312, 5, 0,
  144585. _vq_quantlist__16u2_p8_1,
  144586. NULL,
  144587. &_vq_auxt__16u2_p8_1,
  144588. NULL,
  144589. 0
  144590. };
  144591. static long _vq_quantlist__16u2_p9_0[] = {
  144592. 5586,
  144593. 4655,
  144594. 6517,
  144595. 3724,
  144596. 7448,
  144597. 2793,
  144598. 8379,
  144599. 1862,
  144600. 9310,
  144601. 931,
  144602. 10241,
  144603. 0,
  144604. 11172,
  144605. 5521,
  144606. 5651,
  144607. };
  144608. static long _vq_lengthlist__16u2_p9_0[] = {
  144609. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144610. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144611. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144612. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144613. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144614. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144615. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144616. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144617. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144618. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144619. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144620. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144621. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144622. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144623. 5,
  144624. };
  144625. static float _vq_quantthresh__16u2_p9_0[] = {
  144626. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144627. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144628. };
  144629. static long _vq_quantmap__16u2_p9_0[] = {
  144630. 11, 9, 7, 5, 3, 1, 13, 0,
  144631. 14, 2, 4, 6, 8, 10, 12,
  144632. };
  144633. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144634. _vq_quantthresh__16u2_p9_0,
  144635. _vq_quantmap__16u2_p9_0,
  144636. 15,
  144637. 15
  144638. };
  144639. static static_codebook _16u2_p9_0 = {
  144640. 2, 225,
  144641. _vq_lengthlist__16u2_p9_0,
  144642. 1, -510275072, 1611661312, 14, 0,
  144643. _vq_quantlist__16u2_p9_0,
  144644. NULL,
  144645. &_vq_auxt__16u2_p9_0,
  144646. NULL,
  144647. 0
  144648. };
  144649. static long _vq_quantlist__16u2_p9_1[] = {
  144650. 392,
  144651. 343,
  144652. 441,
  144653. 294,
  144654. 490,
  144655. 245,
  144656. 539,
  144657. 196,
  144658. 588,
  144659. 147,
  144660. 637,
  144661. 98,
  144662. 686,
  144663. 49,
  144664. 735,
  144665. 0,
  144666. 784,
  144667. 388,
  144668. 396,
  144669. };
  144670. static long _vq_lengthlist__16u2_p9_1[] = {
  144671. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144672. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144673. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144674. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144675. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144676. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144677. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144678. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144679. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144680. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144681. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144682. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144683. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144684. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144685. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144687. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144688. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144689. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144690. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144691. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144692. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144693. 11,11,11,11,11,11,11, 5, 4,
  144694. };
  144695. static float _vq_quantthresh__16u2_p9_1[] = {
  144696. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144697. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144698. 318.5, 367.5,
  144699. };
  144700. static long _vq_quantmap__16u2_p9_1[] = {
  144701. 15, 13, 11, 9, 7, 5, 3, 1,
  144702. 17, 0, 18, 2, 4, 6, 8, 10,
  144703. 12, 14, 16,
  144704. };
  144705. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144706. _vq_quantthresh__16u2_p9_1,
  144707. _vq_quantmap__16u2_p9_1,
  144708. 19,
  144709. 19
  144710. };
  144711. static static_codebook _16u2_p9_1 = {
  144712. 2, 361,
  144713. _vq_lengthlist__16u2_p9_1,
  144714. 1, -518488064, 1611661312, 10, 0,
  144715. _vq_quantlist__16u2_p9_1,
  144716. NULL,
  144717. &_vq_auxt__16u2_p9_1,
  144718. NULL,
  144719. 0
  144720. };
  144721. static long _vq_quantlist__16u2_p9_2[] = {
  144722. 24,
  144723. 23,
  144724. 25,
  144725. 22,
  144726. 26,
  144727. 21,
  144728. 27,
  144729. 20,
  144730. 28,
  144731. 19,
  144732. 29,
  144733. 18,
  144734. 30,
  144735. 17,
  144736. 31,
  144737. 16,
  144738. 32,
  144739. 15,
  144740. 33,
  144741. 14,
  144742. 34,
  144743. 13,
  144744. 35,
  144745. 12,
  144746. 36,
  144747. 11,
  144748. 37,
  144749. 10,
  144750. 38,
  144751. 9,
  144752. 39,
  144753. 8,
  144754. 40,
  144755. 7,
  144756. 41,
  144757. 6,
  144758. 42,
  144759. 5,
  144760. 43,
  144761. 4,
  144762. 44,
  144763. 3,
  144764. 45,
  144765. 2,
  144766. 46,
  144767. 1,
  144768. 47,
  144769. 0,
  144770. 48,
  144771. };
  144772. static long _vq_lengthlist__16u2_p9_2[] = {
  144773. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144774. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144775. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144776. 11,
  144777. };
  144778. static float _vq_quantthresh__16u2_p9_2[] = {
  144779. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144780. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144781. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144782. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144783. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144784. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144785. };
  144786. static long _vq_quantmap__16u2_p9_2[] = {
  144787. 47, 45, 43, 41, 39, 37, 35, 33,
  144788. 31, 29, 27, 25, 23, 21, 19, 17,
  144789. 15, 13, 11, 9, 7, 5, 3, 1,
  144790. 0, 2, 4, 6, 8, 10, 12, 14,
  144791. 16, 18, 20, 22, 24, 26, 28, 30,
  144792. 32, 34, 36, 38, 40, 42, 44, 46,
  144793. 48,
  144794. };
  144795. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144796. _vq_quantthresh__16u2_p9_2,
  144797. _vq_quantmap__16u2_p9_2,
  144798. 49,
  144799. 49
  144800. };
  144801. static static_codebook _16u2_p9_2 = {
  144802. 1, 49,
  144803. _vq_lengthlist__16u2_p9_2,
  144804. 1, -526909440, 1611661312, 6, 0,
  144805. _vq_quantlist__16u2_p9_2,
  144806. NULL,
  144807. &_vq_auxt__16u2_p9_2,
  144808. NULL,
  144809. 0
  144810. };
  144811. static long _vq_quantlist__8u0__p1_0[] = {
  144812. 1,
  144813. 0,
  144814. 2,
  144815. };
  144816. static long _vq_lengthlist__8u0__p1_0[] = {
  144817. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144818. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144819. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144820. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144821. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144822. 11,
  144823. };
  144824. static float _vq_quantthresh__8u0__p1_0[] = {
  144825. -0.5, 0.5,
  144826. };
  144827. static long _vq_quantmap__8u0__p1_0[] = {
  144828. 1, 0, 2,
  144829. };
  144830. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144831. _vq_quantthresh__8u0__p1_0,
  144832. _vq_quantmap__8u0__p1_0,
  144833. 3,
  144834. 3
  144835. };
  144836. static static_codebook _8u0__p1_0 = {
  144837. 4, 81,
  144838. _vq_lengthlist__8u0__p1_0,
  144839. 1, -535822336, 1611661312, 2, 0,
  144840. _vq_quantlist__8u0__p1_0,
  144841. NULL,
  144842. &_vq_auxt__8u0__p1_0,
  144843. NULL,
  144844. 0
  144845. };
  144846. static long _vq_quantlist__8u0__p2_0[] = {
  144847. 1,
  144848. 0,
  144849. 2,
  144850. };
  144851. static long _vq_lengthlist__8u0__p2_0[] = {
  144852. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144853. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144854. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144855. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144856. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144857. 8,
  144858. };
  144859. static float _vq_quantthresh__8u0__p2_0[] = {
  144860. -0.5, 0.5,
  144861. };
  144862. static long _vq_quantmap__8u0__p2_0[] = {
  144863. 1, 0, 2,
  144864. };
  144865. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144866. _vq_quantthresh__8u0__p2_0,
  144867. _vq_quantmap__8u0__p2_0,
  144868. 3,
  144869. 3
  144870. };
  144871. static static_codebook _8u0__p2_0 = {
  144872. 4, 81,
  144873. _vq_lengthlist__8u0__p2_0,
  144874. 1, -535822336, 1611661312, 2, 0,
  144875. _vq_quantlist__8u0__p2_0,
  144876. NULL,
  144877. &_vq_auxt__8u0__p2_0,
  144878. NULL,
  144879. 0
  144880. };
  144881. static long _vq_quantlist__8u0__p3_0[] = {
  144882. 2,
  144883. 1,
  144884. 3,
  144885. 0,
  144886. 4,
  144887. };
  144888. static long _vq_lengthlist__8u0__p3_0[] = {
  144889. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144890. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144891. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144892. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144893. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144894. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144895. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144896. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144897. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144898. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144899. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144900. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144901. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144902. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144903. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144904. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144905. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144906. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144907. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144908. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144909. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144910. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144911. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144912. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144913. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144914. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144915. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144916. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144917. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144918. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144919. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144920. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144921. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144922. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144923. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144924. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144925. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144926. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144927. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144928. 16,
  144929. };
  144930. static float _vq_quantthresh__8u0__p3_0[] = {
  144931. -1.5, -0.5, 0.5, 1.5,
  144932. };
  144933. static long _vq_quantmap__8u0__p3_0[] = {
  144934. 3, 1, 0, 2, 4,
  144935. };
  144936. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144937. _vq_quantthresh__8u0__p3_0,
  144938. _vq_quantmap__8u0__p3_0,
  144939. 5,
  144940. 5
  144941. };
  144942. static static_codebook _8u0__p3_0 = {
  144943. 4, 625,
  144944. _vq_lengthlist__8u0__p3_0,
  144945. 1, -533725184, 1611661312, 3, 0,
  144946. _vq_quantlist__8u0__p3_0,
  144947. NULL,
  144948. &_vq_auxt__8u0__p3_0,
  144949. NULL,
  144950. 0
  144951. };
  144952. static long _vq_quantlist__8u0__p4_0[] = {
  144953. 2,
  144954. 1,
  144955. 3,
  144956. 0,
  144957. 4,
  144958. };
  144959. static long _vq_lengthlist__8u0__p4_0[] = {
  144960. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144961. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144962. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144963. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144964. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144965. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144966. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144967. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144968. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144969. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144970. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144971. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144972. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144973. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144974. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144975. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144976. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144977. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144978. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144979. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144980. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144981. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144982. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144983. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144984. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144985. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144986. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144987. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144988. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144989. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144990. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144991. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144992. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144993. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144994. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144995. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144996. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144997. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144998. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144999. 12,
  145000. };
  145001. static float _vq_quantthresh__8u0__p4_0[] = {
  145002. -1.5, -0.5, 0.5, 1.5,
  145003. };
  145004. static long _vq_quantmap__8u0__p4_0[] = {
  145005. 3, 1, 0, 2, 4,
  145006. };
  145007. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145008. _vq_quantthresh__8u0__p4_0,
  145009. _vq_quantmap__8u0__p4_0,
  145010. 5,
  145011. 5
  145012. };
  145013. static static_codebook _8u0__p4_0 = {
  145014. 4, 625,
  145015. _vq_lengthlist__8u0__p4_0,
  145016. 1, -533725184, 1611661312, 3, 0,
  145017. _vq_quantlist__8u0__p4_0,
  145018. NULL,
  145019. &_vq_auxt__8u0__p4_0,
  145020. NULL,
  145021. 0
  145022. };
  145023. static long _vq_quantlist__8u0__p5_0[] = {
  145024. 4,
  145025. 3,
  145026. 5,
  145027. 2,
  145028. 6,
  145029. 1,
  145030. 7,
  145031. 0,
  145032. 8,
  145033. };
  145034. static long _vq_lengthlist__8u0__p5_0[] = {
  145035. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145036. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145037. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145038. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145039. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145040. 12,
  145041. };
  145042. static float _vq_quantthresh__8u0__p5_0[] = {
  145043. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145044. };
  145045. static long _vq_quantmap__8u0__p5_0[] = {
  145046. 7, 5, 3, 1, 0, 2, 4, 6,
  145047. 8,
  145048. };
  145049. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145050. _vq_quantthresh__8u0__p5_0,
  145051. _vq_quantmap__8u0__p5_0,
  145052. 9,
  145053. 9
  145054. };
  145055. static static_codebook _8u0__p5_0 = {
  145056. 2, 81,
  145057. _vq_lengthlist__8u0__p5_0,
  145058. 1, -531628032, 1611661312, 4, 0,
  145059. _vq_quantlist__8u0__p5_0,
  145060. NULL,
  145061. &_vq_auxt__8u0__p5_0,
  145062. NULL,
  145063. 0
  145064. };
  145065. static long _vq_quantlist__8u0__p6_0[] = {
  145066. 6,
  145067. 5,
  145068. 7,
  145069. 4,
  145070. 8,
  145071. 3,
  145072. 9,
  145073. 2,
  145074. 10,
  145075. 1,
  145076. 11,
  145077. 0,
  145078. 12,
  145079. };
  145080. static long _vq_lengthlist__8u0__p6_0[] = {
  145081. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145082. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145083. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145084. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145085. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145086. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145087. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145088. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145089. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145090. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145091. 16, 0,15, 0,17, 0, 0, 0, 0,
  145092. };
  145093. static float _vq_quantthresh__8u0__p6_0[] = {
  145094. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145095. 12.5, 17.5, 22.5, 27.5,
  145096. };
  145097. static long _vq_quantmap__8u0__p6_0[] = {
  145098. 11, 9, 7, 5, 3, 1, 0, 2,
  145099. 4, 6, 8, 10, 12,
  145100. };
  145101. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145102. _vq_quantthresh__8u0__p6_0,
  145103. _vq_quantmap__8u0__p6_0,
  145104. 13,
  145105. 13
  145106. };
  145107. static static_codebook _8u0__p6_0 = {
  145108. 2, 169,
  145109. _vq_lengthlist__8u0__p6_0,
  145110. 1, -526516224, 1616117760, 4, 0,
  145111. _vq_quantlist__8u0__p6_0,
  145112. NULL,
  145113. &_vq_auxt__8u0__p6_0,
  145114. NULL,
  145115. 0
  145116. };
  145117. static long _vq_quantlist__8u0__p6_1[] = {
  145118. 2,
  145119. 1,
  145120. 3,
  145121. 0,
  145122. 4,
  145123. };
  145124. static long _vq_lengthlist__8u0__p6_1[] = {
  145125. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145126. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145127. };
  145128. static float _vq_quantthresh__8u0__p6_1[] = {
  145129. -1.5, -0.5, 0.5, 1.5,
  145130. };
  145131. static long _vq_quantmap__8u0__p6_1[] = {
  145132. 3, 1, 0, 2, 4,
  145133. };
  145134. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145135. _vq_quantthresh__8u0__p6_1,
  145136. _vq_quantmap__8u0__p6_1,
  145137. 5,
  145138. 5
  145139. };
  145140. static static_codebook _8u0__p6_1 = {
  145141. 2, 25,
  145142. _vq_lengthlist__8u0__p6_1,
  145143. 1, -533725184, 1611661312, 3, 0,
  145144. _vq_quantlist__8u0__p6_1,
  145145. NULL,
  145146. &_vq_auxt__8u0__p6_1,
  145147. NULL,
  145148. 0
  145149. };
  145150. static long _vq_quantlist__8u0__p7_0[] = {
  145151. 1,
  145152. 0,
  145153. 2,
  145154. };
  145155. static long _vq_lengthlist__8u0__p7_0[] = {
  145156. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145157. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145158. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145159. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145160. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145161. 7,
  145162. };
  145163. static float _vq_quantthresh__8u0__p7_0[] = {
  145164. -157.5, 157.5,
  145165. };
  145166. static long _vq_quantmap__8u0__p7_0[] = {
  145167. 1, 0, 2,
  145168. };
  145169. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145170. _vq_quantthresh__8u0__p7_0,
  145171. _vq_quantmap__8u0__p7_0,
  145172. 3,
  145173. 3
  145174. };
  145175. static static_codebook _8u0__p7_0 = {
  145176. 4, 81,
  145177. _vq_lengthlist__8u0__p7_0,
  145178. 1, -518803456, 1628680192, 2, 0,
  145179. _vq_quantlist__8u0__p7_0,
  145180. NULL,
  145181. &_vq_auxt__8u0__p7_0,
  145182. NULL,
  145183. 0
  145184. };
  145185. static long _vq_quantlist__8u0__p7_1[] = {
  145186. 7,
  145187. 6,
  145188. 8,
  145189. 5,
  145190. 9,
  145191. 4,
  145192. 10,
  145193. 3,
  145194. 11,
  145195. 2,
  145196. 12,
  145197. 1,
  145198. 13,
  145199. 0,
  145200. 14,
  145201. };
  145202. static long _vq_lengthlist__8u0__p7_1[] = {
  145203. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145204. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145205. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145206. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145207. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145208. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145209. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145210. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145211. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145212. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145213. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145214. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145215. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145216. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145217. 10,
  145218. };
  145219. static float _vq_quantthresh__8u0__p7_1[] = {
  145220. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145221. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145222. };
  145223. static long _vq_quantmap__8u0__p7_1[] = {
  145224. 13, 11, 9, 7, 5, 3, 1, 0,
  145225. 2, 4, 6, 8, 10, 12, 14,
  145226. };
  145227. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145228. _vq_quantthresh__8u0__p7_1,
  145229. _vq_quantmap__8u0__p7_1,
  145230. 15,
  145231. 15
  145232. };
  145233. static static_codebook _8u0__p7_1 = {
  145234. 2, 225,
  145235. _vq_lengthlist__8u0__p7_1,
  145236. 1, -520986624, 1620377600, 4, 0,
  145237. _vq_quantlist__8u0__p7_1,
  145238. NULL,
  145239. &_vq_auxt__8u0__p7_1,
  145240. NULL,
  145241. 0
  145242. };
  145243. static long _vq_quantlist__8u0__p7_2[] = {
  145244. 10,
  145245. 9,
  145246. 11,
  145247. 8,
  145248. 12,
  145249. 7,
  145250. 13,
  145251. 6,
  145252. 14,
  145253. 5,
  145254. 15,
  145255. 4,
  145256. 16,
  145257. 3,
  145258. 17,
  145259. 2,
  145260. 18,
  145261. 1,
  145262. 19,
  145263. 0,
  145264. 20,
  145265. };
  145266. static long _vq_lengthlist__8u0__p7_2[] = {
  145267. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145268. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145269. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145270. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145271. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145272. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145273. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145274. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145275. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145276. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145277. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145278. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145279. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145280. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145281. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145282. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145283. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145284. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145285. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145286. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145287. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145288. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145289. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145290. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145291. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145292. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145293. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145294. 11,12,11,11,11,10,10,11,11,
  145295. };
  145296. static float _vq_quantthresh__8u0__p7_2[] = {
  145297. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145298. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145299. 6.5, 7.5, 8.5, 9.5,
  145300. };
  145301. static long _vq_quantmap__8u0__p7_2[] = {
  145302. 19, 17, 15, 13, 11, 9, 7, 5,
  145303. 3, 1, 0, 2, 4, 6, 8, 10,
  145304. 12, 14, 16, 18, 20,
  145305. };
  145306. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145307. _vq_quantthresh__8u0__p7_2,
  145308. _vq_quantmap__8u0__p7_2,
  145309. 21,
  145310. 21
  145311. };
  145312. static static_codebook _8u0__p7_2 = {
  145313. 2, 441,
  145314. _vq_lengthlist__8u0__p7_2,
  145315. 1, -529268736, 1611661312, 5, 0,
  145316. _vq_quantlist__8u0__p7_2,
  145317. NULL,
  145318. &_vq_auxt__8u0__p7_2,
  145319. NULL,
  145320. 0
  145321. };
  145322. static long _huff_lengthlist__8u0__single[] = {
  145323. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145324. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145325. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145326. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145327. };
  145328. static static_codebook _huff_book__8u0__single = {
  145329. 2, 64,
  145330. _huff_lengthlist__8u0__single,
  145331. 0, 0, 0, 0, 0,
  145332. NULL,
  145333. NULL,
  145334. NULL,
  145335. NULL,
  145336. 0
  145337. };
  145338. static long _vq_quantlist__8u1__p1_0[] = {
  145339. 1,
  145340. 0,
  145341. 2,
  145342. };
  145343. static long _vq_lengthlist__8u1__p1_0[] = {
  145344. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145345. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145346. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145347. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145348. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145349. 10,
  145350. };
  145351. static float _vq_quantthresh__8u1__p1_0[] = {
  145352. -0.5, 0.5,
  145353. };
  145354. static long _vq_quantmap__8u1__p1_0[] = {
  145355. 1, 0, 2,
  145356. };
  145357. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145358. _vq_quantthresh__8u1__p1_0,
  145359. _vq_quantmap__8u1__p1_0,
  145360. 3,
  145361. 3
  145362. };
  145363. static static_codebook _8u1__p1_0 = {
  145364. 4, 81,
  145365. _vq_lengthlist__8u1__p1_0,
  145366. 1, -535822336, 1611661312, 2, 0,
  145367. _vq_quantlist__8u1__p1_0,
  145368. NULL,
  145369. &_vq_auxt__8u1__p1_0,
  145370. NULL,
  145371. 0
  145372. };
  145373. static long _vq_quantlist__8u1__p2_0[] = {
  145374. 1,
  145375. 0,
  145376. 2,
  145377. };
  145378. static long _vq_lengthlist__8u1__p2_0[] = {
  145379. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145380. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145381. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145382. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145383. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145384. 7,
  145385. };
  145386. static float _vq_quantthresh__8u1__p2_0[] = {
  145387. -0.5, 0.5,
  145388. };
  145389. static long _vq_quantmap__8u1__p2_0[] = {
  145390. 1, 0, 2,
  145391. };
  145392. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145393. _vq_quantthresh__8u1__p2_0,
  145394. _vq_quantmap__8u1__p2_0,
  145395. 3,
  145396. 3
  145397. };
  145398. static static_codebook _8u1__p2_0 = {
  145399. 4, 81,
  145400. _vq_lengthlist__8u1__p2_0,
  145401. 1, -535822336, 1611661312, 2, 0,
  145402. _vq_quantlist__8u1__p2_0,
  145403. NULL,
  145404. &_vq_auxt__8u1__p2_0,
  145405. NULL,
  145406. 0
  145407. };
  145408. static long _vq_quantlist__8u1__p3_0[] = {
  145409. 2,
  145410. 1,
  145411. 3,
  145412. 0,
  145413. 4,
  145414. };
  145415. static long _vq_lengthlist__8u1__p3_0[] = {
  145416. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145417. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145418. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145419. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145420. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145421. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145422. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145423. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145424. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145425. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145426. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145427. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145428. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145429. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145430. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145431. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145432. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145433. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145434. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145435. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145436. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145437. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145438. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145439. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145440. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145441. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145442. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145443. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145444. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145445. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145446. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145447. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145448. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145449. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145450. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145451. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145452. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145453. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145454. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145455. 16,
  145456. };
  145457. static float _vq_quantthresh__8u1__p3_0[] = {
  145458. -1.5, -0.5, 0.5, 1.5,
  145459. };
  145460. static long _vq_quantmap__8u1__p3_0[] = {
  145461. 3, 1, 0, 2, 4,
  145462. };
  145463. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145464. _vq_quantthresh__8u1__p3_0,
  145465. _vq_quantmap__8u1__p3_0,
  145466. 5,
  145467. 5
  145468. };
  145469. static static_codebook _8u1__p3_0 = {
  145470. 4, 625,
  145471. _vq_lengthlist__8u1__p3_0,
  145472. 1, -533725184, 1611661312, 3, 0,
  145473. _vq_quantlist__8u1__p3_0,
  145474. NULL,
  145475. &_vq_auxt__8u1__p3_0,
  145476. NULL,
  145477. 0
  145478. };
  145479. static long _vq_quantlist__8u1__p4_0[] = {
  145480. 2,
  145481. 1,
  145482. 3,
  145483. 0,
  145484. 4,
  145485. };
  145486. static long _vq_lengthlist__8u1__p4_0[] = {
  145487. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145488. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145489. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145490. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145491. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145492. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145493. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145494. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145495. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145496. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145497. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145498. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145499. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145500. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145501. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145502. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145503. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145504. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145505. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145506. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145507. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145508. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145509. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145510. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145511. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145512. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145513. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145514. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145515. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145516. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145517. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145518. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145519. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145520. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145521. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145522. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145523. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145524. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145525. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145526. 10,
  145527. };
  145528. static float _vq_quantthresh__8u1__p4_0[] = {
  145529. -1.5, -0.5, 0.5, 1.5,
  145530. };
  145531. static long _vq_quantmap__8u1__p4_0[] = {
  145532. 3, 1, 0, 2, 4,
  145533. };
  145534. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145535. _vq_quantthresh__8u1__p4_0,
  145536. _vq_quantmap__8u1__p4_0,
  145537. 5,
  145538. 5
  145539. };
  145540. static static_codebook _8u1__p4_0 = {
  145541. 4, 625,
  145542. _vq_lengthlist__8u1__p4_0,
  145543. 1, -533725184, 1611661312, 3, 0,
  145544. _vq_quantlist__8u1__p4_0,
  145545. NULL,
  145546. &_vq_auxt__8u1__p4_0,
  145547. NULL,
  145548. 0
  145549. };
  145550. static long _vq_quantlist__8u1__p5_0[] = {
  145551. 4,
  145552. 3,
  145553. 5,
  145554. 2,
  145555. 6,
  145556. 1,
  145557. 7,
  145558. 0,
  145559. 8,
  145560. };
  145561. static long _vq_lengthlist__8u1__p5_0[] = {
  145562. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145563. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145564. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145565. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145566. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145567. 13,
  145568. };
  145569. static float _vq_quantthresh__8u1__p5_0[] = {
  145570. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145571. };
  145572. static long _vq_quantmap__8u1__p5_0[] = {
  145573. 7, 5, 3, 1, 0, 2, 4, 6,
  145574. 8,
  145575. };
  145576. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145577. _vq_quantthresh__8u1__p5_0,
  145578. _vq_quantmap__8u1__p5_0,
  145579. 9,
  145580. 9
  145581. };
  145582. static static_codebook _8u1__p5_0 = {
  145583. 2, 81,
  145584. _vq_lengthlist__8u1__p5_0,
  145585. 1, -531628032, 1611661312, 4, 0,
  145586. _vq_quantlist__8u1__p5_0,
  145587. NULL,
  145588. &_vq_auxt__8u1__p5_0,
  145589. NULL,
  145590. 0
  145591. };
  145592. static long _vq_quantlist__8u1__p6_0[] = {
  145593. 4,
  145594. 3,
  145595. 5,
  145596. 2,
  145597. 6,
  145598. 1,
  145599. 7,
  145600. 0,
  145601. 8,
  145602. };
  145603. static long _vq_lengthlist__8u1__p6_0[] = {
  145604. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145605. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145606. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145607. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145608. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145609. 10,
  145610. };
  145611. static float _vq_quantthresh__8u1__p6_0[] = {
  145612. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145613. };
  145614. static long _vq_quantmap__8u1__p6_0[] = {
  145615. 7, 5, 3, 1, 0, 2, 4, 6,
  145616. 8,
  145617. };
  145618. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145619. _vq_quantthresh__8u1__p6_0,
  145620. _vq_quantmap__8u1__p6_0,
  145621. 9,
  145622. 9
  145623. };
  145624. static static_codebook _8u1__p6_0 = {
  145625. 2, 81,
  145626. _vq_lengthlist__8u1__p6_0,
  145627. 1, -531628032, 1611661312, 4, 0,
  145628. _vq_quantlist__8u1__p6_0,
  145629. NULL,
  145630. &_vq_auxt__8u1__p6_0,
  145631. NULL,
  145632. 0
  145633. };
  145634. static long _vq_quantlist__8u1__p7_0[] = {
  145635. 1,
  145636. 0,
  145637. 2,
  145638. };
  145639. static long _vq_lengthlist__8u1__p7_0[] = {
  145640. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145641. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145642. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145643. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145644. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145645. 11,
  145646. };
  145647. static float _vq_quantthresh__8u1__p7_0[] = {
  145648. -5.5, 5.5,
  145649. };
  145650. static long _vq_quantmap__8u1__p7_0[] = {
  145651. 1, 0, 2,
  145652. };
  145653. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145654. _vq_quantthresh__8u1__p7_0,
  145655. _vq_quantmap__8u1__p7_0,
  145656. 3,
  145657. 3
  145658. };
  145659. static static_codebook _8u1__p7_0 = {
  145660. 4, 81,
  145661. _vq_lengthlist__8u1__p7_0,
  145662. 1, -529137664, 1618345984, 2, 0,
  145663. _vq_quantlist__8u1__p7_0,
  145664. NULL,
  145665. &_vq_auxt__8u1__p7_0,
  145666. NULL,
  145667. 0
  145668. };
  145669. static long _vq_quantlist__8u1__p7_1[] = {
  145670. 5,
  145671. 4,
  145672. 6,
  145673. 3,
  145674. 7,
  145675. 2,
  145676. 8,
  145677. 1,
  145678. 9,
  145679. 0,
  145680. 10,
  145681. };
  145682. static long _vq_lengthlist__8u1__p7_1[] = {
  145683. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145684. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145685. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145686. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145687. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145688. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145689. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145690. 9, 9, 9, 9, 9,10,10,10,10,
  145691. };
  145692. static float _vq_quantthresh__8u1__p7_1[] = {
  145693. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145694. 3.5, 4.5,
  145695. };
  145696. static long _vq_quantmap__8u1__p7_1[] = {
  145697. 9, 7, 5, 3, 1, 0, 2, 4,
  145698. 6, 8, 10,
  145699. };
  145700. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145701. _vq_quantthresh__8u1__p7_1,
  145702. _vq_quantmap__8u1__p7_1,
  145703. 11,
  145704. 11
  145705. };
  145706. static static_codebook _8u1__p7_1 = {
  145707. 2, 121,
  145708. _vq_lengthlist__8u1__p7_1,
  145709. 1, -531365888, 1611661312, 4, 0,
  145710. _vq_quantlist__8u1__p7_1,
  145711. NULL,
  145712. &_vq_auxt__8u1__p7_1,
  145713. NULL,
  145714. 0
  145715. };
  145716. static long _vq_quantlist__8u1__p8_0[] = {
  145717. 5,
  145718. 4,
  145719. 6,
  145720. 3,
  145721. 7,
  145722. 2,
  145723. 8,
  145724. 1,
  145725. 9,
  145726. 0,
  145727. 10,
  145728. };
  145729. static long _vq_lengthlist__8u1__p8_0[] = {
  145730. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145731. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145732. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145733. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145734. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145735. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145736. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145737. 12,13,13,14,14,15,15,15,15,
  145738. };
  145739. static float _vq_quantthresh__8u1__p8_0[] = {
  145740. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145741. 38.5, 49.5,
  145742. };
  145743. static long _vq_quantmap__8u1__p8_0[] = {
  145744. 9, 7, 5, 3, 1, 0, 2, 4,
  145745. 6, 8, 10,
  145746. };
  145747. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145748. _vq_quantthresh__8u1__p8_0,
  145749. _vq_quantmap__8u1__p8_0,
  145750. 11,
  145751. 11
  145752. };
  145753. static static_codebook _8u1__p8_0 = {
  145754. 2, 121,
  145755. _vq_lengthlist__8u1__p8_0,
  145756. 1, -524582912, 1618345984, 4, 0,
  145757. _vq_quantlist__8u1__p8_0,
  145758. NULL,
  145759. &_vq_auxt__8u1__p8_0,
  145760. NULL,
  145761. 0
  145762. };
  145763. static long _vq_quantlist__8u1__p8_1[] = {
  145764. 5,
  145765. 4,
  145766. 6,
  145767. 3,
  145768. 7,
  145769. 2,
  145770. 8,
  145771. 1,
  145772. 9,
  145773. 0,
  145774. 10,
  145775. };
  145776. static long _vq_lengthlist__8u1__p8_1[] = {
  145777. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145778. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145779. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145780. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145781. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145782. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145783. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145784. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145785. };
  145786. static float _vq_quantthresh__8u1__p8_1[] = {
  145787. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145788. 3.5, 4.5,
  145789. };
  145790. static long _vq_quantmap__8u1__p8_1[] = {
  145791. 9, 7, 5, 3, 1, 0, 2, 4,
  145792. 6, 8, 10,
  145793. };
  145794. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145795. _vq_quantthresh__8u1__p8_1,
  145796. _vq_quantmap__8u1__p8_1,
  145797. 11,
  145798. 11
  145799. };
  145800. static static_codebook _8u1__p8_1 = {
  145801. 2, 121,
  145802. _vq_lengthlist__8u1__p8_1,
  145803. 1, -531365888, 1611661312, 4, 0,
  145804. _vq_quantlist__8u1__p8_1,
  145805. NULL,
  145806. &_vq_auxt__8u1__p8_1,
  145807. NULL,
  145808. 0
  145809. };
  145810. static long _vq_quantlist__8u1__p9_0[] = {
  145811. 7,
  145812. 6,
  145813. 8,
  145814. 5,
  145815. 9,
  145816. 4,
  145817. 10,
  145818. 3,
  145819. 11,
  145820. 2,
  145821. 12,
  145822. 1,
  145823. 13,
  145824. 0,
  145825. 14,
  145826. };
  145827. static long _vq_lengthlist__8u1__p9_0[] = {
  145828. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145829. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145830. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145832. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145833. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145834. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145836. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145837. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145838. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145840. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145841. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145842. 10,
  145843. };
  145844. static float _vq_quantthresh__8u1__p9_0[] = {
  145845. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145846. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145847. };
  145848. static long _vq_quantmap__8u1__p9_0[] = {
  145849. 13, 11, 9, 7, 5, 3, 1, 0,
  145850. 2, 4, 6, 8, 10, 12, 14,
  145851. };
  145852. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145853. _vq_quantthresh__8u1__p9_0,
  145854. _vq_quantmap__8u1__p9_0,
  145855. 15,
  145856. 15
  145857. };
  145858. static static_codebook _8u1__p9_0 = {
  145859. 2, 225,
  145860. _vq_lengthlist__8u1__p9_0,
  145861. 1, -514071552, 1627381760, 4, 0,
  145862. _vq_quantlist__8u1__p9_0,
  145863. NULL,
  145864. &_vq_auxt__8u1__p9_0,
  145865. NULL,
  145866. 0
  145867. };
  145868. static long _vq_quantlist__8u1__p9_1[] = {
  145869. 7,
  145870. 6,
  145871. 8,
  145872. 5,
  145873. 9,
  145874. 4,
  145875. 10,
  145876. 3,
  145877. 11,
  145878. 2,
  145879. 12,
  145880. 1,
  145881. 13,
  145882. 0,
  145883. 14,
  145884. };
  145885. static long _vq_lengthlist__8u1__p9_1[] = {
  145886. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145887. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145888. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145889. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145890. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145891. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145892. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145893. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145894. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145895. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145896. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145897. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145898. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145899. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145900. 13,
  145901. };
  145902. static float _vq_quantthresh__8u1__p9_1[] = {
  145903. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145904. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145905. };
  145906. static long _vq_quantmap__8u1__p9_1[] = {
  145907. 13, 11, 9, 7, 5, 3, 1, 0,
  145908. 2, 4, 6, 8, 10, 12, 14,
  145909. };
  145910. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145911. _vq_quantthresh__8u1__p9_1,
  145912. _vq_quantmap__8u1__p9_1,
  145913. 15,
  145914. 15
  145915. };
  145916. static static_codebook _8u1__p9_1 = {
  145917. 2, 225,
  145918. _vq_lengthlist__8u1__p9_1,
  145919. 1, -522338304, 1620115456, 4, 0,
  145920. _vq_quantlist__8u1__p9_1,
  145921. NULL,
  145922. &_vq_auxt__8u1__p9_1,
  145923. NULL,
  145924. 0
  145925. };
  145926. static long _vq_quantlist__8u1__p9_2[] = {
  145927. 8,
  145928. 7,
  145929. 9,
  145930. 6,
  145931. 10,
  145932. 5,
  145933. 11,
  145934. 4,
  145935. 12,
  145936. 3,
  145937. 13,
  145938. 2,
  145939. 14,
  145940. 1,
  145941. 15,
  145942. 0,
  145943. 16,
  145944. };
  145945. static long _vq_lengthlist__8u1__p9_2[] = {
  145946. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145947. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145948. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145949. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145950. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145951. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145952. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145953. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145954. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145955. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145956. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145957. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145958. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145959. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145960. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145961. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145962. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145963. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145964. 10,
  145965. };
  145966. static float _vq_quantthresh__8u1__p9_2[] = {
  145967. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145968. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145969. };
  145970. static long _vq_quantmap__8u1__p9_2[] = {
  145971. 15, 13, 11, 9, 7, 5, 3, 1,
  145972. 0, 2, 4, 6, 8, 10, 12, 14,
  145973. 16,
  145974. };
  145975. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145976. _vq_quantthresh__8u1__p9_2,
  145977. _vq_quantmap__8u1__p9_2,
  145978. 17,
  145979. 17
  145980. };
  145981. static static_codebook _8u1__p9_2 = {
  145982. 2, 289,
  145983. _vq_lengthlist__8u1__p9_2,
  145984. 1, -529530880, 1611661312, 5, 0,
  145985. _vq_quantlist__8u1__p9_2,
  145986. NULL,
  145987. &_vq_auxt__8u1__p9_2,
  145988. NULL,
  145989. 0
  145990. };
  145991. static long _huff_lengthlist__8u1__single[] = {
  145992. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145993. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145994. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145995. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145996. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145997. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145998. 13, 8, 8,15,
  145999. };
  146000. static static_codebook _huff_book__8u1__single = {
  146001. 2, 100,
  146002. _huff_lengthlist__8u1__single,
  146003. 0, 0, 0, 0, 0,
  146004. NULL,
  146005. NULL,
  146006. NULL,
  146007. NULL,
  146008. 0
  146009. };
  146010. static long _huff_lengthlist__44u0__long[] = {
  146011. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146012. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146013. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146014. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146015. };
  146016. static static_codebook _huff_book__44u0__long = {
  146017. 2, 64,
  146018. _huff_lengthlist__44u0__long,
  146019. 0, 0, 0, 0, 0,
  146020. NULL,
  146021. NULL,
  146022. NULL,
  146023. NULL,
  146024. 0
  146025. };
  146026. static long _vq_quantlist__44u0__p1_0[] = {
  146027. 1,
  146028. 0,
  146029. 2,
  146030. };
  146031. static long _vq_lengthlist__44u0__p1_0[] = {
  146032. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146033. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146034. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146035. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146036. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146037. 13,
  146038. };
  146039. static float _vq_quantthresh__44u0__p1_0[] = {
  146040. -0.5, 0.5,
  146041. };
  146042. static long _vq_quantmap__44u0__p1_0[] = {
  146043. 1, 0, 2,
  146044. };
  146045. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146046. _vq_quantthresh__44u0__p1_0,
  146047. _vq_quantmap__44u0__p1_0,
  146048. 3,
  146049. 3
  146050. };
  146051. static static_codebook _44u0__p1_0 = {
  146052. 4, 81,
  146053. _vq_lengthlist__44u0__p1_0,
  146054. 1, -535822336, 1611661312, 2, 0,
  146055. _vq_quantlist__44u0__p1_0,
  146056. NULL,
  146057. &_vq_auxt__44u0__p1_0,
  146058. NULL,
  146059. 0
  146060. };
  146061. static long _vq_quantlist__44u0__p2_0[] = {
  146062. 1,
  146063. 0,
  146064. 2,
  146065. };
  146066. static long _vq_lengthlist__44u0__p2_0[] = {
  146067. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146068. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146069. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146070. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146071. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146072. 9,
  146073. };
  146074. static float _vq_quantthresh__44u0__p2_0[] = {
  146075. -0.5, 0.5,
  146076. };
  146077. static long _vq_quantmap__44u0__p2_0[] = {
  146078. 1, 0, 2,
  146079. };
  146080. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146081. _vq_quantthresh__44u0__p2_0,
  146082. _vq_quantmap__44u0__p2_0,
  146083. 3,
  146084. 3
  146085. };
  146086. static static_codebook _44u0__p2_0 = {
  146087. 4, 81,
  146088. _vq_lengthlist__44u0__p2_0,
  146089. 1, -535822336, 1611661312, 2, 0,
  146090. _vq_quantlist__44u0__p2_0,
  146091. NULL,
  146092. &_vq_auxt__44u0__p2_0,
  146093. NULL,
  146094. 0
  146095. };
  146096. static long _vq_quantlist__44u0__p3_0[] = {
  146097. 2,
  146098. 1,
  146099. 3,
  146100. 0,
  146101. 4,
  146102. };
  146103. static long _vq_lengthlist__44u0__p3_0[] = {
  146104. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146105. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146106. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146107. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146108. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146109. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146110. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146111. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146112. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146113. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146114. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146115. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146116. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146117. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146118. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146119. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146120. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146121. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146122. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146123. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146124. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146125. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146126. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146127. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146128. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146129. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146130. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146131. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146132. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146133. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146134. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146135. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146136. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146137. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146138. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146139. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146140. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146141. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146142. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146143. 19,
  146144. };
  146145. static float _vq_quantthresh__44u0__p3_0[] = {
  146146. -1.5, -0.5, 0.5, 1.5,
  146147. };
  146148. static long _vq_quantmap__44u0__p3_0[] = {
  146149. 3, 1, 0, 2, 4,
  146150. };
  146151. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146152. _vq_quantthresh__44u0__p3_0,
  146153. _vq_quantmap__44u0__p3_0,
  146154. 5,
  146155. 5
  146156. };
  146157. static static_codebook _44u0__p3_0 = {
  146158. 4, 625,
  146159. _vq_lengthlist__44u0__p3_0,
  146160. 1, -533725184, 1611661312, 3, 0,
  146161. _vq_quantlist__44u0__p3_0,
  146162. NULL,
  146163. &_vq_auxt__44u0__p3_0,
  146164. NULL,
  146165. 0
  146166. };
  146167. static long _vq_quantlist__44u0__p4_0[] = {
  146168. 2,
  146169. 1,
  146170. 3,
  146171. 0,
  146172. 4,
  146173. };
  146174. static long _vq_lengthlist__44u0__p4_0[] = {
  146175. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146176. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146177. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146178. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146179. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146180. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146181. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146182. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146183. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146184. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146185. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146186. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146187. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146188. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146189. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146190. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146191. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146192. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146193. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146194. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146195. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146196. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146197. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146198. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146199. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146200. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146201. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146202. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146203. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146204. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146205. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146206. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146207. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146208. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146209. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146210. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146211. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146212. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146213. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146214. 12,
  146215. };
  146216. static float _vq_quantthresh__44u0__p4_0[] = {
  146217. -1.5, -0.5, 0.5, 1.5,
  146218. };
  146219. static long _vq_quantmap__44u0__p4_0[] = {
  146220. 3, 1, 0, 2, 4,
  146221. };
  146222. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146223. _vq_quantthresh__44u0__p4_0,
  146224. _vq_quantmap__44u0__p4_0,
  146225. 5,
  146226. 5
  146227. };
  146228. static static_codebook _44u0__p4_0 = {
  146229. 4, 625,
  146230. _vq_lengthlist__44u0__p4_0,
  146231. 1, -533725184, 1611661312, 3, 0,
  146232. _vq_quantlist__44u0__p4_0,
  146233. NULL,
  146234. &_vq_auxt__44u0__p4_0,
  146235. NULL,
  146236. 0
  146237. };
  146238. static long _vq_quantlist__44u0__p5_0[] = {
  146239. 4,
  146240. 3,
  146241. 5,
  146242. 2,
  146243. 6,
  146244. 1,
  146245. 7,
  146246. 0,
  146247. 8,
  146248. };
  146249. static long _vq_lengthlist__44u0__p5_0[] = {
  146250. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146251. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146252. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146253. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146254. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146255. 12,
  146256. };
  146257. static float _vq_quantthresh__44u0__p5_0[] = {
  146258. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146259. };
  146260. static long _vq_quantmap__44u0__p5_0[] = {
  146261. 7, 5, 3, 1, 0, 2, 4, 6,
  146262. 8,
  146263. };
  146264. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146265. _vq_quantthresh__44u0__p5_0,
  146266. _vq_quantmap__44u0__p5_0,
  146267. 9,
  146268. 9
  146269. };
  146270. static static_codebook _44u0__p5_0 = {
  146271. 2, 81,
  146272. _vq_lengthlist__44u0__p5_0,
  146273. 1, -531628032, 1611661312, 4, 0,
  146274. _vq_quantlist__44u0__p5_0,
  146275. NULL,
  146276. &_vq_auxt__44u0__p5_0,
  146277. NULL,
  146278. 0
  146279. };
  146280. static long _vq_quantlist__44u0__p6_0[] = {
  146281. 6,
  146282. 5,
  146283. 7,
  146284. 4,
  146285. 8,
  146286. 3,
  146287. 9,
  146288. 2,
  146289. 10,
  146290. 1,
  146291. 11,
  146292. 0,
  146293. 12,
  146294. };
  146295. static long _vq_lengthlist__44u0__p6_0[] = {
  146296. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146297. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146298. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146299. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146300. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146301. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146302. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146303. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146304. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146305. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146306. 15,17,16,17,18,17,17,18, 0,
  146307. };
  146308. static float _vq_quantthresh__44u0__p6_0[] = {
  146309. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146310. 12.5, 17.5, 22.5, 27.5,
  146311. };
  146312. static long _vq_quantmap__44u0__p6_0[] = {
  146313. 11, 9, 7, 5, 3, 1, 0, 2,
  146314. 4, 6, 8, 10, 12,
  146315. };
  146316. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146317. _vq_quantthresh__44u0__p6_0,
  146318. _vq_quantmap__44u0__p6_0,
  146319. 13,
  146320. 13
  146321. };
  146322. static static_codebook _44u0__p6_0 = {
  146323. 2, 169,
  146324. _vq_lengthlist__44u0__p6_0,
  146325. 1, -526516224, 1616117760, 4, 0,
  146326. _vq_quantlist__44u0__p6_0,
  146327. NULL,
  146328. &_vq_auxt__44u0__p6_0,
  146329. NULL,
  146330. 0
  146331. };
  146332. static long _vq_quantlist__44u0__p6_1[] = {
  146333. 2,
  146334. 1,
  146335. 3,
  146336. 0,
  146337. 4,
  146338. };
  146339. static long _vq_lengthlist__44u0__p6_1[] = {
  146340. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146341. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146342. };
  146343. static float _vq_quantthresh__44u0__p6_1[] = {
  146344. -1.5, -0.5, 0.5, 1.5,
  146345. };
  146346. static long _vq_quantmap__44u0__p6_1[] = {
  146347. 3, 1, 0, 2, 4,
  146348. };
  146349. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146350. _vq_quantthresh__44u0__p6_1,
  146351. _vq_quantmap__44u0__p6_1,
  146352. 5,
  146353. 5
  146354. };
  146355. static static_codebook _44u0__p6_1 = {
  146356. 2, 25,
  146357. _vq_lengthlist__44u0__p6_1,
  146358. 1, -533725184, 1611661312, 3, 0,
  146359. _vq_quantlist__44u0__p6_1,
  146360. NULL,
  146361. &_vq_auxt__44u0__p6_1,
  146362. NULL,
  146363. 0
  146364. };
  146365. static long _vq_quantlist__44u0__p7_0[] = {
  146366. 2,
  146367. 1,
  146368. 3,
  146369. 0,
  146370. 4,
  146371. };
  146372. static long _vq_lengthlist__44u0__p7_0[] = {
  146373. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146374. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146375. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146376. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146377. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146378. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146379. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146380. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146381. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146382. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146383. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146384. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146385. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146387. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146388. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146390. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146391. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146393. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146394. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146395. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146396. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146397. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146398. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146399. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146400. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146401. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146402. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146403. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146404. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146405. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146406. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146407. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146408. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146409. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146410. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146411. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146412. 10,
  146413. };
  146414. static float _vq_quantthresh__44u0__p7_0[] = {
  146415. -253.5, -84.5, 84.5, 253.5,
  146416. };
  146417. static long _vq_quantmap__44u0__p7_0[] = {
  146418. 3, 1, 0, 2, 4,
  146419. };
  146420. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146421. _vq_quantthresh__44u0__p7_0,
  146422. _vq_quantmap__44u0__p7_0,
  146423. 5,
  146424. 5
  146425. };
  146426. static static_codebook _44u0__p7_0 = {
  146427. 4, 625,
  146428. _vq_lengthlist__44u0__p7_0,
  146429. 1, -518709248, 1626677248, 3, 0,
  146430. _vq_quantlist__44u0__p7_0,
  146431. NULL,
  146432. &_vq_auxt__44u0__p7_0,
  146433. NULL,
  146434. 0
  146435. };
  146436. static long _vq_quantlist__44u0__p7_1[] = {
  146437. 6,
  146438. 5,
  146439. 7,
  146440. 4,
  146441. 8,
  146442. 3,
  146443. 9,
  146444. 2,
  146445. 10,
  146446. 1,
  146447. 11,
  146448. 0,
  146449. 12,
  146450. };
  146451. static long _vq_lengthlist__44u0__p7_1[] = {
  146452. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146453. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146454. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146455. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146456. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146457. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146458. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146459. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146460. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146461. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146462. 15,15,15,15,15,15,15,15,15,
  146463. };
  146464. static float _vq_quantthresh__44u0__p7_1[] = {
  146465. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146466. 32.5, 45.5, 58.5, 71.5,
  146467. };
  146468. static long _vq_quantmap__44u0__p7_1[] = {
  146469. 11, 9, 7, 5, 3, 1, 0, 2,
  146470. 4, 6, 8, 10, 12,
  146471. };
  146472. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146473. _vq_quantthresh__44u0__p7_1,
  146474. _vq_quantmap__44u0__p7_1,
  146475. 13,
  146476. 13
  146477. };
  146478. static static_codebook _44u0__p7_1 = {
  146479. 2, 169,
  146480. _vq_lengthlist__44u0__p7_1,
  146481. 1, -523010048, 1618608128, 4, 0,
  146482. _vq_quantlist__44u0__p7_1,
  146483. NULL,
  146484. &_vq_auxt__44u0__p7_1,
  146485. NULL,
  146486. 0
  146487. };
  146488. static long _vq_quantlist__44u0__p7_2[] = {
  146489. 6,
  146490. 5,
  146491. 7,
  146492. 4,
  146493. 8,
  146494. 3,
  146495. 9,
  146496. 2,
  146497. 10,
  146498. 1,
  146499. 11,
  146500. 0,
  146501. 12,
  146502. };
  146503. static long _vq_lengthlist__44u0__p7_2[] = {
  146504. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146505. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146506. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146507. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146508. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146509. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146510. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146511. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146512. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146513. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146514. 9, 9, 9,10, 9, 9,10,10, 9,
  146515. };
  146516. static float _vq_quantthresh__44u0__p7_2[] = {
  146517. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146518. 2.5, 3.5, 4.5, 5.5,
  146519. };
  146520. static long _vq_quantmap__44u0__p7_2[] = {
  146521. 11, 9, 7, 5, 3, 1, 0, 2,
  146522. 4, 6, 8, 10, 12,
  146523. };
  146524. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146525. _vq_quantthresh__44u0__p7_2,
  146526. _vq_quantmap__44u0__p7_2,
  146527. 13,
  146528. 13
  146529. };
  146530. static static_codebook _44u0__p7_2 = {
  146531. 2, 169,
  146532. _vq_lengthlist__44u0__p7_2,
  146533. 1, -531103744, 1611661312, 4, 0,
  146534. _vq_quantlist__44u0__p7_2,
  146535. NULL,
  146536. &_vq_auxt__44u0__p7_2,
  146537. NULL,
  146538. 0
  146539. };
  146540. static long _huff_lengthlist__44u0__short[] = {
  146541. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146542. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146543. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146544. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146545. };
  146546. static static_codebook _huff_book__44u0__short = {
  146547. 2, 64,
  146548. _huff_lengthlist__44u0__short,
  146549. 0, 0, 0, 0, 0,
  146550. NULL,
  146551. NULL,
  146552. NULL,
  146553. NULL,
  146554. 0
  146555. };
  146556. static long _huff_lengthlist__44u1__long[] = {
  146557. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146558. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146559. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146560. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146561. };
  146562. static static_codebook _huff_book__44u1__long = {
  146563. 2, 64,
  146564. _huff_lengthlist__44u1__long,
  146565. 0, 0, 0, 0, 0,
  146566. NULL,
  146567. NULL,
  146568. NULL,
  146569. NULL,
  146570. 0
  146571. };
  146572. static long _vq_quantlist__44u1__p1_0[] = {
  146573. 1,
  146574. 0,
  146575. 2,
  146576. };
  146577. static long _vq_lengthlist__44u1__p1_0[] = {
  146578. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146579. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146580. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146581. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146582. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146583. 13,
  146584. };
  146585. static float _vq_quantthresh__44u1__p1_0[] = {
  146586. -0.5, 0.5,
  146587. };
  146588. static long _vq_quantmap__44u1__p1_0[] = {
  146589. 1, 0, 2,
  146590. };
  146591. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146592. _vq_quantthresh__44u1__p1_0,
  146593. _vq_quantmap__44u1__p1_0,
  146594. 3,
  146595. 3
  146596. };
  146597. static static_codebook _44u1__p1_0 = {
  146598. 4, 81,
  146599. _vq_lengthlist__44u1__p1_0,
  146600. 1, -535822336, 1611661312, 2, 0,
  146601. _vq_quantlist__44u1__p1_0,
  146602. NULL,
  146603. &_vq_auxt__44u1__p1_0,
  146604. NULL,
  146605. 0
  146606. };
  146607. static long _vq_quantlist__44u1__p2_0[] = {
  146608. 1,
  146609. 0,
  146610. 2,
  146611. };
  146612. static long _vq_lengthlist__44u1__p2_0[] = {
  146613. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146614. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146615. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146616. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146617. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146618. 9,
  146619. };
  146620. static float _vq_quantthresh__44u1__p2_0[] = {
  146621. -0.5, 0.5,
  146622. };
  146623. static long _vq_quantmap__44u1__p2_0[] = {
  146624. 1, 0, 2,
  146625. };
  146626. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146627. _vq_quantthresh__44u1__p2_0,
  146628. _vq_quantmap__44u1__p2_0,
  146629. 3,
  146630. 3
  146631. };
  146632. static static_codebook _44u1__p2_0 = {
  146633. 4, 81,
  146634. _vq_lengthlist__44u1__p2_0,
  146635. 1, -535822336, 1611661312, 2, 0,
  146636. _vq_quantlist__44u1__p2_0,
  146637. NULL,
  146638. &_vq_auxt__44u1__p2_0,
  146639. NULL,
  146640. 0
  146641. };
  146642. static long _vq_quantlist__44u1__p3_0[] = {
  146643. 2,
  146644. 1,
  146645. 3,
  146646. 0,
  146647. 4,
  146648. };
  146649. static long _vq_lengthlist__44u1__p3_0[] = {
  146650. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146651. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146652. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146653. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146654. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146655. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146656. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146657. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146658. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146659. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146660. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146661. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146662. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146663. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146664. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146665. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146666. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146667. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146668. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146669. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146670. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146671. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146672. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146673. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146674. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146675. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146676. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146677. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146678. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146679. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146680. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146681. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146682. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146683. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146684. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146685. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146686. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146687. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146688. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146689. 19,
  146690. };
  146691. static float _vq_quantthresh__44u1__p3_0[] = {
  146692. -1.5, -0.5, 0.5, 1.5,
  146693. };
  146694. static long _vq_quantmap__44u1__p3_0[] = {
  146695. 3, 1, 0, 2, 4,
  146696. };
  146697. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146698. _vq_quantthresh__44u1__p3_0,
  146699. _vq_quantmap__44u1__p3_0,
  146700. 5,
  146701. 5
  146702. };
  146703. static static_codebook _44u1__p3_0 = {
  146704. 4, 625,
  146705. _vq_lengthlist__44u1__p3_0,
  146706. 1, -533725184, 1611661312, 3, 0,
  146707. _vq_quantlist__44u1__p3_0,
  146708. NULL,
  146709. &_vq_auxt__44u1__p3_0,
  146710. NULL,
  146711. 0
  146712. };
  146713. static long _vq_quantlist__44u1__p4_0[] = {
  146714. 2,
  146715. 1,
  146716. 3,
  146717. 0,
  146718. 4,
  146719. };
  146720. static long _vq_lengthlist__44u1__p4_0[] = {
  146721. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146722. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146723. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146724. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146725. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146726. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146727. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146728. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146729. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146730. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146731. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146732. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146733. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146734. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146735. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146736. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146737. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146738. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146739. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146740. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146741. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146742. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146743. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146744. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146745. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146746. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146747. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146748. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146749. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146750. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146751. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146752. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146753. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146754. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146755. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146756. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146757. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146758. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146759. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146760. 12,
  146761. };
  146762. static float _vq_quantthresh__44u1__p4_0[] = {
  146763. -1.5, -0.5, 0.5, 1.5,
  146764. };
  146765. static long _vq_quantmap__44u1__p4_0[] = {
  146766. 3, 1, 0, 2, 4,
  146767. };
  146768. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146769. _vq_quantthresh__44u1__p4_0,
  146770. _vq_quantmap__44u1__p4_0,
  146771. 5,
  146772. 5
  146773. };
  146774. static static_codebook _44u1__p4_0 = {
  146775. 4, 625,
  146776. _vq_lengthlist__44u1__p4_0,
  146777. 1, -533725184, 1611661312, 3, 0,
  146778. _vq_quantlist__44u1__p4_0,
  146779. NULL,
  146780. &_vq_auxt__44u1__p4_0,
  146781. NULL,
  146782. 0
  146783. };
  146784. static long _vq_quantlist__44u1__p5_0[] = {
  146785. 4,
  146786. 3,
  146787. 5,
  146788. 2,
  146789. 6,
  146790. 1,
  146791. 7,
  146792. 0,
  146793. 8,
  146794. };
  146795. static long _vq_lengthlist__44u1__p5_0[] = {
  146796. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146797. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146798. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146799. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146800. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146801. 12,
  146802. };
  146803. static float _vq_quantthresh__44u1__p5_0[] = {
  146804. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146805. };
  146806. static long _vq_quantmap__44u1__p5_0[] = {
  146807. 7, 5, 3, 1, 0, 2, 4, 6,
  146808. 8,
  146809. };
  146810. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146811. _vq_quantthresh__44u1__p5_0,
  146812. _vq_quantmap__44u1__p5_0,
  146813. 9,
  146814. 9
  146815. };
  146816. static static_codebook _44u1__p5_0 = {
  146817. 2, 81,
  146818. _vq_lengthlist__44u1__p5_0,
  146819. 1, -531628032, 1611661312, 4, 0,
  146820. _vq_quantlist__44u1__p5_0,
  146821. NULL,
  146822. &_vq_auxt__44u1__p5_0,
  146823. NULL,
  146824. 0
  146825. };
  146826. static long _vq_quantlist__44u1__p6_0[] = {
  146827. 6,
  146828. 5,
  146829. 7,
  146830. 4,
  146831. 8,
  146832. 3,
  146833. 9,
  146834. 2,
  146835. 10,
  146836. 1,
  146837. 11,
  146838. 0,
  146839. 12,
  146840. };
  146841. static long _vq_lengthlist__44u1__p6_0[] = {
  146842. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146843. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146844. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146845. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146846. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146847. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146848. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146849. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146850. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146851. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146852. 15,17,16,17,18,17,17,18, 0,
  146853. };
  146854. static float _vq_quantthresh__44u1__p6_0[] = {
  146855. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146856. 12.5, 17.5, 22.5, 27.5,
  146857. };
  146858. static long _vq_quantmap__44u1__p6_0[] = {
  146859. 11, 9, 7, 5, 3, 1, 0, 2,
  146860. 4, 6, 8, 10, 12,
  146861. };
  146862. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146863. _vq_quantthresh__44u1__p6_0,
  146864. _vq_quantmap__44u1__p6_0,
  146865. 13,
  146866. 13
  146867. };
  146868. static static_codebook _44u1__p6_0 = {
  146869. 2, 169,
  146870. _vq_lengthlist__44u1__p6_0,
  146871. 1, -526516224, 1616117760, 4, 0,
  146872. _vq_quantlist__44u1__p6_0,
  146873. NULL,
  146874. &_vq_auxt__44u1__p6_0,
  146875. NULL,
  146876. 0
  146877. };
  146878. static long _vq_quantlist__44u1__p6_1[] = {
  146879. 2,
  146880. 1,
  146881. 3,
  146882. 0,
  146883. 4,
  146884. };
  146885. static long _vq_lengthlist__44u1__p6_1[] = {
  146886. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146887. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146888. };
  146889. static float _vq_quantthresh__44u1__p6_1[] = {
  146890. -1.5, -0.5, 0.5, 1.5,
  146891. };
  146892. static long _vq_quantmap__44u1__p6_1[] = {
  146893. 3, 1, 0, 2, 4,
  146894. };
  146895. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146896. _vq_quantthresh__44u1__p6_1,
  146897. _vq_quantmap__44u1__p6_1,
  146898. 5,
  146899. 5
  146900. };
  146901. static static_codebook _44u1__p6_1 = {
  146902. 2, 25,
  146903. _vq_lengthlist__44u1__p6_1,
  146904. 1, -533725184, 1611661312, 3, 0,
  146905. _vq_quantlist__44u1__p6_1,
  146906. NULL,
  146907. &_vq_auxt__44u1__p6_1,
  146908. NULL,
  146909. 0
  146910. };
  146911. static long _vq_quantlist__44u1__p7_0[] = {
  146912. 3,
  146913. 2,
  146914. 4,
  146915. 1,
  146916. 5,
  146917. 0,
  146918. 6,
  146919. };
  146920. static long _vq_lengthlist__44u1__p7_0[] = {
  146921. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146922. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146923. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146924. 8,
  146925. };
  146926. static float _vq_quantthresh__44u1__p7_0[] = {
  146927. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146928. };
  146929. static long _vq_quantmap__44u1__p7_0[] = {
  146930. 5, 3, 1, 0, 2, 4, 6,
  146931. };
  146932. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146933. _vq_quantthresh__44u1__p7_0,
  146934. _vq_quantmap__44u1__p7_0,
  146935. 7,
  146936. 7
  146937. };
  146938. static static_codebook _44u1__p7_0 = {
  146939. 2, 49,
  146940. _vq_lengthlist__44u1__p7_0,
  146941. 1, -518017024, 1626677248, 3, 0,
  146942. _vq_quantlist__44u1__p7_0,
  146943. NULL,
  146944. &_vq_auxt__44u1__p7_0,
  146945. NULL,
  146946. 0
  146947. };
  146948. static long _vq_quantlist__44u1__p7_1[] = {
  146949. 6,
  146950. 5,
  146951. 7,
  146952. 4,
  146953. 8,
  146954. 3,
  146955. 9,
  146956. 2,
  146957. 10,
  146958. 1,
  146959. 11,
  146960. 0,
  146961. 12,
  146962. };
  146963. static long _vq_lengthlist__44u1__p7_1[] = {
  146964. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146965. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146966. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146967. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146968. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146969. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146970. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146971. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146972. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146973. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146974. 15,15,15,15,15,15,15,15,15,
  146975. };
  146976. static float _vq_quantthresh__44u1__p7_1[] = {
  146977. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146978. 32.5, 45.5, 58.5, 71.5,
  146979. };
  146980. static long _vq_quantmap__44u1__p7_1[] = {
  146981. 11, 9, 7, 5, 3, 1, 0, 2,
  146982. 4, 6, 8, 10, 12,
  146983. };
  146984. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146985. _vq_quantthresh__44u1__p7_1,
  146986. _vq_quantmap__44u1__p7_1,
  146987. 13,
  146988. 13
  146989. };
  146990. static static_codebook _44u1__p7_1 = {
  146991. 2, 169,
  146992. _vq_lengthlist__44u1__p7_1,
  146993. 1, -523010048, 1618608128, 4, 0,
  146994. _vq_quantlist__44u1__p7_1,
  146995. NULL,
  146996. &_vq_auxt__44u1__p7_1,
  146997. NULL,
  146998. 0
  146999. };
  147000. static long _vq_quantlist__44u1__p7_2[] = {
  147001. 6,
  147002. 5,
  147003. 7,
  147004. 4,
  147005. 8,
  147006. 3,
  147007. 9,
  147008. 2,
  147009. 10,
  147010. 1,
  147011. 11,
  147012. 0,
  147013. 12,
  147014. };
  147015. static long _vq_lengthlist__44u1__p7_2[] = {
  147016. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147017. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147018. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147019. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147020. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147021. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147022. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147023. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147024. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147025. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147026. 9, 9, 9,10, 9, 9,10,10, 9,
  147027. };
  147028. static float _vq_quantthresh__44u1__p7_2[] = {
  147029. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147030. 2.5, 3.5, 4.5, 5.5,
  147031. };
  147032. static long _vq_quantmap__44u1__p7_2[] = {
  147033. 11, 9, 7, 5, 3, 1, 0, 2,
  147034. 4, 6, 8, 10, 12,
  147035. };
  147036. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147037. _vq_quantthresh__44u1__p7_2,
  147038. _vq_quantmap__44u1__p7_2,
  147039. 13,
  147040. 13
  147041. };
  147042. static static_codebook _44u1__p7_2 = {
  147043. 2, 169,
  147044. _vq_lengthlist__44u1__p7_2,
  147045. 1, -531103744, 1611661312, 4, 0,
  147046. _vq_quantlist__44u1__p7_2,
  147047. NULL,
  147048. &_vq_auxt__44u1__p7_2,
  147049. NULL,
  147050. 0
  147051. };
  147052. static long _huff_lengthlist__44u1__short[] = {
  147053. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147054. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147055. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147056. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147057. };
  147058. static static_codebook _huff_book__44u1__short = {
  147059. 2, 64,
  147060. _huff_lengthlist__44u1__short,
  147061. 0, 0, 0, 0, 0,
  147062. NULL,
  147063. NULL,
  147064. NULL,
  147065. NULL,
  147066. 0
  147067. };
  147068. static long _huff_lengthlist__44u2__long[] = {
  147069. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147070. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147071. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147072. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147073. };
  147074. static static_codebook _huff_book__44u2__long = {
  147075. 2, 64,
  147076. _huff_lengthlist__44u2__long,
  147077. 0, 0, 0, 0, 0,
  147078. NULL,
  147079. NULL,
  147080. NULL,
  147081. NULL,
  147082. 0
  147083. };
  147084. static long _vq_quantlist__44u2__p1_0[] = {
  147085. 1,
  147086. 0,
  147087. 2,
  147088. };
  147089. static long _vq_lengthlist__44u2__p1_0[] = {
  147090. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147091. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147092. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147093. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147094. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147095. 13,
  147096. };
  147097. static float _vq_quantthresh__44u2__p1_0[] = {
  147098. -0.5, 0.5,
  147099. };
  147100. static long _vq_quantmap__44u2__p1_0[] = {
  147101. 1, 0, 2,
  147102. };
  147103. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147104. _vq_quantthresh__44u2__p1_0,
  147105. _vq_quantmap__44u2__p1_0,
  147106. 3,
  147107. 3
  147108. };
  147109. static static_codebook _44u2__p1_0 = {
  147110. 4, 81,
  147111. _vq_lengthlist__44u2__p1_0,
  147112. 1, -535822336, 1611661312, 2, 0,
  147113. _vq_quantlist__44u2__p1_0,
  147114. NULL,
  147115. &_vq_auxt__44u2__p1_0,
  147116. NULL,
  147117. 0
  147118. };
  147119. static long _vq_quantlist__44u2__p2_0[] = {
  147120. 1,
  147121. 0,
  147122. 2,
  147123. };
  147124. static long _vq_lengthlist__44u2__p2_0[] = {
  147125. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147126. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147127. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147128. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147129. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147130. 9,
  147131. };
  147132. static float _vq_quantthresh__44u2__p2_0[] = {
  147133. -0.5, 0.5,
  147134. };
  147135. static long _vq_quantmap__44u2__p2_0[] = {
  147136. 1, 0, 2,
  147137. };
  147138. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147139. _vq_quantthresh__44u2__p2_0,
  147140. _vq_quantmap__44u2__p2_0,
  147141. 3,
  147142. 3
  147143. };
  147144. static static_codebook _44u2__p2_0 = {
  147145. 4, 81,
  147146. _vq_lengthlist__44u2__p2_0,
  147147. 1, -535822336, 1611661312, 2, 0,
  147148. _vq_quantlist__44u2__p2_0,
  147149. NULL,
  147150. &_vq_auxt__44u2__p2_0,
  147151. NULL,
  147152. 0
  147153. };
  147154. static long _vq_quantlist__44u2__p3_0[] = {
  147155. 2,
  147156. 1,
  147157. 3,
  147158. 0,
  147159. 4,
  147160. };
  147161. static long _vq_lengthlist__44u2__p3_0[] = {
  147162. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147163. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147164. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147165. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147166. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147167. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147168. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147169. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147170. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147171. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147172. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147173. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147174. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147175. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147176. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147177. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147178. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147179. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147180. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147181. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147182. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147183. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147184. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147185. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147186. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147187. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147188. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147189. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147190. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147191. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147192. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147193. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147194. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147195. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147196. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147197. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147198. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147199. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147200. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147201. 0,
  147202. };
  147203. static float _vq_quantthresh__44u2__p3_0[] = {
  147204. -1.5, -0.5, 0.5, 1.5,
  147205. };
  147206. static long _vq_quantmap__44u2__p3_0[] = {
  147207. 3, 1, 0, 2, 4,
  147208. };
  147209. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147210. _vq_quantthresh__44u2__p3_0,
  147211. _vq_quantmap__44u2__p3_0,
  147212. 5,
  147213. 5
  147214. };
  147215. static static_codebook _44u2__p3_0 = {
  147216. 4, 625,
  147217. _vq_lengthlist__44u2__p3_0,
  147218. 1, -533725184, 1611661312, 3, 0,
  147219. _vq_quantlist__44u2__p3_0,
  147220. NULL,
  147221. &_vq_auxt__44u2__p3_0,
  147222. NULL,
  147223. 0
  147224. };
  147225. static long _vq_quantlist__44u2__p4_0[] = {
  147226. 2,
  147227. 1,
  147228. 3,
  147229. 0,
  147230. 4,
  147231. };
  147232. static long _vq_lengthlist__44u2__p4_0[] = {
  147233. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147234. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147235. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147236. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147237. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147238. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147239. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147240. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147241. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147242. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147243. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147244. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147245. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147246. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147247. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147248. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147249. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147250. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147251. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147252. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147253. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147254. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147255. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147256. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147257. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147258. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147259. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147260. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147261. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147262. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147263. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147264. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147265. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147266. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147267. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147268. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147269. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147270. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147271. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147272. 13,
  147273. };
  147274. static float _vq_quantthresh__44u2__p4_0[] = {
  147275. -1.5, -0.5, 0.5, 1.5,
  147276. };
  147277. static long _vq_quantmap__44u2__p4_0[] = {
  147278. 3, 1, 0, 2, 4,
  147279. };
  147280. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147281. _vq_quantthresh__44u2__p4_0,
  147282. _vq_quantmap__44u2__p4_0,
  147283. 5,
  147284. 5
  147285. };
  147286. static static_codebook _44u2__p4_0 = {
  147287. 4, 625,
  147288. _vq_lengthlist__44u2__p4_0,
  147289. 1, -533725184, 1611661312, 3, 0,
  147290. _vq_quantlist__44u2__p4_0,
  147291. NULL,
  147292. &_vq_auxt__44u2__p4_0,
  147293. NULL,
  147294. 0
  147295. };
  147296. static long _vq_quantlist__44u2__p5_0[] = {
  147297. 4,
  147298. 3,
  147299. 5,
  147300. 2,
  147301. 6,
  147302. 1,
  147303. 7,
  147304. 0,
  147305. 8,
  147306. };
  147307. static long _vq_lengthlist__44u2__p5_0[] = {
  147308. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147309. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147310. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147311. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147312. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147313. 13,
  147314. };
  147315. static float _vq_quantthresh__44u2__p5_0[] = {
  147316. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147317. };
  147318. static long _vq_quantmap__44u2__p5_0[] = {
  147319. 7, 5, 3, 1, 0, 2, 4, 6,
  147320. 8,
  147321. };
  147322. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147323. _vq_quantthresh__44u2__p5_0,
  147324. _vq_quantmap__44u2__p5_0,
  147325. 9,
  147326. 9
  147327. };
  147328. static static_codebook _44u2__p5_0 = {
  147329. 2, 81,
  147330. _vq_lengthlist__44u2__p5_0,
  147331. 1, -531628032, 1611661312, 4, 0,
  147332. _vq_quantlist__44u2__p5_0,
  147333. NULL,
  147334. &_vq_auxt__44u2__p5_0,
  147335. NULL,
  147336. 0
  147337. };
  147338. static long _vq_quantlist__44u2__p6_0[] = {
  147339. 6,
  147340. 5,
  147341. 7,
  147342. 4,
  147343. 8,
  147344. 3,
  147345. 9,
  147346. 2,
  147347. 10,
  147348. 1,
  147349. 11,
  147350. 0,
  147351. 12,
  147352. };
  147353. static long _vq_lengthlist__44u2__p6_0[] = {
  147354. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147355. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147356. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147357. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147358. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147359. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147360. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147361. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147362. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147363. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147364. 15,17,17,16,18,17,18, 0, 0,
  147365. };
  147366. static float _vq_quantthresh__44u2__p6_0[] = {
  147367. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147368. 12.5, 17.5, 22.5, 27.5,
  147369. };
  147370. static long _vq_quantmap__44u2__p6_0[] = {
  147371. 11, 9, 7, 5, 3, 1, 0, 2,
  147372. 4, 6, 8, 10, 12,
  147373. };
  147374. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147375. _vq_quantthresh__44u2__p6_0,
  147376. _vq_quantmap__44u2__p6_0,
  147377. 13,
  147378. 13
  147379. };
  147380. static static_codebook _44u2__p6_0 = {
  147381. 2, 169,
  147382. _vq_lengthlist__44u2__p6_0,
  147383. 1, -526516224, 1616117760, 4, 0,
  147384. _vq_quantlist__44u2__p6_0,
  147385. NULL,
  147386. &_vq_auxt__44u2__p6_0,
  147387. NULL,
  147388. 0
  147389. };
  147390. static long _vq_quantlist__44u2__p6_1[] = {
  147391. 2,
  147392. 1,
  147393. 3,
  147394. 0,
  147395. 4,
  147396. };
  147397. static long _vq_lengthlist__44u2__p6_1[] = {
  147398. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147399. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147400. };
  147401. static float _vq_quantthresh__44u2__p6_1[] = {
  147402. -1.5, -0.5, 0.5, 1.5,
  147403. };
  147404. static long _vq_quantmap__44u2__p6_1[] = {
  147405. 3, 1, 0, 2, 4,
  147406. };
  147407. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147408. _vq_quantthresh__44u2__p6_1,
  147409. _vq_quantmap__44u2__p6_1,
  147410. 5,
  147411. 5
  147412. };
  147413. static static_codebook _44u2__p6_1 = {
  147414. 2, 25,
  147415. _vq_lengthlist__44u2__p6_1,
  147416. 1, -533725184, 1611661312, 3, 0,
  147417. _vq_quantlist__44u2__p6_1,
  147418. NULL,
  147419. &_vq_auxt__44u2__p6_1,
  147420. NULL,
  147421. 0
  147422. };
  147423. static long _vq_quantlist__44u2__p7_0[] = {
  147424. 4,
  147425. 3,
  147426. 5,
  147427. 2,
  147428. 6,
  147429. 1,
  147430. 7,
  147431. 0,
  147432. 8,
  147433. };
  147434. static long _vq_lengthlist__44u2__p7_0[] = {
  147435. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147436. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147437. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147438. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147439. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147440. 11,
  147441. };
  147442. static float _vq_quantthresh__44u2__p7_0[] = {
  147443. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147444. };
  147445. static long _vq_quantmap__44u2__p7_0[] = {
  147446. 7, 5, 3, 1, 0, 2, 4, 6,
  147447. 8,
  147448. };
  147449. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147450. _vq_quantthresh__44u2__p7_0,
  147451. _vq_quantmap__44u2__p7_0,
  147452. 9,
  147453. 9
  147454. };
  147455. static static_codebook _44u2__p7_0 = {
  147456. 2, 81,
  147457. _vq_lengthlist__44u2__p7_0,
  147458. 1, -516612096, 1626677248, 4, 0,
  147459. _vq_quantlist__44u2__p7_0,
  147460. NULL,
  147461. &_vq_auxt__44u2__p7_0,
  147462. NULL,
  147463. 0
  147464. };
  147465. static long _vq_quantlist__44u2__p7_1[] = {
  147466. 6,
  147467. 5,
  147468. 7,
  147469. 4,
  147470. 8,
  147471. 3,
  147472. 9,
  147473. 2,
  147474. 10,
  147475. 1,
  147476. 11,
  147477. 0,
  147478. 12,
  147479. };
  147480. static long _vq_lengthlist__44u2__p7_1[] = {
  147481. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147482. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147483. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147484. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147485. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147486. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147487. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147488. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147489. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147490. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147491. 14,14,14,17,15,17,17,17,17,
  147492. };
  147493. static float _vq_quantthresh__44u2__p7_1[] = {
  147494. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147495. 32.5, 45.5, 58.5, 71.5,
  147496. };
  147497. static long _vq_quantmap__44u2__p7_1[] = {
  147498. 11, 9, 7, 5, 3, 1, 0, 2,
  147499. 4, 6, 8, 10, 12,
  147500. };
  147501. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147502. _vq_quantthresh__44u2__p7_1,
  147503. _vq_quantmap__44u2__p7_1,
  147504. 13,
  147505. 13
  147506. };
  147507. static static_codebook _44u2__p7_1 = {
  147508. 2, 169,
  147509. _vq_lengthlist__44u2__p7_1,
  147510. 1, -523010048, 1618608128, 4, 0,
  147511. _vq_quantlist__44u2__p7_1,
  147512. NULL,
  147513. &_vq_auxt__44u2__p7_1,
  147514. NULL,
  147515. 0
  147516. };
  147517. static long _vq_quantlist__44u2__p7_2[] = {
  147518. 6,
  147519. 5,
  147520. 7,
  147521. 4,
  147522. 8,
  147523. 3,
  147524. 9,
  147525. 2,
  147526. 10,
  147527. 1,
  147528. 11,
  147529. 0,
  147530. 12,
  147531. };
  147532. static long _vq_lengthlist__44u2__p7_2[] = {
  147533. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147534. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147535. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147536. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147537. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147538. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147539. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147540. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147541. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147542. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147543. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147544. };
  147545. static float _vq_quantthresh__44u2__p7_2[] = {
  147546. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147547. 2.5, 3.5, 4.5, 5.5,
  147548. };
  147549. static long _vq_quantmap__44u2__p7_2[] = {
  147550. 11, 9, 7, 5, 3, 1, 0, 2,
  147551. 4, 6, 8, 10, 12,
  147552. };
  147553. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147554. _vq_quantthresh__44u2__p7_2,
  147555. _vq_quantmap__44u2__p7_2,
  147556. 13,
  147557. 13
  147558. };
  147559. static static_codebook _44u2__p7_2 = {
  147560. 2, 169,
  147561. _vq_lengthlist__44u2__p7_2,
  147562. 1, -531103744, 1611661312, 4, 0,
  147563. _vq_quantlist__44u2__p7_2,
  147564. NULL,
  147565. &_vq_auxt__44u2__p7_2,
  147566. NULL,
  147567. 0
  147568. };
  147569. static long _huff_lengthlist__44u2__short[] = {
  147570. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147571. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147572. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147573. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147574. };
  147575. static static_codebook _huff_book__44u2__short = {
  147576. 2, 64,
  147577. _huff_lengthlist__44u2__short,
  147578. 0, 0, 0, 0, 0,
  147579. NULL,
  147580. NULL,
  147581. NULL,
  147582. NULL,
  147583. 0
  147584. };
  147585. static long _huff_lengthlist__44u3__long[] = {
  147586. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147587. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147588. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147589. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147590. };
  147591. static static_codebook _huff_book__44u3__long = {
  147592. 2, 64,
  147593. _huff_lengthlist__44u3__long,
  147594. 0, 0, 0, 0, 0,
  147595. NULL,
  147596. NULL,
  147597. NULL,
  147598. NULL,
  147599. 0
  147600. };
  147601. static long _vq_quantlist__44u3__p1_0[] = {
  147602. 1,
  147603. 0,
  147604. 2,
  147605. };
  147606. static long _vq_lengthlist__44u3__p1_0[] = {
  147607. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147608. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147609. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147610. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147611. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147612. 13,
  147613. };
  147614. static float _vq_quantthresh__44u3__p1_0[] = {
  147615. -0.5, 0.5,
  147616. };
  147617. static long _vq_quantmap__44u3__p1_0[] = {
  147618. 1, 0, 2,
  147619. };
  147620. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147621. _vq_quantthresh__44u3__p1_0,
  147622. _vq_quantmap__44u3__p1_0,
  147623. 3,
  147624. 3
  147625. };
  147626. static static_codebook _44u3__p1_0 = {
  147627. 4, 81,
  147628. _vq_lengthlist__44u3__p1_0,
  147629. 1, -535822336, 1611661312, 2, 0,
  147630. _vq_quantlist__44u3__p1_0,
  147631. NULL,
  147632. &_vq_auxt__44u3__p1_0,
  147633. NULL,
  147634. 0
  147635. };
  147636. static long _vq_quantlist__44u3__p2_0[] = {
  147637. 1,
  147638. 0,
  147639. 2,
  147640. };
  147641. static long _vq_lengthlist__44u3__p2_0[] = {
  147642. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147643. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147644. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147645. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147646. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147647. 9,
  147648. };
  147649. static float _vq_quantthresh__44u3__p2_0[] = {
  147650. -0.5, 0.5,
  147651. };
  147652. static long _vq_quantmap__44u3__p2_0[] = {
  147653. 1, 0, 2,
  147654. };
  147655. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147656. _vq_quantthresh__44u3__p2_0,
  147657. _vq_quantmap__44u3__p2_0,
  147658. 3,
  147659. 3
  147660. };
  147661. static static_codebook _44u3__p2_0 = {
  147662. 4, 81,
  147663. _vq_lengthlist__44u3__p2_0,
  147664. 1, -535822336, 1611661312, 2, 0,
  147665. _vq_quantlist__44u3__p2_0,
  147666. NULL,
  147667. &_vq_auxt__44u3__p2_0,
  147668. NULL,
  147669. 0
  147670. };
  147671. static long _vq_quantlist__44u3__p3_0[] = {
  147672. 2,
  147673. 1,
  147674. 3,
  147675. 0,
  147676. 4,
  147677. };
  147678. static long _vq_lengthlist__44u3__p3_0[] = {
  147679. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147680. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147681. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147682. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147683. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147684. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147685. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147686. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147687. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147688. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147689. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147690. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147691. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147692. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147693. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147694. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147695. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147696. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147697. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147698. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147699. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147700. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147701. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147702. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147703. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147704. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147705. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147706. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147707. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147708. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147709. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147710. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147711. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147712. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147713. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147714. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147715. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147716. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147717. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147718. 0,
  147719. };
  147720. static float _vq_quantthresh__44u3__p3_0[] = {
  147721. -1.5, -0.5, 0.5, 1.5,
  147722. };
  147723. static long _vq_quantmap__44u3__p3_0[] = {
  147724. 3, 1, 0, 2, 4,
  147725. };
  147726. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147727. _vq_quantthresh__44u3__p3_0,
  147728. _vq_quantmap__44u3__p3_0,
  147729. 5,
  147730. 5
  147731. };
  147732. static static_codebook _44u3__p3_0 = {
  147733. 4, 625,
  147734. _vq_lengthlist__44u3__p3_0,
  147735. 1, -533725184, 1611661312, 3, 0,
  147736. _vq_quantlist__44u3__p3_0,
  147737. NULL,
  147738. &_vq_auxt__44u3__p3_0,
  147739. NULL,
  147740. 0
  147741. };
  147742. static long _vq_quantlist__44u3__p4_0[] = {
  147743. 2,
  147744. 1,
  147745. 3,
  147746. 0,
  147747. 4,
  147748. };
  147749. static long _vq_lengthlist__44u3__p4_0[] = {
  147750. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147751. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147752. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147753. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147754. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147755. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147756. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147757. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147758. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147759. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147760. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147761. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147762. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147763. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147764. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147765. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147766. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147767. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147768. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147769. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147770. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147771. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147772. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147773. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147774. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147775. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147776. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147777. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147778. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147779. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147780. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147781. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147782. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147783. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147784. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147785. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147786. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147787. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147788. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147789. 13,
  147790. };
  147791. static float _vq_quantthresh__44u3__p4_0[] = {
  147792. -1.5, -0.5, 0.5, 1.5,
  147793. };
  147794. static long _vq_quantmap__44u3__p4_0[] = {
  147795. 3, 1, 0, 2, 4,
  147796. };
  147797. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147798. _vq_quantthresh__44u3__p4_0,
  147799. _vq_quantmap__44u3__p4_0,
  147800. 5,
  147801. 5
  147802. };
  147803. static static_codebook _44u3__p4_0 = {
  147804. 4, 625,
  147805. _vq_lengthlist__44u3__p4_0,
  147806. 1, -533725184, 1611661312, 3, 0,
  147807. _vq_quantlist__44u3__p4_0,
  147808. NULL,
  147809. &_vq_auxt__44u3__p4_0,
  147810. NULL,
  147811. 0
  147812. };
  147813. static long _vq_quantlist__44u3__p5_0[] = {
  147814. 4,
  147815. 3,
  147816. 5,
  147817. 2,
  147818. 6,
  147819. 1,
  147820. 7,
  147821. 0,
  147822. 8,
  147823. };
  147824. static long _vq_lengthlist__44u3__p5_0[] = {
  147825. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147826. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147827. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147828. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147829. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147830. 12,
  147831. };
  147832. static float _vq_quantthresh__44u3__p5_0[] = {
  147833. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147834. };
  147835. static long _vq_quantmap__44u3__p5_0[] = {
  147836. 7, 5, 3, 1, 0, 2, 4, 6,
  147837. 8,
  147838. };
  147839. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147840. _vq_quantthresh__44u3__p5_0,
  147841. _vq_quantmap__44u3__p5_0,
  147842. 9,
  147843. 9
  147844. };
  147845. static static_codebook _44u3__p5_0 = {
  147846. 2, 81,
  147847. _vq_lengthlist__44u3__p5_0,
  147848. 1, -531628032, 1611661312, 4, 0,
  147849. _vq_quantlist__44u3__p5_0,
  147850. NULL,
  147851. &_vq_auxt__44u3__p5_0,
  147852. NULL,
  147853. 0
  147854. };
  147855. static long _vq_quantlist__44u3__p6_0[] = {
  147856. 6,
  147857. 5,
  147858. 7,
  147859. 4,
  147860. 8,
  147861. 3,
  147862. 9,
  147863. 2,
  147864. 10,
  147865. 1,
  147866. 11,
  147867. 0,
  147868. 12,
  147869. };
  147870. static long _vq_lengthlist__44u3__p6_0[] = {
  147871. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147872. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147873. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147874. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147875. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147876. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147877. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147878. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147879. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147880. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147881. 15,16,16,16,17,18,16,20,18,
  147882. };
  147883. static float _vq_quantthresh__44u3__p6_0[] = {
  147884. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147885. 12.5, 17.5, 22.5, 27.5,
  147886. };
  147887. static long _vq_quantmap__44u3__p6_0[] = {
  147888. 11, 9, 7, 5, 3, 1, 0, 2,
  147889. 4, 6, 8, 10, 12,
  147890. };
  147891. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147892. _vq_quantthresh__44u3__p6_0,
  147893. _vq_quantmap__44u3__p6_0,
  147894. 13,
  147895. 13
  147896. };
  147897. static static_codebook _44u3__p6_0 = {
  147898. 2, 169,
  147899. _vq_lengthlist__44u3__p6_0,
  147900. 1, -526516224, 1616117760, 4, 0,
  147901. _vq_quantlist__44u3__p6_0,
  147902. NULL,
  147903. &_vq_auxt__44u3__p6_0,
  147904. NULL,
  147905. 0
  147906. };
  147907. static long _vq_quantlist__44u3__p6_1[] = {
  147908. 2,
  147909. 1,
  147910. 3,
  147911. 0,
  147912. 4,
  147913. };
  147914. static long _vq_lengthlist__44u3__p6_1[] = {
  147915. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147916. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147917. };
  147918. static float _vq_quantthresh__44u3__p6_1[] = {
  147919. -1.5, -0.5, 0.5, 1.5,
  147920. };
  147921. static long _vq_quantmap__44u3__p6_1[] = {
  147922. 3, 1, 0, 2, 4,
  147923. };
  147924. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147925. _vq_quantthresh__44u3__p6_1,
  147926. _vq_quantmap__44u3__p6_1,
  147927. 5,
  147928. 5
  147929. };
  147930. static static_codebook _44u3__p6_1 = {
  147931. 2, 25,
  147932. _vq_lengthlist__44u3__p6_1,
  147933. 1, -533725184, 1611661312, 3, 0,
  147934. _vq_quantlist__44u3__p6_1,
  147935. NULL,
  147936. &_vq_auxt__44u3__p6_1,
  147937. NULL,
  147938. 0
  147939. };
  147940. static long _vq_quantlist__44u3__p7_0[] = {
  147941. 4,
  147942. 3,
  147943. 5,
  147944. 2,
  147945. 6,
  147946. 1,
  147947. 7,
  147948. 0,
  147949. 8,
  147950. };
  147951. static long _vq_lengthlist__44u3__p7_0[] = {
  147952. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147953. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147954. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147955. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147956. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147957. 9,
  147958. };
  147959. static float _vq_quantthresh__44u3__p7_0[] = {
  147960. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147961. };
  147962. static long _vq_quantmap__44u3__p7_0[] = {
  147963. 7, 5, 3, 1, 0, 2, 4, 6,
  147964. 8,
  147965. };
  147966. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147967. _vq_quantthresh__44u3__p7_0,
  147968. _vq_quantmap__44u3__p7_0,
  147969. 9,
  147970. 9
  147971. };
  147972. static static_codebook _44u3__p7_0 = {
  147973. 2, 81,
  147974. _vq_lengthlist__44u3__p7_0,
  147975. 1, -515907584, 1627381760, 4, 0,
  147976. _vq_quantlist__44u3__p7_0,
  147977. NULL,
  147978. &_vq_auxt__44u3__p7_0,
  147979. NULL,
  147980. 0
  147981. };
  147982. static long _vq_quantlist__44u3__p7_1[] = {
  147983. 7,
  147984. 6,
  147985. 8,
  147986. 5,
  147987. 9,
  147988. 4,
  147989. 10,
  147990. 3,
  147991. 11,
  147992. 2,
  147993. 12,
  147994. 1,
  147995. 13,
  147996. 0,
  147997. 14,
  147998. };
  147999. static long _vq_lengthlist__44u3__p7_1[] = {
  148000. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148001. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148002. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148003. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148004. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148005. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148006. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148007. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148008. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148009. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148010. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148011. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148012. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148013. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148014. 17,
  148015. };
  148016. static float _vq_quantthresh__44u3__p7_1[] = {
  148017. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148018. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148019. };
  148020. static long _vq_quantmap__44u3__p7_1[] = {
  148021. 13, 11, 9, 7, 5, 3, 1, 0,
  148022. 2, 4, 6, 8, 10, 12, 14,
  148023. };
  148024. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148025. _vq_quantthresh__44u3__p7_1,
  148026. _vq_quantmap__44u3__p7_1,
  148027. 15,
  148028. 15
  148029. };
  148030. static static_codebook _44u3__p7_1 = {
  148031. 2, 225,
  148032. _vq_lengthlist__44u3__p7_1,
  148033. 1, -522338304, 1620115456, 4, 0,
  148034. _vq_quantlist__44u3__p7_1,
  148035. NULL,
  148036. &_vq_auxt__44u3__p7_1,
  148037. NULL,
  148038. 0
  148039. };
  148040. static long _vq_quantlist__44u3__p7_2[] = {
  148041. 8,
  148042. 7,
  148043. 9,
  148044. 6,
  148045. 10,
  148046. 5,
  148047. 11,
  148048. 4,
  148049. 12,
  148050. 3,
  148051. 13,
  148052. 2,
  148053. 14,
  148054. 1,
  148055. 15,
  148056. 0,
  148057. 16,
  148058. };
  148059. static long _vq_lengthlist__44u3__p7_2[] = {
  148060. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148061. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148062. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148063. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148064. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148065. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148066. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148067. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148068. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148069. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148070. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148071. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148072. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148073. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148074. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148075. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148076. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148077. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148078. 11,
  148079. };
  148080. static float _vq_quantthresh__44u3__p7_2[] = {
  148081. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148082. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148083. };
  148084. static long _vq_quantmap__44u3__p7_2[] = {
  148085. 15, 13, 11, 9, 7, 5, 3, 1,
  148086. 0, 2, 4, 6, 8, 10, 12, 14,
  148087. 16,
  148088. };
  148089. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148090. _vq_quantthresh__44u3__p7_2,
  148091. _vq_quantmap__44u3__p7_2,
  148092. 17,
  148093. 17
  148094. };
  148095. static static_codebook _44u3__p7_2 = {
  148096. 2, 289,
  148097. _vq_lengthlist__44u3__p7_2,
  148098. 1, -529530880, 1611661312, 5, 0,
  148099. _vq_quantlist__44u3__p7_2,
  148100. NULL,
  148101. &_vq_auxt__44u3__p7_2,
  148102. NULL,
  148103. 0
  148104. };
  148105. static long _huff_lengthlist__44u3__short[] = {
  148106. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148107. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148108. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148109. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148110. };
  148111. static static_codebook _huff_book__44u3__short = {
  148112. 2, 64,
  148113. _huff_lengthlist__44u3__short,
  148114. 0, 0, 0, 0, 0,
  148115. NULL,
  148116. NULL,
  148117. NULL,
  148118. NULL,
  148119. 0
  148120. };
  148121. static long _huff_lengthlist__44u4__long[] = {
  148122. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148123. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148124. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148125. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148126. };
  148127. static static_codebook _huff_book__44u4__long = {
  148128. 2, 64,
  148129. _huff_lengthlist__44u4__long,
  148130. 0, 0, 0, 0, 0,
  148131. NULL,
  148132. NULL,
  148133. NULL,
  148134. NULL,
  148135. 0
  148136. };
  148137. static long _vq_quantlist__44u4__p1_0[] = {
  148138. 1,
  148139. 0,
  148140. 2,
  148141. };
  148142. static long _vq_lengthlist__44u4__p1_0[] = {
  148143. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148144. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148145. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148146. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148147. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148148. 13,
  148149. };
  148150. static float _vq_quantthresh__44u4__p1_0[] = {
  148151. -0.5, 0.5,
  148152. };
  148153. static long _vq_quantmap__44u4__p1_0[] = {
  148154. 1, 0, 2,
  148155. };
  148156. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148157. _vq_quantthresh__44u4__p1_0,
  148158. _vq_quantmap__44u4__p1_0,
  148159. 3,
  148160. 3
  148161. };
  148162. static static_codebook _44u4__p1_0 = {
  148163. 4, 81,
  148164. _vq_lengthlist__44u4__p1_0,
  148165. 1, -535822336, 1611661312, 2, 0,
  148166. _vq_quantlist__44u4__p1_0,
  148167. NULL,
  148168. &_vq_auxt__44u4__p1_0,
  148169. NULL,
  148170. 0
  148171. };
  148172. static long _vq_quantlist__44u4__p2_0[] = {
  148173. 1,
  148174. 0,
  148175. 2,
  148176. };
  148177. static long _vq_lengthlist__44u4__p2_0[] = {
  148178. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148179. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148180. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148181. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148182. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148183. 9,
  148184. };
  148185. static float _vq_quantthresh__44u4__p2_0[] = {
  148186. -0.5, 0.5,
  148187. };
  148188. static long _vq_quantmap__44u4__p2_0[] = {
  148189. 1, 0, 2,
  148190. };
  148191. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148192. _vq_quantthresh__44u4__p2_0,
  148193. _vq_quantmap__44u4__p2_0,
  148194. 3,
  148195. 3
  148196. };
  148197. static static_codebook _44u4__p2_0 = {
  148198. 4, 81,
  148199. _vq_lengthlist__44u4__p2_0,
  148200. 1, -535822336, 1611661312, 2, 0,
  148201. _vq_quantlist__44u4__p2_0,
  148202. NULL,
  148203. &_vq_auxt__44u4__p2_0,
  148204. NULL,
  148205. 0
  148206. };
  148207. static long _vq_quantlist__44u4__p3_0[] = {
  148208. 2,
  148209. 1,
  148210. 3,
  148211. 0,
  148212. 4,
  148213. };
  148214. static long _vq_lengthlist__44u4__p3_0[] = {
  148215. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148216. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148217. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148218. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148219. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148220. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148221. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148222. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148223. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148224. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148225. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148226. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148227. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148228. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148229. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148230. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148231. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148232. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148233. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148234. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148235. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148236. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148237. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148238. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148239. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148240. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148241. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148242. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148243. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148244. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148245. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148246. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148247. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148248. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148249. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148250. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148251. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148252. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148253. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148254. 0,
  148255. };
  148256. static float _vq_quantthresh__44u4__p3_0[] = {
  148257. -1.5, -0.5, 0.5, 1.5,
  148258. };
  148259. static long _vq_quantmap__44u4__p3_0[] = {
  148260. 3, 1, 0, 2, 4,
  148261. };
  148262. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148263. _vq_quantthresh__44u4__p3_0,
  148264. _vq_quantmap__44u4__p3_0,
  148265. 5,
  148266. 5
  148267. };
  148268. static static_codebook _44u4__p3_0 = {
  148269. 4, 625,
  148270. _vq_lengthlist__44u4__p3_0,
  148271. 1, -533725184, 1611661312, 3, 0,
  148272. _vq_quantlist__44u4__p3_0,
  148273. NULL,
  148274. &_vq_auxt__44u4__p3_0,
  148275. NULL,
  148276. 0
  148277. };
  148278. static long _vq_quantlist__44u4__p4_0[] = {
  148279. 2,
  148280. 1,
  148281. 3,
  148282. 0,
  148283. 4,
  148284. };
  148285. static long _vq_lengthlist__44u4__p4_0[] = {
  148286. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148287. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148288. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148289. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148290. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148291. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148292. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148293. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148294. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148295. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148296. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148297. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148298. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148299. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148300. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148301. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148302. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148303. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148304. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148305. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148306. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148307. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148308. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148309. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148310. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148311. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148312. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148313. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148314. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148315. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148316. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148317. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148318. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148319. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148320. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148321. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148322. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148323. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148324. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148325. 13,
  148326. };
  148327. static float _vq_quantthresh__44u4__p4_0[] = {
  148328. -1.5, -0.5, 0.5, 1.5,
  148329. };
  148330. static long _vq_quantmap__44u4__p4_0[] = {
  148331. 3, 1, 0, 2, 4,
  148332. };
  148333. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148334. _vq_quantthresh__44u4__p4_0,
  148335. _vq_quantmap__44u4__p4_0,
  148336. 5,
  148337. 5
  148338. };
  148339. static static_codebook _44u4__p4_0 = {
  148340. 4, 625,
  148341. _vq_lengthlist__44u4__p4_0,
  148342. 1, -533725184, 1611661312, 3, 0,
  148343. _vq_quantlist__44u4__p4_0,
  148344. NULL,
  148345. &_vq_auxt__44u4__p4_0,
  148346. NULL,
  148347. 0
  148348. };
  148349. static long _vq_quantlist__44u4__p5_0[] = {
  148350. 4,
  148351. 3,
  148352. 5,
  148353. 2,
  148354. 6,
  148355. 1,
  148356. 7,
  148357. 0,
  148358. 8,
  148359. };
  148360. static long _vq_lengthlist__44u4__p5_0[] = {
  148361. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148362. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148363. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148364. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148365. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148366. 12,
  148367. };
  148368. static float _vq_quantthresh__44u4__p5_0[] = {
  148369. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148370. };
  148371. static long _vq_quantmap__44u4__p5_0[] = {
  148372. 7, 5, 3, 1, 0, 2, 4, 6,
  148373. 8,
  148374. };
  148375. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148376. _vq_quantthresh__44u4__p5_0,
  148377. _vq_quantmap__44u4__p5_0,
  148378. 9,
  148379. 9
  148380. };
  148381. static static_codebook _44u4__p5_0 = {
  148382. 2, 81,
  148383. _vq_lengthlist__44u4__p5_0,
  148384. 1, -531628032, 1611661312, 4, 0,
  148385. _vq_quantlist__44u4__p5_0,
  148386. NULL,
  148387. &_vq_auxt__44u4__p5_0,
  148388. NULL,
  148389. 0
  148390. };
  148391. static long _vq_quantlist__44u4__p6_0[] = {
  148392. 6,
  148393. 5,
  148394. 7,
  148395. 4,
  148396. 8,
  148397. 3,
  148398. 9,
  148399. 2,
  148400. 10,
  148401. 1,
  148402. 11,
  148403. 0,
  148404. 12,
  148405. };
  148406. static long _vq_lengthlist__44u4__p6_0[] = {
  148407. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148408. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148409. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148410. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148411. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148412. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148413. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148414. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148415. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148416. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148417. 16,16,16,17,17,18,17,20,21,
  148418. };
  148419. static float _vq_quantthresh__44u4__p6_0[] = {
  148420. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148421. 12.5, 17.5, 22.5, 27.5,
  148422. };
  148423. static long _vq_quantmap__44u4__p6_0[] = {
  148424. 11, 9, 7, 5, 3, 1, 0, 2,
  148425. 4, 6, 8, 10, 12,
  148426. };
  148427. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148428. _vq_quantthresh__44u4__p6_0,
  148429. _vq_quantmap__44u4__p6_0,
  148430. 13,
  148431. 13
  148432. };
  148433. static static_codebook _44u4__p6_0 = {
  148434. 2, 169,
  148435. _vq_lengthlist__44u4__p6_0,
  148436. 1, -526516224, 1616117760, 4, 0,
  148437. _vq_quantlist__44u4__p6_0,
  148438. NULL,
  148439. &_vq_auxt__44u4__p6_0,
  148440. NULL,
  148441. 0
  148442. };
  148443. static long _vq_quantlist__44u4__p6_1[] = {
  148444. 2,
  148445. 1,
  148446. 3,
  148447. 0,
  148448. 4,
  148449. };
  148450. static long _vq_lengthlist__44u4__p6_1[] = {
  148451. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148452. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148453. };
  148454. static float _vq_quantthresh__44u4__p6_1[] = {
  148455. -1.5, -0.5, 0.5, 1.5,
  148456. };
  148457. static long _vq_quantmap__44u4__p6_1[] = {
  148458. 3, 1, 0, 2, 4,
  148459. };
  148460. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148461. _vq_quantthresh__44u4__p6_1,
  148462. _vq_quantmap__44u4__p6_1,
  148463. 5,
  148464. 5
  148465. };
  148466. static static_codebook _44u4__p6_1 = {
  148467. 2, 25,
  148468. _vq_lengthlist__44u4__p6_1,
  148469. 1, -533725184, 1611661312, 3, 0,
  148470. _vq_quantlist__44u4__p6_1,
  148471. NULL,
  148472. &_vq_auxt__44u4__p6_1,
  148473. NULL,
  148474. 0
  148475. };
  148476. static long _vq_quantlist__44u4__p7_0[] = {
  148477. 6,
  148478. 5,
  148479. 7,
  148480. 4,
  148481. 8,
  148482. 3,
  148483. 9,
  148484. 2,
  148485. 10,
  148486. 1,
  148487. 11,
  148488. 0,
  148489. 12,
  148490. };
  148491. static long _vq_lengthlist__44u4__p7_0[] = {
  148492. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148493. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148494. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148495. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148496. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148497. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148502. 11,11,11,11,11,11,11,11,11,
  148503. };
  148504. static float _vq_quantthresh__44u4__p7_0[] = {
  148505. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148506. 637.5, 892.5, 1147.5, 1402.5,
  148507. };
  148508. static long _vq_quantmap__44u4__p7_0[] = {
  148509. 11, 9, 7, 5, 3, 1, 0, 2,
  148510. 4, 6, 8, 10, 12,
  148511. };
  148512. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148513. _vq_quantthresh__44u4__p7_0,
  148514. _vq_quantmap__44u4__p7_0,
  148515. 13,
  148516. 13
  148517. };
  148518. static static_codebook _44u4__p7_0 = {
  148519. 2, 169,
  148520. _vq_lengthlist__44u4__p7_0,
  148521. 1, -514332672, 1627381760, 4, 0,
  148522. _vq_quantlist__44u4__p7_0,
  148523. NULL,
  148524. &_vq_auxt__44u4__p7_0,
  148525. NULL,
  148526. 0
  148527. };
  148528. static long _vq_quantlist__44u4__p7_1[] = {
  148529. 7,
  148530. 6,
  148531. 8,
  148532. 5,
  148533. 9,
  148534. 4,
  148535. 10,
  148536. 3,
  148537. 11,
  148538. 2,
  148539. 12,
  148540. 1,
  148541. 13,
  148542. 0,
  148543. 14,
  148544. };
  148545. static long _vq_lengthlist__44u4__p7_1[] = {
  148546. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148547. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148548. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148549. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148550. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148551. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148552. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148553. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148554. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148555. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148556. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148557. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148558. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148559. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148560. 16,
  148561. };
  148562. static float _vq_quantthresh__44u4__p7_1[] = {
  148563. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148564. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148565. };
  148566. static long _vq_quantmap__44u4__p7_1[] = {
  148567. 13, 11, 9, 7, 5, 3, 1, 0,
  148568. 2, 4, 6, 8, 10, 12, 14,
  148569. };
  148570. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148571. _vq_quantthresh__44u4__p7_1,
  148572. _vq_quantmap__44u4__p7_1,
  148573. 15,
  148574. 15
  148575. };
  148576. static static_codebook _44u4__p7_1 = {
  148577. 2, 225,
  148578. _vq_lengthlist__44u4__p7_1,
  148579. 1, -522338304, 1620115456, 4, 0,
  148580. _vq_quantlist__44u4__p7_1,
  148581. NULL,
  148582. &_vq_auxt__44u4__p7_1,
  148583. NULL,
  148584. 0
  148585. };
  148586. static long _vq_quantlist__44u4__p7_2[] = {
  148587. 8,
  148588. 7,
  148589. 9,
  148590. 6,
  148591. 10,
  148592. 5,
  148593. 11,
  148594. 4,
  148595. 12,
  148596. 3,
  148597. 13,
  148598. 2,
  148599. 14,
  148600. 1,
  148601. 15,
  148602. 0,
  148603. 16,
  148604. };
  148605. static long _vq_lengthlist__44u4__p7_2[] = {
  148606. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148607. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148608. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148609. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148610. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148611. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148612. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148613. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148614. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148615. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148616. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148617. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148618. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148619. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148620. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148621. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148622. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148623. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148624. 10,
  148625. };
  148626. static float _vq_quantthresh__44u4__p7_2[] = {
  148627. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148628. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148629. };
  148630. static long _vq_quantmap__44u4__p7_2[] = {
  148631. 15, 13, 11, 9, 7, 5, 3, 1,
  148632. 0, 2, 4, 6, 8, 10, 12, 14,
  148633. 16,
  148634. };
  148635. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148636. _vq_quantthresh__44u4__p7_2,
  148637. _vq_quantmap__44u4__p7_2,
  148638. 17,
  148639. 17
  148640. };
  148641. static static_codebook _44u4__p7_2 = {
  148642. 2, 289,
  148643. _vq_lengthlist__44u4__p7_2,
  148644. 1, -529530880, 1611661312, 5, 0,
  148645. _vq_quantlist__44u4__p7_2,
  148646. NULL,
  148647. &_vq_auxt__44u4__p7_2,
  148648. NULL,
  148649. 0
  148650. };
  148651. static long _huff_lengthlist__44u4__short[] = {
  148652. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148653. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148654. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148655. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148656. };
  148657. static static_codebook _huff_book__44u4__short = {
  148658. 2, 64,
  148659. _huff_lengthlist__44u4__short,
  148660. 0, 0, 0, 0, 0,
  148661. NULL,
  148662. NULL,
  148663. NULL,
  148664. NULL,
  148665. 0
  148666. };
  148667. static long _huff_lengthlist__44u5__long[] = {
  148668. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148669. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148670. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148671. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148672. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148673. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148674. 14, 8, 7, 8,
  148675. };
  148676. static static_codebook _huff_book__44u5__long = {
  148677. 2, 100,
  148678. _huff_lengthlist__44u5__long,
  148679. 0, 0, 0, 0, 0,
  148680. NULL,
  148681. NULL,
  148682. NULL,
  148683. NULL,
  148684. 0
  148685. };
  148686. static long _vq_quantlist__44u5__p1_0[] = {
  148687. 1,
  148688. 0,
  148689. 2,
  148690. };
  148691. static long _vq_lengthlist__44u5__p1_0[] = {
  148692. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148693. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148694. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148695. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148696. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148697. 12,
  148698. };
  148699. static float _vq_quantthresh__44u5__p1_0[] = {
  148700. -0.5, 0.5,
  148701. };
  148702. static long _vq_quantmap__44u5__p1_0[] = {
  148703. 1, 0, 2,
  148704. };
  148705. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148706. _vq_quantthresh__44u5__p1_0,
  148707. _vq_quantmap__44u5__p1_0,
  148708. 3,
  148709. 3
  148710. };
  148711. static static_codebook _44u5__p1_0 = {
  148712. 4, 81,
  148713. _vq_lengthlist__44u5__p1_0,
  148714. 1, -535822336, 1611661312, 2, 0,
  148715. _vq_quantlist__44u5__p1_0,
  148716. NULL,
  148717. &_vq_auxt__44u5__p1_0,
  148718. NULL,
  148719. 0
  148720. };
  148721. static long _vq_quantlist__44u5__p2_0[] = {
  148722. 1,
  148723. 0,
  148724. 2,
  148725. };
  148726. static long _vq_lengthlist__44u5__p2_0[] = {
  148727. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148728. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148729. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148730. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148731. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148732. 9,
  148733. };
  148734. static float _vq_quantthresh__44u5__p2_0[] = {
  148735. -0.5, 0.5,
  148736. };
  148737. static long _vq_quantmap__44u5__p2_0[] = {
  148738. 1, 0, 2,
  148739. };
  148740. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148741. _vq_quantthresh__44u5__p2_0,
  148742. _vq_quantmap__44u5__p2_0,
  148743. 3,
  148744. 3
  148745. };
  148746. static static_codebook _44u5__p2_0 = {
  148747. 4, 81,
  148748. _vq_lengthlist__44u5__p2_0,
  148749. 1, -535822336, 1611661312, 2, 0,
  148750. _vq_quantlist__44u5__p2_0,
  148751. NULL,
  148752. &_vq_auxt__44u5__p2_0,
  148753. NULL,
  148754. 0
  148755. };
  148756. static long _vq_quantlist__44u5__p3_0[] = {
  148757. 2,
  148758. 1,
  148759. 3,
  148760. 0,
  148761. 4,
  148762. };
  148763. static long _vq_lengthlist__44u5__p3_0[] = {
  148764. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148765. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148766. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148767. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148768. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148769. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148770. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148771. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148772. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148773. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148774. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148775. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148776. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148777. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148778. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148779. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148780. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148781. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148782. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148783. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148784. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148785. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148786. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148787. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148788. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148789. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148790. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148791. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148792. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148793. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148794. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148795. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148796. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148797. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148798. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148799. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148800. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148801. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148802. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148803. 0,
  148804. };
  148805. static float _vq_quantthresh__44u5__p3_0[] = {
  148806. -1.5, -0.5, 0.5, 1.5,
  148807. };
  148808. static long _vq_quantmap__44u5__p3_0[] = {
  148809. 3, 1, 0, 2, 4,
  148810. };
  148811. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148812. _vq_quantthresh__44u5__p3_0,
  148813. _vq_quantmap__44u5__p3_0,
  148814. 5,
  148815. 5
  148816. };
  148817. static static_codebook _44u5__p3_0 = {
  148818. 4, 625,
  148819. _vq_lengthlist__44u5__p3_0,
  148820. 1, -533725184, 1611661312, 3, 0,
  148821. _vq_quantlist__44u5__p3_0,
  148822. NULL,
  148823. &_vq_auxt__44u5__p3_0,
  148824. NULL,
  148825. 0
  148826. };
  148827. static long _vq_quantlist__44u5__p4_0[] = {
  148828. 2,
  148829. 1,
  148830. 3,
  148831. 0,
  148832. 4,
  148833. };
  148834. static long _vq_lengthlist__44u5__p4_0[] = {
  148835. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148836. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148837. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148838. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148839. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148840. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148841. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148842. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148843. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148844. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148845. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148846. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148847. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148848. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148849. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148850. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148851. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148852. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148853. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148854. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148855. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148856. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148857. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148858. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148859. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148860. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148861. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148862. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148863. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148864. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148865. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148866. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148867. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148868. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148869. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148870. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148871. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148872. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148873. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148874. 12,
  148875. };
  148876. static float _vq_quantthresh__44u5__p4_0[] = {
  148877. -1.5, -0.5, 0.5, 1.5,
  148878. };
  148879. static long _vq_quantmap__44u5__p4_0[] = {
  148880. 3, 1, 0, 2, 4,
  148881. };
  148882. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148883. _vq_quantthresh__44u5__p4_0,
  148884. _vq_quantmap__44u5__p4_0,
  148885. 5,
  148886. 5
  148887. };
  148888. static static_codebook _44u5__p4_0 = {
  148889. 4, 625,
  148890. _vq_lengthlist__44u5__p4_0,
  148891. 1, -533725184, 1611661312, 3, 0,
  148892. _vq_quantlist__44u5__p4_0,
  148893. NULL,
  148894. &_vq_auxt__44u5__p4_0,
  148895. NULL,
  148896. 0
  148897. };
  148898. static long _vq_quantlist__44u5__p5_0[] = {
  148899. 4,
  148900. 3,
  148901. 5,
  148902. 2,
  148903. 6,
  148904. 1,
  148905. 7,
  148906. 0,
  148907. 8,
  148908. };
  148909. static long _vq_lengthlist__44u5__p5_0[] = {
  148910. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148911. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148912. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148913. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148914. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148915. 14,
  148916. };
  148917. static float _vq_quantthresh__44u5__p5_0[] = {
  148918. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148919. };
  148920. static long _vq_quantmap__44u5__p5_0[] = {
  148921. 7, 5, 3, 1, 0, 2, 4, 6,
  148922. 8,
  148923. };
  148924. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148925. _vq_quantthresh__44u5__p5_0,
  148926. _vq_quantmap__44u5__p5_0,
  148927. 9,
  148928. 9
  148929. };
  148930. static static_codebook _44u5__p5_0 = {
  148931. 2, 81,
  148932. _vq_lengthlist__44u5__p5_0,
  148933. 1, -531628032, 1611661312, 4, 0,
  148934. _vq_quantlist__44u5__p5_0,
  148935. NULL,
  148936. &_vq_auxt__44u5__p5_0,
  148937. NULL,
  148938. 0
  148939. };
  148940. static long _vq_quantlist__44u5__p6_0[] = {
  148941. 4,
  148942. 3,
  148943. 5,
  148944. 2,
  148945. 6,
  148946. 1,
  148947. 7,
  148948. 0,
  148949. 8,
  148950. };
  148951. static long _vq_lengthlist__44u5__p6_0[] = {
  148952. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148953. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148954. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148955. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148956. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148957. 11,
  148958. };
  148959. static float _vq_quantthresh__44u5__p6_0[] = {
  148960. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148961. };
  148962. static long _vq_quantmap__44u5__p6_0[] = {
  148963. 7, 5, 3, 1, 0, 2, 4, 6,
  148964. 8,
  148965. };
  148966. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148967. _vq_quantthresh__44u5__p6_0,
  148968. _vq_quantmap__44u5__p6_0,
  148969. 9,
  148970. 9
  148971. };
  148972. static static_codebook _44u5__p6_0 = {
  148973. 2, 81,
  148974. _vq_lengthlist__44u5__p6_0,
  148975. 1, -531628032, 1611661312, 4, 0,
  148976. _vq_quantlist__44u5__p6_0,
  148977. NULL,
  148978. &_vq_auxt__44u5__p6_0,
  148979. NULL,
  148980. 0
  148981. };
  148982. static long _vq_quantlist__44u5__p7_0[] = {
  148983. 1,
  148984. 0,
  148985. 2,
  148986. };
  148987. static long _vq_lengthlist__44u5__p7_0[] = {
  148988. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148989. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148990. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148991. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148992. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148993. 12,
  148994. };
  148995. static float _vq_quantthresh__44u5__p7_0[] = {
  148996. -5.5, 5.5,
  148997. };
  148998. static long _vq_quantmap__44u5__p7_0[] = {
  148999. 1, 0, 2,
  149000. };
  149001. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149002. _vq_quantthresh__44u5__p7_0,
  149003. _vq_quantmap__44u5__p7_0,
  149004. 3,
  149005. 3
  149006. };
  149007. static static_codebook _44u5__p7_0 = {
  149008. 4, 81,
  149009. _vq_lengthlist__44u5__p7_0,
  149010. 1, -529137664, 1618345984, 2, 0,
  149011. _vq_quantlist__44u5__p7_0,
  149012. NULL,
  149013. &_vq_auxt__44u5__p7_0,
  149014. NULL,
  149015. 0
  149016. };
  149017. static long _vq_quantlist__44u5__p7_1[] = {
  149018. 5,
  149019. 4,
  149020. 6,
  149021. 3,
  149022. 7,
  149023. 2,
  149024. 8,
  149025. 1,
  149026. 9,
  149027. 0,
  149028. 10,
  149029. };
  149030. static long _vq_lengthlist__44u5__p7_1[] = {
  149031. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149032. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149033. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149034. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149035. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149036. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149037. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149038. 9, 9, 9, 9, 9,10,10,10,10,
  149039. };
  149040. static float _vq_quantthresh__44u5__p7_1[] = {
  149041. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149042. 3.5, 4.5,
  149043. };
  149044. static long _vq_quantmap__44u5__p7_1[] = {
  149045. 9, 7, 5, 3, 1, 0, 2, 4,
  149046. 6, 8, 10,
  149047. };
  149048. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149049. _vq_quantthresh__44u5__p7_1,
  149050. _vq_quantmap__44u5__p7_1,
  149051. 11,
  149052. 11
  149053. };
  149054. static static_codebook _44u5__p7_1 = {
  149055. 2, 121,
  149056. _vq_lengthlist__44u5__p7_1,
  149057. 1, -531365888, 1611661312, 4, 0,
  149058. _vq_quantlist__44u5__p7_1,
  149059. NULL,
  149060. &_vq_auxt__44u5__p7_1,
  149061. NULL,
  149062. 0
  149063. };
  149064. static long _vq_quantlist__44u5__p8_0[] = {
  149065. 5,
  149066. 4,
  149067. 6,
  149068. 3,
  149069. 7,
  149070. 2,
  149071. 8,
  149072. 1,
  149073. 9,
  149074. 0,
  149075. 10,
  149076. };
  149077. static long _vq_lengthlist__44u5__p8_0[] = {
  149078. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149079. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149080. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149081. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149082. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149083. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149084. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149085. 12,13,13,14,14,14,14,15,15,
  149086. };
  149087. static float _vq_quantthresh__44u5__p8_0[] = {
  149088. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149089. 38.5, 49.5,
  149090. };
  149091. static long _vq_quantmap__44u5__p8_0[] = {
  149092. 9, 7, 5, 3, 1, 0, 2, 4,
  149093. 6, 8, 10,
  149094. };
  149095. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149096. _vq_quantthresh__44u5__p8_0,
  149097. _vq_quantmap__44u5__p8_0,
  149098. 11,
  149099. 11
  149100. };
  149101. static static_codebook _44u5__p8_0 = {
  149102. 2, 121,
  149103. _vq_lengthlist__44u5__p8_0,
  149104. 1, -524582912, 1618345984, 4, 0,
  149105. _vq_quantlist__44u5__p8_0,
  149106. NULL,
  149107. &_vq_auxt__44u5__p8_0,
  149108. NULL,
  149109. 0
  149110. };
  149111. static long _vq_quantlist__44u5__p8_1[] = {
  149112. 5,
  149113. 4,
  149114. 6,
  149115. 3,
  149116. 7,
  149117. 2,
  149118. 8,
  149119. 1,
  149120. 9,
  149121. 0,
  149122. 10,
  149123. };
  149124. static long _vq_lengthlist__44u5__p8_1[] = {
  149125. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149126. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149127. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149128. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149129. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149130. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149131. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149132. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149133. };
  149134. static float _vq_quantthresh__44u5__p8_1[] = {
  149135. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149136. 3.5, 4.5,
  149137. };
  149138. static long _vq_quantmap__44u5__p8_1[] = {
  149139. 9, 7, 5, 3, 1, 0, 2, 4,
  149140. 6, 8, 10,
  149141. };
  149142. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149143. _vq_quantthresh__44u5__p8_1,
  149144. _vq_quantmap__44u5__p8_1,
  149145. 11,
  149146. 11
  149147. };
  149148. static static_codebook _44u5__p8_1 = {
  149149. 2, 121,
  149150. _vq_lengthlist__44u5__p8_1,
  149151. 1, -531365888, 1611661312, 4, 0,
  149152. _vq_quantlist__44u5__p8_1,
  149153. NULL,
  149154. &_vq_auxt__44u5__p8_1,
  149155. NULL,
  149156. 0
  149157. };
  149158. static long _vq_quantlist__44u5__p9_0[] = {
  149159. 6,
  149160. 5,
  149161. 7,
  149162. 4,
  149163. 8,
  149164. 3,
  149165. 9,
  149166. 2,
  149167. 10,
  149168. 1,
  149169. 11,
  149170. 0,
  149171. 12,
  149172. };
  149173. static long _vq_lengthlist__44u5__p9_0[] = {
  149174. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149175. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149176. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149177. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149178. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149179. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149180. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149181. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149182. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149183. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149184. 12,12,12,12,12,12,12,12,12,
  149185. };
  149186. static float _vq_quantthresh__44u5__p9_0[] = {
  149187. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149188. 637.5, 892.5, 1147.5, 1402.5,
  149189. };
  149190. static long _vq_quantmap__44u5__p9_0[] = {
  149191. 11, 9, 7, 5, 3, 1, 0, 2,
  149192. 4, 6, 8, 10, 12,
  149193. };
  149194. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149195. _vq_quantthresh__44u5__p9_0,
  149196. _vq_quantmap__44u5__p9_0,
  149197. 13,
  149198. 13
  149199. };
  149200. static static_codebook _44u5__p9_0 = {
  149201. 2, 169,
  149202. _vq_lengthlist__44u5__p9_0,
  149203. 1, -514332672, 1627381760, 4, 0,
  149204. _vq_quantlist__44u5__p9_0,
  149205. NULL,
  149206. &_vq_auxt__44u5__p9_0,
  149207. NULL,
  149208. 0
  149209. };
  149210. static long _vq_quantlist__44u5__p9_1[] = {
  149211. 7,
  149212. 6,
  149213. 8,
  149214. 5,
  149215. 9,
  149216. 4,
  149217. 10,
  149218. 3,
  149219. 11,
  149220. 2,
  149221. 12,
  149222. 1,
  149223. 13,
  149224. 0,
  149225. 14,
  149226. };
  149227. static long _vq_lengthlist__44u5__p9_1[] = {
  149228. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149229. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149230. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149231. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149232. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149233. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149234. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149235. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149236. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149237. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149238. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149239. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149240. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149241. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149242. 14,
  149243. };
  149244. static float _vq_quantthresh__44u5__p9_1[] = {
  149245. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149246. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149247. };
  149248. static long _vq_quantmap__44u5__p9_1[] = {
  149249. 13, 11, 9, 7, 5, 3, 1, 0,
  149250. 2, 4, 6, 8, 10, 12, 14,
  149251. };
  149252. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149253. _vq_quantthresh__44u5__p9_1,
  149254. _vq_quantmap__44u5__p9_1,
  149255. 15,
  149256. 15
  149257. };
  149258. static static_codebook _44u5__p9_1 = {
  149259. 2, 225,
  149260. _vq_lengthlist__44u5__p9_1,
  149261. 1, -522338304, 1620115456, 4, 0,
  149262. _vq_quantlist__44u5__p9_1,
  149263. NULL,
  149264. &_vq_auxt__44u5__p9_1,
  149265. NULL,
  149266. 0
  149267. };
  149268. static long _vq_quantlist__44u5__p9_2[] = {
  149269. 8,
  149270. 7,
  149271. 9,
  149272. 6,
  149273. 10,
  149274. 5,
  149275. 11,
  149276. 4,
  149277. 12,
  149278. 3,
  149279. 13,
  149280. 2,
  149281. 14,
  149282. 1,
  149283. 15,
  149284. 0,
  149285. 16,
  149286. };
  149287. static long _vq_lengthlist__44u5__p9_2[] = {
  149288. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149289. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149290. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149291. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149292. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149293. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149294. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149295. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149296. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149297. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149298. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149299. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149300. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149301. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149302. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149303. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149304. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149305. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149306. 10,
  149307. };
  149308. static float _vq_quantthresh__44u5__p9_2[] = {
  149309. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149310. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149311. };
  149312. static long _vq_quantmap__44u5__p9_2[] = {
  149313. 15, 13, 11, 9, 7, 5, 3, 1,
  149314. 0, 2, 4, 6, 8, 10, 12, 14,
  149315. 16,
  149316. };
  149317. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149318. _vq_quantthresh__44u5__p9_2,
  149319. _vq_quantmap__44u5__p9_2,
  149320. 17,
  149321. 17
  149322. };
  149323. static static_codebook _44u5__p9_2 = {
  149324. 2, 289,
  149325. _vq_lengthlist__44u5__p9_2,
  149326. 1, -529530880, 1611661312, 5, 0,
  149327. _vq_quantlist__44u5__p9_2,
  149328. NULL,
  149329. &_vq_auxt__44u5__p9_2,
  149330. NULL,
  149331. 0
  149332. };
  149333. static long _huff_lengthlist__44u5__short[] = {
  149334. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149335. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149336. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149337. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149338. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149339. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149340. 6, 8,15,17,
  149341. };
  149342. static static_codebook _huff_book__44u5__short = {
  149343. 2, 100,
  149344. _huff_lengthlist__44u5__short,
  149345. 0, 0, 0, 0, 0,
  149346. NULL,
  149347. NULL,
  149348. NULL,
  149349. NULL,
  149350. 0
  149351. };
  149352. static long _huff_lengthlist__44u6__long[] = {
  149353. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149354. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149355. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149356. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149357. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149358. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149359. 13, 8, 7, 7,
  149360. };
  149361. static static_codebook _huff_book__44u6__long = {
  149362. 2, 100,
  149363. _huff_lengthlist__44u6__long,
  149364. 0, 0, 0, 0, 0,
  149365. NULL,
  149366. NULL,
  149367. NULL,
  149368. NULL,
  149369. 0
  149370. };
  149371. static long _vq_quantlist__44u6__p1_0[] = {
  149372. 1,
  149373. 0,
  149374. 2,
  149375. };
  149376. static long _vq_lengthlist__44u6__p1_0[] = {
  149377. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149378. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149379. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149380. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149381. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149382. 12,
  149383. };
  149384. static float _vq_quantthresh__44u6__p1_0[] = {
  149385. -0.5, 0.5,
  149386. };
  149387. static long _vq_quantmap__44u6__p1_0[] = {
  149388. 1, 0, 2,
  149389. };
  149390. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149391. _vq_quantthresh__44u6__p1_0,
  149392. _vq_quantmap__44u6__p1_0,
  149393. 3,
  149394. 3
  149395. };
  149396. static static_codebook _44u6__p1_0 = {
  149397. 4, 81,
  149398. _vq_lengthlist__44u6__p1_0,
  149399. 1, -535822336, 1611661312, 2, 0,
  149400. _vq_quantlist__44u6__p1_0,
  149401. NULL,
  149402. &_vq_auxt__44u6__p1_0,
  149403. NULL,
  149404. 0
  149405. };
  149406. static long _vq_quantlist__44u6__p2_0[] = {
  149407. 1,
  149408. 0,
  149409. 2,
  149410. };
  149411. static long _vq_lengthlist__44u6__p2_0[] = {
  149412. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149413. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149414. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149415. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149416. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149417. 9,
  149418. };
  149419. static float _vq_quantthresh__44u6__p2_0[] = {
  149420. -0.5, 0.5,
  149421. };
  149422. static long _vq_quantmap__44u6__p2_0[] = {
  149423. 1, 0, 2,
  149424. };
  149425. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149426. _vq_quantthresh__44u6__p2_0,
  149427. _vq_quantmap__44u6__p2_0,
  149428. 3,
  149429. 3
  149430. };
  149431. static static_codebook _44u6__p2_0 = {
  149432. 4, 81,
  149433. _vq_lengthlist__44u6__p2_0,
  149434. 1, -535822336, 1611661312, 2, 0,
  149435. _vq_quantlist__44u6__p2_0,
  149436. NULL,
  149437. &_vq_auxt__44u6__p2_0,
  149438. NULL,
  149439. 0
  149440. };
  149441. static long _vq_quantlist__44u6__p3_0[] = {
  149442. 2,
  149443. 1,
  149444. 3,
  149445. 0,
  149446. 4,
  149447. };
  149448. static long _vq_lengthlist__44u6__p3_0[] = {
  149449. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149450. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149451. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149452. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149453. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149454. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149455. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149456. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149457. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149458. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149459. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149460. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149461. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149462. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149463. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149464. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149465. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149466. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149467. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149468. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149469. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149470. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149471. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149472. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149473. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149474. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149475. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149476. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149477. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149478. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149479. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149480. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149481. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149482. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149483. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149484. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149485. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149486. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149487. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149488. 19,
  149489. };
  149490. static float _vq_quantthresh__44u6__p3_0[] = {
  149491. -1.5, -0.5, 0.5, 1.5,
  149492. };
  149493. static long _vq_quantmap__44u6__p3_0[] = {
  149494. 3, 1, 0, 2, 4,
  149495. };
  149496. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149497. _vq_quantthresh__44u6__p3_0,
  149498. _vq_quantmap__44u6__p3_0,
  149499. 5,
  149500. 5
  149501. };
  149502. static static_codebook _44u6__p3_0 = {
  149503. 4, 625,
  149504. _vq_lengthlist__44u6__p3_0,
  149505. 1, -533725184, 1611661312, 3, 0,
  149506. _vq_quantlist__44u6__p3_0,
  149507. NULL,
  149508. &_vq_auxt__44u6__p3_0,
  149509. NULL,
  149510. 0
  149511. };
  149512. static long _vq_quantlist__44u6__p4_0[] = {
  149513. 2,
  149514. 1,
  149515. 3,
  149516. 0,
  149517. 4,
  149518. };
  149519. static long _vq_lengthlist__44u6__p4_0[] = {
  149520. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149521. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149522. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149523. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149524. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149525. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149526. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149527. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149528. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149529. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149530. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149531. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149532. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149533. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149534. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149535. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149536. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149537. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149538. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149539. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149540. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149541. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149542. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149543. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149544. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149545. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149546. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149547. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149548. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149549. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149550. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149551. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149552. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149553. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149554. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149555. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149556. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149557. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149558. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149559. 13,
  149560. };
  149561. static float _vq_quantthresh__44u6__p4_0[] = {
  149562. -1.5, -0.5, 0.5, 1.5,
  149563. };
  149564. static long _vq_quantmap__44u6__p4_0[] = {
  149565. 3, 1, 0, 2, 4,
  149566. };
  149567. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149568. _vq_quantthresh__44u6__p4_0,
  149569. _vq_quantmap__44u6__p4_0,
  149570. 5,
  149571. 5
  149572. };
  149573. static static_codebook _44u6__p4_0 = {
  149574. 4, 625,
  149575. _vq_lengthlist__44u6__p4_0,
  149576. 1, -533725184, 1611661312, 3, 0,
  149577. _vq_quantlist__44u6__p4_0,
  149578. NULL,
  149579. &_vq_auxt__44u6__p4_0,
  149580. NULL,
  149581. 0
  149582. };
  149583. static long _vq_quantlist__44u6__p5_0[] = {
  149584. 4,
  149585. 3,
  149586. 5,
  149587. 2,
  149588. 6,
  149589. 1,
  149590. 7,
  149591. 0,
  149592. 8,
  149593. };
  149594. static long _vq_lengthlist__44u6__p5_0[] = {
  149595. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149596. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149597. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149598. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149599. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149600. 14,
  149601. };
  149602. static float _vq_quantthresh__44u6__p5_0[] = {
  149603. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149604. };
  149605. static long _vq_quantmap__44u6__p5_0[] = {
  149606. 7, 5, 3, 1, 0, 2, 4, 6,
  149607. 8,
  149608. };
  149609. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149610. _vq_quantthresh__44u6__p5_0,
  149611. _vq_quantmap__44u6__p5_0,
  149612. 9,
  149613. 9
  149614. };
  149615. static static_codebook _44u6__p5_0 = {
  149616. 2, 81,
  149617. _vq_lengthlist__44u6__p5_0,
  149618. 1, -531628032, 1611661312, 4, 0,
  149619. _vq_quantlist__44u6__p5_0,
  149620. NULL,
  149621. &_vq_auxt__44u6__p5_0,
  149622. NULL,
  149623. 0
  149624. };
  149625. static long _vq_quantlist__44u6__p6_0[] = {
  149626. 4,
  149627. 3,
  149628. 5,
  149629. 2,
  149630. 6,
  149631. 1,
  149632. 7,
  149633. 0,
  149634. 8,
  149635. };
  149636. static long _vq_lengthlist__44u6__p6_0[] = {
  149637. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149638. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149639. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149640. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149641. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149642. 12,
  149643. };
  149644. static float _vq_quantthresh__44u6__p6_0[] = {
  149645. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149646. };
  149647. static long _vq_quantmap__44u6__p6_0[] = {
  149648. 7, 5, 3, 1, 0, 2, 4, 6,
  149649. 8,
  149650. };
  149651. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149652. _vq_quantthresh__44u6__p6_0,
  149653. _vq_quantmap__44u6__p6_0,
  149654. 9,
  149655. 9
  149656. };
  149657. static static_codebook _44u6__p6_0 = {
  149658. 2, 81,
  149659. _vq_lengthlist__44u6__p6_0,
  149660. 1, -531628032, 1611661312, 4, 0,
  149661. _vq_quantlist__44u6__p6_0,
  149662. NULL,
  149663. &_vq_auxt__44u6__p6_0,
  149664. NULL,
  149665. 0
  149666. };
  149667. static long _vq_quantlist__44u6__p7_0[] = {
  149668. 1,
  149669. 0,
  149670. 2,
  149671. };
  149672. static long _vq_lengthlist__44u6__p7_0[] = {
  149673. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149674. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149675. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149676. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149677. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149678. 10,
  149679. };
  149680. static float _vq_quantthresh__44u6__p7_0[] = {
  149681. -5.5, 5.5,
  149682. };
  149683. static long _vq_quantmap__44u6__p7_0[] = {
  149684. 1, 0, 2,
  149685. };
  149686. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149687. _vq_quantthresh__44u6__p7_0,
  149688. _vq_quantmap__44u6__p7_0,
  149689. 3,
  149690. 3
  149691. };
  149692. static static_codebook _44u6__p7_0 = {
  149693. 4, 81,
  149694. _vq_lengthlist__44u6__p7_0,
  149695. 1, -529137664, 1618345984, 2, 0,
  149696. _vq_quantlist__44u6__p7_0,
  149697. NULL,
  149698. &_vq_auxt__44u6__p7_0,
  149699. NULL,
  149700. 0
  149701. };
  149702. static long _vq_quantlist__44u6__p7_1[] = {
  149703. 5,
  149704. 4,
  149705. 6,
  149706. 3,
  149707. 7,
  149708. 2,
  149709. 8,
  149710. 1,
  149711. 9,
  149712. 0,
  149713. 10,
  149714. };
  149715. static long _vq_lengthlist__44u6__p7_1[] = {
  149716. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149717. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149718. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149719. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149720. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149721. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149722. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149723. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149724. };
  149725. static float _vq_quantthresh__44u6__p7_1[] = {
  149726. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149727. 3.5, 4.5,
  149728. };
  149729. static long _vq_quantmap__44u6__p7_1[] = {
  149730. 9, 7, 5, 3, 1, 0, 2, 4,
  149731. 6, 8, 10,
  149732. };
  149733. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149734. _vq_quantthresh__44u6__p7_1,
  149735. _vq_quantmap__44u6__p7_1,
  149736. 11,
  149737. 11
  149738. };
  149739. static static_codebook _44u6__p7_1 = {
  149740. 2, 121,
  149741. _vq_lengthlist__44u6__p7_1,
  149742. 1, -531365888, 1611661312, 4, 0,
  149743. _vq_quantlist__44u6__p7_1,
  149744. NULL,
  149745. &_vq_auxt__44u6__p7_1,
  149746. NULL,
  149747. 0
  149748. };
  149749. static long _vq_quantlist__44u6__p8_0[] = {
  149750. 5,
  149751. 4,
  149752. 6,
  149753. 3,
  149754. 7,
  149755. 2,
  149756. 8,
  149757. 1,
  149758. 9,
  149759. 0,
  149760. 10,
  149761. };
  149762. static long _vq_lengthlist__44u6__p8_0[] = {
  149763. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149764. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149765. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149766. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149767. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149768. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149769. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149770. 12,13,13,14,14,14,15,15,15,
  149771. };
  149772. static float _vq_quantthresh__44u6__p8_0[] = {
  149773. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149774. 38.5, 49.5,
  149775. };
  149776. static long _vq_quantmap__44u6__p8_0[] = {
  149777. 9, 7, 5, 3, 1, 0, 2, 4,
  149778. 6, 8, 10,
  149779. };
  149780. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149781. _vq_quantthresh__44u6__p8_0,
  149782. _vq_quantmap__44u6__p8_0,
  149783. 11,
  149784. 11
  149785. };
  149786. static static_codebook _44u6__p8_0 = {
  149787. 2, 121,
  149788. _vq_lengthlist__44u6__p8_0,
  149789. 1, -524582912, 1618345984, 4, 0,
  149790. _vq_quantlist__44u6__p8_0,
  149791. NULL,
  149792. &_vq_auxt__44u6__p8_0,
  149793. NULL,
  149794. 0
  149795. };
  149796. static long _vq_quantlist__44u6__p8_1[] = {
  149797. 5,
  149798. 4,
  149799. 6,
  149800. 3,
  149801. 7,
  149802. 2,
  149803. 8,
  149804. 1,
  149805. 9,
  149806. 0,
  149807. 10,
  149808. };
  149809. static long _vq_lengthlist__44u6__p8_1[] = {
  149810. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149811. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149812. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149813. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149814. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149815. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149816. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149817. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149818. };
  149819. static float _vq_quantthresh__44u6__p8_1[] = {
  149820. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149821. 3.5, 4.5,
  149822. };
  149823. static long _vq_quantmap__44u6__p8_1[] = {
  149824. 9, 7, 5, 3, 1, 0, 2, 4,
  149825. 6, 8, 10,
  149826. };
  149827. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149828. _vq_quantthresh__44u6__p8_1,
  149829. _vq_quantmap__44u6__p8_1,
  149830. 11,
  149831. 11
  149832. };
  149833. static static_codebook _44u6__p8_1 = {
  149834. 2, 121,
  149835. _vq_lengthlist__44u6__p8_1,
  149836. 1, -531365888, 1611661312, 4, 0,
  149837. _vq_quantlist__44u6__p8_1,
  149838. NULL,
  149839. &_vq_auxt__44u6__p8_1,
  149840. NULL,
  149841. 0
  149842. };
  149843. static long _vq_quantlist__44u6__p9_0[] = {
  149844. 7,
  149845. 6,
  149846. 8,
  149847. 5,
  149848. 9,
  149849. 4,
  149850. 10,
  149851. 3,
  149852. 11,
  149853. 2,
  149854. 12,
  149855. 1,
  149856. 13,
  149857. 0,
  149858. 14,
  149859. };
  149860. static long _vq_lengthlist__44u6__p9_0[] = {
  149861. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149862. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149863. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149864. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149865. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149866. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149867. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149868. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149869. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149870. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149871. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149872. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149873. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149874. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149875. 14,
  149876. };
  149877. static float _vq_quantthresh__44u6__p9_0[] = {
  149878. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149879. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149880. };
  149881. static long _vq_quantmap__44u6__p9_0[] = {
  149882. 13, 11, 9, 7, 5, 3, 1, 0,
  149883. 2, 4, 6, 8, 10, 12, 14,
  149884. };
  149885. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149886. _vq_quantthresh__44u6__p9_0,
  149887. _vq_quantmap__44u6__p9_0,
  149888. 15,
  149889. 15
  149890. };
  149891. static static_codebook _44u6__p9_0 = {
  149892. 2, 225,
  149893. _vq_lengthlist__44u6__p9_0,
  149894. 1, -514071552, 1627381760, 4, 0,
  149895. _vq_quantlist__44u6__p9_0,
  149896. NULL,
  149897. &_vq_auxt__44u6__p9_0,
  149898. NULL,
  149899. 0
  149900. };
  149901. static long _vq_quantlist__44u6__p9_1[] = {
  149902. 7,
  149903. 6,
  149904. 8,
  149905. 5,
  149906. 9,
  149907. 4,
  149908. 10,
  149909. 3,
  149910. 11,
  149911. 2,
  149912. 12,
  149913. 1,
  149914. 13,
  149915. 0,
  149916. 14,
  149917. };
  149918. static long _vq_lengthlist__44u6__p9_1[] = {
  149919. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149920. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149921. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149922. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149923. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149924. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149925. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149926. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149927. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149928. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149929. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149930. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149931. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149932. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149933. 13,
  149934. };
  149935. static float _vq_quantthresh__44u6__p9_1[] = {
  149936. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149937. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149938. };
  149939. static long _vq_quantmap__44u6__p9_1[] = {
  149940. 13, 11, 9, 7, 5, 3, 1, 0,
  149941. 2, 4, 6, 8, 10, 12, 14,
  149942. };
  149943. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149944. _vq_quantthresh__44u6__p9_1,
  149945. _vq_quantmap__44u6__p9_1,
  149946. 15,
  149947. 15
  149948. };
  149949. static static_codebook _44u6__p9_1 = {
  149950. 2, 225,
  149951. _vq_lengthlist__44u6__p9_1,
  149952. 1, -522338304, 1620115456, 4, 0,
  149953. _vq_quantlist__44u6__p9_1,
  149954. NULL,
  149955. &_vq_auxt__44u6__p9_1,
  149956. NULL,
  149957. 0
  149958. };
  149959. static long _vq_quantlist__44u6__p9_2[] = {
  149960. 8,
  149961. 7,
  149962. 9,
  149963. 6,
  149964. 10,
  149965. 5,
  149966. 11,
  149967. 4,
  149968. 12,
  149969. 3,
  149970. 13,
  149971. 2,
  149972. 14,
  149973. 1,
  149974. 15,
  149975. 0,
  149976. 16,
  149977. };
  149978. static long _vq_lengthlist__44u6__p9_2[] = {
  149979. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149980. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149981. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149982. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149983. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149984. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149985. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149986. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149987. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149988. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149989. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149990. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149991. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149992. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149993. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149994. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149995. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149996. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149997. 10,
  149998. };
  149999. static float _vq_quantthresh__44u6__p9_2[] = {
  150000. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150001. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150002. };
  150003. static long _vq_quantmap__44u6__p9_2[] = {
  150004. 15, 13, 11, 9, 7, 5, 3, 1,
  150005. 0, 2, 4, 6, 8, 10, 12, 14,
  150006. 16,
  150007. };
  150008. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150009. _vq_quantthresh__44u6__p9_2,
  150010. _vq_quantmap__44u6__p9_2,
  150011. 17,
  150012. 17
  150013. };
  150014. static static_codebook _44u6__p9_2 = {
  150015. 2, 289,
  150016. _vq_lengthlist__44u6__p9_2,
  150017. 1, -529530880, 1611661312, 5, 0,
  150018. _vq_quantlist__44u6__p9_2,
  150019. NULL,
  150020. &_vq_auxt__44u6__p9_2,
  150021. NULL,
  150022. 0
  150023. };
  150024. static long _huff_lengthlist__44u6__short[] = {
  150025. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150026. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150027. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150028. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150029. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150030. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150031. 7, 6, 9,16,
  150032. };
  150033. static static_codebook _huff_book__44u6__short = {
  150034. 2, 100,
  150035. _huff_lengthlist__44u6__short,
  150036. 0, 0, 0, 0, 0,
  150037. NULL,
  150038. NULL,
  150039. NULL,
  150040. NULL,
  150041. 0
  150042. };
  150043. static long _huff_lengthlist__44u7__long[] = {
  150044. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150045. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150046. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150047. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150048. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150049. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150050. 12, 8, 6, 7,
  150051. };
  150052. static static_codebook _huff_book__44u7__long = {
  150053. 2, 100,
  150054. _huff_lengthlist__44u7__long,
  150055. 0, 0, 0, 0, 0,
  150056. NULL,
  150057. NULL,
  150058. NULL,
  150059. NULL,
  150060. 0
  150061. };
  150062. static long _vq_quantlist__44u7__p1_0[] = {
  150063. 1,
  150064. 0,
  150065. 2,
  150066. };
  150067. static long _vq_lengthlist__44u7__p1_0[] = {
  150068. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150069. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150070. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150071. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150072. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150073. 12,
  150074. };
  150075. static float _vq_quantthresh__44u7__p1_0[] = {
  150076. -0.5, 0.5,
  150077. };
  150078. static long _vq_quantmap__44u7__p1_0[] = {
  150079. 1, 0, 2,
  150080. };
  150081. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150082. _vq_quantthresh__44u7__p1_0,
  150083. _vq_quantmap__44u7__p1_0,
  150084. 3,
  150085. 3
  150086. };
  150087. static static_codebook _44u7__p1_0 = {
  150088. 4, 81,
  150089. _vq_lengthlist__44u7__p1_0,
  150090. 1, -535822336, 1611661312, 2, 0,
  150091. _vq_quantlist__44u7__p1_0,
  150092. NULL,
  150093. &_vq_auxt__44u7__p1_0,
  150094. NULL,
  150095. 0
  150096. };
  150097. static long _vq_quantlist__44u7__p2_0[] = {
  150098. 1,
  150099. 0,
  150100. 2,
  150101. };
  150102. static long _vq_lengthlist__44u7__p2_0[] = {
  150103. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150104. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150105. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150106. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150107. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150108. 9,
  150109. };
  150110. static float _vq_quantthresh__44u7__p2_0[] = {
  150111. -0.5, 0.5,
  150112. };
  150113. static long _vq_quantmap__44u7__p2_0[] = {
  150114. 1, 0, 2,
  150115. };
  150116. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150117. _vq_quantthresh__44u7__p2_0,
  150118. _vq_quantmap__44u7__p2_0,
  150119. 3,
  150120. 3
  150121. };
  150122. static static_codebook _44u7__p2_0 = {
  150123. 4, 81,
  150124. _vq_lengthlist__44u7__p2_0,
  150125. 1, -535822336, 1611661312, 2, 0,
  150126. _vq_quantlist__44u7__p2_0,
  150127. NULL,
  150128. &_vq_auxt__44u7__p2_0,
  150129. NULL,
  150130. 0
  150131. };
  150132. static long _vq_quantlist__44u7__p3_0[] = {
  150133. 2,
  150134. 1,
  150135. 3,
  150136. 0,
  150137. 4,
  150138. };
  150139. static long _vq_lengthlist__44u7__p3_0[] = {
  150140. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150141. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150142. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150143. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150144. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150145. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150146. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150147. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150148. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150149. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150150. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150151. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150152. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150153. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150154. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150155. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150156. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150157. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150158. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150159. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150160. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150161. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150162. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150163. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150164. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150165. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150166. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150167. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150168. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150169. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150170. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150171. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150172. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150173. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150174. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150175. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150176. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150177. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150178. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150179. 0,
  150180. };
  150181. static float _vq_quantthresh__44u7__p3_0[] = {
  150182. -1.5, -0.5, 0.5, 1.5,
  150183. };
  150184. static long _vq_quantmap__44u7__p3_0[] = {
  150185. 3, 1, 0, 2, 4,
  150186. };
  150187. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150188. _vq_quantthresh__44u7__p3_0,
  150189. _vq_quantmap__44u7__p3_0,
  150190. 5,
  150191. 5
  150192. };
  150193. static static_codebook _44u7__p3_0 = {
  150194. 4, 625,
  150195. _vq_lengthlist__44u7__p3_0,
  150196. 1, -533725184, 1611661312, 3, 0,
  150197. _vq_quantlist__44u7__p3_0,
  150198. NULL,
  150199. &_vq_auxt__44u7__p3_0,
  150200. NULL,
  150201. 0
  150202. };
  150203. static long _vq_quantlist__44u7__p4_0[] = {
  150204. 2,
  150205. 1,
  150206. 3,
  150207. 0,
  150208. 4,
  150209. };
  150210. static long _vq_lengthlist__44u7__p4_0[] = {
  150211. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150212. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150213. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150214. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150215. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150216. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150217. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150218. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150219. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150220. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150221. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150222. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150223. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150224. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150225. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150226. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150227. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150228. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150229. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150230. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150231. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150232. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150233. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150234. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150235. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150236. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150237. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150238. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150239. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150240. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150241. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150242. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150243. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150244. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150245. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150246. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150247. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150248. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150249. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150250. 14,
  150251. };
  150252. static float _vq_quantthresh__44u7__p4_0[] = {
  150253. -1.5, -0.5, 0.5, 1.5,
  150254. };
  150255. static long _vq_quantmap__44u7__p4_0[] = {
  150256. 3, 1, 0, 2, 4,
  150257. };
  150258. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150259. _vq_quantthresh__44u7__p4_0,
  150260. _vq_quantmap__44u7__p4_0,
  150261. 5,
  150262. 5
  150263. };
  150264. static static_codebook _44u7__p4_0 = {
  150265. 4, 625,
  150266. _vq_lengthlist__44u7__p4_0,
  150267. 1, -533725184, 1611661312, 3, 0,
  150268. _vq_quantlist__44u7__p4_0,
  150269. NULL,
  150270. &_vq_auxt__44u7__p4_0,
  150271. NULL,
  150272. 0
  150273. };
  150274. static long _vq_quantlist__44u7__p5_0[] = {
  150275. 4,
  150276. 3,
  150277. 5,
  150278. 2,
  150279. 6,
  150280. 1,
  150281. 7,
  150282. 0,
  150283. 8,
  150284. };
  150285. static long _vq_lengthlist__44u7__p5_0[] = {
  150286. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150287. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150288. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150289. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150290. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150291. 14,
  150292. };
  150293. static float _vq_quantthresh__44u7__p5_0[] = {
  150294. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150295. };
  150296. static long _vq_quantmap__44u7__p5_0[] = {
  150297. 7, 5, 3, 1, 0, 2, 4, 6,
  150298. 8,
  150299. };
  150300. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150301. _vq_quantthresh__44u7__p5_0,
  150302. _vq_quantmap__44u7__p5_0,
  150303. 9,
  150304. 9
  150305. };
  150306. static static_codebook _44u7__p5_0 = {
  150307. 2, 81,
  150308. _vq_lengthlist__44u7__p5_0,
  150309. 1, -531628032, 1611661312, 4, 0,
  150310. _vq_quantlist__44u7__p5_0,
  150311. NULL,
  150312. &_vq_auxt__44u7__p5_0,
  150313. NULL,
  150314. 0
  150315. };
  150316. static long _vq_quantlist__44u7__p6_0[] = {
  150317. 4,
  150318. 3,
  150319. 5,
  150320. 2,
  150321. 6,
  150322. 1,
  150323. 7,
  150324. 0,
  150325. 8,
  150326. };
  150327. static long _vq_lengthlist__44u7__p6_0[] = {
  150328. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150329. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150330. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150331. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150332. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150333. 12,
  150334. };
  150335. static float _vq_quantthresh__44u7__p6_0[] = {
  150336. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150337. };
  150338. static long _vq_quantmap__44u7__p6_0[] = {
  150339. 7, 5, 3, 1, 0, 2, 4, 6,
  150340. 8,
  150341. };
  150342. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150343. _vq_quantthresh__44u7__p6_0,
  150344. _vq_quantmap__44u7__p6_0,
  150345. 9,
  150346. 9
  150347. };
  150348. static static_codebook _44u7__p6_0 = {
  150349. 2, 81,
  150350. _vq_lengthlist__44u7__p6_0,
  150351. 1, -531628032, 1611661312, 4, 0,
  150352. _vq_quantlist__44u7__p6_0,
  150353. NULL,
  150354. &_vq_auxt__44u7__p6_0,
  150355. NULL,
  150356. 0
  150357. };
  150358. static long _vq_quantlist__44u7__p7_0[] = {
  150359. 1,
  150360. 0,
  150361. 2,
  150362. };
  150363. static long _vq_lengthlist__44u7__p7_0[] = {
  150364. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150365. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150366. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150367. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150368. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150369. 10,
  150370. };
  150371. static float _vq_quantthresh__44u7__p7_0[] = {
  150372. -5.5, 5.5,
  150373. };
  150374. static long _vq_quantmap__44u7__p7_0[] = {
  150375. 1, 0, 2,
  150376. };
  150377. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150378. _vq_quantthresh__44u7__p7_0,
  150379. _vq_quantmap__44u7__p7_0,
  150380. 3,
  150381. 3
  150382. };
  150383. static static_codebook _44u7__p7_0 = {
  150384. 4, 81,
  150385. _vq_lengthlist__44u7__p7_0,
  150386. 1, -529137664, 1618345984, 2, 0,
  150387. _vq_quantlist__44u7__p7_0,
  150388. NULL,
  150389. &_vq_auxt__44u7__p7_0,
  150390. NULL,
  150391. 0
  150392. };
  150393. static long _vq_quantlist__44u7__p7_1[] = {
  150394. 5,
  150395. 4,
  150396. 6,
  150397. 3,
  150398. 7,
  150399. 2,
  150400. 8,
  150401. 1,
  150402. 9,
  150403. 0,
  150404. 10,
  150405. };
  150406. static long _vq_lengthlist__44u7__p7_1[] = {
  150407. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150408. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150409. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150410. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150411. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150412. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150413. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150414. 8, 9, 9, 9, 9, 9,10,10,10,
  150415. };
  150416. static float _vq_quantthresh__44u7__p7_1[] = {
  150417. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150418. 3.5, 4.5,
  150419. };
  150420. static long _vq_quantmap__44u7__p7_1[] = {
  150421. 9, 7, 5, 3, 1, 0, 2, 4,
  150422. 6, 8, 10,
  150423. };
  150424. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150425. _vq_quantthresh__44u7__p7_1,
  150426. _vq_quantmap__44u7__p7_1,
  150427. 11,
  150428. 11
  150429. };
  150430. static static_codebook _44u7__p7_1 = {
  150431. 2, 121,
  150432. _vq_lengthlist__44u7__p7_1,
  150433. 1, -531365888, 1611661312, 4, 0,
  150434. _vq_quantlist__44u7__p7_1,
  150435. NULL,
  150436. &_vq_auxt__44u7__p7_1,
  150437. NULL,
  150438. 0
  150439. };
  150440. static long _vq_quantlist__44u7__p8_0[] = {
  150441. 5,
  150442. 4,
  150443. 6,
  150444. 3,
  150445. 7,
  150446. 2,
  150447. 8,
  150448. 1,
  150449. 9,
  150450. 0,
  150451. 10,
  150452. };
  150453. static long _vq_lengthlist__44u7__p8_0[] = {
  150454. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150455. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150456. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150457. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150458. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150459. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150460. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150461. 12,13,13,14,14,15,15,15,16,
  150462. };
  150463. static float _vq_quantthresh__44u7__p8_0[] = {
  150464. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150465. 38.5, 49.5,
  150466. };
  150467. static long _vq_quantmap__44u7__p8_0[] = {
  150468. 9, 7, 5, 3, 1, 0, 2, 4,
  150469. 6, 8, 10,
  150470. };
  150471. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150472. _vq_quantthresh__44u7__p8_0,
  150473. _vq_quantmap__44u7__p8_0,
  150474. 11,
  150475. 11
  150476. };
  150477. static static_codebook _44u7__p8_0 = {
  150478. 2, 121,
  150479. _vq_lengthlist__44u7__p8_0,
  150480. 1, -524582912, 1618345984, 4, 0,
  150481. _vq_quantlist__44u7__p8_0,
  150482. NULL,
  150483. &_vq_auxt__44u7__p8_0,
  150484. NULL,
  150485. 0
  150486. };
  150487. static long _vq_quantlist__44u7__p8_1[] = {
  150488. 5,
  150489. 4,
  150490. 6,
  150491. 3,
  150492. 7,
  150493. 2,
  150494. 8,
  150495. 1,
  150496. 9,
  150497. 0,
  150498. 10,
  150499. };
  150500. static long _vq_lengthlist__44u7__p8_1[] = {
  150501. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150502. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150503. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150504. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150505. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150506. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150507. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150508. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150509. };
  150510. static float _vq_quantthresh__44u7__p8_1[] = {
  150511. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150512. 3.5, 4.5,
  150513. };
  150514. static long _vq_quantmap__44u7__p8_1[] = {
  150515. 9, 7, 5, 3, 1, 0, 2, 4,
  150516. 6, 8, 10,
  150517. };
  150518. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150519. _vq_quantthresh__44u7__p8_1,
  150520. _vq_quantmap__44u7__p8_1,
  150521. 11,
  150522. 11
  150523. };
  150524. static static_codebook _44u7__p8_1 = {
  150525. 2, 121,
  150526. _vq_lengthlist__44u7__p8_1,
  150527. 1, -531365888, 1611661312, 4, 0,
  150528. _vq_quantlist__44u7__p8_1,
  150529. NULL,
  150530. &_vq_auxt__44u7__p8_1,
  150531. NULL,
  150532. 0
  150533. };
  150534. static long _vq_quantlist__44u7__p9_0[] = {
  150535. 5,
  150536. 4,
  150537. 6,
  150538. 3,
  150539. 7,
  150540. 2,
  150541. 8,
  150542. 1,
  150543. 9,
  150544. 0,
  150545. 10,
  150546. };
  150547. static long _vq_lengthlist__44u7__p9_0[] = {
  150548. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150549. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150550. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150551. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150552. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150553. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150554. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150555. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150556. };
  150557. static float _vq_quantthresh__44u7__p9_0[] = {
  150558. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150559. 2229.5, 2866.5,
  150560. };
  150561. static long _vq_quantmap__44u7__p9_0[] = {
  150562. 9, 7, 5, 3, 1, 0, 2, 4,
  150563. 6, 8, 10,
  150564. };
  150565. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150566. _vq_quantthresh__44u7__p9_0,
  150567. _vq_quantmap__44u7__p9_0,
  150568. 11,
  150569. 11
  150570. };
  150571. static static_codebook _44u7__p9_0 = {
  150572. 2, 121,
  150573. _vq_lengthlist__44u7__p9_0,
  150574. 1, -512171520, 1630791680, 4, 0,
  150575. _vq_quantlist__44u7__p9_0,
  150576. NULL,
  150577. &_vq_auxt__44u7__p9_0,
  150578. NULL,
  150579. 0
  150580. };
  150581. static long _vq_quantlist__44u7__p9_1[] = {
  150582. 6,
  150583. 5,
  150584. 7,
  150585. 4,
  150586. 8,
  150587. 3,
  150588. 9,
  150589. 2,
  150590. 10,
  150591. 1,
  150592. 11,
  150593. 0,
  150594. 12,
  150595. };
  150596. static long _vq_lengthlist__44u7__p9_1[] = {
  150597. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150598. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150599. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150600. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150601. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150602. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150603. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150604. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150605. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150606. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150607. 15,15,15,15,17,17,16,17,16,
  150608. };
  150609. static float _vq_quantthresh__44u7__p9_1[] = {
  150610. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150611. 122.5, 171.5, 220.5, 269.5,
  150612. };
  150613. static long _vq_quantmap__44u7__p9_1[] = {
  150614. 11, 9, 7, 5, 3, 1, 0, 2,
  150615. 4, 6, 8, 10, 12,
  150616. };
  150617. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150618. _vq_quantthresh__44u7__p9_1,
  150619. _vq_quantmap__44u7__p9_1,
  150620. 13,
  150621. 13
  150622. };
  150623. static static_codebook _44u7__p9_1 = {
  150624. 2, 169,
  150625. _vq_lengthlist__44u7__p9_1,
  150626. 1, -518889472, 1622704128, 4, 0,
  150627. _vq_quantlist__44u7__p9_1,
  150628. NULL,
  150629. &_vq_auxt__44u7__p9_1,
  150630. NULL,
  150631. 0
  150632. };
  150633. static long _vq_quantlist__44u7__p9_2[] = {
  150634. 24,
  150635. 23,
  150636. 25,
  150637. 22,
  150638. 26,
  150639. 21,
  150640. 27,
  150641. 20,
  150642. 28,
  150643. 19,
  150644. 29,
  150645. 18,
  150646. 30,
  150647. 17,
  150648. 31,
  150649. 16,
  150650. 32,
  150651. 15,
  150652. 33,
  150653. 14,
  150654. 34,
  150655. 13,
  150656. 35,
  150657. 12,
  150658. 36,
  150659. 11,
  150660. 37,
  150661. 10,
  150662. 38,
  150663. 9,
  150664. 39,
  150665. 8,
  150666. 40,
  150667. 7,
  150668. 41,
  150669. 6,
  150670. 42,
  150671. 5,
  150672. 43,
  150673. 4,
  150674. 44,
  150675. 3,
  150676. 45,
  150677. 2,
  150678. 46,
  150679. 1,
  150680. 47,
  150681. 0,
  150682. 48,
  150683. };
  150684. static long _vq_lengthlist__44u7__p9_2[] = {
  150685. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150686. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150687. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150688. 8,
  150689. };
  150690. static float _vq_quantthresh__44u7__p9_2[] = {
  150691. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150692. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150693. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150694. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150695. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150696. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150697. };
  150698. static long _vq_quantmap__44u7__p9_2[] = {
  150699. 47, 45, 43, 41, 39, 37, 35, 33,
  150700. 31, 29, 27, 25, 23, 21, 19, 17,
  150701. 15, 13, 11, 9, 7, 5, 3, 1,
  150702. 0, 2, 4, 6, 8, 10, 12, 14,
  150703. 16, 18, 20, 22, 24, 26, 28, 30,
  150704. 32, 34, 36, 38, 40, 42, 44, 46,
  150705. 48,
  150706. };
  150707. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150708. _vq_quantthresh__44u7__p9_2,
  150709. _vq_quantmap__44u7__p9_2,
  150710. 49,
  150711. 49
  150712. };
  150713. static static_codebook _44u7__p9_2 = {
  150714. 1, 49,
  150715. _vq_lengthlist__44u7__p9_2,
  150716. 1, -526909440, 1611661312, 6, 0,
  150717. _vq_quantlist__44u7__p9_2,
  150718. NULL,
  150719. &_vq_auxt__44u7__p9_2,
  150720. NULL,
  150721. 0
  150722. };
  150723. static long _huff_lengthlist__44u7__short[] = {
  150724. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150725. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150726. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150727. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150728. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150729. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150730. 6, 8, 5, 9,
  150731. };
  150732. static static_codebook _huff_book__44u7__short = {
  150733. 2, 100,
  150734. _huff_lengthlist__44u7__short,
  150735. 0, 0, 0, 0, 0,
  150736. NULL,
  150737. NULL,
  150738. NULL,
  150739. NULL,
  150740. 0
  150741. };
  150742. static long _huff_lengthlist__44u8__long[] = {
  150743. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150744. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150745. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150746. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150747. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150748. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150749. 10, 8, 8, 9,
  150750. };
  150751. static static_codebook _huff_book__44u8__long = {
  150752. 2, 100,
  150753. _huff_lengthlist__44u8__long,
  150754. 0, 0, 0, 0, 0,
  150755. NULL,
  150756. NULL,
  150757. NULL,
  150758. NULL,
  150759. 0
  150760. };
  150761. static long _huff_lengthlist__44u8__short[] = {
  150762. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150763. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150764. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150765. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150766. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150767. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150768. 10,10,15,17,
  150769. };
  150770. static static_codebook _huff_book__44u8__short = {
  150771. 2, 100,
  150772. _huff_lengthlist__44u8__short,
  150773. 0, 0, 0, 0, 0,
  150774. NULL,
  150775. NULL,
  150776. NULL,
  150777. NULL,
  150778. 0
  150779. };
  150780. static long _vq_quantlist__44u8_p1_0[] = {
  150781. 1,
  150782. 0,
  150783. 2,
  150784. };
  150785. static long _vq_lengthlist__44u8_p1_0[] = {
  150786. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150787. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150788. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150789. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150790. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150791. 10,
  150792. };
  150793. static float _vq_quantthresh__44u8_p1_0[] = {
  150794. -0.5, 0.5,
  150795. };
  150796. static long _vq_quantmap__44u8_p1_0[] = {
  150797. 1, 0, 2,
  150798. };
  150799. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150800. _vq_quantthresh__44u8_p1_0,
  150801. _vq_quantmap__44u8_p1_0,
  150802. 3,
  150803. 3
  150804. };
  150805. static static_codebook _44u8_p1_0 = {
  150806. 4, 81,
  150807. _vq_lengthlist__44u8_p1_0,
  150808. 1, -535822336, 1611661312, 2, 0,
  150809. _vq_quantlist__44u8_p1_0,
  150810. NULL,
  150811. &_vq_auxt__44u8_p1_0,
  150812. NULL,
  150813. 0
  150814. };
  150815. static long _vq_quantlist__44u8_p2_0[] = {
  150816. 2,
  150817. 1,
  150818. 3,
  150819. 0,
  150820. 4,
  150821. };
  150822. static long _vq_lengthlist__44u8_p2_0[] = {
  150823. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150824. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150825. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150826. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150827. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150828. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150829. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150830. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150831. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150832. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150833. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150834. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150835. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150836. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150837. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150838. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150839. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150840. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150841. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150842. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150843. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150844. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150845. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150846. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150847. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150848. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150849. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150850. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150851. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150852. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150853. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150854. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150855. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150856. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150857. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150858. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150859. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150860. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150861. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150862. 14,
  150863. };
  150864. static float _vq_quantthresh__44u8_p2_0[] = {
  150865. -1.5, -0.5, 0.5, 1.5,
  150866. };
  150867. static long _vq_quantmap__44u8_p2_0[] = {
  150868. 3, 1, 0, 2, 4,
  150869. };
  150870. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150871. _vq_quantthresh__44u8_p2_0,
  150872. _vq_quantmap__44u8_p2_0,
  150873. 5,
  150874. 5
  150875. };
  150876. static static_codebook _44u8_p2_0 = {
  150877. 4, 625,
  150878. _vq_lengthlist__44u8_p2_0,
  150879. 1, -533725184, 1611661312, 3, 0,
  150880. _vq_quantlist__44u8_p2_0,
  150881. NULL,
  150882. &_vq_auxt__44u8_p2_0,
  150883. NULL,
  150884. 0
  150885. };
  150886. static long _vq_quantlist__44u8_p3_0[] = {
  150887. 4,
  150888. 3,
  150889. 5,
  150890. 2,
  150891. 6,
  150892. 1,
  150893. 7,
  150894. 0,
  150895. 8,
  150896. };
  150897. static long _vq_lengthlist__44u8_p3_0[] = {
  150898. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150899. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150900. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150901. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150902. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150903. 12,
  150904. };
  150905. static float _vq_quantthresh__44u8_p3_0[] = {
  150906. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150907. };
  150908. static long _vq_quantmap__44u8_p3_0[] = {
  150909. 7, 5, 3, 1, 0, 2, 4, 6,
  150910. 8,
  150911. };
  150912. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150913. _vq_quantthresh__44u8_p3_0,
  150914. _vq_quantmap__44u8_p3_0,
  150915. 9,
  150916. 9
  150917. };
  150918. static static_codebook _44u8_p3_0 = {
  150919. 2, 81,
  150920. _vq_lengthlist__44u8_p3_0,
  150921. 1, -531628032, 1611661312, 4, 0,
  150922. _vq_quantlist__44u8_p3_0,
  150923. NULL,
  150924. &_vq_auxt__44u8_p3_0,
  150925. NULL,
  150926. 0
  150927. };
  150928. static long _vq_quantlist__44u8_p4_0[] = {
  150929. 8,
  150930. 7,
  150931. 9,
  150932. 6,
  150933. 10,
  150934. 5,
  150935. 11,
  150936. 4,
  150937. 12,
  150938. 3,
  150939. 13,
  150940. 2,
  150941. 14,
  150942. 1,
  150943. 15,
  150944. 0,
  150945. 16,
  150946. };
  150947. static long _vq_lengthlist__44u8_p4_0[] = {
  150948. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150949. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150950. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150951. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150952. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150953. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150954. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150955. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150956. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150957. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150958. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150959. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150960. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150961. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150962. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150963. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150964. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150965. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150966. 14,
  150967. };
  150968. static float _vq_quantthresh__44u8_p4_0[] = {
  150969. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150970. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150971. };
  150972. static long _vq_quantmap__44u8_p4_0[] = {
  150973. 15, 13, 11, 9, 7, 5, 3, 1,
  150974. 0, 2, 4, 6, 8, 10, 12, 14,
  150975. 16,
  150976. };
  150977. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150978. _vq_quantthresh__44u8_p4_0,
  150979. _vq_quantmap__44u8_p4_0,
  150980. 17,
  150981. 17
  150982. };
  150983. static static_codebook _44u8_p4_0 = {
  150984. 2, 289,
  150985. _vq_lengthlist__44u8_p4_0,
  150986. 1, -529530880, 1611661312, 5, 0,
  150987. _vq_quantlist__44u8_p4_0,
  150988. NULL,
  150989. &_vq_auxt__44u8_p4_0,
  150990. NULL,
  150991. 0
  150992. };
  150993. static long _vq_quantlist__44u8_p5_0[] = {
  150994. 1,
  150995. 0,
  150996. 2,
  150997. };
  150998. static long _vq_lengthlist__44u8_p5_0[] = {
  150999. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151000. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151001. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151002. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151003. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151004. 10,
  151005. };
  151006. static float _vq_quantthresh__44u8_p5_0[] = {
  151007. -5.5, 5.5,
  151008. };
  151009. static long _vq_quantmap__44u8_p5_0[] = {
  151010. 1, 0, 2,
  151011. };
  151012. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151013. _vq_quantthresh__44u8_p5_0,
  151014. _vq_quantmap__44u8_p5_0,
  151015. 3,
  151016. 3
  151017. };
  151018. static static_codebook _44u8_p5_0 = {
  151019. 4, 81,
  151020. _vq_lengthlist__44u8_p5_0,
  151021. 1, -529137664, 1618345984, 2, 0,
  151022. _vq_quantlist__44u8_p5_0,
  151023. NULL,
  151024. &_vq_auxt__44u8_p5_0,
  151025. NULL,
  151026. 0
  151027. };
  151028. static long _vq_quantlist__44u8_p5_1[] = {
  151029. 5,
  151030. 4,
  151031. 6,
  151032. 3,
  151033. 7,
  151034. 2,
  151035. 8,
  151036. 1,
  151037. 9,
  151038. 0,
  151039. 10,
  151040. };
  151041. static long _vq_lengthlist__44u8_p5_1[] = {
  151042. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151043. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151044. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151045. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151046. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151047. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151048. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151049. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151050. };
  151051. static float _vq_quantthresh__44u8_p5_1[] = {
  151052. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151053. 3.5, 4.5,
  151054. };
  151055. static long _vq_quantmap__44u8_p5_1[] = {
  151056. 9, 7, 5, 3, 1, 0, 2, 4,
  151057. 6, 8, 10,
  151058. };
  151059. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151060. _vq_quantthresh__44u8_p5_1,
  151061. _vq_quantmap__44u8_p5_1,
  151062. 11,
  151063. 11
  151064. };
  151065. static static_codebook _44u8_p5_1 = {
  151066. 2, 121,
  151067. _vq_lengthlist__44u8_p5_1,
  151068. 1, -531365888, 1611661312, 4, 0,
  151069. _vq_quantlist__44u8_p5_1,
  151070. NULL,
  151071. &_vq_auxt__44u8_p5_1,
  151072. NULL,
  151073. 0
  151074. };
  151075. static long _vq_quantlist__44u8_p6_0[] = {
  151076. 6,
  151077. 5,
  151078. 7,
  151079. 4,
  151080. 8,
  151081. 3,
  151082. 9,
  151083. 2,
  151084. 10,
  151085. 1,
  151086. 11,
  151087. 0,
  151088. 12,
  151089. };
  151090. static long _vq_lengthlist__44u8_p6_0[] = {
  151091. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151092. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151093. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151094. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151095. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151096. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151097. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151098. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151099. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151100. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151101. 11,11,11,11,11,12,11,12,12,
  151102. };
  151103. static float _vq_quantthresh__44u8_p6_0[] = {
  151104. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151105. 12.5, 17.5, 22.5, 27.5,
  151106. };
  151107. static long _vq_quantmap__44u8_p6_0[] = {
  151108. 11, 9, 7, 5, 3, 1, 0, 2,
  151109. 4, 6, 8, 10, 12,
  151110. };
  151111. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151112. _vq_quantthresh__44u8_p6_0,
  151113. _vq_quantmap__44u8_p6_0,
  151114. 13,
  151115. 13
  151116. };
  151117. static static_codebook _44u8_p6_0 = {
  151118. 2, 169,
  151119. _vq_lengthlist__44u8_p6_0,
  151120. 1, -526516224, 1616117760, 4, 0,
  151121. _vq_quantlist__44u8_p6_0,
  151122. NULL,
  151123. &_vq_auxt__44u8_p6_0,
  151124. NULL,
  151125. 0
  151126. };
  151127. static long _vq_quantlist__44u8_p6_1[] = {
  151128. 2,
  151129. 1,
  151130. 3,
  151131. 0,
  151132. 4,
  151133. };
  151134. static long _vq_lengthlist__44u8_p6_1[] = {
  151135. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151136. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151137. };
  151138. static float _vq_quantthresh__44u8_p6_1[] = {
  151139. -1.5, -0.5, 0.5, 1.5,
  151140. };
  151141. static long _vq_quantmap__44u8_p6_1[] = {
  151142. 3, 1, 0, 2, 4,
  151143. };
  151144. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151145. _vq_quantthresh__44u8_p6_1,
  151146. _vq_quantmap__44u8_p6_1,
  151147. 5,
  151148. 5
  151149. };
  151150. static static_codebook _44u8_p6_1 = {
  151151. 2, 25,
  151152. _vq_lengthlist__44u8_p6_1,
  151153. 1, -533725184, 1611661312, 3, 0,
  151154. _vq_quantlist__44u8_p6_1,
  151155. NULL,
  151156. &_vq_auxt__44u8_p6_1,
  151157. NULL,
  151158. 0
  151159. };
  151160. static long _vq_quantlist__44u8_p7_0[] = {
  151161. 6,
  151162. 5,
  151163. 7,
  151164. 4,
  151165. 8,
  151166. 3,
  151167. 9,
  151168. 2,
  151169. 10,
  151170. 1,
  151171. 11,
  151172. 0,
  151173. 12,
  151174. };
  151175. static long _vq_lengthlist__44u8_p7_0[] = {
  151176. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151177. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151178. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151179. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151180. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151181. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151182. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151183. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151184. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151185. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151186. 13,13,14,14,14,15,15,15,16,
  151187. };
  151188. static float _vq_quantthresh__44u8_p7_0[] = {
  151189. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151190. 27.5, 38.5, 49.5, 60.5,
  151191. };
  151192. static long _vq_quantmap__44u8_p7_0[] = {
  151193. 11, 9, 7, 5, 3, 1, 0, 2,
  151194. 4, 6, 8, 10, 12,
  151195. };
  151196. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151197. _vq_quantthresh__44u8_p7_0,
  151198. _vq_quantmap__44u8_p7_0,
  151199. 13,
  151200. 13
  151201. };
  151202. static static_codebook _44u8_p7_0 = {
  151203. 2, 169,
  151204. _vq_lengthlist__44u8_p7_0,
  151205. 1, -523206656, 1618345984, 4, 0,
  151206. _vq_quantlist__44u8_p7_0,
  151207. NULL,
  151208. &_vq_auxt__44u8_p7_0,
  151209. NULL,
  151210. 0
  151211. };
  151212. static long _vq_quantlist__44u8_p7_1[] = {
  151213. 5,
  151214. 4,
  151215. 6,
  151216. 3,
  151217. 7,
  151218. 2,
  151219. 8,
  151220. 1,
  151221. 9,
  151222. 0,
  151223. 10,
  151224. };
  151225. static long _vq_lengthlist__44u8_p7_1[] = {
  151226. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151227. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151228. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151229. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151230. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151231. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151232. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151233. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151234. };
  151235. static float _vq_quantthresh__44u8_p7_1[] = {
  151236. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151237. 3.5, 4.5,
  151238. };
  151239. static long _vq_quantmap__44u8_p7_1[] = {
  151240. 9, 7, 5, 3, 1, 0, 2, 4,
  151241. 6, 8, 10,
  151242. };
  151243. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151244. _vq_quantthresh__44u8_p7_1,
  151245. _vq_quantmap__44u8_p7_1,
  151246. 11,
  151247. 11
  151248. };
  151249. static static_codebook _44u8_p7_1 = {
  151250. 2, 121,
  151251. _vq_lengthlist__44u8_p7_1,
  151252. 1, -531365888, 1611661312, 4, 0,
  151253. _vq_quantlist__44u8_p7_1,
  151254. NULL,
  151255. &_vq_auxt__44u8_p7_1,
  151256. NULL,
  151257. 0
  151258. };
  151259. static long _vq_quantlist__44u8_p8_0[] = {
  151260. 7,
  151261. 6,
  151262. 8,
  151263. 5,
  151264. 9,
  151265. 4,
  151266. 10,
  151267. 3,
  151268. 11,
  151269. 2,
  151270. 12,
  151271. 1,
  151272. 13,
  151273. 0,
  151274. 14,
  151275. };
  151276. static long _vq_lengthlist__44u8_p8_0[] = {
  151277. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151278. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151279. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151280. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151281. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151282. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151283. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151284. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151285. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151286. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151287. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151288. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151289. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151290. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151291. 17,
  151292. };
  151293. static float _vq_quantthresh__44u8_p8_0[] = {
  151294. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151295. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151296. };
  151297. static long _vq_quantmap__44u8_p8_0[] = {
  151298. 13, 11, 9, 7, 5, 3, 1, 0,
  151299. 2, 4, 6, 8, 10, 12, 14,
  151300. };
  151301. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151302. _vq_quantthresh__44u8_p8_0,
  151303. _vq_quantmap__44u8_p8_0,
  151304. 15,
  151305. 15
  151306. };
  151307. static static_codebook _44u8_p8_0 = {
  151308. 2, 225,
  151309. _vq_lengthlist__44u8_p8_0,
  151310. 1, -520986624, 1620377600, 4, 0,
  151311. _vq_quantlist__44u8_p8_0,
  151312. NULL,
  151313. &_vq_auxt__44u8_p8_0,
  151314. NULL,
  151315. 0
  151316. };
  151317. static long _vq_quantlist__44u8_p8_1[] = {
  151318. 10,
  151319. 9,
  151320. 11,
  151321. 8,
  151322. 12,
  151323. 7,
  151324. 13,
  151325. 6,
  151326. 14,
  151327. 5,
  151328. 15,
  151329. 4,
  151330. 16,
  151331. 3,
  151332. 17,
  151333. 2,
  151334. 18,
  151335. 1,
  151336. 19,
  151337. 0,
  151338. 20,
  151339. };
  151340. static long _vq_lengthlist__44u8_p8_1[] = {
  151341. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151342. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151343. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151344. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151345. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151346. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151347. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151348. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151349. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151350. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151351. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151352. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151353. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151354. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151355. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151356. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151357. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151358. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151359. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151360. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151361. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151362. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151363. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151364. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151365. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151366. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151367. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151368. 10,10,10,10,10,10,10,10,10,
  151369. };
  151370. static float _vq_quantthresh__44u8_p8_1[] = {
  151371. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151372. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151373. 6.5, 7.5, 8.5, 9.5,
  151374. };
  151375. static long _vq_quantmap__44u8_p8_1[] = {
  151376. 19, 17, 15, 13, 11, 9, 7, 5,
  151377. 3, 1, 0, 2, 4, 6, 8, 10,
  151378. 12, 14, 16, 18, 20,
  151379. };
  151380. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151381. _vq_quantthresh__44u8_p8_1,
  151382. _vq_quantmap__44u8_p8_1,
  151383. 21,
  151384. 21
  151385. };
  151386. static static_codebook _44u8_p8_1 = {
  151387. 2, 441,
  151388. _vq_lengthlist__44u8_p8_1,
  151389. 1, -529268736, 1611661312, 5, 0,
  151390. _vq_quantlist__44u8_p8_1,
  151391. NULL,
  151392. &_vq_auxt__44u8_p8_1,
  151393. NULL,
  151394. 0
  151395. };
  151396. static long _vq_quantlist__44u8_p9_0[] = {
  151397. 4,
  151398. 3,
  151399. 5,
  151400. 2,
  151401. 6,
  151402. 1,
  151403. 7,
  151404. 0,
  151405. 8,
  151406. };
  151407. static long _vq_lengthlist__44u8_p9_0[] = {
  151408. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151409. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151410. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151411. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151412. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151413. 8,
  151414. };
  151415. static float _vq_quantthresh__44u8_p9_0[] = {
  151416. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151417. };
  151418. static long _vq_quantmap__44u8_p9_0[] = {
  151419. 7, 5, 3, 1, 0, 2, 4, 6,
  151420. 8,
  151421. };
  151422. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151423. _vq_quantthresh__44u8_p9_0,
  151424. _vq_quantmap__44u8_p9_0,
  151425. 9,
  151426. 9
  151427. };
  151428. static static_codebook _44u8_p9_0 = {
  151429. 2, 81,
  151430. _vq_lengthlist__44u8_p9_0,
  151431. 1, -511895552, 1631393792, 4, 0,
  151432. _vq_quantlist__44u8_p9_0,
  151433. NULL,
  151434. &_vq_auxt__44u8_p9_0,
  151435. NULL,
  151436. 0
  151437. };
  151438. static long _vq_quantlist__44u8_p9_1[] = {
  151439. 9,
  151440. 8,
  151441. 10,
  151442. 7,
  151443. 11,
  151444. 6,
  151445. 12,
  151446. 5,
  151447. 13,
  151448. 4,
  151449. 14,
  151450. 3,
  151451. 15,
  151452. 2,
  151453. 16,
  151454. 1,
  151455. 17,
  151456. 0,
  151457. 18,
  151458. };
  151459. static long _vq_lengthlist__44u8_p9_1[] = {
  151460. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151461. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151462. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151463. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151464. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151465. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151466. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151467. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151468. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151469. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151470. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151471. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151472. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151473. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151474. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151475. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151476. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151477. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151478. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151479. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151480. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151481. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151482. 16,15,16,16,16,16,16,16,16,
  151483. };
  151484. static float _vq_quantthresh__44u8_p9_1[] = {
  151485. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151486. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151487. 367.5, 416.5,
  151488. };
  151489. static long _vq_quantmap__44u8_p9_1[] = {
  151490. 17, 15, 13, 11, 9, 7, 5, 3,
  151491. 1, 0, 2, 4, 6, 8, 10, 12,
  151492. 14, 16, 18,
  151493. };
  151494. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151495. _vq_quantthresh__44u8_p9_1,
  151496. _vq_quantmap__44u8_p9_1,
  151497. 19,
  151498. 19
  151499. };
  151500. static static_codebook _44u8_p9_1 = {
  151501. 2, 361,
  151502. _vq_lengthlist__44u8_p9_1,
  151503. 1, -518287360, 1622704128, 5, 0,
  151504. _vq_quantlist__44u8_p9_1,
  151505. NULL,
  151506. &_vq_auxt__44u8_p9_1,
  151507. NULL,
  151508. 0
  151509. };
  151510. static long _vq_quantlist__44u8_p9_2[] = {
  151511. 24,
  151512. 23,
  151513. 25,
  151514. 22,
  151515. 26,
  151516. 21,
  151517. 27,
  151518. 20,
  151519. 28,
  151520. 19,
  151521. 29,
  151522. 18,
  151523. 30,
  151524. 17,
  151525. 31,
  151526. 16,
  151527. 32,
  151528. 15,
  151529. 33,
  151530. 14,
  151531. 34,
  151532. 13,
  151533. 35,
  151534. 12,
  151535. 36,
  151536. 11,
  151537. 37,
  151538. 10,
  151539. 38,
  151540. 9,
  151541. 39,
  151542. 8,
  151543. 40,
  151544. 7,
  151545. 41,
  151546. 6,
  151547. 42,
  151548. 5,
  151549. 43,
  151550. 4,
  151551. 44,
  151552. 3,
  151553. 45,
  151554. 2,
  151555. 46,
  151556. 1,
  151557. 47,
  151558. 0,
  151559. 48,
  151560. };
  151561. static long _vq_lengthlist__44u8_p9_2[] = {
  151562. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151563. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151564. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151565. 7,
  151566. };
  151567. static float _vq_quantthresh__44u8_p9_2[] = {
  151568. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151569. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151570. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151571. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151572. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151573. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151574. };
  151575. static long _vq_quantmap__44u8_p9_2[] = {
  151576. 47, 45, 43, 41, 39, 37, 35, 33,
  151577. 31, 29, 27, 25, 23, 21, 19, 17,
  151578. 15, 13, 11, 9, 7, 5, 3, 1,
  151579. 0, 2, 4, 6, 8, 10, 12, 14,
  151580. 16, 18, 20, 22, 24, 26, 28, 30,
  151581. 32, 34, 36, 38, 40, 42, 44, 46,
  151582. 48,
  151583. };
  151584. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151585. _vq_quantthresh__44u8_p9_2,
  151586. _vq_quantmap__44u8_p9_2,
  151587. 49,
  151588. 49
  151589. };
  151590. static static_codebook _44u8_p9_2 = {
  151591. 1, 49,
  151592. _vq_lengthlist__44u8_p9_2,
  151593. 1, -526909440, 1611661312, 6, 0,
  151594. _vq_quantlist__44u8_p9_2,
  151595. NULL,
  151596. &_vq_auxt__44u8_p9_2,
  151597. NULL,
  151598. 0
  151599. };
  151600. static long _huff_lengthlist__44u9__long[] = {
  151601. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151602. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151603. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151604. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151605. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151606. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151607. 10, 8, 8, 9,
  151608. };
  151609. static static_codebook _huff_book__44u9__long = {
  151610. 2, 100,
  151611. _huff_lengthlist__44u9__long,
  151612. 0, 0, 0, 0, 0,
  151613. NULL,
  151614. NULL,
  151615. NULL,
  151616. NULL,
  151617. 0
  151618. };
  151619. static long _huff_lengthlist__44u9__short[] = {
  151620. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151621. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151622. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151623. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151624. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151625. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151626. 9, 9,12,15,
  151627. };
  151628. static static_codebook _huff_book__44u9__short = {
  151629. 2, 100,
  151630. _huff_lengthlist__44u9__short,
  151631. 0, 0, 0, 0, 0,
  151632. NULL,
  151633. NULL,
  151634. NULL,
  151635. NULL,
  151636. 0
  151637. };
  151638. static long _vq_quantlist__44u9_p1_0[] = {
  151639. 1,
  151640. 0,
  151641. 2,
  151642. };
  151643. static long _vq_lengthlist__44u9_p1_0[] = {
  151644. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151645. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151646. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151647. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151648. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151649. 10,
  151650. };
  151651. static float _vq_quantthresh__44u9_p1_0[] = {
  151652. -0.5, 0.5,
  151653. };
  151654. static long _vq_quantmap__44u9_p1_0[] = {
  151655. 1, 0, 2,
  151656. };
  151657. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151658. _vq_quantthresh__44u9_p1_0,
  151659. _vq_quantmap__44u9_p1_0,
  151660. 3,
  151661. 3
  151662. };
  151663. static static_codebook _44u9_p1_0 = {
  151664. 4, 81,
  151665. _vq_lengthlist__44u9_p1_0,
  151666. 1, -535822336, 1611661312, 2, 0,
  151667. _vq_quantlist__44u9_p1_0,
  151668. NULL,
  151669. &_vq_auxt__44u9_p1_0,
  151670. NULL,
  151671. 0
  151672. };
  151673. static long _vq_quantlist__44u9_p2_0[] = {
  151674. 2,
  151675. 1,
  151676. 3,
  151677. 0,
  151678. 4,
  151679. };
  151680. static long _vq_lengthlist__44u9_p2_0[] = {
  151681. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151682. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151683. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151684. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151685. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151686. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151687. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151688. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151689. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151690. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151691. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151692. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151693. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151694. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151695. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151696. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151697. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151698. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151699. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151700. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151701. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151702. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151703. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151704. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151705. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151706. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151707. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151708. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151709. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151710. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151711. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151712. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151713. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151714. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151715. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151716. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151717. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151718. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151719. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151720. 14,
  151721. };
  151722. static float _vq_quantthresh__44u9_p2_0[] = {
  151723. -1.5, -0.5, 0.5, 1.5,
  151724. };
  151725. static long _vq_quantmap__44u9_p2_0[] = {
  151726. 3, 1, 0, 2, 4,
  151727. };
  151728. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151729. _vq_quantthresh__44u9_p2_0,
  151730. _vq_quantmap__44u9_p2_0,
  151731. 5,
  151732. 5
  151733. };
  151734. static static_codebook _44u9_p2_0 = {
  151735. 4, 625,
  151736. _vq_lengthlist__44u9_p2_0,
  151737. 1, -533725184, 1611661312, 3, 0,
  151738. _vq_quantlist__44u9_p2_0,
  151739. NULL,
  151740. &_vq_auxt__44u9_p2_0,
  151741. NULL,
  151742. 0
  151743. };
  151744. static long _vq_quantlist__44u9_p3_0[] = {
  151745. 4,
  151746. 3,
  151747. 5,
  151748. 2,
  151749. 6,
  151750. 1,
  151751. 7,
  151752. 0,
  151753. 8,
  151754. };
  151755. static long _vq_lengthlist__44u9_p3_0[] = {
  151756. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151757. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151758. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151759. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151760. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151761. 11,
  151762. };
  151763. static float _vq_quantthresh__44u9_p3_0[] = {
  151764. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151765. };
  151766. static long _vq_quantmap__44u9_p3_0[] = {
  151767. 7, 5, 3, 1, 0, 2, 4, 6,
  151768. 8,
  151769. };
  151770. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151771. _vq_quantthresh__44u9_p3_0,
  151772. _vq_quantmap__44u9_p3_0,
  151773. 9,
  151774. 9
  151775. };
  151776. static static_codebook _44u9_p3_0 = {
  151777. 2, 81,
  151778. _vq_lengthlist__44u9_p3_0,
  151779. 1, -531628032, 1611661312, 4, 0,
  151780. _vq_quantlist__44u9_p3_0,
  151781. NULL,
  151782. &_vq_auxt__44u9_p3_0,
  151783. NULL,
  151784. 0
  151785. };
  151786. static long _vq_quantlist__44u9_p4_0[] = {
  151787. 8,
  151788. 7,
  151789. 9,
  151790. 6,
  151791. 10,
  151792. 5,
  151793. 11,
  151794. 4,
  151795. 12,
  151796. 3,
  151797. 13,
  151798. 2,
  151799. 14,
  151800. 1,
  151801. 15,
  151802. 0,
  151803. 16,
  151804. };
  151805. static long _vq_lengthlist__44u9_p4_0[] = {
  151806. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151807. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151808. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151809. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151810. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151811. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151812. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151813. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151814. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151815. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151816. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151817. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151818. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151819. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151820. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151821. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151822. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151823. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151824. 14,
  151825. };
  151826. static float _vq_quantthresh__44u9_p4_0[] = {
  151827. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151828. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151829. };
  151830. static long _vq_quantmap__44u9_p4_0[] = {
  151831. 15, 13, 11, 9, 7, 5, 3, 1,
  151832. 0, 2, 4, 6, 8, 10, 12, 14,
  151833. 16,
  151834. };
  151835. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151836. _vq_quantthresh__44u9_p4_0,
  151837. _vq_quantmap__44u9_p4_0,
  151838. 17,
  151839. 17
  151840. };
  151841. static static_codebook _44u9_p4_0 = {
  151842. 2, 289,
  151843. _vq_lengthlist__44u9_p4_0,
  151844. 1, -529530880, 1611661312, 5, 0,
  151845. _vq_quantlist__44u9_p4_0,
  151846. NULL,
  151847. &_vq_auxt__44u9_p4_0,
  151848. NULL,
  151849. 0
  151850. };
  151851. static long _vq_quantlist__44u9_p5_0[] = {
  151852. 1,
  151853. 0,
  151854. 2,
  151855. };
  151856. static long _vq_lengthlist__44u9_p5_0[] = {
  151857. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151858. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151859. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151860. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151861. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151862. 10,
  151863. };
  151864. static float _vq_quantthresh__44u9_p5_0[] = {
  151865. -5.5, 5.5,
  151866. };
  151867. static long _vq_quantmap__44u9_p5_0[] = {
  151868. 1, 0, 2,
  151869. };
  151870. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151871. _vq_quantthresh__44u9_p5_0,
  151872. _vq_quantmap__44u9_p5_0,
  151873. 3,
  151874. 3
  151875. };
  151876. static static_codebook _44u9_p5_0 = {
  151877. 4, 81,
  151878. _vq_lengthlist__44u9_p5_0,
  151879. 1, -529137664, 1618345984, 2, 0,
  151880. _vq_quantlist__44u9_p5_0,
  151881. NULL,
  151882. &_vq_auxt__44u9_p5_0,
  151883. NULL,
  151884. 0
  151885. };
  151886. static long _vq_quantlist__44u9_p5_1[] = {
  151887. 5,
  151888. 4,
  151889. 6,
  151890. 3,
  151891. 7,
  151892. 2,
  151893. 8,
  151894. 1,
  151895. 9,
  151896. 0,
  151897. 10,
  151898. };
  151899. static long _vq_lengthlist__44u9_p5_1[] = {
  151900. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151901. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151902. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151903. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151904. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151905. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151906. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151907. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151908. };
  151909. static float _vq_quantthresh__44u9_p5_1[] = {
  151910. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151911. 3.5, 4.5,
  151912. };
  151913. static long _vq_quantmap__44u9_p5_1[] = {
  151914. 9, 7, 5, 3, 1, 0, 2, 4,
  151915. 6, 8, 10,
  151916. };
  151917. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151918. _vq_quantthresh__44u9_p5_1,
  151919. _vq_quantmap__44u9_p5_1,
  151920. 11,
  151921. 11
  151922. };
  151923. static static_codebook _44u9_p5_1 = {
  151924. 2, 121,
  151925. _vq_lengthlist__44u9_p5_1,
  151926. 1, -531365888, 1611661312, 4, 0,
  151927. _vq_quantlist__44u9_p5_1,
  151928. NULL,
  151929. &_vq_auxt__44u9_p5_1,
  151930. NULL,
  151931. 0
  151932. };
  151933. static long _vq_quantlist__44u9_p6_0[] = {
  151934. 6,
  151935. 5,
  151936. 7,
  151937. 4,
  151938. 8,
  151939. 3,
  151940. 9,
  151941. 2,
  151942. 10,
  151943. 1,
  151944. 11,
  151945. 0,
  151946. 12,
  151947. };
  151948. static long _vq_lengthlist__44u9_p6_0[] = {
  151949. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151950. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151951. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151952. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151953. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151954. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151955. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151956. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151957. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151958. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151959. 10,11,11,11,11,12,11,12,12,
  151960. };
  151961. static float _vq_quantthresh__44u9_p6_0[] = {
  151962. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151963. 12.5, 17.5, 22.5, 27.5,
  151964. };
  151965. static long _vq_quantmap__44u9_p6_0[] = {
  151966. 11, 9, 7, 5, 3, 1, 0, 2,
  151967. 4, 6, 8, 10, 12,
  151968. };
  151969. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151970. _vq_quantthresh__44u9_p6_0,
  151971. _vq_quantmap__44u9_p6_0,
  151972. 13,
  151973. 13
  151974. };
  151975. static static_codebook _44u9_p6_0 = {
  151976. 2, 169,
  151977. _vq_lengthlist__44u9_p6_0,
  151978. 1, -526516224, 1616117760, 4, 0,
  151979. _vq_quantlist__44u9_p6_0,
  151980. NULL,
  151981. &_vq_auxt__44u9_p6_0,
  151982. NULL,
  151983. 0
  151984. };
  151985. static long _vq_quantlist__44u9_p6_1[] = {
  151986. 2,
  151987. 1,
  151988. 3,
  151989. 0,
  151990. 4,
  151991. };
  151992. static long _vq_lengthlist__44u9_p6_1[] = {
  151993. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151994. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151995. };
  151996. static float _vq_quantthresh__44u9_p6_1[] = {
  151997. -1.5, -0.5, 0.5, 1.5,
  151998. };
  151999. static long _vq_quantmap__44u9_p6_1[] = {
  152000. 3, 1, 0, 2, 4,
  152001. };
  152002. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152003. _vq_quantthresh__44u9_p6_1,
  152004. _vq_quantmap__44u9_p6_1,
  152005. 5,
  152006. 5
  152007. };
  152008. static static_codebook _44u9_p6_1 = {
  152009. 2, 25,
  152010. _vq_lengthlist__44u9_p6_1,
  152011. 1, -533725184, 1611661312, 3, 0,
  152012. _vq_quantlist__44u9_p6_1,
  152013. NULL,
  152014. &_vq_auxt__44u9_p6_1,
  152015. NULL,
  152016. 0
  152017. };
  152018. static long _vq_quantlist__44u9_p7_0[] = {
  152019. 6,
  152020. 5,
  152021. 7,
  152022. 4,
  152023. 8,
  152024. 3,
  152025. 9,
  152026. 2,
  152027. 10,
  152028. 1,
  152029. 11,
  152030. 0,
  152031. 12,
  152032. };
  152033. static long _vq_lengthlist__44u9_p7_0[] = {
  152034. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152035. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152036. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152037. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152038. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152039. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152040. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152041. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152042. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152043. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152044. 12,13,13,14,14,14,15,15,15,
  152045. };
  152046. static float _vq_quantthresh__44u9_p7_0[] = {
  152047. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152048. 27.5, 38.5, 49.5, 60.5,
  152049. };
  152050. static long _vq_quantmap__44u9_p7_0[] = {
  152051. 11, 9, 7, 5, 3, 1, 0, 2,
  152052. 4, 6, 8, 10, 12,
  152053. };
  152054. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152055. _vq_quantthresh__44u9_p7_0,
  152056. _vq_quantmap__44u9_p7_0,
  152057. 13,
  152058. 13
  152059. };
  152060. static static_codebook _44u9_p7_0 = {
  152061. 2, 169,
  152062. _vq_lengthlist__44u9_p7_0,
  152063. 1, -523206656, 1618345984, 4, 0,
  152064. _vq_quantlist__44u9_p7_0,
  152065. NULL,
  152066. &_vq_auxt__44u9_p7_0,
  152067. NULL,
  152068. 0
  152069. };
  152070. static long _vq_quantlist__44u9_p7_1[] = {
  152071. 5,
  152072. 4,
  152073. 6,
  152074. 3,
  152075. 7,
  152076. 2,
  152077. 8,
  152078. 1,
  152079. 9,
  152080. 0,
  152081. 10,
  152082. };
  152083. static long _vq_lengthlist__44u9_p7_1[] = {
  152084. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152085. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152086. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152087. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152088. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152089. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152090. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152091. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152092. };
  152093. static float _vq_quantthresh__44u9_p7_1[] = {
  152094. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152095. 3.5, 4.5,
  152096. };
  152097. static long _vq_quantmap__44u9_p7_1[] = {
  152098. 9, 7, 5, 3, 1, 0, 2, 4,
  152099. 6, 8, 10,
  152100. };
  152101. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152102. _vq_quantthresh__44u9_p7_1,
  152103. _vq_quantmap__44u9_p7_1,
  152104. 11,
  152105. 11
  152106. };
  152107. static static_codebook _44u9_p7_1 = {
  152108. 2, 121,
  152109. _vq_lengthlist__44u9_p7_1,
  152110. 1, -531365888, 1611661312, 4, 0,
  152111. _vq_quantlist__44u9_p7_1,
  152112. NULL,
  152113. &_vq_auxt__44u9_p7_1,
  152114. NULL,
  152115. 0
  152116. };
  152117. static long _vq_quantlist__44u9_p8_0[] = {
  152118. 7,
  152119. 6,
  152120. 8,
  152121. 5,
  152122. 9,
  152123. 4,
  152124. 10,
  152125. 3,
  152126. 11,
  152127. 2,
  152128. 12,
  152129. 1,
  152130. 13,
  152131. 0,
  152132. 14,
  152133. };
  152134. static long _vq_lengthlist__44u9_p8_0[] = {
  152135. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152136. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152137. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152138. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152139. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152140. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152141. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152142. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152143. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152144. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152145. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152146. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152147. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152148. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152149. 15,
  152150. };
  152151. static float _vq_quantthresh__44u9_p8_0[] = {
  152152. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152153. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152154. };
  152155. static long _vq_quantmap__44u9_p8_0[] = {
  152156. 13, 11, 9, 7, 5, 3, 1, 0,
  152157. 2, 4, 6, 8, 10, 12, 14,
  152158. };
  152159. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152160. _vq_quantthresh__44u9_p8_0,
  152161. _vq_quantmap__44u9_p8_0,
  152162. 15,
  152163. 15
  152164. };
  152165. static static_codebook _44u9_p8_0 = {
  152166. 2, 225,
  152167. _vq_lengthlist__44u9_p8_0,
  152168. 1, -520986624, 1620377600, 4, 0,
  152169. _vq_quantlist__44u9_p8_0,
  152170. NULL,
  152171. &_vq_auxt__44u9_p8_0,
  152172. NULL,
  152173. 0
  152174. };
  152175. static long _vq_quantlist__44u9_p8_1[] = {
  152176. 10,
  152177. 9,
  152178. 11,
  152179. 8,
  152180. 12,
  152181. 7,
  152182. 13,
  152183. 6,
  152184. 14,
  152185. 5,
  152186. 15,
  152187. 4,
  152188. 16,
  152189. 3,
  152190. 17,
  152191. 2,
  152192. 18,
  152193. 1,
  152194. 19,
  152195. 0,
  152196. 20,
  152197. };
  152198. static long _vq_lengthlist__44u9_p8_1[] = {
  152199. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152200. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152201. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152202. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152203. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152204. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152205. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152206. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152207. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152208. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152209. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152210. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152211. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152212. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152213. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152214. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152215. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152216. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152217. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152218. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152219. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152220. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152221. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152222. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152223. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152224. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152225. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152226. 10,10,10,10,10,10,10,10,10,
  152227. };
  152228. static float _vq_quantthresh__44u9_p8_1[] = {
  152229. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152230. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152231. 6.5, 7.5, 8.5, 9.5,
  152232. };
  152233. static long _vq_quantmap__44u9_p8_1[] = {
  152234. 19, 17, 15, 13, 11, 9, 7, 5,
  152235. 3, 1, 0, 2, 4, 6, 8, 10,
  152236. 12, 14, 16, 18, 20,
  152237. };
  152238. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152239. _vq_quantthresh__44u9_p8_1,
  152240. _vq_quantmap__44u9_p8_1,
  152241. 21,
  152242. 21
  152243. };
  152244. static static_codebook _44u9_p8_1 = {
  152245. 2, 441,
  152246. _vq_lengthlist__44u9_p8_1,
  152247. 1, -529268736, 1611661312, 5, 0,
  152248. _vq_quantlist__44u9_p8_1,
  152249. NULL,
  152250. &_vq_auxt__44u9_p8_1,
  152251. NULL,
  152252. 0
  152253. };
  152254. static long _vq_quantlist__44u9_p9_0[] = {
  152255. 7,
  152256. 6,
  152257. 8,
  152258. 5,
  152259. 9,
  152260. 4,
  152261. 10,
  152262. 3,
  152263. 11,
  152264. 2,
  152265. 12,
  152266. 1,
  152267. 13,
  152268. 0,
  152269. 14,
  152270. };
  152271. static long _vq_lengthlist__44u9_p9_0[] = {
  152272. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152273. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152274. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152281. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152282. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152283. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152284. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152285. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152286. 10,
  152287. };
  152288. static float _vq_quantthresh__44u9_p9_0[] = {
  152289. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152290. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152291. };
  152292. static long _vq_quantmap__44u9_p9_0[] = {
  152293. 13, 11, 9, 7, 5, 3, 1, 0,
  152294. 2, 4, 6, 8, 10, 12, 14,
  152295. };
  152296. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152297. _vq_quantthresh__44u9_p9_0,
  152298. _vq_quantmap__44u9_p9_0,
  152299. 15,
  152300. 15
  152301. };
  152302. static static_codebook _44u9_p9_0 = {
  152303. 2, 225,
  152304. _vq_lengthlist__44u9_p9_0,
  152305. 1, -510036736, 1631393792, 4, 0,
  152306. _vq_quantlist__44u9_p9_0,
  152307. NULL,
  152308. &_vq_auxt__44u9_p9_0,
  152309. NULL,
  152310. 0
  152311. };
  152312. static long _vq_quantlist__44u9_p9_1[] = {
  152313. 9,
  152314. 8,
  152315. 10,
  152316. 7,
  152317. 11,
  152318. 6,
  152319. 12,
  152320. 5,
  152321. 13,
  152322. 4,
  152323. 14,
  152324. 3,
  152325. 15,
  152326. 2,
  152327. 16,
  152328. 1,
  152329. 17,
  152330. 0,
  152331. 18,
  152332. };
  152333. static long _vq_lengthlist__44u9_p9_1[] = {
  152334. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152335. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152336. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152337. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152338. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152339. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152340. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152341. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152342. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152343. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152344. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152345. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152346. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152347. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152348. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152349. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152350. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152351. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152352. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152353. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152354. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152355. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152356. 17,17,15,17,15,17,16,16,17,
  152357. };
  152358. static float _vq_quantthresh__44u9_p9_1[] = {
  152359. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152360. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152361. 367.5, 416.5,
  152362. };
  152363. static long _vq_quantmap__44u9_p9_1[] = {
  152364. 17, 15, 13, 11, 9, 7, 5, 3,
  152365. 1, 0, 2, 4, 6, 8, 10, 12,
  152366. 14, 16, 18,
  152367. };
  152368. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152369. _vq_quantthresh__44u9_p9_1,
  152370. _vq_quantmap__44u9_p9_1,
  152371. 19,
  152372. 19
  152373. };
  152374. static static_codebook _44u9_p9_1 = {
  152375. 2, 361,
  152376. _vq_lengthlist__44u9_p9_1,
  152377. 1, -518287360, 1622704128, 5, 0,
  152378. _vq_quantlist__44u9_p9_1,
  152379. NULL,
  152380. &_vq_auxt__44u9_p9_1,
  152381. NULL,
  152382. 0
  152383. };
  152384. static long _vq_quantlist__44u9_p9_2[] = {
  152385. 24,
  152386. 23,
  152387. 25,
  152388. 22,
  152389. 26,
  152390. 21,
  152391. 27,
  152392. 20,
  152393. 28,
  152394. 19,
  152395. 29,
  152396. 18,
  152397. 30,
  152398. 17,
  152399. 31,
  152400. 16,
  152401. 32,
  152402. 15,
  152403. 33,
  152404. 14,
  152405. 34,
  152406. 13,
  152407. 35,
  152408. 12,
  152409. 36,
  152410. 11,
  152411. 37,
  152412. 10,
  152413. 38,
  152414. 9,
  152415. 39,
  152416. 8,
  152417. 40,
  152418. 7,
  152419. 41,
  152420. 6,
  152421. 42,
  152422. 5,
  152423. 43,
  152424. 4,
  152425. 44,
  152426. 3,
  152427. 45,
  152428. 2,
  152429. 46,
  152430. 1,
  152431. 47,
  152432. 0,
  152433. 48,
  152434. };
  152435. static long _vq_lengthlist__44u9_p9_2[] = {
  152436. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152437. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152438. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152439. 7,
  152440. };
  152441. static float _vq_quantthresh__44u9_p9_2[] = {
  152442. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152443. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152444. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152445. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152446. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152447. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152448. };
  152449. static long _vq_quantmap__44u9_p9_2[] = {
  152450. 47, 45, 43, 41, 39, 37, 35, 33,
  152451. 31, 29, 27, 25, 23, 21, 19, 17,
  152452. 15, 13, 11, 9, 7, 5, 3, 1,
  152453. 0, 2, 4, 6, 8, 10, 12, 14,
  152454. 16, 18, 20, 22, 24, 26, 28, 30,
  152455. 32, 34, 36, 38, 40, 42, 44, 46,
  152456. 48,
  152457. };
  152458. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152459. _vq_quantthresh__44u9_p9_2,
  152460. _vq_quantmap__44u9_p9_2,
  152461. 49,
  152462. 49
  152463. };
  152464. static static_codebook _44u9_p9_2 = {
  152465. 1, 49,
  152466. _vq_lengthlist__44u9_p9_2,
  152467. 1, -526909440, 1611661312, 6, 0,
  152468. _vq_quantlist__44u9_p9_2,
  152469. NULL,
  152470. &_vq_auxt__44u9_p9_2,
  152471. NULL,
  152472. 0
  152473. };
  152474. static long _huff_lengthlist__44un1__long[] = {
  152475. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152476. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152477. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152478. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152479. };
  152480. static static_codebook _huff_book__44un1__long = {
  152481. 2, 64,
  152482. _huff_lengthlist__44un1__long,
  152483. 0, 0, 0, 0, 0,
  152484. NULL,
  152485. NULL,
  152486. NULL,
  152487. NULL,
  152488. 0
  152489. };
  152490. static long _vq_quantlist__44un1__p1_0[] = {
  152491. 1,
  152492. 0,
  152493. 2,
  152494. };
  152495. static long _vq_lengthlist__44un1__p1_0[] = {
  152496. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152497. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152498. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152499. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152500. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152501. 12,
  152502. };
  152503. static float _vq_quantthresh__44un1__p1_0[] = {
  152504. -0.5, 0.5,
  152505. };
  152506. static long _vq_quantmap__44un1__p1_0[] = {
  152507. 1, 0, 2,
  152508. };
  152509. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152510. _vq_quantthresh__44un1__p1_0,
  152511. _vq_quantmap__44un1__p1_0,
  152512. 3,
  152513. 3
  152514. };
  152515. static static_codebook _44un1__p1_0 = {
  152516. 4, 81,
  152517. _vq_lengthlist__44un1__p1_0,
  152518. 1, -535822336, 1611661312, 2, 0,
  152519. _vq_quantlist__44un1__p1_0,
  152520. NULL,
  152521. &_vq_auxt__44un1__p1_0,
  152522. NULL,
  152523. 0
  152524. };
  152525. static long _vq_quantlist__44un1__p2_0[] = {
  152526. 1,
  152527. 0,
  152528. 2,
  152529. };
  152530. static long _vq_lengthlist__44un1__p2_0[] = {
  152531. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152532. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152533. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152534. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152535. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152536. 8,
  152537. };
  152538. static float _vq_quantthresh__44un1__p2_0[] = {
  152539. -0.5, 0.5,
  152540. };
  152541. static long _vq_quantmap__44un1__p2_0[] = {
  152542. 1, 0, 2,
  152543. };
  152544. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152545. _vq_quantthresh__44un1__p2_0,
  152546. _vq_quantmap__44un1__p2_0,
  152547. 3,
  152548. 3
  152549. };
  152550. static static_codebook _44un1__p2_0 = {
  152551. 4, 81,
  152552. _vq_lengthlist__44un1__p2_0,
  152553. 1, -535822336, 1611661312, 2, 0,
  152554. _vq_quantlist__44un1__p2_0,
  152555. NULL,
  152556. &_vq_auxt__44un1__p2_0,
  152557. NULL,
  152558. 0
  152559. };
  152560. static long _vq_quantlist__44un1__p3_0[] = {
  152561. 2,
  152562. 1,
  152563. 3,
  152564. 0,
  152565. 4,
  152566. };
  152567. static long _vq_lengthlist__44un1__p3_0[] = {
  152568. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152569. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152570. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152571. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152572. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152573. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152574. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152575. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152576. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152577. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152578. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152579. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152580. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152581. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152582. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152583. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152584. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152585. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152586. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152587. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152588. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152589. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152590. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152591. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152592. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152593. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152594. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152595. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152596. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152597. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152598. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152599. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152600. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152601. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152602. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152603. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152604. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152605. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152606. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152607. 17,
  152608. };
  152609. static float _vq_quantthresh__44un1__p3_0[] = {
  152610. -1.5, -0.5, 0.5, 1.5,
  152611. };
  152612. static long _vq_quantmap__44un1__p3_0[] = {
  152613. 3, 1, 0, 2, 4,
  152614. };
  152615. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152616. _vq_quantthresh__44un1__p3_0,
  152617. _vq_quantmap__44un1__p3_0,
  152618. 5,
  152619. 5
  152620. };
  152621. static static_codebook _44un1__p3_0 = {
  152622. 4, 625,
  152623. _vq_lengthlist__44un1__p3_0,
  152624. 1, -533725184, 1611661312, 3, 0,
  152625. _vq_quantlist__44un1__p3_0,
  152626. NULL,
  152627. &_vq_auxt__44un1__p3_0,
  152628. NULL,
  152629. 0
  152630. };
  152631. static long _vq_quantlist__44un1__p4_0[] = {
  152632. 2,
  152633. 1,
  152634. 3,
  152635. 0,
  152636. 4,
  152637. };
  152638. static long _vq_lengthlist__44un1__p4_0[] = {
  152639. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152640. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152641. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152642. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152643. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152644. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152645. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152646. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152647. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152648. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152649. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152650. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152651. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152652. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152653. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152654. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152655. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152656. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152657. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152658. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152659. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152660. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152661. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152662. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152663. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152664. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152665. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152666. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152667. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152668. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152669. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152670. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152671. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152672. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152673. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152674. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152675. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152676. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152677. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152678. 12,
  152679. };
  152680. static float _vq_quantthresh__44un1__p4_0[] = {
  152681. -1.5, -0.5, 0.5, 1.5,
  152682. };
  152683. static long _vq_quantmap__44un1__p4_0[] = {
  152684. 3, 1, 0, 2, 4,
  152685. };
  152686. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152687. _vq_quantthresh__44un1__p4_0,
  152688. _vq_quantmap__44un1__p4_0,
  152689. 5,
  152690. 5
  152691. };
  152692. static static_codebook _44un1__p4_0 = {
  152693. 4, 625,
  152694. _vq_lengthlist__44un1__p4_0,
  152695. 1, -533725184, 1611661312, 3, 0,
  152696. _vq_quantlist__44un1__p4_0,
  152697. NULL,
  152698. &_vq_auxt__44un1__p4_0,
  152699. NULL,
  152700. 0
  152701. };
  152702. static long _vq_quantlist__44un1__p5_0[] = {
  152703. 4,
  152704. 3,
  152705. 5,
  152706. 2,
  152707. 6,
  152708. 1,
  152709. 7,
  152710. 0,
  152711. 8,
  152712. };
  152713. static long _vq_lengthlist__44un1__p5_0[] = {
  152714. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152715. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152716. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152717. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152718. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152719. 12,
  152720. };
  152721. static float _vq_quantthresh__44un1__p5_0[] = {
  152722. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152723. };
  152724. static long _vq_quantmap__44un1__p5_0[] = {
  152725. 7, 5, 3, 1, 0, 2, 4, 6,
  152726. 8,
  152727. };
  152728. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152729. _vq_quantthresh__44un1__p5_0,
  152730. _vq_quantmap__44un1__p5_0,
  152731. 9,
  152732. 9
  152733. };
  152734. static static_codebook _44un1__p5_0 = {
  152735. 2, 81,
  152736. _vq_lengthlist__44un1__p5_0,
  152737. 1, -531628032, 1611661312, 4, 0,
  152738. _vq_quantlist__44un1__p5_0,
  152739. NULL,
  152740. &_vq_auxt__44un1__p5_0,
  152741. NULL,
  152742. 0
  152743. };
  152744. static long _vq_quantlist__44un1__p6_0[] = {
  152745. 6,
  152746. 5,
  152747. 7,
  152748. 4,
  152749. 8,
  152750. 3,
  152751. 9,
  152752. 2,
  152753. 10,
  152754. 1,
  152755. 11,
  152756. 0,
  152757. 12,
  152758. };
  152759. static long _vq_lengthlist__44un1__p6_0[] = {
  152760. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152761. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152762. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152763. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152764. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152765. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152766. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152767. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152768. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152769. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152770. 16, 0,15,18,18, 0,16, 0, 0,
  152771. };
  152772. static float _vq_quantthresh__44un1__p6_0[] = {
  152773. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152774. 12.5, 17.5, 22.5, 27.5,
  152775. };
  152776. static long _vq_quantmap__44un1__p6_0[] = {
  152777. 11, 9, 7, 5, 3, 1, 0, 2,
  152778. 4, 6, 8, 10, 12,
  152779. };
  152780. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152781. _vq_quantthresh__44un1__p6_0,
  152782. _vq_quantmap__44un1__p6_0,
  152783. 13,
  152784. 13
  152785. };
  152786. static static_codebook _44un1__p6_0 = {
  152787. 2, 169,
  152788. _vq_lengthlist__44un1__p6_0,
  152789. 1, -526516224, 1616117760, 4, 0,
  152790. _vq_quantlist__44un1__p6_0,
  152791. NULL,
  152792. &_vq_auxt__44un1__p6_0,
  152793. NULL,
  152794. 0
  152795. };
  152796. static long _vq_quantlist__44un1__p6_1[] = {
  152797. 2,
  152798. 1,
  152799. 3,
  152800. 0,
  152801. 4,
  152802. };
  152803. static long _vq_lengthlist__44un1__p6_1[] = {
  152804. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152805. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152806. };
  152807. static float _vq_quantthresh__44un1__p6_1[] = {
  152808. -1.5, -0.5, 0.5, 1.5,
  152809. };
  152810. static long _vq_quantmap__44un1__p6_1[] = {
  152811. 3, 1, 0, 2, 4,
  152812. };
  152813. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152814. _vq_quantthresh__44un1__p6_1,
  152815. _vq_quantmap__44un1__p6_1,
  152816. 5,
  152817. 5
  152818. };
  152819. static static_codebook _44un1__p6_1 = {
  152820. 2, 25,
  152821. _vq_lengthlist__44un1__p6_1,
  152822. 1, -533725184, 1611661312, 3, 0,
  152823. _vq_quantlist__44un1__p6_1,
  152824. NULL,
  152825. &_vq_auxt__44un1__p6_1,
  152826. NULL,
  152827. 0
  152828. };
  152829. static long _vq_quantlist__44un1__p7_0[] = {
  152830. 2,
  152831. 1,
  152832. 3,
  152833. 0,
  152834. 4,
  152835. };
  152836. static long _vq_lengthlist__44un1__p7_0[] = {
  152837. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152838. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152840. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152844. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152852. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152853. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152854. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152855. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152856. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152857. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152858. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152860. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152861. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152867. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152873. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152874. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152875. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152876. 10,
  152877. };
  152878. static float _vq_quantthresh__44un1__p7_0[] = {
  152879. -253.5, -84.5, 84.5, 253.5,
  152880. };
  152881. static long _vq_quantmap__44un1__p7_0[] = {
  152882. 3, 1, 0, 2, 4,
  152883. };
  152884. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152885. _vq_quantthresh__44un1__p7_0,
  152886. _vq_quantmap__44un1__p7_0,
  152887. 5,
  152888. 5
  152889. };
  152890. static static_codebook _44un1__p7_0 = {
  152891. 4, 625,
  152892. _vq_lengthlist__44un1__p7_0,
  152893. 1, -518709248, 1626677248, 3, 0,
  152894. _vq_quantlist__44un1__p7_0,
  152895. NULL,
  152896. &_vq_auxt__44un1__p7_0,
  152897. NULL,
  152898. 0
  152899. };
  152900. static long _vq_quantlist__44un1__p7_1[] = {
  152901. 6,
  152902. 5,
  152903. 7,
  152904. 4,
  152905. 8,
  152906. 3,
  152907. 9,
  152908. 2,
  152909. 10,
  152910. 1,
  152911. 11,
  152912. 0,
  152913. 12,
  152914. };
  152915. static long _vq_lengthlist__44un1__p7_1[] = {
  152916. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152917. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152918. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152919. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152920. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152921. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152922. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152923. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152924. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152925. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152926. 12,13,13,12,13,13,14,14,14,
  152927. };
  152928. static float _vq_quantthresh__44un1__p7_1[] = {
  152929. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152930. 32.5, 45.5, 58.5, 71.5,
  152931. };
  152932. static long _vq_quantmap__44un1__p7_1[] = {
  152933. 11, 9, 7, 5, 3, 1, 0, 2,
  152934. 4, 6, 8, 10, 12,
  152935. };
  152936. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152937. _vq_quantthresh__44un1__p7_1,
  152938. _vq_quantmap__44un1__p7_1,
  152939. 13,
  152940. 13
  152941. };
  152942. static static_codebook _44un1__p7_1 = {
  152943. 2, 169,
  152944. _vq_lengthlist__44un1__p7_1,
  152945. 1, -523010048, 1618608128, 4, 0,
  152946. _vq_quantlist__44un1__p7_1,
  152947. NULL,
  152948. &_vq_auxt__44un1__p7_1,
  152949. NULL,
  152950. 0
  152951. };
  152952. static long _vq_quantlist__44un1__p7_2[] = {
  152953. 6,
  152954. 5,
  152955. 7,
  152956. 4,
  152957. 8,
  152958. 3,
  152959. 9,
  152960. 2,
  152961. 10,
  152962. 1,
  152963. 11,
  152964. 0,
  152965. 12,
  152966. };
  152967. static long _vq_lengthlist__44un1__p7_2[] = {
  152968. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152969. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152970. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152971. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152972. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152973. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152974. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152975. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152976. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152977. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152978. 9, 9, 9,10,10,10,10,10,10,
  152979. };
  152980. static float _vq_quantthresh__44un1__p7_2[] = {
  152981. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152982. 2.5, 3.5, 4.5, 5.5,
  152983. };
  152984. static long _vq_quantmap__44un1__p7_2[] = {
  152985. 11, 9, 7, 5, 3, 1, 0, 2,
  152986. 4, 6, 8, 10, 12,
  152987. };
  152988. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152989. _vq_quantthresh__44un1__p7_2,
  152990. _vq_quantmap__44un1__p7_2,
  152991. 13,
  152992. 13
  152993. };
  152994. static static_codebook _44un1__p7_2 = {
  152995. 2, 169,
  152996. _vq_lengthlist__44un1__p7_2,
  152997. 1, -531103744, 1611661312, 4, 0,
  152998. _vq_quantlist__44un1__p7_2,
  152999. NULL,
  153000. &_vq_auxt__44un1__p7_2,
  153001. NULL,
  153002. 0
  153003. };
  153004. static long _huff_lengthlist__44un1__short[] = {
  153005. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153006. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153007. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153008. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153009. };
  153010. static static_codebook _huff_book__44un1__short = {
  153011. 2, 64,
  153012. _huff_lengthlist__44un1__short,
  153013. 0, 0, 0, 0, 0,
  153014. NULL,
  153015. NULL,
  153016. NULL,
  153017. NULL,
  153018. 0
  153019. };
  153020. /*** End of inlined file: res_books_uncoupled.h ***/
  153021. /***** residue backends *********************************************/
  153022. static vorbis_info_residue0 _residue_44_low_un={
  153023. 0,-1, -1, 8,-1,
  153024. {0},
  153025. {-1},
  153026. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153027. { -1, 25, -1, 45, -1, -1, -1}
  153028. };
  153029. static vorbis_info_residue0 _residue_44_mid_un={
  153030. 0,-1, -1, 10,-1,
  153031. /* 0 1 2 3 4 5 6 7 8 9 */
  153032. {0},
  153033. {-1},
  153034. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153035. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153036. };
  153037. static vorbis_info_residue0 _residue_44_hi_un={
  153038. 0,-1, -1, 10,-1,
  153039. /* 0 1 2 3 4 5 6 7 8 9 */
  153040. {0},
  153041. {-1},
  153042. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153043. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153044. };
  153045. /* mapping conventions:
  153046. only one submap (this would change for efficient 5.1 support for example)*/
  153047. /* Four psychoacoustic profiles are used, one for each blocktype */
  153048. static vorbis_info_mapping0 _map_nominal_u[2]={
  153049. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153050. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153051. };
  153052. static static_bookblock _resbook_44u_n1={
  153053. {
  153054. {0},
  153055. {0,0,&_44un1__p1_0},
  153056. {0,0,&_44un1__p2_0},
  153057. {0,0,&_44un1__p3_0},
  153058. {0,0,&_44un1__p4_0},
  153059. {0,0,&_44un1__p5_0},
  153060. {&_44un1__p6_0,&_44un1__p6_1},
  153061. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153062. }
  153063. };
  153064. static static_bookblock _resbook_44u_0={
  153065. {
  153066. {0},
  153067. {0,0,&_44u0__p1_0},
  153068. {0,0,&_44u0__p2_0},
  153069. {0,0,&_44u0__p3_0},
  153070. {0,0,&_44u0__p4_0},
  153071. {0,0,&_44u0__p5_0},
  153072. {&_44u0__p6_0,&_44u0__p6_1},
  153073. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153074. }
  153075. };
  153076. static static_bookblock _resbook_44u_1={
  153077. {
  153078. {0},
  153079. {0,0,&_44u1__p1_0},
  153080. {0,0,&_44u1__p2_0},
  153081. {0,0,&_44u1__p3_0},
  153082. {0,0,&_44u1__p4_0},
  153083. {0,0,&_44u1__p5_0},
  153084. {&_44u1__p6_0,&_44u1__p6_1},
  153085. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153086. }
  153087. };
  153088. static static_bookblock _resbook_44u_2={
  153089. {
  153090. {0},
  153091. {0,0,&_44u2__p1_0},
  153092. {0,0,&_44u2__p2_0},
  153093. {0,0,&_44u2__p3_0},
  153094. {0,0,&_44u2__p4_0},
  153095. {0,0,&_44u2__p5_0},
  153096. {&_44u2__p6_0,&_44u2__p6_1},
  153097. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153098. }
  153099. };
  153100. static static_bookblock _resbook_44u_3={
  153101. {
  153102. {0},
  153103. {0,0,&_44u3__p1_0},
  153104. {0,0,&_44u3__p2_0},
  153105. {0,0,&_44u3__p3_0},
  153106. {0,0,&_44u3__p4_0},
  153107. {0,0,&_44u3__p5_0},
  153108. {&_44u3__p6_0,&_44u3__p6_1},
  153109. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153110. }
  153111. };
  153112. static static_bookblock _resbook_44u_4={
  153113. {
  153114. {0},
  153115. {0,0,&_44u4__p1_0},
  153116. {0,0,&_44u4__p2_0},
  153117. {0,0,&_44u4__p3_0},
  153118. {0,0,&_44u4__p4_0},
  153119. {0,0,&_44u4__p5_0},
  153120. {&_44u4__p6_0,&_44u4__p6_1},
  153121. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153122. }
  153123. };
  153124. static static_bookblock _resbook_44u_5={
  153125. {
  153126. {0},
  153127. {0,0,&_44u5__p1_0},
  153128. {0,0,&_44u5__p2_0},
  153129. {0,0,&_44u5__p3_0},
  153130. {0,0,&_44u5__p4_0},
  153131. {0,0,&_44u5__p5_0},
  153132. {0,0,&_44u5__p6_0},
  153133. {&_44u5__p7_0,&_44u5__p7_1},
  153134. {&_44u5__p8_0,&_44u5__p8_1},
  153135. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153136. }
  153137. };
  153138. static static_bookblock _resbook_44u_6={
  153139. {
  153140. {0},
  153141. {0,0,&_44u6__p1_0},
  153142. {0,0,&_44u6__p2_0},
  153143. {0,0,&_44u6__p3_0},
  153144. {0,0,&_44u6__p4_0},
  153145. {0,0,&_44u6__p5_0},
  153146. {0,0,&_44u6__p6_0},
  153147. {&_44u6__p7_0,&_44u6__p7_1},
  153148. {&_44u6__p8_0,&_44u6__p8_1},
  153149. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153150. }
  153151. };
  153152. static static_bookblock _resbook_44u_7={
  153153. {
  153154. {0},
  153155. {0,0,&_44u7__p1_0},
  153156. {0,0,&_44u7__p2_0},
  153157. {0,0,&_44u7__p3_0},
  153158. {0,0,&_44u7__p4_0},
  153159. {0,0,&_44u7__p5_0},
  153160. {0,0,&_44u7__p6_0},
  153161. {&_44u7__p7_0,&_44u7__p7_1},
  153162. {&_44u7__p8_0,&_44u7__p8_1},
  153163. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153164. }
  153165. };
  153166. static static_bookblock _resbook_44u_8={
  153167. {
  153168. {0},
  153169. {0,0,&_44u8_p1_0},
  153170. {0,0,&_44u8_p2_0},
  153171. {0,0,&_44u8_p3_0},
  153172. {0,0,&_44u8_p4_0},
  153173. {&_44u8_p5_0,&_44u8_p5_1},
  153174. {&_44u8_p6_0,&_44u8_p6_1},
  153175. {&_44u8_p7_0,&_44u8_p7_1},
  153176. {&_44u8_p8_0,&_44u8_p8_1},
  153177. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153178. }
  153179. };
  153180. static static_bookblock _resbook_44u_9={
  153181. {
  153182. {0},
  153183. {0,0,&_44u9_p1_0},
  153184. {0,0,&_44u9_p2_0},
  153185. {0,0,&_44u9_p3_0},
  153186. {0,0,&_44u9_p4_0},
  153187. {&_44u9_p5_0,&_44u9_p5_1},
  153188. {&_44u9_p6_0,&_44u9_p6_1},
  153189. {&_44u9_p7_0,&_44u9_p7_1},
  153190. {&_44u9_p8_0,&_44u9_p8_1},
  153191. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153192. }
  153193. };
  153194. static vorbis_residue_template _res_44u_n1[]={
  153195. {1,0, &_residue_44_low_un,
  153196. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153197. &_resbook_44u_n1,&_resbook_44u_n1},
  153198. {1,0, &_residue_44_low_un,
  153199. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153200. &_resbook_44u_n1,&_resbook_44u_n1}
  153201. };
  153202. static vorbis_residue_template _res_44u_0[]={
  153203. {1,0, &_residue_44_low_un,
  153204. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153205. &_resbook_44u_0,&_resbook_44u_0},
  153206. {1,0, &_residue_44_low_un,
  153207. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153208. &_resbook_44u_0,&_resbook_44u_0}
  153209. };
  153210. static vorbis_residue_template _res_44u_1[]={
  153211. {1,0, &_residue_44_low_un,
  153212. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153213. &_resbook_44u_1,&_resbook_44u_1},
  153214. {1,0, &_residue_44_low_un,
  153215. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153216. &_resbook_44u_1,&_resbook_44u_1}
  153217. };
  153218. static vorbis_residue_template _res_44u_2[]={
  153219. {1,0, &_residue_44_low_un,
  153220. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153221. &_resbook_44u_2,&_resbook_44u_2},
  153222. {1,0, &_residue_44_low_un,
  153223. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153224. &_resbook_44u_2,&_resbook_44u_2}
  153225. };
  153226. static vorbis_residue_template _res_44u_3[]={
  153227. {1,0, &_residue_44_low_un,
  153228. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153229. &_resbook_44u_3,&_resbook_44u_3},
  153230. {1,0, &_residue_44_low_un,
  153231. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153232. &_resbook_44u_3,&_resbook_44u_3}
  153233. };
  153234. static vorbis_residue_template _res_44u_4[]={
  153235. {1,0, &_residue_44_low_un,
  153236. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153237. &_resbook_44u_4,&_resbook_44u_4},
  153238. {1,0, &_residue_44_low_un,
  153239. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153240. &_resbook_44u_4,&_resbook_44u_4}
  153241. };
  153242. static vorbis_residue_template _res_44u_5[]={
  153243. {1,0, &_residue_44_mid_un,
  153244. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153245. &_resbook_44u_5,&_resbook_44u_5},
  153246. {1,0, &_residue_44_mid_un,
  153247. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153248. &_resbook_44u_5,&_resbook_44u_5}
  153249. };
  153250. static vorbis_residue_template _res_44u_6[]={
  153251. {1,0, &_residue_44_mid_un,
  153252. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153253. &_resbook_44u_6,&_resbook_44u_6},
  153254. {1,0, &_residue_44_mid_un,
  153255. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153256. &_resbook_44u_6,&_resbook_44u_6}
  153257. };
  153258. static vorbis_residue_template _res_44u_7[]={
  153259. {1,0, &_residue_44_mid_un,
  153260. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153261. &_resbook_44u_7,&_resbook_44u_7},
  153262. {1,0, &_residue_44_mid_un,
  153263. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153264. &_resbook_44u_7,&_resbook_44u_7}
  153265. };
  153266. static vorbis_residue_template _res_44u_8[]={
  153267. {1,0, &_residue_44_hi_un,
  153268. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153269. &_resbook_44u_8,&_resbook_44u_8},
  153270. {1,0, &_residue_44_hi_un,
  153271. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153272. &_resbook_44u_8,&_resbook_44u_8}
  153273. };
  153274. static vorbis_residue_template _res_44u_9[]={
  153275. {1,0, &_residue_44_hi_un,
  153276. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153277. &_resbook_44u_9,&_resbook_44u_9},
  153278. {1,0, &_residue_44_hi_un,
  153279. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153280. &_resbook_44u_9,&_resbook_44u_9}
  153281. };
  153282. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153283. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153284. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153285. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153286. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153287. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153288. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153289. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153290. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153291. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153292. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153293. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153294. };
  153295. /*** End of inlined file: residue_44u.h ***/
  153296. static double rate_mapping_44_un[12]={
  153297. 32000.,48000.,60000.,70000.,80000.,86000.,
  153298. 96000.,110000.,120000.,140000.,160000.,240001.
  153299. };
  153300. ve_setup_data_template ve_setup_44_uncoupled={
  153301. 11,
  153302. rate_mapping_44_un,
  153303. quality_mapping_44,
  153304. -1,
  153305. 40000,
  153306. 50000,
  153307. blocksize_short_44,
  153308. blocksize_long_44,
  153309. _psy_tone_masteratt_44,
  153310. _psy_tone_0dB,
  153311. _psy_tone_suppress,
  153312. _vp_tonemask_adj_otherblock,
  153313. _vp_tonemask_adj_longblock,
  153314. _vp_tonemask_adj_otherblock,
  153315. _psy_noiseguards_44,
  153316. _psy_noisebias_impulse,
  153317. _psy_noisebias_padding,
  153318. _psy_noisebias_trans,
  153319. _psy_noisebias_long,
  153320. _psy_noise_suppress,
  153321. _psy_compand_44,
  153322. _psy_compand_short_mapping,
  153323. _psy_compand_long_mapping,
  153324. {_noise_start_short_44,_noise_start_long_44},
  153325. {_noise_part_short_44,_noise_part_long_44},
  153326. _noise_thresh_44,
  153327. _psy_ath_floater,
  153328. _psy_ath_abs,
  153329. _psy_lowpass_44,
  153330. _psy_global_44,
  153331. _global_mapping_44,
  153332. NULL,
  153333. _floor_books,
  153334. _floor,
  153335. _floor_short_mapping_44,
  153336. _floor_long_mapping_44,
  153337. _mapres_template_44_uncoupled
  153338. };
  153339. /*** End of inlined file: setup_44u.h ***/
  153340. /*** Start of inlined file: setup_32.h ***/
  153341. static double rate_mapping_32[12]={
  153342. 18000.,28000.,35000.,45000.,56000.,60000.,
  153343. 75000.,90000.,100000.,115000.,150000.,190000.,
  153344. };
  153345. static double rate_mapping_32_un[12]={
  153346. 30000.,42000.,52000.,64000.,72000.,78000.,
  153347. 86000.,92000.,110000.,120000.,140000.,190000.,
  153348. };
  153349. static double _psy_lowpass_32[12]={
  153350. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153351. };
  153352. ve_setup_data_template ve_setup_32_stereo={
  153353. 11,
  153354. rate_mapping_32,
  153355. quality_mapping_44,
  153356. 2,
  153357. 26000,
  153358. 40000,
  153359. blocksize_short_44,
  153360. blocksize_long_44,
  153361. _psy_tone_masteratt_44,
  153362. _psy_tone_0dB,
  153363. _psy_tone_suppress,
  153364. _vp_tonemask_adj_otherblock,
  153365. _vp_tonemask_adj_longblock,
  153366. _vp_tonemask_adj_otherblock,
  153367. _psy_noiseguards_44,
  153368. _psy_noisebias_impulse,
  153369. _psy_noisebias_padding,
  153370. _psy_noisebias_trans,
  153371. _psy_noisebias_long,
  153372. _psy_noise_suppress,
  153373. _psy_compand_44,
  153374. _psy_compand_short_mapping,
  153375. _psy_compand_long_mapping,
  153376. {_noise_start_short_44,_noise_start_long_44},
  153377. {_noise_part_short_44,_noise_part_long_44},
  153378. _noise_thresh_44,
  153379. _psy_ath_floater,
  153380. _psy_ath_abs,
  153381. _psy_lowpass_32,
  153382. _psy_global_44,
  153383. _global_mapping_44,
  153384. _psy_stereo_modes_44,
  153385. _floor_books,
  153386. _floor,
  153387. _floor_short_mapping_44,
  153388. _floor_long_mapping_44,
  153389. _mapres_template_44_stereo
  153390. };
  153391. ve_setup_data_template ve_setup_32_uncoupled={
  153392. 11,
  153393. rate_mapping_32_un,
  153394. quality_mapping_44,
  153395. -1,
  153396. 26000,
  153397. 40000,
  153398. blocksize_short_44,
  153399. blocksize_long_44,
  153400. _psy_tone_masteratt_44,
  153401. _psy_tone_0dB,
  153402. _psy_tone_suppress,
  153403. _vp_tonemask_adj_otherblock,
  153404. _vp_tonemask_adj_longblock,
  153405. _vp_tonemask_adj_otherblock,
  153406. _psy_noiseguards_44,
  153407. _psy_noisebias_impulse,
  153408. _psy_noisebias_padding,
  153409. _psy_noisebias_trans,
  153410. _psy_noisebias_long,
  153411. _psy_noise_suppress,
  153412. _psy_compand_44,
  153413. _psy_compand_short_mapping,
  153414. _psy_compand_long_mapping,
  153415. {_noise_start_short_44,_noise_start_long_44},
  153416. {_noise_part_short_44,_noise_part_long_44},
  153417. _noise_thresh_44,
  153418. _psy_ath_floater,
  153419. _psy_ath_abs,
  153420. _psy_lowpass_32,
  153421. _psy_global_44,
  153422. _global_mapping_44,
  153423. NULL,
  153424. _floor_books,
  153425. _floor,
  153426. _floor_short_mapping_44,
  153427. _floor_long_mapping_44,
  153428. _mapres_template_44_uncoupled
  153429. };
  153430. /*** End of inlined file: setup_32.h ***/
  153431. /*** Start of inlined file: setup_8.h ***/
  153432. /*** Start of inlined file: psych_8.h ***/
  153433. static att3 _psy_tone_masteratt_8[3]={
  153434. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153435. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153436. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153437. };
  153438. static vp_adjblock _vp_tonemask_adj_8[3]={
  153439. /* adjust for mode zero */
  153440. /* 63 125 250 500 1 2 4 8 16 */
  153441. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153442. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153443. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153444. };
  153445. static noise3 _psy_noisebias_8[3]={
  153446. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153447. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153448. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153449. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153450. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153451. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153452. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153453. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153454. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153455. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153456. };
  153457. /* stereo mode by base quality level */
  153458. static adj_stereo _psy_stereo_modes_8[3]={
  153459. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153460. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153461. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153462. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153463. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153464. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153465. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153466. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153467. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153468. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153469. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153470. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153471. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153472. };
  153473. static noiseguard _psy_noiseguards_8[2]={
  153474. {10,10,-1},
  153475. {10,10,-1},
  153476. };
  153477. static compandblock _psy_compand_8[2]={
  153478. {{
  153479. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153480. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153481. 12,12,13,13,14,14,15, 15, /* 23dB */
  153482. 16,16,17,17,17,18,18, 19, /* 31dB */
  153483. 19,19,20,21,22,23,24, 25, /* 39dB */
  153484. }},
  153485. {{
  153486. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153487. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153488. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153489. 9,10,11,12,13,14,15, 16, /* 31dB */
  153490. 17,18,19,20,21,22,23, 24, /* 39dB */
  153491. }},
  153492. };
  153493. static double _psy_lowpass_8[3]={3.,4.,4.};
  153494. static int _noise_start_8[2]={
  153495. 64,64,
  153496. };
  153497. static int _noise_part_8[2]={
  153498. 8,8,
  153499. };
  153500. static int _psy_ath_floater_8[3]={
  153501. -100,-100,-105,
  153502. };
  153503. static int _psy_ath_abs_8[3]={
  153504. -130,-130,-140,
  153505. };
  153506. /*** End of inlined file: psych_8.h ***/
  153507. /*** Start of inlined file: residue_8.h ***/
  153508. /***** residue backends *********************************************/
  153509. static static_bookblock _resbook_8s_0={
  153510. {
  153511. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153512. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153513. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153514. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153515. }
  153516. };
  153517. static static_bookblock _resbook_8s_1={
  153518. {
  153519. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153520. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153521. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153522. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153523. }
  153524. };
  153525. static vorbis_residue_template _res_8s_0[]={
  153526. {2,0, &_residue_44_mid,
  153527. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153528. &_resbook_8s_0,&_resbook_8s_0},
  153529. };
  153530. static vorbis_residue_template _res_8s_1[]={
  153531. {2,0, &_residue_44_mid,
  153532. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153533. &_resbook_8s_1,&_resbook_8s_1},
  153534. };
  153535. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153536. { _map_nominal, _res_8s_0 }, /* 0 */
  153537. { _map_nominal, _res_8s_1 }, /* 1 */
  153538. };
  153539. static static_bookblock _resbook_8u_0={
  153540. {
  153541. {0},
  153542. {0,0,&_8u0__p1_0},
  153543. {0,0,&_8u0__p2_0},
  153544. {0,0,&_8u0__p3_0},
  153545. {0,0,&_8u0__p4_0},
  153546. {0,0,&_8u0__p5_0},
  153547. {&_8u0__p6_0,&_8u0__p6_1},
  153548. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153549. }
  153550. };
  153551. static static_bookblock _resbook_8u_1={
  153552. {
  153553. {0},
  153554. {0,0,&_8u1__p1_0},
  153555. {0,0,&_8u1__p2_0},
  153556. {0,0,&_8u1__p3_0},
  153557. {0,0,&_8u1__p4_0},
  153558. {0,0,&_8u1__p5_0},
  153559. {0,0,&_8u1__p6_0},
  153560. {&_8u1__p7_0,&_8u1__p7_1},
  153561. {&_8u1__p8_0,&_8u1__p8_1},
  153562. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153563. }
  153564. };
  153565. static vorbis_residue_template _res_8u_0[]={
  153566. {1,0, &_residue_44_low_un,
  153567. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153568. &_resbook_8u_0,&_resbook_8u_0},
  153569. };
  153570. static vorbis_residue_template _res_8u_1[]={
  153571. {1,0, &_residue_44_mid_un,
  153572. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153573. &_resbook_8u_1,&_resbook_8u_1},
  153574. };
  153575. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153576. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153577. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153578. };
  153579. /*** End of inlined file: residue_8.h ***/
  153580. static int blocksize_8[2]={
  153581. 512,512
  153582. };
  153583. static int _floor_mapping_8[2]={
  153584. 6,6,
  153585. };
  153586. static double rate_mapping_8[3]={
  153587. 6000.,9000.,32000.,
  153588. };
  153589. static double rate_mapping_8_uncoupled[3]={
  153590. 8000.,14000.,42000.,
  153591. };
  153592. static double quality_mapping_8[3]={
  153593. -.1,.0,1.
  153594. };
  153595. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153596. static double _global_mapping_8[3]={ 1., 2., 3. };
  153597. ve_setup_data_template ve_setup_8_stereo={
  153598. 2,
  153599. rate_mapping_8,
  153600. quality_mapping_8,
  153601. 2,
  153602. 8000,
  153603. 9000,
  153604. blocksize_8,
  153605. blocksize_8,
  153606. _psy_tone_masteratt_8,
  153607. _psy_tone_0dB,
  153608. _psy_tone_suppress,
  153609. _vp_tonemask_adj_8,
  153610. NULL,
  153611. _vp_tonemask_adj_8,
  153612. _psy_noiseguards_8,
  153613. _psy_noisebias_8,
  153614. _psy_noisebias_8,
  153615. NULL,
  153616. NULL,
  153617. _psy_noise_suppress,
  153618. _psy_compand_8,
  153619. _psy_compand_8_mapping,
  153620. NULL,
  153621. {_noise_start_8,_noise_start_8},
  153622. {_noise_part_8,_noise_part_8},
  153623. _noise_thresh_5only,
  153624. _psy_ath_floater_8,
  153625. _psy_ath_abs_8,
  153626. _psy_lowpass_8,
  153627. _psy_global_44,
  153628. _global_mapping_8,
  153629. _psy_stereo_modes_8,
  153630. _floor_books,
  153631. _floor,
  153632. _floor_mapping_8,
  153633. NULL,
  153634. _mapres_template_8_stereo
  153635. };
  153636. ve_setup_data_template ve_setup_8_uncoupled={
  153637. 2,
  153638. rate_mapping_8_uncoupled,
  153639. quality_mapping_8,
  153640. -1,
  153641. 8000,
  153642. 9000,
  153643. blocksize_8,
  153644. blocksize_8,
  153645. _psy_tone_masteratt_8,
  153646. _psy_tone_0dB,
  153647. _psy_tone_suppress,
  153648. _vp_tonemask_adj_8,
  153649. NULL,
  153650. _vp_tonemask_adj_8,
  153651. _psy_noiseguards_8,
  153652. _psy_noisebias_8,
  153653. _psy_noisebias_8,
  153654. NULL,
  153655. NULL,
  153656. _psy_noise_suppress,
  153657. _psy_compand_8,
  153658. _psy_compand_8_mapping,
  153659. NULL,
  153660. {_noise_start_8,_noise_start_8},
  153661. {_noise_part_8,_noise_part_8},
  153662. _noise_thresh_5only,
  153663. _psy_ath_floater_8,
  153664. _psy_ath_abs_8,
  153665. _psy_lowpass_8,
  153666. _psy_global_44,
  153667. _global_mapping_8,
  153668. _psy_stereo_modes_8,
  153669. _floor_books,
  153670. _floor,
  153671. _floor_mapping_8,
  153672. NULL,
  153673. _mapres_template_8_uncoupled
  153674. };
  153675. /*** End of inlined file: setup_8.h ***/
  153676. /*** Start of inlined file: setup_11.h ***/
  153677. /*** Start of inlined file: psych_11.h ***/
  153678. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153679. static att3 _psy_tone_masteratt_11[3]={
  153680. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153681. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153682. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153683. };
  153684. static vp_adjblock _vp_tonemask_adj_11[3]={
  153685. /* adjust for mode zero */
  153686. /* 63 125 250 500 1 2 4 8 16 */
  153687. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153688. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153689. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153690. };
  153691. static noise3 _psy_noisebias_11[3]={
  153692. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153693. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153694. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153695. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153696. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153697. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153698. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153699. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153700. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153701. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153702. };
  153703. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153704. /*** End of inlined file: psych_11.h ***/
  153705. static int blocksize_11[2]={
  153706. 512,512
  153707. };
  153708. static int _floor_mapping_11[2]={
  153709. 6,6,
  153710. };
  153711. static double rate_mapping_11[3]={
  153712. 8000.,13000.,44000.,
  153713. };
  153714. static double rate_mapping_11_uncoupled[3]={
  153715. 12000.,20000.,50000.,
  153716. };
  153717. static double quality_mapping_11[3]={
  153718. -.1,.0,1.
  153719. };
  153720. ve_setup_data_template ve_setup_11_stereo={
  153721. 2,
  153722. rate_mapping_11,
  153723. quality_mapping_11,
  153724. 2,
  153725. 9000,
  153726. 15000,
  153727. blocksize_11,
  153728. blocksize_11,
  153729. _psy_tone_masteratt_11,
  153730. _psy_tone_0dB,
  153731. _psy_tone_suppress,
  153732. _vp_tonemask_adj_11,
  153733. NULL,
  153734. _vp_tonemask_adj_11,
  153735. _psy_noiseguards_8,
  153736. _psy_noisebias_11,
  153737. _psy_noisebias_11,
  153738. NULL,
  153739. NULL,
  153740. _psy_noise_suppress,
  153741. _psy_compand_8,
  153742. _psy_compand_8_mapping,
  153743. NULL,
  153744. {_noise_start_8,_noise_start_8},
  153745. {_noise_part_8,_noise_part_8},
  153746. _noise_thresh_11,
  153747. _psy_ath_floater_8,
  153748. _psy_ath_abs_8,
  153749. _psy_lowpass_11,
  153750. _psy_global_44,
  153751. _global_mapping_8,
  153752. _psy_stereo_modes_8,
  153753. _floor_books,
  153754. _floor,
  153755. _floor_mapping_11,
  153756. NULL,
  153757. _mapres_template_8_stereo
  153758. };
  153759. ve_setup_data_template ve_setup_11_uncoupled={
  153760. 2,
  153761. rate_mapping_11_uncoupled,
  153762. quality_mapping_11,
  153763. -1,
  153764. 9000,
  153765. 15000,
  153766. blocksize_11,
  153767. blocksize_11,
  153768. _psy_tone_masteratt_11,
  153769. _psy_tone_0dB,
  153770. _psy_tone_suppress,
  153771. _vp_tonemask_adj_11,
  153772. NULL,
  153773. _vp_tonemask_adj_11,
  153774. _psy_noiseguards_8,
  153775. _psy_noisebias_11,
  153776. _psy_noisebias_11,
  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_11,
  153786. _psy_ath_floater_8,
  153787. _psy_ath_abs_8,
  153788. _psy_lowpass_11,
  153789. _psy_global_44,
  153790. _global_mapping_8,
  153791. _psy_stereo_modes_8,
  153792. _floor_books,
  153793. _floor,
  153794. _floor_mapping_11,
  153795. NULL,
  153796. _mapres_template_8_uncoupled
  153797. };
  153798. /*** End of inlined file: setup_11.h ***/
  153799. /*** Start of inlined file: setup_16.h ***/
  153800. /*** Start of inlined file: psych_16.h ***/
  153801. /* stereo mode by base quality level */
  153802. static adj_stereo _psy_stereo_modes_16[4]={
  153803. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153804. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153805. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153806. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153807. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153808. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153809. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153810. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153811. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153812. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153813. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153814. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153815. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153816. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153817. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153818. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153819. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153820. };
  153821. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153822. static att3 _psy_tone_masteratt_16[4]={
  153823. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153824. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153825. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153826. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153827. };
  153828. static vp_adjblock _vp_tonemask_adj_16[4]={
  153829. /* adjust for mode zero */
  153830. /* 63 125 250 500 1 2 4 8 16 */
  153831. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153832. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153833. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153834. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153835. };
  153836. static noise3 _psy_noisebias_16_short[4]={
  153837. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153838. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153839. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153840. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153841. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153842. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153843. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153844. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153845. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153846. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153847. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153848. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153849. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153850. };
  153851. static noise3 _psy_noisebias_16_impulse[4]={
  153852. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153853. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153854. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153855. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153856. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153857. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153858. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153859. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153860. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153861. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153862. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153863. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153864. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153865. };
  153866. static noise3 _psy_noisebias_16[4]={
  153867. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153868. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153869. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153870. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153871. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153872. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153873. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153874. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153875. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153876. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153877. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153878. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153879. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153880. };
  153881. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153882. static int _noise_start_16[3]={ 256,256,9999 };
  153883. static int _noise_part_16[4]={ 8,8,8,8 };
  153884. static int _psy_ath_floater_16[4]={
  153885. -100,-100,-100,-105,
  153886. };
  153887. static int _psy_ath_abs_16[4]={
  153888. -130,-130,-130,-140,
  153889. };
  153890. /*** End of inlined file: psych_16.h ***/
  153891. /*** Start of inlined file: residue_16.h ***/
  153892. /***** residue backends *********************************************/
  153893. static static_bookblock _resbook_16s_0={
  153894. {
  153895. {0},
  153896. {0,0,&_16c0_s_p1_0},
  153897. {0,0,&_16c0_s_p2_0},
  153898. {0,0,&_16c0_s_p3_0},
  153899. {0,0,&_16c0_s_p4_0},
  153900. {0,0,&_16c0_s_p5_0},
  153901. {0,0,&_16c0_s_p6_0},
  153902. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153903. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153904. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153905. }
  153906. };
  153907. static static_bookblock _resbook_16s_1={
  153908. {
  153909. {0},
  153910. {0,0,&_16c1_s_p1_0},
  153911. {0,0,&_16c1_s_p2_0},
  153912. {0,0,&_16c1_s_p3_0},
  153913. {0,0,&_16c1_s_p4_0},
  153914. {0,0,&_16c1_s_p5_0},
  153915. {0,0,&_16c1_s_p6_0},
  153916. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153917. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153918. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153919. }
  153920. };
  153921. static static_bookblock _resbook_16s_2={
  153922. {
  153923. {0},
  153924. {0,0,&_16c2_s_p1_0},
  153925. {0,0,&_16c2_s_p2_0},
  153926. {0,0,&_16c2_s_p3_0},
  153927. {0,0,&_16c2_s_p4_0},
  153928. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153929. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153930. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153931. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153932. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153933. }
  153934. };
  153935. static vorbis_residue_template _res_16s_0[]={
  153936. {2,0, &_residue_44_mid,
  153937. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153938. &_resbook_16s_0,&_resbook_16s_0},
  153939. };
  153940. static vorbis_residue_template _res_16s_1[]={
  153941. {2,0, &_residue_44_mid,
  153942. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153943. &_resbook_16s_1,&_resbook_16s_1},
  153944. {2,0, &_residue_44_mid,
  153945. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153946. &_resbook_16s_1,&_resbook_16s_1}
  153947. };
  153948. static vorbis_residue_template _res_16s_2[]={
  153949. {2,0, &_residue_44_high,
  153950. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153951. &_resbook_16s_2,&_resbook_16s_2},
  153952. {2,0, &_residue_44_high,
  153953. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153954. &_resbook_16s_2,&_resbook_16s_2}
  153955. };
  153956. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153957. { _map_nominal, _res_16s_0 }, /* 0 */
  153958. { _map_nominal, _res_16s_1 }, /* 1 */
  153959. { _map_nominal, _res_16s_2 }, /* 2 */
  153960. };
  153961. static static_bookblock _resbook_16u_0={
  153962. {
  153963. {0},
  153964. {0,0,&_16u0__p1_0},
  153965. {0,0,&_16u0__p2_0},
  153966. {0,0,&_16u0__p3_0},
  153967. {0,0,&_16u0__p4_0},
  153968. {0,0,&_16u0__p5_0},
  153969. {&_16u0__p6_0,&_16u0__p6_1},
  153970. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153971. }
  153972. };
  153973. static static_bookblock _resbook_16u_1={
  153974. {
  153975. {0},
  153976. {0,0,&_16u1__p1_0},
  153977. {0,0,&_16u1__p2_0},
  153978. {0,0,&_16u1__p3_0},
  153979. {0,0,&_16u1__p4_0},
  153980. {0,0,&_16u1__p5_0},
  153981. {0,0,&_16u1__p6_0},
  153982. {&_16u1__p7_0,&_16u1__p7_1},
  153983. {&_16u1__p8_0,&_16u1__p8_1},
  153984. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153985. }
  153986. };
  153987. static static_bookblock _resbook_16u_2={
  153988. {
  153989. {0},
  153990. {0,0,&_16u2_p1_0},
  153991. {0,0,&_16u2_p2_0},
  153992. {0,0,&_16u2_p3_0},
  153993. {0,0,&_16u2_p4_0},
  153994. {&_16u2_p5_0,&_16u2_p5_1},
  153995. {&_16u2_p6_0,&_16u2_p6_1},
  153996. {&_16u2_p7_0,&_16u2_p7_1},
  153997. {&_16u2_p8_0,&_16u2_p8_1},
  153998. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153999. }
  154000. };
  154001. static vorbis_residue_template _res_16u_0[]={
  154002. {1,0, &_residue_44_low_un,
  154003. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154004. &_resbook_16u_0,&_resbook_16u_0},
  154005. };
  154006. static vorbis_residue_template _res_16u_1[]={
  154007. {1,0, &_residue_44_mid_un,
  154008. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154009. &_resbook_16u_1,&_resbook_16u_1},
  154010. {1,0, &_residue_44_mid_un,
  154011. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154012. &_resbook_16u_1,&_resbook_16u_1}
  154013. };
  154014. static vorbis_residue_template _res_16u_2[]={
  154015. {1,0, &_residue_44_hi_un,
  154016. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154017. &_resbook_16u_2,&_resbook_16u_2},
  154018. {1,0, &_residue_44_hi_un,
  154019. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154020. &_resbook_16u_2,&_resbook_16u_2}
  154021. };
  154022. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154023. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154024. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154025. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154026. };
  154027. /*** End of inlined file: residue_16.h ***/
  154028. static int blocksize_16_short[3]={
  154029. 1024,512,512
  154030. };
  154031. static int blocksize_16_long[3]={
  154032. 1024,1024,1024
  154033. };
  154034. static int _floor_mapping_16_short[3]={
  154035. 9,3,3
  154036. };
  154037. static int _floor_mapping_16[3]={
  154038. 9,9,9
  154039. };
  154040. static double rate_mapping_16[4]={
  154041. 12000.,20000.,44000.,86000.
  154042. };
  154043. static double rate_mapping_16_uncoupled[4]={
  154044. 16000.,28000.,64000.,100000.
  154045. };
  154046. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154047. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154048. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154049. ve_setup_data_template ve_setup_16_stereo={
  154050. 3,
  154051. rate_mapping_16,
  154052. quality_mapping_16,
  154053. 2,
  154054. 15000,
  154055. 19000,
  154056. blocksize_16_short,
  154057. blocksize_16_long,
  154058. _psy_tone_masteratt_16,
  154059. _psy_tone_0dB,
  154060. _psy_tone_suppress,
  154061. _vp_tonemask_adj_16,
  154062. _vp_tonemask_adj_16,
  154063. _vp_tonemask_adj_16,
  154064. _psy_noiseguards_8,
  154065. _psy_noisebias_16_impulse,
  154066. _psy_noisebias_16_short,
  154067. _psy_noisebias_16_short,
  154068. _psy_noisebias_16,
  154069. _psy_noise_suppress,
  154070. _psy_compand_8,
  154071. _psy_compand_16_mapping,
  154072. _psy_compand_16_mapping,
  154073. {_noise_start_16,_noise_start_16},
  154074. { _noise_part_16, _noise_part_16},
  154075. _noise_thresh_16,
  154076. _psy_ath_floater_16,
  154077. _psy_ath_abs_16,
  154078. _psy_lowpass_16,
  154079. _psy_global_44,
  154080. _global_mapping_16,
  154081. _psy_stereo_modes_16,
  154082. _floor_books,
  154083. _floor,
  154084. _floor_mapping_16_short,
  154085. _floor_mapping_16,
  154086. _mapres_template_16_stereo
  154087. };
  154088. ve_setup_data_template ve_setup_16_uncoupled={
  154089. 3,
  154090. rate_mapping_16_uncoupled,
  154091. quality_mapping_16,
  154092. -1,
  154093. 15000,
  154094. 19000,
  154095. blocksize_16_short,
  154096. blocksize_16_long,
  154097. _psy_tone_masteratt_16,
  154098. _psy_tone_0dB,
  154099. _psy_tone_suppress,
  154100. _vp_tonemask_adj_16,
  154101. _vp_tonemask_adj_16,
  154102. _vp_tonemask_adj_16,
  154103. _psy_noiseguards_8,
  154104. _psy_noisebias_16_impulse,
  154105. _psy_noisebias_16_short,
  154106. _psy_noisebias_16_short,
  154107. _psy_noisebias_16,
  154108. _psy_noise_suppress,
  154109. _psy_compand_8,
  154110. _psy_compand_16_mapping,
  154111. _psy_compand_16_mapping,
  154112. {_noise_start_16,_noise_start_16},
  154113. { _noise_part_16, _noise_part_16},
  154114. _noise_thresh_16,
  154115. _psy_ath_floater_16,
  154116. _psy_ath_abs_16,
  154117. _psy_lowpass_16,
  154118. _psy_global_44,
  154119. _global_mapping_16,
  154120. _psy_stereo_modes_16,
  154121. _floor_books,
  154122. _floor,
  154123. _floor_mapping_16_short,
  154124. _floor_mapping_16,
  154125. _mapres_template_16_uncoupled
  154126. };
  154127. /*** End of inlined file: setup_16.h ***/
  154128. /*** Start of inlined file: setup_22.h ***/
  154129. static double rate_mapping_22[4]={
  154130. 15000.,20000.,44000.,86000.
  154131. };
  154132. static double rate_mapping_22_uncoupled[4]={
  154133. 16000.,28000.,50000.,90000.
  154134. };
  154135. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154136. ve_setup_data_template ve_setup_22_stereo={
  154137. 3,
  154138. rate_mapping_22,
  154139. quality_mapping_16,
  154140. 2,
  154141. 19000,
  154142. 26000,
  154143. blocksize_16_short,
  154144. blocksize_16_long,
  154145. _psy_tone_masteratt_16,
  154146. _psy_tone_0dB,
  154147. _psy_tone_suppress,
  154148. _vp_tonemask_adj_16,
  154149. _vp_tonemask_adj_16,
  154150. _vp_tonemask_adj_16,
  154151. _psy_noiseguards_8,
  154152. _psy_noisebias_16_impulse,
  154153. _psy_noisebias_16_short,
  154154. _psy_noisebias_16_short,
  154155. _psy_noisebias_16,
  154156. _psy_noise_suppress,
  154157. _psy_compand_8,
  154158. _psy_compand_8_mapping,
  154159. _psy_compand_8_mapping,
  154160. {_noise_start_16,_noise_start_16},
  154161. { _noise_part_16, _noise_part_16},
  154162. _noise_thresh_16,
  154163. _psy_ath_floater_16,
  154164. _psy_ath_abs_16,
  154165. _psy_lowpass_22,
  154166. _psy_global_44,
  154167. _global_mapping_16,
  154168. _psy_stereo_modes_16,
  154169. _floor_books,
  154170. _floor,
  154171. _floor_mapping_16_short,
  154172. _floor_mapping_16,
  154173. _mapres_template_16_stereo
  154174. };
  154175. ve_setup_data_template ve_setup_22_uncoupled={
  154176. 3,
  154177. rate_mapping_22_uncoupled,
  154178. quality_mapping_16,
  154179. -1,
  154180. 19000,
  154181. 26000,
  154182. blocksize_16_short,
  154183. blocksize_16_long,
  154184. _psy_tone_masteratt_16,
  154185. _psy_tone_0dB,
  154186. _psy_tone_suppress,
  154187. _vp_tonemask_adj_16,
  154188. _vp_tonemask_adj_16,
  154189. _vp_tonemask_adj_16,
  154190. _psy_noiseguards_8,
  154191. _psy_noisebias_16_impulse,
  154192. _psy_noisebias_16_short,
  154193. _psy_noisebias_16_short,
  154194. _psy_noisebias_16,
  154195. _psy_noise_suppress,
  154196. _psy_compand_8,
  154197. _psy_compand_8_mapping,
  154198. _psy_compand_8_mapping,
  154199. {_noise_start_16,_noise_start_16},
  154200. { _noise_part_16, _noise_part_16},
  154201. _noise_thresh_16,
  154202. _psy_ath_floater_16,
  154203. _psy_ath_abs_16,
  154204. _psy_lowpass_22,
  154205. _psy_global_44,
  154206. _global_mapping_16,
  154207. _psy_stereo_modes_16,
  154208. _floor_books,
  154209. _floor,
  154210. _floor_mapping_16_short,
  154211. _floor_mapping_16,
  154212. _mapres_template_16_uncoupled
  154213. };
  154214. /*** End of inlined file: setup_22.h ***/
  154215. /*** Start of inlined file: setup_X.h ***/
  154216. static double rate_mapping_X[12]={
  154217. -1.,-1.,-1.,-1.,-1.,-1.,
  154218. -1.,-1.,-1.,-1.,-1.,-1.
  154219. };
  154220. ve_setup_data_template ve_setup_X_stereo={
  154221. 11,
  154222. rate_mapping_X,
  154223. quality_mapping_44,
  154224. 2,
  154225. 50000,
  154226. 200000,
  154227. blocksize_short_44,
  154228. blocksize_long_44,
  154229. _psy_tone_masteratt_44,
  154230. _psy_tone_0dB,
  154231. _psy_tone_suppress,
  154232. _vp_tonemask_adj_otherblock,
  154233. _vp_tonemask_adj_longblock,
  154234. _vp_tonemask_adj_otherblock,
  154235. _psy_noiseguards_44,
  154236. _psy_noisebias_impulse,
  154237. _psy_noisebias_padding,
  154238. _psy_noisebias_trans,
  154239. _psy_noisebias_long,
  154240. _psy_noise_suppress,
  154241. _psy_compand_44,
  154242. _psy_compand_short_mapping,
  154243. _psy_compand_long_mapping,
  154244. {_noise_start_short_44,_noise_start_long_44},
  154245. {_noise_part_short_44,_noise_part_long_44},
  154246. _noise_thresh_44,
  154247. _psy_ath_floater,
  154248. _psy_ath_abs,
  154249. _psy_lowpass_44,
  154250. _psy_global_44,
  154251. _global_mapping_44,
  154252. _psy_stereo_modes_44,
  154253. _floor_books,
  154254. _floor,
  154255. _floor_short_mapping_44,
  154256. _floor_long_mapping_44,
  154257. _mapres_template_44_stereo
  154258. };
  154259. ve_setup_data_template ve_setup_X_uncoupled={
  154260. 11,
  154261. rate_mapping_X,
  154262. quality_mapping_44,
  154263. -1,
  154264. 50000,
  154265. 200000,
  154266. blocksize_short_44,
  154267. blocksize_long_44,
  154268. _psy_tone_masteratt_44,
  154269. _psy_tone_0dB,
  154270. _psy_tone_suppress,
  154271. _vp_tonemask_adj_otherblock,
  154272. _vp_tonemask_adj_longblock,
  154273. _vp_tonemask_adj_otherblock,
  154274. _psy_noiseguards_44,
  154275. _psy_noisebias_impulse,
  154276. _psy_noisebias_padding,
  154277. _psy_noisebias_trans,
  154278. _psy_noisebias_long,
  154279. _psy_noise_suppress,
  154280. _psy_compand_44,
  154281. _psy_compand_short_mapping,
  154282. _psy_compand_long_mapping,
  154283. {_noise_start_short_44,_noise_start_long_44},
  154284. {_noise_part_short_44,_noise_part_long_44},
  154285. _noise_thresh_44,
  154286. _psy_ath_floater,
  154287. _psy_ath_abs,
  154288. _psy_lowpass_44,
  154289. _psy_global_44,
  154290. _global_mapping_44,
  154291. NULL,
  154292. _floor_books,
  154293. _floor,
  154294. _floor_short_mapping_44,
  154295. _floor_long_mapping_44,
  154296. _mapres_template_44_uncoupled
  154297. };
  154298. ve_setup_data_template ve_setup_XX_stereo={
  154299. 2,
  154300. rate_mapping_X,
  154301. quality_mapping_8,
  154302. 2,
  154303. 0,
  154304. 8000,
  154305. blocksize_8,
  154306. blocksize_8,
  154307. _psy_tone_masteratt_8,
  154308. _psy_tone_0dB,
  154309. _psy_tone_suppress,
  154310. _vp_tonemask_adj_8,
  154311. NULL,
  154312. _vp_tonemask_adj_8,
  154313. _psy_noiseguards_8,
  154314. _psy_noisebias_8,
  154315. _psy_noisebias_8,
  154316. NULL,
  154317. NULL,
  154318. _psy_noise_suppress,
  154319. _psy_compand_8,
  154320. _psy_compand_8_mapping,
  154321. NULL,
  154322. {_noise_start_8,_noise_start_8},
  154323. {_noise_part_8,_noise_part_8},
  154324. _noise_thresh_5only,
  154325. _psy_ath_floater_8,
  154326. _psy_ath_abs_8,
  154327. _psy_lowpass_8,
  154328. _psy_global_44,
  154329. _global_mapping_8,
  154330. _psy_stereo_modes_8,
  154331. _floor_books,
  154332. _floor,
  154333. _floor_mapping_8,
  154334. NULL,
  154335. _mapres_template_8_stereo
  154336. };
  154337. ve_setup_data_template ve_setup_XX_uncoupled={
  154338. 2,
  154339. rate_mapping_X,
  154340. quality_mapping_8,
  154341. -1,
  154342. 0,
  154343. 8000,
  154344. blocksize_8,
  154345. blocksize_8,
  154346. _psy_tone_masteratt_8,
  154347. _psy_tone_0dB,
  154348. _psy_tone_suppress,
  154349. _vp_tonemask_adj_8,
  154350. NULL,
  154351. _vp_tonemask_adj_8,
  154352. _psy_noiseguards_8,
  154353. _psy_noisebias_8,
  154354. _psy_noisebias_8,
  154355. NULL,
  154356. NULL,
  154357. _psy_noise_suppress,
  154358. _psy_compand_8,
  154359. _psy_compand_8_mapping,
  154360. NULL,
  154361. {_noise_start_8,_noise_start_8},
  154362. {_noise_part_8,_noise_part_8},
  154363. _noise_thresh_5only,
  154364. _psy_ath_floater_8,
  154365. _psy_ath_abs_8,
  154366. _psy_lowpass_8,
  154367. _psy_global_44,
  154368. _global_mapping_8,
  154369. _psy_stereo_modes_8,
  154370. _floor_books,
  154371. _floor,
  154372. _floor_mapping_8,
  154373. NULL,
  154374. _mapres_template_8_uncoupled
  154375. };
  154376. /*** End of inlined file: setup_X.h ***/
  154377. static ve_setup_data_template *setup_list[]={
  154378. &ve_setup_44_stereo,
  154379. &ve_setup_44_uncoupled,
  154380. &ve_setup_32_stereo,
  154381. &ve_setup_32_uncoupled,
  154382. &ve_setup_22_stereo,
  154383. &ve_setup_22_uncoupled,
  154384. &ve_setup_16_stereo,
  154385. &ve_setup_16_uncoupled,
  154386. &ve_setup_11_stereo,
  154387. &ve_setup_11_uncoupled,
  154388. &ve_setup_8_stereo,
  154389. &ve_setup_8_uncoupled,
  154390. &ve_setup_X_stereo,
  154391. &ve_setup_X_uncoupled,
  154392. &ve_setup_XX_stereo,
  154393. &ve_setup_XX_uncoupled,
  154394. 0
  154395. };
  154396. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154397. if(vi && vi->codec_setup){
  154398. vi->version=0;
  154399. vi->channels=ch;
  154400. vi->rate=rate;
  154401. return(0);
  154402. }
  154403. return(OV_EINVAL);
  154404. }
  154405. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154406. static_codebook ***books,
  154407. vorbis_info_floor1 *in,
  154408. int *x){
  154409. int i,k,is=s;
  154410. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154411. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154412. memcpy(f,in+x[is],sizeof(*f));
  154413. /* fill in the lowpass field, even if it's temporary */
  154414. f->n=ci->blocksizes[block]>>1;
  154415. /* books */
  154416. {
  154417. int partitions=f->partitions;
  154418. int maxclass=-1;
  154419. int maxbook=-1;
  154420. for(i=0;i<partitions;i++)
  154421. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154422. for(i=0;i<=maxclass;i++){
  154423. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154424. f->class_book[i]+=ci->books;
  154425. for(k=0;k<(1<<f->class_subs[i]);k++){
  154426. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154427. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154428. }
  154429. }
  154430. for(i=0;i<=maxbook;i++)
  154431. ci->book_param[ci->books++]=books[x[is]][i];
  154432. }
  154433. /* for now, we're only using floor 1 */
  154434. ci->floor_type[ci->floors]=1;
  154435. ci->floor_param[ci->floors]=f;
  154436. ci->floors++;
  154437. return;
  154438. }
  154439. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154440. vorbis_info_psy_global *in,
  154441. double *x){
  154442. int i,is=s;
  154443. double ds=s-is;
  154444. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154445. vorbis_info_psy_global *g=&ci->psy_g_param;
  154446. memcpy(g,in+(int)x[is],sizeof(*g));
  154447. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154448. is=(int)ds;
  154449. ds-=is;
  154450. if(ds==0 && is>0){
  154451. is--;
  154452. ds=1.;
  154453. }
  154454. /* interpolate the trigger threshholds */
  154455. for(i=0;i<4;i++){
  154456. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154457. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154458. }
  154459. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154460. return;
  154461. }
  154462. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154463. highlevel_encode_setup *hi,
  154464. adj_stereo *p){
  154465. float s=hi->stereo_point_setting;
  154466. int i,is=s;
  154467. double ds=s-is;
  154468. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154469. vorbis_info_psy_global *g=&ci->psy_g_param;
  154470. if(p){
  154471. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154472. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154473. if(hi->managed){
  154474. /* interpolate the kHz threshholds */
  154475. for(i=0;i<PACKETBLOBS;i++){
  154476. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154477. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154478. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154479. g->coupling_pkHz[i]=kHz;
  154480. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154481. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154482. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154483. }
  154484. }else{
  154485. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154486. for(i=0;i<PACKETBLOBS;i++){
  154487. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154488. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154489. g->coupling_pkHz[i]=kHz;
  154490. }
  154491. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154492. for(i=0;i<PACKETBLOBS;i++){
  154493. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154494. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154495. }
  154496. }
  154497. }else{
  154498. for(i=0;i<PACKETBLOBS;i++){
  154499. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154500. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154501. }
  154502. }
  154503. return;
  154504. }
  154505. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154506. int *nn_start,
  154507. int *nn_partition,
  154508. double *nn_thresh,
  154509. int block){
  154510. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154511. vorbis_info_psy *p=ci->psy_param[block];
  154512. highlevel_encode_setup *hi=&ci->hi;
  154513. int is=s;
  154514. if(block>=ci->psys)
  154515. ci->psys=block+1;
  154516. if(!p){
  154517. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154518. ci->psy_param[block]=p;
  154519. }
  154520. memcpy(p,&_psy_info_template,sizeof(*p));
  154521. p->blockflag=block>>1;
  154522. if(hi->noise_normalize_p){
  154523. p->normal_channel_p=1;
  154524. p->normal_point_p=1;
  154525. p->normal_start=nn_start[is];
  154526. p->normal_partition=nn_partition[is];
  154527. p->normal_thresh=nn_thresh[is];
  154528. }
  154529. return;
  154530. }
  154531. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154532. att3 *att,
  154533. int *max,
  154534. vp_adjblock *in){
  154535. int i,is=s;
  154536. double ds=s-is;
  154537. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154538. vorbis_info_psy *p=ci->psy_param[block];
  154539. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154540. filling the values in here */
  154541. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154542. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154543. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154544. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154545. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154546. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154547. for(i=0;i<P_BANDS;i++)
  154548. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154549. return;
  154550. }
  154551. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154552. compandblock *in, double *x){
  154553. int i,is=s;
  154554. double ds=s-is;
  154555. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154556. vorbis_info_psy *p=ci->psy_param[block];
  154557. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154558. is=(int)ds;
  154559. ds-=is;
  154560. if(ds==0 && is>0){
  154561. is--;
  154562. ds=1.;
  154563. }
  154564. /* interpolate the compander settings */
  154565. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154566. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154567. return;
  154568. }
  154569. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154570. int *suppress){
  154571. int is=s;
  154572. double ds=s-is;
  154573. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154574. vorbis_info_psy *p=ci->psy_param[block];
  154575. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154576. return;
  154577. }
  154578. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154579. int *suppress,
  154580. noise3 *in,
  154581. noiseguard *guard,
  154582. double userbias){
  154583. int i,is=s,j;
  154584. double ds=s-is;
  154585. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154586. vorbis_info_psy *p=ci->psy_param[block];
  154587. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154588. p->noisewindowlomin=guard[block].lo;
  154589. p->noisewindowhimin=guard[block].hi;
  154590. p->noisewindowfixed=guard[block].fixed;
  154591. for(j=0;j<P_NOISECURVES;j++)
  154592. for(i=0;i<P_BANDS;i++)
  154593. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154594. /* impulse blocks may take a user specified bias to boost the
  154595. nominal/high noise encoding depth */
  154596. for(j=0;j<P_NOISECURVES;j++){
  154597. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154598. for(i=0;i<P_BANDS;i++){
  154599. p->noiseoff[j][i]+=userbias;
  154600. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154601. }
  154602. }
  154603. return;
  154604. }
  154605. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154606. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154607. vorbis_info_psy *p=ci->psy_param[block];
  154608. p->ath_adjatt=ci->hi.ath_floating_dB;
  154609. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154610. return;
  154611. }
  154612. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154613. int i;
  154614. for(i=0;i<ci->books;i++)
  154615. if(ci->book_param[i]==book)return(i);
  154616. return(ci->books++);
  154617. }
  154618. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154619. int *shortb,int *longb){
  154620. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154621. int is=s;
  154622. int blockshort=shortb[is];
  154623. int blocklong=longb[is];
  154624. ci->blocksizes[0]=blockshort;
  154625. ci->blocksizes[1]=blocklong;
  154626. }
  154627. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154628. int number, int block,
  154629. vorbis_residue_template *res){
  154630. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154631. int i,n;
  154632. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154633. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154634. memcpy(r,res->res,sizeof(*r));
  154635. if(ci->residues<=number)ci->residues=number+1;
  154636. switch(ci->blocksizes[block]){
  154637. case 64:case 128:case 256:
  154638. r->grouping=16;
  154639. break;
  154640. default:
  154641. r->grouping=32;
  154642. break;
  154643. }
  154644. ci->residue_type[number]=res->res_type;
  154645. /* to be adjusted by lowpass/pointlimit later */
  154646. n=r->end=ci->blocksizes[block]>>1;
  154647. if(res->res_type==2)
  154648. n=r->end*=vi->channels;
  154649. /* fill in all the books */
  154650. {
  154651. int booklist=0,k;
  154652. if(ci->hi.managed){
  154653. for(i=0;i<r->partitions;i++)
  154654. for(k=0;k<3;k++)
  154655. if(res->books_base_managed->books[i][k])
  154656. r->secondstages[i]|=(1<<k);
  154657. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154658. ci->book_param[r->groupbook]=res->book_aux_managed;
  154659. for(i=0;i<r->partitions;i++){
  154660. for(k=0;k<3;k++){
  154661. if(res->books_base_managed->books[i][k]){
  154662. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154663. r->booklist[booklist++]=bookid;
  154664. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154665. }
  154666. }
  154667. }
  154668. }else{
  154669. for(i=0;i<r->partitions;i++)
  154670. for(k=0;k<3;k++)
  154671. if(res->books_base->books[i][k])
  154672. r->secondstages[i]|=(1<<k);
  154673. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154674. ci->book_param[r->groupbook]=res->book_aux;
  154675. for(i=0;i<r->partitions;i++){
  154676. for(k=0;k<3;k++){
  154677. if(res->books_base->books[i][k]){
  154678. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154679. r->booklist[booklist++]=bookid;
  154680. ci->book_param[bookid]=res->books_base->books[i][k];
  154681. }
  154682. }
  154683. }
  154684. }
  154685. }
  154686. /* lowpass setup/pointlimit */
  154687. {
  154688. double freq=ci->hi.lowpass_kHz*1000.;
  154689. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154690. double nyq=vi->rate/2.;
  154691. long blocksize=ci->blocksizes[block]>>1;
  154692. /* lowpass needs to be set in the floor and the residue. */
  154693. if(freq>nyq)freq=nyq;
  154694. /* in the floor, the granularity can be very fine; it doesn't alter
  154695. the encoding structure, only the samples used to fit the floor
  154696. approximation */
  154697. f->n=freq/nyq*blocksize;
  154698. /* this res may by limited by the maximum pointlimit of the mode,
  154699. not the lowpass. the floor is always lowpass limited. */
  154700. if(res->limit_type){
  154701. if(ci->hi.managed)
  154702. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154703. else
  154704. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154705. if(freq>nyq)freq=nyq;
  154706. }
  154707. /* in the residue, we're constrained, physically, by partition
  154708. boundaries. We still lowpass 'wherever', but we have to round up
  154709. here to next boundary, or the vorbis spec will round it *down* to
  154710. previous boundary in encode/decode */
  154711. if(ci->residue_type[block]==2)
  154712. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154713. r->grouping;
  154714. else
  154715. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154716. r->grouping;
  154717. }
  154718. }
  154719. /* we assume two maps in this encoder */
  154720. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154721. vorbis_mapping_template *maps){
  154722. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154723. int i,j,is=s,modes=2;
  154724. vorbis_info_mapping0 *map=maps[is].map;
  154725. vorbis_info_mode *mode=_mode_template;
  154726. vorbis_residue_template *res=maps[is].res;
  154727. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154728. for(i=0;i<modes;i++){
  154729. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154730. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154731. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154732. if(i>=ci->modes)ci->modes=i+1;
  154733. ci->map_type[i]=0;
  154734. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154735. if(i>=ci->maps)ci->maps=i+1;
  154736. for(j=0;j<map[i].submaps;j++)
  154737. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154738. ,res+map[i].residuesubmap[j]);
  154739. }
  154740. }
  154741. static double setting_to_approx_bitrate(vorbis_info *vi){
  154742. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154743. highlevel_encode_setup *hi=&ci->hi;
  154744. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154745. int is=hi->base_setting;
  154746. double ds=hi->base_setting-is;
  154747. int ch=vi->channels;
  154748. double *r=setup->rate_mapping;
  154749. if(r==NULL)
  154750. return(-1);
  154751. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154752. }
  154753. static void get_setup_template(vorbis_info *vi,
  154754. long ch,long srate,
  154755. double req,int q_or_bitrate){
  154756. int i=0,j;
  154757. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154758. highlevel_encode_setup *hi=&ci->hi;
  154759. if(q_or_bitrate)req/=ch;
  154760. while(setup_list[i]){
  154761. if(setup_list[i]->coupling_restriction==-1 ||
  154762. setup_list[i]->coupling_restriction==ch){
  154763. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154764. srate<=setup_list[i]->samplerate_max_restriction){
  154765. int mappings=setup_list[i]->mappings;
  154766. double *map=(q_or_bitrate?
  154767. setup_list[i]->rate_mapping:
  154768. setup_list[i]->quality_mapping);
  154769. /* the template matches. Does the requested quality mode
  154770. fall within this template's modes? */
  154771. if(req<map[0]){++i;continue;}
  154772. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154773. for(j=0;j<mappings;j++)
  154774. if(req>=map[j] && req<map[j+1])break;
  154775. /* an all-points match */
  154776. hi->setup=setup_list[i];
  154777. if(j==mappings)
  154778. hi->base_setting=j-.001;
  154779. else{
  154780. float low=map[j];
  154781. float high=map[j+1];
  154782. float del=(req-low)/(high-low);
  154783. hi->base_setting=j+del;
  154784. }
  154785. return;
  154786. }
  154787. }
  154788. i++;
  154789. }
  154790. hi->setup=NULL;
  154791. }
  154792. /* encoders will need to use vorbis_info_init beforehand and call
  154793. vorbis_info clear when all done */
  154794. /* two interfaces; this, more detailed one, and later a convenience
  154795. layer on top */
  154796. /* the final setup call */
  154797. int vorbis_encode_setup_init(vorbis_info *vi){
  154798. int i0=0,singleblock=0;
  154799. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154800. ve_setup_data_template *setup=NULL;
  154801. highlevel_encode_setup *hi=&ci->hi;
  154802. if(ci==NULL)return(OV_EINVAL);
  154803. if(!hi->impulse_block_p)i0=1;
  154804. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154805. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154806. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154807. /* again, bound this to avoid the app shooting itself int he foot
  154808. too badly */
  154809. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154810. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154811. /* get the appropriate setup template; matches the fetch in previous
  154812. stages */
  154813. setup=(ve_setup_data_template *)hi->setup;
  154814. if(setup==NULL)return(OV_EINVAL);
  154815. hi->set_in_stone=1;
  154816. /* choose block sizes from configured sizes as well as paying
  154817. attention to long_block_p and short_block_p. If the configured
  154818. short and long blocks are the same length, we set long_block_p
  154819. and unset short_block_p */
  154820. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154821. setup->blocksize_short,
  154822. setup->blocksize_long);
  154823. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154824. /* floor setup; choose proper floor params. Allocated on the floor
  154825. stack in order; if we alloc only long floor, it's 0 */
  154826. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154827. setup->floor_books,
  154828. setup->floor_params,
  154829. setup->floor_short_mapping);
  154830. if(!singleblock)
  154831. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154832. setup->floor_books,
  154833. setup->floor_params,
  154834. setup->floor_long_mapping);
  154835. /* setup of [mostly] short block detection and stereo*/
  154836. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154837. setup->global_params,
  154838. setup->global_mapping);
  154839. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154840. /* basic psych setup and noise normalization */
  154841. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154842. setup->psy_noise_normal_start[0],
  154843. setup->psy_noise_normal_partition[0],
  154844. setup->psy_noise_normal_thresh,
  154845. 0);
  154846. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154847. setup->psy_noise_normal_start[0],
  154848. setup->psy_noise_normal_partition[0],
  154849. setup->psy_noise_normal_thresh,
  154850. 1);
  154851. if(!singleblock){
  154852. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154853. setup->psy_noise_normal_start[1],
  154854. setup->psy_noise_normal_partition[1],
  154855. setup->psy_noise_normal_thresh,
  154856. 2);
  154857. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154858. setup->psy_noise_normal_start[1],
  154859. setup->psy_noise_normal_partition[1],
  154860. setup->psy_noise_normal_thresh,
  154861. 3);
  154862. }
  154863. /* tone masking setup */
  154864. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154865. setup->psy_tone_masteratt,
  154866. setup->psy_tone_0dB,
  154867. setup->psy_tone_adj_impulse);
  154868. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154869. setup->psy_tone_masteratt,
  154870. setup->psy_tone_0dB,
  154871. setup->psy_tone_adj_other);
  154872. if(!singleblock){
  154873. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154874. setup->psy_tone_masteratt,
  154875. setup->psy_tone_0dB,
  154876. setup->psy_tone_adj_other);
  154877. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154878. setup->psy_tone_masteratt,
  154879. setup->psy_tone_0dB,
  154880. setup->psy_tone_adj_long);
  154881. }
  154882. /* noise companding setup */
  154883. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154884. setup->psy_noise_compand,
  154885. setup->psy_noise_compand_short_mapping);
  154886. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154887. setup->psy_noise_compand,
  154888. setup->psy_noise_compand_short_mapping);
  154889. if(!singleblock){
  154890. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154891. setup->psy_noise_compand,
  154892. setup->psy_noise_compand_long_mapping);
  154893. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154894. setup->psy_noise_compand,
  154895. setup->psy_noise_compand_long_mapping);
  154896. }
  154897. /* peak guarding setup */
  154898. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154899. setup->psy_tone_dBsuppress);
  154900. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154901. setup->psy_tone_dBsuppress);
  154902. if(!singleblock){
  154903. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154904. setup->psy_tone_dBsuppress);
  154905. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154906. setup->psy_tone_dBsuppress);
  154907. }
  154908. /* noise bias setup */
  154909. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154910. setup->psy_noise_dBsuppress,
  154911. setup->psy_noise_bias_impulse,
  154912. setup->psy_noiseguards,
  154913. (i0==0?hi->impulse_noisetune:0.));
  154914. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154915. setup->psy_noise_dBsuppress,
  154916. setup->psy_noise_bias_padding,
  154917. setup->psy_noiseguards,0.);
  154918. if(!singleblock){
  154919. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154920. setup->psy_noise_dBsuppress,
  154921. setup->psy_noise_bias_trans,
  154922. setup->psy_noiseguards,0.);
  154923. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154924. setup->psy_noise_dBsuppress,
  154925. setup->psy_noise_bias_long,
  154926. setup->psy_noiseguards,0.);
  154927. }
  154928. vorbis_encode_ath_setup(vi,0);
  154929. vorbis_encode_ath_setup(vi,1);
  154930. if(!singleblock){
  154931. vorbis_encode_ath_setup(vi,2);
  154932. vorbis_encode_ath_setup(vi,3);
  154933. }
  154934. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154935. /* set bitrate readonlies and management */
  154936. if(hi->bitrate_av>0)
  154937. vi->bitrate_nominal=hi->bitrate_av;
  154938. else{
  154939. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154940. }
  154941. vi->bitrate_lower=hi->bitrate_min;
  154942. vi->bitrate_upper=hi->bitrate_max;
  154943. if(hi->bitrate_av)
  154944. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154945. else
  154946. vi->bitrate_window=0.;
  154947. if(hi->managed){
  154948. ci->bi.avg_rate=hi->bitrate_av;
  154949. ci->bi.min_rate=hi->bitrate_min;
  154950. ci->bi.max_rate=hi->bitrate_max;
  154951. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154952. ci->bi.reservoir_bias=
  154953. hi->bitrate_reservoir_bias;
  154954. ci->bi.slew_damp=hi->bitrate_av_damp;
  154955. }
  154956. return(0);
  154957. }
  154958. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154959. long channels,
  154960. long rate){
  154961. int ret=0,i,is;
  154962. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154963. highlevel_encode_setup *hi=&ci->hi;
  154964. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154965. double ds;
  154966. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154967. if(ret)return(ret);
  154968. is=hi->base_setting;
  154969. ds=hi->base_setting-is;
  154970. hi->short_setting=hi->base_setting;
  154971. hi->long_setting=hi->base_setting;
  154972. hi->managed=0;
  154973. hi->impulse_block_p=1;
  154974. hi->noise_normalize_p=1;
  154975. hi->stereo_point_setting=hi->base_setting;
  154976. hi->lowpass_kHz=
  154977. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154978. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154979. setup->psy_ath_float[is+1]*ds;
  154980. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154981. setup->psy_ath_abs[is+1]*ds;
  154982. hi->amplitude_track_dBpersec=-6.;
  154983. hi->trigger_setting=hi->base_setting;
  154984. for(i=0;i<4;i++){
  154985. hi->block[i].tone_mask_setting=hi->base_setting;
  154986. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154987. hi->block[i].noise_bias_setting=hi->base_setting;
  154988. hi->block[i].noise_compand_setting=hi->base_setting;
  154989. }
  154990. return(ret);
  154991. }
  154992. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154993. long channels,
  154994. long rate,
  154995. float quality){
  154996. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154997. highlevel_encode_setup *hi=&ci->hi;
  154998. quality+=.0000001;
  154999. if(quality>=1.)quality=.9999;
  155000. get_setup_template(vi,channels,rate,quality,0);
  155001. if(!hi->setup)return OV_EIMPL;
  155002. return vorbis_encode_setup_setting(vi,channels,rate);
  155003. }
  155004. int vorbis_encode_init_vbr(vorbis_info *vi,
  155005. long channels,
  155006. long rate,
  155007. float base_quality /* 0. to 1. */
  155008. ){
  155009. int ret=0;
  155010. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155011. if(ret){
  155012. vorbis_info_clear(vi);
  155013. return ret;
  155014. }
  155015. ret=vorbis_encode_setup_init(vi);
  155016. if(ret)
  155017. vorbis_info_clear(vi);
  155018. return(ret);
  155019. }
  155020. int vorbis_encode_setup_managed(vorbis_info *vi,
  155021. long channels,
  155022. long rate,
  155023. long max_bitrate,
  155024. long nominal_bitrate,
  155025. long min_bitrate){
  155026. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155027. highlevel_encode_setup *hi=&ci->hi;
  155028. double tnominal=nominal_bitrate;
  155029. int ret=0;
  155030. if(nominal_bitrate<=0.){
  155031. if(max_bitrate>0.){
  155032. if(min_bitrate>0.)
  155033. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155034. else
  155035. nominal_bitrate=max_bitrate*.875;
  155036. }else{
  155037. if(min_bitrate>0.){
  155038. nominal_bitrate=min_bitrate;
  155039. }else{
  155040. return(OV_EINVAL);
  155041. }
  155042. }
  155043. }
  155044. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155045. if(!hi->setup)return OV_EIMPL;
  155046. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155047. if(ret){
  155048. vorbis_info_clear(vi);
  155049. return ret;
  155050. }
  155051. /* initialize management with sane defaults */
  155052. hi->managed=1;
  155053. hi->bitrate_min=min_bitrate;
  155054. hi->bitrate_max=max_bitrate;
  155055. hi->bitrate_av=tnominal;
  155056. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155057. hi->bitrate_reservoir=nominal_bitrate*2;
  155058. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155059. return(ret);
  155060. }
  155061. int vorbis_encode_init(vorbis_info *vi,
  155062. long channels,
  155063. long rate,
  155064. long max_bitrate,
  155065. long nominal_bitrate,
  155066. long min_bitrate){
  155067. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155068. max_bitrate,
  155069. nominal_bitrate,
  155070. min_bitrate);
  155071. if(ret){
  155072. vorbis_info_clear(vi);
  155073. return(ret);
  155074. }
  155075. ret=vorbis_encode_setup_init(vi);
  155076. if(ret)
  155077. vorbis_info_clear(vi);
  155078. return(ret);
  155079. }
  155080. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155081. if(vi){
  155082. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155083. highlevel_encode_setup *hi=&ci->hi;
  155084. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155085. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155086. switch(number){
  155087. /* now deprecated *****************/
  155088. case OV_ECTL_RATEMANAGE_GET:
  155089. {
  155090. struct ovectl_ratemanage_arg *ai=
  155091. (struct ovectl_ratemanage_arg *)arg;
  155092. ai->management_active=hi->managed;
  155093. ai->bitrate_hard_window=ai->bitrate_av_window=
  155094. (double)hi->bitrate_reservoir/vi->rate;
  155095. ai->bitrate_av_window_center=1.;
  155096. ai->bitrate_hard_min=hi->bitrate_min;
  155097. ai->bitrate_hard_max=hi->bitrate_max;
  155098. ai->bitrate_av_lo=hi->bitrate_av;
  155099. ai->bitrate_av_hi=hi->bitrate_av;
  155100. }
  155101. return(0);
  155102. /* now deprecated *****************/
  155103. case OV_ECTL_RATEMANAGE_SET:
  155104. {
  155105. struct ovectl_ratemanage_arg *ai=
  155106. (struct ovectl_ratemanage_arg *)arg;
  155107. if(ai==NULL){
  155108. hi->managed=0;
  155109. }else{
  155110. hi->managed=ai->management_active;
  155111. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155112. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155113. }
  155114. }
  155115. return 0;
  155116. /* now deprecated *****************/
  155117. case OV_ECTL_RATEMANAGE_AVG:
  155118. {
  155119. struct ovectl_ratemanage_arg *ai=
  155120. (struct ovectl_ratemanage_arg *)arg;
  155121. if(ai==NULL){
  155122. hi->bitrate_av=0;
  155123. }else{
  155124. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155125. }
  155126. }
  155127. return(0);
  155128. /* now deprecated *****************/
  155129. case OV_ECTL_RATEMANAGE_HARD:
  155130. {
  155131. struct ovectl_ratemanage_arg *ai=
  155132. (struct ovectl_ratemanage_arg *)arg;
  155133. if(ai==NULL){
  155134. hi->bitrate_min=0;
  155135. hi->bitrate_max=0;
  155136. }else{
  155137. hi->bitrate_min=ai->bitrate_hard_min;
  155138. hi->bitrate_max=ai->bitrate_hard_max;
  155139. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155140. (hi->bitrate_max+hi->bitrate_min)*.5;
  155141. }
  155142. if(hi->bitrate_reservoir<128.)
  155143. hi->bitrate_reservoir=128.;
  155144. }
  155145. return(0);
  155146. /* replacement ratemanage interface */
  155147. case OV_ECTL_RATEMANAGE2_GET:
  155148. {
  155149. struct ovectl_ratemanage2_arg *ai=
  155150. (struct ovectl_ratemanage2_arg *)arg;
  155151. if(ai==NULL)return OV_EINVAL;
  155152. ai->management_active=hi->managed;
  155153. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155154. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155155. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155156. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155157. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155158. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155159. }
  155160. return (0);
  155161. case OV_ECTL_RATEMANAGE2_SET:
  155162. {
  155163. struct ovectl_ratemanage2_arg *ai=
  155164. (struct ovectl_ratemanage2_arg *)arg;
  155165. if(ai==NULL){
  155166. hi->managed=0;
  155167. }else{
  155168. /* sanity check; only catch invariant violations */
  155169. if(ai->bitrate_limit_min_kbps>0 &&
  155170. ai->bitrate_average_kbps>0 &&
  155171. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155172. return OV_EINVAL;
  155173. if(ai->bitrate_limit_max_kbps>0 &&
  155174. ai->bitrate_average_kbps>0 &&
  155175. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155176. return OV_EINVAL;
  155177. if(ai->bitrate_limit_min_kbps>0 &&
  155178. ai->bitrate_limit_max_kbps>0 &&
  155179. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155180. return OV_EINVAL;
  155181. if(ai->bitrate_average_damping <= 0.)
  155182. return OV_EINVAL;
  155183. if(ai->bitrate_limit_reservoir_bits < 0)
  155184. return OV_EINVAL;
  155185. if(ai->bitrate_limit_reservoir_bias < 0.)
  155186. return OV_EINVAL;
  155187. if(ai->bitrate_limit_reservoir_bias > 1.)
  155188. return OV_EINVAL;
  155189. hi->managed=ai->management_active;
  155190. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155191. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155192. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155193. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155194. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155195. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155196. }
  155197. }
  155198. return 0;
  155199. case OV_ECTL_LOWPASS_GET:
  155200. {
  155201. double *farg=(double *)arg;
  155202. *farg=hi->lowpass_kHz;
  155203. }
  155204. return(0);
  155205. case OV_ECTL_LOWPASS_SET:
  155206. {
  155207. double *farg=(double *)arg;
  155208. hi->lowpass_kHz=*farg;
  155209. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155210. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155211. }
  155212. return(0);
  155213. case OV_ECTL_IBLOCK_GET:
  155214. {
  155215. double *farg=(double *)arg;
  155216. *farg=hi->impulse_noisetune;
  155217. }
  155218. return(0);
  155219. case OV_ECTL_IBLOCK_SET:
  155220. {
  155221. double *farg=(double *)arg;
  155222. hi->impulse_noisetune=*farg;
  155223. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155224. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155225. }
  155226. return(0);
  155227. }
  155228. return(OV_EIMPL);
  155229. }
  155230. return(OV_EINVAL);
  155231. }
  155232. #endif
  155233. /*** End of inlined file: vorbisenc.c ***/
  155234. /*** Start of inlined file: vorbisfile.c ***/
  155235. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155236. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155237. // tasks..
  155238. #if JUCE_MSVC
  155239. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155240. #endif
  155241. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155242. #if JUCE_USE_OGGVORBIS
  155243. #include <stdlib.h>
  155244. #include <stdio.h>
  155245. #include <errno.h>
  155246. #include <string.h>
  155247. #include <math.h>
  155248. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155249. one logical bitstream arranged end to end (the only form of Ogg
  155250. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155251. multiplexing] is not allowed in Vorbis) */
  155252. /* A Vorbis file can be played beginning to end (streamed) without
  155253. worrying ahead of time about chaining (see decoder_example.c). If
  155254. we have the whole file, however, and want random access
  155255. (seeking/scrubbing) or desire to know the total length/time of a
  155256. file, we need to account for the possibility of chaining. */
  155257. /* We can handle things a number of ways; we can determine the entire
  155258. bitstream structure right off the bat, or find pieces on demand.
  155259. This example determines and caches structure for the entire
  155260. bitstream, but builds a virtual decoder on the fly when moving
  155261. between links in the chain. */
  155262. /* There are also different ways to implement seeking. Enough
  155263. information exists in an Ogg bitstream to seek to
  155264. sample-granularity positions in the output. Or, one can seek by
  155265. picking some portion of the stream roughly in the desired area if
  155266. we only want coarse navigation through the stream. */
  155267. /*************************************************************************
  155268. * Many, many internal helpers. The intention is not to be confusing;
  155269. * rampant duplication and monolithic function implementation would be
  155270. * harder to understand anyway. The high level functions are last. Begin
  155271. * grokking near the end of the file */
  155272. /* read a little more data from the file/pipe into the ogg_sync framer
  155273. */
  155274. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155275. over 8k gets what they deserve */
  155276. static long _get_data(OggVorbis_File *vf){
  155277. errno=0;
  155278. if(vf->datasource){
  155279. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155280. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155281. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155282. if(bytes==0 && errno)return(-1);
  155283. return(bytes);
  155284. }else
  155285. return(0);
  155286. }
  155287. /* save a tiny smidge of verbosity to make the code more readable */
  155288. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155289. if(vf->datasource){
  155290. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155291. vf->offset=offset;
  155292. ogg_sync_reset(&vf->oy);
  155293. }else{
  155294. /* shouldn't happen unless someone writes a broken callback */
  155295. return;
  155296. }
  155297. }
  155298. /* The read/seek functions track absolute position within the stream */
  155299. /* from the head of the stream, get the next page. boundary specifies
  155300. if the function is allowed to fetch more data from the stream (and
  155301. how much) or only use internally buffered data.
  155302. boundary: -1) unbounded search
  155303. 0) read no additional data; use cached only
  155304. n) search for a new page beginning for n bytes
  155305. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155306. n) found a page at absolute offset n */
  155307. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155308. ogg_int64_t boundary){
  155309. if(boundary>0)boundary+=vf->offset;
  155310. while(1){
  155311. long more;
  155312. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155313. more=ogg_sync_pageseek(&vf->oy,og);
  155314. if(more<0){
  155315. /* skipped n bytes */
  155316. vf->offset-=more;
  155317. }else{
  155318. if(more==0){
  155319. /* send more paramedics */
  155320. if(!boundary)return(OV_FALSE);
  155321. {
  155322. long ret=_get_data(vf);
  155323. if(ret==0)return(OV_EOF);
  155324. if(ret<0)return(OV_EREAD);
  155325. }
  155326. }else{
  155327. /* got a page. Return the offset at the page beginning,
  155328. advance the internal offset past the page end */
  155329. ogg_int64_t ret=vf->offset;
  155330. vf->offset+=more;
  155331. return(ret);
  155332. }
  155333. }
  155334. }
  155335. }
  155336. /* find the latest page beginning before the current stream cursor
  155337. position. Much dirtier than the above as Ogg doesn't have any
  155338. backward search linkage. no 'readp' as it will certainly have to
  155339. read. */
  155340. /* returns offset or OV_EREAD, OV_FAULT */
  155341. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155342. ogg_int64_t begin=vf->offset;
  155343. ogg_int64_t end=begin;
  155344. ogg_int64_t ret;
  155345. ogg_int64_t offset=-1;
  155346. while(offset==-1){
  155347. begin-=CHUNKSIZE;
  155348. if(begin<0)
  155349. begin=0;
  155350. _seek_helper(vf,begin);
  155351. while(vf->offset<end){
  155352. ret=_get_next_page(vf,og,end-vf->offset);
  155353. if(ret==OV_EREAD)return(OV_EREAD);
  155354. if(ret<0){
  155355. break;
  155356. }else{
  155357. offset=ret;
  155358. }
  155359. }
  155360. }
  155361. /* we have the offset. Actually snork and hold the page now */
  155362. _seek_helper(vf,offset);
  155363. ret=_get_next_page(vf,og,CHUNKSIZE);
  155364. if(ret<0)
  155365. /* this shouldn't be possible */
  155366. return(OV_EFAULT);
  155367. return(offset);
  155368. }
  155369. /* finds each bitstream link one at a time using a bisection search
  155370. (has to begin by knowing the offset of the lb's initial page).
  155371. Recurses for each link so it can alloc the link storage after
  155372. finding them all, then unroll and fill the cache at the same time */
  155373. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155374. ogg_int64_t begin,
  155375. ogg_int64_t searched,
  155376. ogg_int64_t end,
  155377. long currentno,
  155378. long m){
  155379. ogg_int64_t endsearched=end;
  155380. ogg_int64_t next=end;
  155381. ogg_page og;
  155382. ogg_int64_t ret;
  155383. /* the below guards against garbage seperating the last and
  155384. first pages of two links. */
  155385. while(searched<endsearched){
  155386. ogg_int64_t bisect;
  155387. if(endsearched-searched<CHUNKSIZE){
  155388. bisect=searched;
  155389. }else{
  155390. bisect=(searched+endsearched)/2;
  155391. }
  155392. _seek_helper(vf,bisect);
  155393. ret=_get_next_page(vf,&og,-1);
  155394. if(ret==OV_EREAD)return(OV_EREAD);
  155395. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155396. endsearched=bisect;
  155397. if(ret>=0)next=ret;
  155398. }else{
  155399. searched=ret+og.header_len+og.body_len;
  155400. }
  155401. }
  155402. _seek_helper(vf,next);
  155403. ret=_get_next_page(vf,&og,-1);
  155404. if(ret==OV_EREAD)return(OV_EREAD);
  155405. if(searched>=end || ret<0){
  155406. vf->links=m+1;
  155407. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155408. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155409. vf->offsets[m+1]=searched;
  155410. }else{
  155411. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155412. end,ogg_page_serialno(&og),m+1);
  155413. if(ret==OV_EREAD)return(OV_EREAD);
  155414. }
  155415. vf->offsets[m]=begin;
  155416. vf->serialnos[m]=currentno;
  155417. return(0);
  155418. }
  155419. /* uses the local ogg_stream storage in vf; this is important for
  155420. non-streaming input sources */
  155421. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155422. long *serialno,ogg_page *og_ptr){
  155423. ogg_page og;
  155424. ogg_packet op;
  155425. int i,ret;
  155426. if(!og_ptr){
  155427. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155428. if(llret==OV_EREAD)return(OV_EREAD);
  155429. if(llret<0)return OV_ENOTVORBIS;
  155430. og_ptr=&og;
  155431. }
  155432. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155433. if(serialno)*serialno=vf->os.serialno;
  155434. vf->ready_state=STREAMSET;
  155435. /* extract the initial header from the first page and verify that the
  155436. Ogg bitstream is in fact Vorbis data */
  155437. vorbis_info_init(vi);
  155438. vorbis_comment_init(vc);
  155439. i=0;
  155440. while(i<3){
  155441. ogg_stream_pagein(&vf->os,og_ptr);
  155442. while(i<3){
  155443. int result=ogg_stream_packetout(&vf->os,&op);
  155444. if(result==0)break;
  155445. if(result==-1){
  155446. ret=OV_EBADHEADER;
  155447. goto bail_header;
  155448. }
  155449. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155450. goto bail_header;
  155451. }
  155452. i++;
  155453. }
  155454. if(i<3)
  155455. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155456. ret=OV_EBADHEADER;
  155457. goto bail_header;
  155458. }
  155459. }
  155460. return 0;
  155461. bail_header:
  155462. vorbis_info_clear(vi);
  155463. vorbis_comment_clear(vc);
  155464. vf->ready_state=OPENED;
  155465. return ret;
  155466. }
  155467. /* last step of the OggVorbis_File initialization; get all the
  155468. vorbis_info structs and PCM positions. Only called by the seekable
  155469. initialization (local stream storage is hacked slightly; pay
  155470. attention to how that's done) */
  155471. /* this is void and does not propogate errors up because we want to be
  155472. able to open and use damaged bitstreams as well as we can. Just
  155473. watch out for missing information for links in the OggVorbis_File
  155474. struct */
  155475. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155476. ogg_page og;
  155477. int i;
  155478. ogg_int64_t ret;
  155479. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155480. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155481. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155482. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155483. for(i=0;i<vf->links;i++){
  155484. if(i==0){
  155485. /* we already grabbed the initial header earlier. Just set the offset */
  155486. vf->dataoffsets[i]=dataoffset;
  155487. _seek_helper(vf,dataoffset);
  155488. }else{
  155489. /* seek to the location of the initial header */
  155490. _seek_helper(vf,vf->offsets[i]);
  155491. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155492. vf->dataoffsets[i]=-1;
  155493. }else{
  155494. vf->dataoffsets[i]=vf->offset;
  155495. }
  155496. }
  155497. /* fetch beginning PCM offset */
  155498. if(vf->dataoffsets[i]!=-1){
  155499. ogg_int64_t accumulated=0;
  155500. long lastblock=-1;
  155501. int result;
  155502. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155503. while(1){
  155504. ogg_packet op;
  155505. ret=_get_next_page(vf,&og,-1);
  155506. if(ret<0)
  155507. /* this should not be possible unless the file is
  155508. truncated/mangled */
  155509. break;
  155510. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155511. break;
  155512. /* count blocksizes of all frames in the page */
  155513. ogg_stream_pagein(&vf->os,&og);
  155514. while((result=ogg_stream_packetout(&vf->os,&op))){
  155515. if(result>0){ /* ignore holes */
  155516. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155517. if(lastblock!=-1)
  155518. accumulated+=(lastblock+thisblock)>>2;
  155519. lastblock=thisblock;
  155520. }
  155521. }
  155522. if(ogg_page_granulepos(&og)!=-1){
  155523. /* pcm offset of last packet on the first audio page */
  155524. accumulated= ogg_page_granulepos(&og)-accumulated;
  155525. break;
  155526. }
  155527. }
  155528. /* less than zero? This is a stream with samples trimmed off
  155529. the beginning, a normal occurrence; set the offset to zero */
  155530. if(accumulated<0)accumulated=0;
  155531. vf->pcmlengths[i*2]=accumulated;
  155532. }
  155533. /* get the PCM length of this link. To do this,
  155534. get the last page of the stream */
  155535. {
  155536. ogg_int64_t end=vf->offsets[i+1];
  155537. _seek_helper(vf,end);
  155538. while(1){
  155539. ret=_get_prev_page(vf,&og);
  155540. if(ret<0){
  155541. /* this should not be possible */
  155542. vorbis_info_clear(vf->vi+i);
  155543. vorbis_comment_clear(vf->vc+i);
  155544. break;
  155545. }
  155546. if(ogg_page_granulepos(&og)!=-1){
  155547. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155548. break;
  155549. }
  155550. vf->offset=ret;
  155551. }
  155552. }
  155553. }
  155554. }
  155555. static int _make_decode_ready(OggVorbis_File *vf){
  155556. if(vf->ready_state>STREAMSET)return 0;
  155557. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155558. if(vf->seekable){
  155559. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155560. return OV_EBADLINK;
  155561. }else{
  155562. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155563. return OV_EBADLINK;
  155564. }
  155565. vorbis_block_init(&vf->vd,&vf->vb);
  155566. vf->ready_state=INITSET;
  155567. vf->bittrack=0.f;
  155568. vf->samptrack=0.f;
  155569. return 0;
  155570. }
  155571. static int _open_seekable2(OggVorbis_File *vf){
  155572. long serialno=vf->current_serialno;
  155573. ogg_int64_t dataoffset=vf->offset, end;
  155574. ogg_page og;
  155575. /* we're partially open and have a first link header state in
  155576. storage in vf */
  155577. /* we can seek, so set out learning all about this file */
  155578. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155579. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155580. /* We get the offset for the last page of the physical bitstream.
  155581. Most OggVorbis files will contain a single logical bitstream */
  155582. end=_get_prev_page(vf,&og);
  155583. if(end<0)return(end);
  155584. /* more than one logical bitstream? */
  155585. if(ogg_page_serialno(&og)!=serialno){
  155586. /* Chained bitstream. Bisect-search each logical bitstream
  155587. section. Do so based on serial number only */
  155588. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155589. }else{
  155590. /* Only one logical bitstream */
  155591. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155592. }
  155593. /* the initial header memory is referenced by vf after; don't free it */
  155594. _prefetch_all_headers(vf,dataoffset);
  155595. return(ov_raw_seek(vf,0));
  155596. }
  155597. /* clear out the current logical bitstream decoder */
  155598. static void _decode_clear(OggVorbis_File *vf){
  155599. vorbis_dsp_clear(&vf->vd);
  155600. vorbis_block_clear(&vf->vb);
  155601. vf->ready_state=OPENED;
  155602. }
  155603. /* fetch and process a packet. Handles the case where we're at a
  155604. bitstream boundary and dumps the decoding machine. If the decoding
  155605. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155606. date (seek and read both use this. seek uses a special hack with
  155607. readp).
  155608. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155609. 0) need more data (only if readp==0)
  155610. 1) got a packet
  155611. */
  155612. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155613. ogg_packet *op_in,
  155614. int readp,
  155615. int spanp){
  155616. ogg_page og;
  155617. /* handle one packet. Try to fetch it from current stream state */
  155618. /* extract packets from page */
  155619. while(1){
  155620. /* process a packet if we can. If the machine isn't loaded,
  155621. neither is a page */
  155622. if(vf->ready_state==INITSET){
  155623. while(1) {
  155624. ogg_packet op;
  155625. ogg_packet *op_ptr=(op_in?op_in:&op);
  155626. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155627. ogg_int64_t granulepos;
  155628. op_in=NULL;
  155629. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155630. if(result>0){
  155631. /* got a packet. process it */
  155632. granulepos=op_ptr->granulepos;
  155633. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155634. header handling. The
  155635. header packets aren't
  155636. audio, so if/when we
  155637. submit them,
  155638. vorbis_synthesis will
  155639. reject them */
  155640. /* suck in the synthesis data and track bitrate */
  155641. {
  155642. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155643. /* for proper use of libvorbis within libvorbisfile,
  155644. oldsamples will always be zero. */
  155645. if(oldsamples)return(OV_EFAULT);
  155646. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155647. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155648. vf->bittrack+=op_ptr->bytes*8;
  155649. }
  155650. /* update the pcm offset. */
  155651. if(granulepos!=-1 && !op_ptr->e_o_s){
  155652. int link=(vf->seekable?vf->current_link:0);
  155653. int i,samples;
  155654. /* this packet has a pcm_offset on it (the last packet
  155655. completed on a page carries the offset) After processing
  155656. (above), we know the pcm position of the *last* sample
  155657. ready to be returned. Find the offset of the *first*
  155658. As an aside, this trick is inaccurate if we begin
  155659. reading anew right at the last page; the end-of-stream
  155660. granulepos declares the last frame in the stream, and the
  155661. last packet of the last page may be a partial frame.
  155662. So, we need a previous granulepos from an in-sequence page
  155663. to have a reference point. Thus the !op_ptr->e_o_s clause
  155664. above */
  155665. if(vf->seekable && link>0)
  155666. granulepos-=vf->pcmlengths[link*2];
  155667. if(granulepos<0)granulepos=0; /* actually, this
  155668. shouldn't be possible
  155669. here unless the stream
  155670. is very broken */
  155671. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155672. granulepos-=samples;
  155673. for(i=0;i<link;i++)
  155674. granulepos+=vf->pcmlengths[i*2+1];
  155675. vf->pcm_offset=granulepos;
  155676. }
  155677. return(1);
  155678. }
  155679. }
  155680. else
  155681. break;
  155682. }
  155683. }
  155684. if(vf->ready_state>=OPENED){
  155685. ogg_int64_t ret;
  155686. if(!readp)return(0);
  155687. if((ret=_get_next_page(vf,&og,-1))<0){
  155688. return(OV_EOF); /* eof.
  155689. leave unitialized */
  155690. }
  155691. /* bitrate tracking; add the header's bytes here, the body bytes
  155692. are done by packet above */
  155693. vf->bittrack+=og.header_len*8;
  155694. /* has our decoding just traversed a bitstream boundary? */
  155695. if(vf->ready_state==INITSET){
  155696. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155697. if(!spanp)
  155698. return(OV_EOF);
  155699. _decode_clear(vf);
  155700. if(!vf->seekable){
  155701. vorbis_info_clear(vf->vi);
  155702. vorbis_comment_clear(vf->vc);
  155703. }
  155704. }
  155705. }
  155706. }
  155707. /* Do we need to load a new machine before submitting the page? */
  155708. /* This is different in the seekable and non-seekable cases.
  155709. In the seekable case, we already have all the header
  155710. information loaded and cached; we just initialize the machine
  155711. with it and continue on our merry way.
  155712. In the non-seekable (streaming) case, we'll only be at a
  155713. boundary if we just left the previous logical bitstream and
  155714. we're now nominally at the header of the next bitstream
  155715. */
  155716. if(vf->ready_state!=INITSET){
  155717. int link;
  155718. if(vf->ready_state<STREAMSET){
  155719. if(vf->seekable){
  155720. vf->current_serialno=ogg_page_serialno(&og);
  155721. /* match the serialno to bitstream section. We use this rather than
  155722. offset positions to avoid problems near logical bitstream
  155723. boundaries */
  155724. for(link=0;link<vf->links;link++)
  155725. if(vf->serialnos[link]==vf->current_serialno)break;
  155726. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155727. stream. error out,
  155728. leave machine
  155729. uninitialized */
  155730. vf->current_link=link;
  155731. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155732. vf->ready_state=STREAMSET;
  155733. }else{
  155734. /* we're streaming */
  155735. /* fetch the three header packets, build the info struct */
  155736. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155737. if(ret)return(ret);
  155738. vf->current_link++;
  155739. link=0;
  155740. }
  155741. }
  155742. {
  155743. int ret=_make_decode_ready(vf);
  155744. if(ret<0)return ret;
  155745. }
  155746. }
  155747. ogg_stream_pagein(&vf->os,&og);
  155748. }
  155749. }
  155750. /* if, eg, 64 bit stdio is configured by default, this will build with
  155751. fseek64 */
  155752. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155753. if(f==NULL)return(-1);
  155754. return fseek(f,off,whence);
  155755. }
  155756. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155757. long ibytes, ov_callbacks callbacks){
  155758. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155759. int ret;
  155760. memset(vf,0,sizeof(*vf));
  155761. vf->datasource=f;
  155762. vf->callbacks = callbacks;
  155763. /* init the framing state */
  155764. ogg_sync_init(&vf->oy);
  155765. /* perhaps some data was previously read into a buffer for testing
  155766. against other stream types. Allow initialization from this
  155767. previously read data (as we may be reading from a non-seekable
  155768. stream) */
  155769. if(initial){
  155770. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155771. memcpy(buffer,initial,ibytes);
  155772. ogg_sync_wrote(&vf->oy,ibytes);
  155773. }
  155774. /* can we seek? Stevens suggests the seek test was portable */
  155775. if(offsettest!=-1)vf->seekable=1;
  155776. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155777. entry for partial open */
  155778. vf->links=1;
  155779. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155780. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155781. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155782. /* Try to fetch the headers, maintaining all the storage */
  155783. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155784. vf->datasource=NULL;
  155785. ov_clear(vf);
  155786. }else
  155787. vf->ready_state=PARTOPEN;
  155788. return(ret);
  155789. }
  155790. static int _ov_open2(OggVorbis_File *vf){
  155791. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155792. vf->ready_state=OPENED;
  155793. if(vf->seekable){
  155794. int ret=_open_seekable2(vf);
  155795. if(ret){
  155796. vf->datasource=NULL;
  155797. ov_clear(vf);
  155798. }
  155799. return(ret);
  155800. }else
  155801. vf->ready_state=STREAMSET;
  155802. return 0;
  155803. }
  155804. /* clear out the OggVorbis_File struct */
  155805. int ov_clear(OggVorbis_File *vf){
  155806. if(vf){
  155807. vorbis_block_clear(&vf->vb);
  155808. vorbis_dsp_clear(&vf->vd);
  155809. ogg_stream_clear(&vf->os);
  155810. if(vf->vi && vf->links){
  155811. int i;
  155812. for(i=0;i<vf->links;i++){
  155813. vorbis_info_clear(vf->vi+i);
  155814. vorbis_comment_clear(vf->vc+i);
  155815. }
  155816. _ogg_free(vf->vi);
  155817. _ogg_free(vf->vc);
  155818. }
  155819. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155820. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155821. if(vf->serialnos)_ogg_free(vf->serialnos);
  155822. if(vf->offsets)_ogg_free(vf->offsets);
  155823. ogg_sync_clear(&vf->oy);
  155824. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155825. memset(vf,0,sizeof(*vf));
  155826. }
  155827. #ifdef DEBUG_LEAKS
  155828. _VDBG_dump();
  155829. #endif
  155830. return(0);
  155831. }
  155832. /* inspects the OggVorbis file and finds/documents all the logical
  155833. bitstreams contained in it. Tries to be tolerant of logical
  155834. bitstream sections that are truncated/woogie.
  155835. return: -1) error
  155836. 0) OK
  155837. */
  155838. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155839. ov_callbacks callbacks){
  155840. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155841. if(ret)return ret;
  155842. return _ov_open2(vf);
  155843. }
  155844. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155845. ov_callbacks callbacks = {
  155846. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155847. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155848. (int (*)(void *)) fclose,
  155849. (long (*)(void *)) ftell
  155850. };
  155851. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155852. }
  155853. /* cheap hack for game usage where downsampling is desirable; there's
  155854. no need for SRC as we can just do it cheaply in libvorbis. */
  155855. int ov_halfrate(OggVorbis_File *vf,int flag){
  155856. int i;
  155857. if(vf->vi==NULL)return OV_EINVAL;
  155858. if(!vf->seekable)return OV_EINVAL;
  155859. if(vf->ready_state>=STREAMSET)
  155860. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155861. will be able to swap this on the fly, but
  155862. for now dumping the decode machine is needed
  155863. to reinit the MDCT lookups. 1.1 libvorbis
  155864. is planned to be able to switch on the fly */
  155865. for(i=0;i<vf->links;i++){
  155866. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155867. ov_halfrate(vf,0);
  155868. return OV_EINVAL;
  155869. }
  155870. }
  155871. return 0;
  155872. }
  155873. int ov_halfrate_p(OggVorbis_File *vf){
  155874. if(vf->vi==NULL)return OV_EINVAL;
  155875. return vorbis_synthesis_halfrate_p(vf->vi);
  155876. }
  155877. /* Only partially open the vorbis file; test for Vorbisness, and load
  155878. the headers for the first chain. Do not seek (although test for
  155879. seekability). Use ov_test_open to finish opening the file, else
  155880. ov_clear to close/free it. Same return codes as open. */
  155881. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155882. ov_callbacks callbacks)
  155883. {
  155884. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155885. }
  155886. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155887. ov_callbacks callbacks = {
  155888. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155889. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155890. (int (*)(void *)) fclose,
  155891. (long (*)(void *)) ftell
  155892. };
  155893. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155894. }
  155895. int ov_test_open(OggVorbis_File *vf){
  155896. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155897. return _ov_open2(vf);
  155898. }
  155899. /* How many logical bitstreams in this physical bitstream? */
  155900. long ov_streams(OggVorbis_File *vf){
  155901. return vf->links;
  155902. }
  155903. /* Is the FILE * associated with vf seekable? */
  155904. long ov_seekable(OggVorbis_File *vf){
  155905. return vf->seekable;
  155906. }
  155907. /* returns the bitrate for a given logical bitstream or the entire
  155908. physical bitstream. If the file is open for random access, it will
  155909. find the *actual* average bitrate. If the file is streaming, it
  155910. returns the nominal bitrate (if set) else the average of the
  155911. upper/lower bounds (if set) else -1 (unset).
  155912. If you want the actual bitrate field settings, get them from the
  155913. vorbis_info structs */
  155914. long ov_bitrate(OggVorbis_File *vf,int i){
  155915. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155916. if(i>=vf->links)return(OV_EINVAL);
  155917. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155918. if(i<0){
  155919. ogg_int64_t bits=0;
  155920. int i;
  155921. float br;
  155922. for(i=0;i<vf->links;i++)
  155923. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155924. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155925. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155926. * so this is slightly transformed to make it work.
  155927. */
  155928. br = bits/ov_time_total(vf,-1);
  155929. return(rint(br));
  155930. }else{
  155931. if(vf->seekable){
  155932. /* return the actual bitrate */
  155933. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155934. }else{
  155935. /* return nominal if set */
  155936. if(vf->vi[i].bitrate_nominal>0){
  155937. return vf->vi[i].bitrate_nominal;
  155938. }else{
  155939. if(vf->vi[i].bitrate_upper>0){
  155940. if(vf->vi[i].bitrate_lower>0){
  155941. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155942. }else{
  155943. return vf->vi[i].bitrate_upper;
  155944. }
  155945. }
  155946. return(OV_FALSE);
  155947. }
  155948. }
  155949. }
  155950. }
  155951. /* returns the actual bitrate since last call. returns -1 if no
  155952. additional data to offer since last call (or at beginning of stream),
  155953. EINVAL if stream is only partially open
  155954. */
  155955. long ov_bitrate_instant(OggVorbis_File *vf){
  155956. int link=(vf->seekable?vf->current_link:0);
  155957. long ret;
  155958. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155959. if(vf->samptrack==0)return(OV_FALSE);
  155960. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155961. vf->bittrack=0.f;
  155962. vf->samptrack=0.f;
  155963. return(ret);
  155964. }
  155965. /* Guess */
  155966. long ov_serialnumber(OggVorbis_File *vf,int i){
  155967. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155968. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155969. if(i<0){
  155970. return(vf->current_serialno);
  155971. }else{
  155972. return(vf->serialnos[i]);
  155973. }
  155974. }
  155975. /* returns: total raw (compressed) length of content if i==-1
  155976. raw (compressed) length of that logical bitstream for i==0 to n
  155977. OV_EINVAL if the stream is not seekable (we can't know the length)
  155978. or if stream is only partially open
  155979. */
  155980. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155981. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155982. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155983. if(i<0){
  155984. ogg_int64_t acc=0;
  155985. int i;
  155986. for(i=0;i<vf->links;i++)
  155987. acc+=ov_raw_total(vf,i);
  155988. return(acc);
  155989. }else{
  155990. return(vf->offsets[i+1]-vf->offsets[i]);
  155991. }
  155992. }
  155993. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155994. (samples) of that logical bitstream for i==0 to n
  155995. OV_EINVAL if the stream is not seekable (we can't know the
  155996. length) or only partially open
  155997. */
  155998. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155999. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156000. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156001. if(i<0){
  156002. ogg_int64_t acc=0;
  156003. int i;
  156004. for(i=0;i<vf->links;i++)
  156005. acc+=ov_pcm_total(vf,i);
  156006. return(acc);
  156007. }else{
  156008. return(vf->pcmlengths[i*2+1]);
  156009. }
  156010. }
  156011. /* returns: total seconds of content if i==-1
  156012. seconds in that logical bitstream for i==0 to n
  156013. OV_EINVAL if the stream is not seekable (we can't know the
  156014. length) or only partially open
  156015. */
  156016. double ov_time_total(OggVorbis_File *vf,int i){
  156017. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156018. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156019. if(i<0){
  156020. double acc=0;
  156021. int i;
  156022. for(i=0;i<vf->links;i++)
  156023. acc+=ov_time_total(vf,i);
  156024. return(acc);
  156025. }else{
  156026. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156027. }
  156028. }
  156029. /* seek to an offset relative to the *compressed* data. This also
  156030. scans packets to update the PCM cursor. It will cross a logical
  156031. bitstream boundary, but only if it can't get any packets out of the
  156032. tail of the bitstream we seek to (so no surprises).
  156033. returns zero on success, nonzero on failure */
  156034. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156035. ogg_stream_state work_os;
  156036. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156037. if(!vf->seekable)
  156038. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156039. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156040. /* don't yet clear out decoding machine (if it's initialized), in
  156041. the case we're in the same link. Restart the decode lapping, and
  156042. let _fetch_and_process_packet deal with a potential bitstream
  156043. boundary */
  156044. vf->pcm_offset=-1;
  156045. ogg_stream_reset_serialno(&vf->os,
  156046. vf->current_serialno); /* must set serialno */
  156047. vorbis_synthesis_restart(&vf->vd);
  156048. _seek_helper(vf,pos);
  156049. /* we need to make sure the pcm_offset is set, but we don't want to
  156050. advance the raw cursor past good packets just to get to the first
  156051. with a granulepos. That's not equivalent behavior to beginning
  156052. decoding as immediately after the seek position as possible.
  156053. So, a hack. We use two stream states; a local scratch state and
  156054. the shared vf->os stream state. We use the local state to
  156055. scan, and the shared state as a buffer for later decode.
  156056. Unfortuantely, on the last page we still advance to last packet
  156057. because the granulepos on the last page is not necessarily on a
  156058. packet boundary, and we need to make sure the granpos is
  156059. correct.
  156060. */
  156061. {
  156062. ogg_page og;
  156063. ogg_packet op;
  156064. int lastblock=0;
  156065. int accblock=0;
  156066. int thisblock;
  156067. int eosflag;
  156068. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156069. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156070. return from not necessarily
  156071. starting from the beginning */
  156072. while(1){
  156073. if(vf->ready_state>=STREAMSET){
  156074. /* snarf/scan a packet if we can */
  156075. int result=ogg_stream_packetout(&work_os,&op);
  156076. if(result>0){
  156077. if(vf->vi[vf->current_link].codec_setup){
  156078. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156079. if(thisblock<0){
  156080. ogg_stream_packetout(&vf->os,NULL);
  156081. thisblock=0;
  156082. }else{
  156083. if(eosflag)
  156084. ogg_stream_packetout(&vf->os,NULL);
  156085. else
  156086. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156087. }
  156088. if(op.granulepos!=-1){
  156089. int i,link=vf->current_link;
  156090. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156091. if(granulepos<0)granulepos=0;
  156092. for(i=0;i<link;i++)
  156093. granulepos+=vf->pcmlengths[i*2+1];
  156094. vf->pcm_offset=granulepos-accblock;
  156095. break;
  156096. }
  156097. lastblock=thisblock;
  156098. continue;
  156099. }else
  156100. ogg_stream_packetout(&vf->os,NULL);
  156101. }
  156102. }
  156103. if(!lastblock){
  156104. if(_get_next_page(vf,&og,-1)<0){
  156105. vf->pcm_offset=ov_pcm_total(vf,-1);
  156106. break;
  156107. }
  156108. }else{
  156109. /* huh? Bogus stream with packets but no granulepos */
  156110. vf->pcm_offset=-1;
  156111. break;
  156112. }
  156113. /* has our decoding just traversed a bitstream boundary? */
  156114. if(vf->ready_state>=STREAMSET)
  156115. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156116. _decode_clear(vf); /* clear out stream state */
  156117. ogg_stream_clear(&work_os);
  156118. }
  156119. if(vf->ready_state<STREAMSET){
  156120. int link;
  156121. vf->current_serialno=ogg_page_serialno(&og);
  156122. for(link=0;link<vf->links;link++)
  156123. if(vf->serialnos[link]==vf->current_serialno)break;
  156124. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156125. error out, leave
  156126. machine uninitialized */
  156127. vf->current_link=link;
  156128. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156129. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156130. vf->ready_state=STREAMSET;
  156131. }
  156132. ogg_stream_pagein(&vf->os,&og);
  156133. ogg_stream_pagein(&work_os,&og);
  156134. eosflag=ogg_page_eos(&og);
  156135. }
  156136. }
  156137. ogg_stream_clear(&work_os);
  156138. vf->bittrack=0.f;
  156139. vf->samptrack=0.f;
  156140. return(0);
  156141. seek_error:
  156142. /* dump the machine so we're in a known state */
  156143. vf->pcm_offset=-1;
  156144. ogg_stream_clear(&work_os);
  156145. _decode_clear(vf);
  156146. return OV_EBADLINK;
  156147. }
  156148. /* Page granularity seek (faster than sample granularity because we
  156149. don't do the last bit of decode to find a specific sample).
  156150. Seek to the last [granule marked] page preceeding the specified pos
  156151. location, such that decoding past the returned point will quickly
  156152. arrive at the requested position. */
  156153. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156154. int link=-1;
  156155. ogg_int64_t result=0;
  156156. ogg_int64_t total=ov_pcm_total(vf,-1);
  156157. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156158. if(!vf->seekable)return(OV_ENOSEEK);
  156159. if(pos<0 || pos>total)return(OV_EINVAL);
  156160. /* which bitstream section does this pcm offset occur in? */
  156161. for(link=vf->links-1;link>=0;link--){
  156162. total-=vf->pcmlengths[link*2+1];
  156163. if(pos>=total)break;
  156164. }
  156165. /* search within the logical bitstream for the page with the highest
  156166. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156167. missing pages or incorrect frame number information in the
  156168. bitstream could make our task impossible. Account for that (it
  156169. would be an error condition) */
  156170. /* new search algorithm by HB (Nicholas Vinen) */
  156171. {
  156172. ogg_int64_t end=vf->offsets[link+1];
  156173. ogg_int64_t begin=vf->offsets[link];
  156174. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156175. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156176. ogg_int64_t target=pos-total+begintime;
  156177. ogg_int64_t best=begin;
  156178. ogg_page og;
  156179. while(begin<end){
  156180. ogg_int64_t bisect;
  156181. if(end-begin<CHUNKSIZE){
  156182. bisect=begin;
  156183. }else{
  156184. /* take a (pretty decent) guess. */
  156185. bisect=begin +
  156186. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156187. if(bisect<=begin)
  156188. bisect=begin+1;
  156189. }
  156190. _seek_helper(vf,bisect);
  156191. while(begin<end){
  156192. result=_get_next_page(vf,&og,end-vf->offset);
  156193. if(result==OV_EREAD) goto seek_error;
  156194. if(result<0){
  156195. if(bisect<=begin+1)
  156196. end=begin; /* found it */
  156197. else{
  156198. if(bisect==0) goto seek_error;
  156199. bisect-=CHUNKSIZE;
  156200. if(bisect<=begin)bisect=begin+1;
  156201. _seek_helper(vf,bisect);
  156202. }
  156203. }else{
  156204. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156205. if(granulepos==-1)continue;
  156206. if(granulepos<target){
  156207. best=result; /* raw offset of packet with granulepos */
  156208. begin=vf->offset; /* raw offset of next page */
  156209. begintime=granulepos;
  156210. if(target-begintime>44100)break;
  156211. bisect=begin; /* *not* begin + 1 */
  156212. }else{
  156213. if(bisect<=begin+1)
  156214. end=begin; /* found it */
  156215. else{
  156216. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156217. end=result;
  156218. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156219. if(bisect<=begin)bisect=begin+1;
  156220. _seek_helper(vf,bisect);
  156221. }else{
  156222. end=result;
  156223. endtime=granulepos;
  156224. break;
  156225. }
  156226. }
  156227. }
  156228. }
  156229. }
  156230. }
  156231. /* found our page. seek to it, update pcm offset. Easier case than
  156232. raw_seek, don't keep packets preceeding granulepos. */
  156233. {
  156234. ogg_page og;
  156235. ogg_packet op;
  156236. /* seek */
  156237. _seek_helper(vf,best);
  156238. vf->pcm_offset=-1;
  156239. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156240. if(link!=vf->current_link){
  156241. /* Different link; dump entire decode machine */
  156242. _decode_clear(vf);
  156243. vf->current_link=link;
  156244. vf->current_serialno=ogg_page_serialno(&og);
  156245. vf->ready_state=STREAMSET;
  156246. }else{
  156247. vorbis_synthesis_restart(&vf->vd);
  156248. }
  156249. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156250. ogg_stream_pagein(&vf->os,&og);
  156251. /* pull out all but last packet; the one with granulepos */
  156252. while(1){
  156253. result=ogg_stream_packetpeek(&vf->os,&op);
  156254. if(result==0){
  156255. /* !!! the packet finishing this page originated on a
  156256. preceeding page. Keep fetching previous pages until we
  156257. get one with a granulepos or without the 'continued' flag
  156258. set. Then just use raw_seek for simplicity. */
  156259. _seek_helper(vf,best);
  156260. while(1){
  156261. result=_get_prev_page(vf,&og);
  156262. if(result<0) goto seek_error;
  156263. if(ogg_page_granulepos(&og)>-1 ||
  156264. !ogg_page_continued(&og)){
  156265. return ov_raw_seek(vf,result);
  156266. }
  156267. vf->offset=result;
  156268. }
  156269. }
  156270. if(result<0){
  156271. result = OV_EBADPACKET;
  156272. goto seek_error;
  156273. }
  156274. if(op.granulepos!=-1){
  156275. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156276. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156277. vf->pcm_offset+=total;
  156278. break;
  156279. }else
  156280. result=ogg_stream_packetout(&vf->os,NULL);
  156281. }
  156282. }
  156283. }
  156284. /* verify result */
  156285. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156286. result=OV_EFAULT;
  156287. goto seek_error;
  156288. }
  156289. vf->bittrack=0.f;
  156290. vf->samptrack=0.f;
  156291. return(0);
  156292. seek_error:
  156293. /* dump machine so we're in a known state */
  156294. vf->pcm_offset=-1;
  156295. _decode_clear(vf);
  156296. return (int)result;
  156297. }
  156298. /* seek to a sample offset relative to the decompressed pcm stream
  156299. returns zero on success, nonzero on failure */
  156300. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156301. int thisblock,lastblock=0;
  156302. int ret=ov_pcm_seek_page(vf,pos);
  156303. if(ret<0)return(ret);
  156304. if((ret=_make_decode_ready(vf)))return ret;
  156305. /* discard leading packets we don't need for the lapping of the
  156306. position we want; don't decode them */
  156307. while(1){
  156308. ogg_packet op;
  156309. ogg_page og;
  156310. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156311. if(ret>0){
  156312. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156313. if(thisblock<0){
  156314. ogg_stream_packetout(&vf->os,NULL);
  156315. continue; /* non audio packet */
  156316. }
  156317. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156318. if(vf->pcm_offset+((thisblock+
  156319. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156320. /* remove the packet from packet queue and track its granulepos */
  156321. ogg_stream_packetout(&vf->os,NULL);
  156322. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156323. only tracking, no
  156324. pcm_decode */
  156325. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156326. /* end of logical stream case is hard, especially with exact
  156327. length positioning. */
  156328. if(op.granulepos>-1){
  156329. int i;
  156330. /* always believe the stream markers */
  156331. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156332. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156333. for(i=0;i<vf->current_link;i++)
  156334. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156335. }
  156336. lastblock=thisblock;
  156337. }else{
  156338. if(ret<0 && ret!=OV_HOLE)break;
  156339. /* suck in a new page */
  156340. if(_get_next_page(vf,&og,-1)<0)break;
  156341. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156342. if(vf->ready_state<STREAMSET){
  156343. int link;
  156344. vf->current_serialno=ogg_page_serialno(&og);
  156345. for(link=0;link<vf->links;link++)
  156346. if(vf->serialnos[link]==vf->current_serialno)break;
  156347. if(link==vf->links)return(OV_EBADLINK);
  156348. vf->current_link=link;
  156349. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156350. vf->ready_state=STREAMSET;
  156351. ret=_make_decode_ready(vf);
  156352. if(ret)return ret;
  156353. lastblock=0;
  156354. }
  156355. ogg_stream_pagein(&vf->os,&og);
  156356. }
  156357. }
  156358. vf->bittrack=0.f;
  156359. vf->samptrack=0.f;
  156360. /* discard samples until we reach the desired position. Crossing a
  156361. logical bitstream boundary with abandon is OK. */
  156362. while(vf->pcm_offset<pos){
  156363. ogg_int64_t target=pos-vf->pcm_offset;
  156364. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156365. if(samples>target)samples=target;
  156366. vorbis_synthesis_read(&vf->vd,samples);
  156367. vf->pcm_offset+=samples;
  156368. if(samples<target)
  156369. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156370. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156371. }
  156372. return 0;
  156373. }
  156374. /* seek to a playback time relative to the decompressed pcm stream
  156375. returns zero on success, nonzero on failure */
  156376. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156377. /* translate time to PCM position and call ov_pcm_seek */
  156378. int link=-1;
  156379. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156380. double time_total=ov_time_total(vf,-1);
  156381. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156382. if(!vf->seekable)return(OV_ENOSEEK);
  156383. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156384. /* which bitstream section does this time offset occur in? */
  156385. for(link=vf->links-1;link>=0;link--){
  156386. pcm_total-=vf->pcmlengths[link*2+1];
  156387. time_total-=ov_time_total(vf,link);
  156388. if(seconds>=time_total)break;
  156389. }
  156390. /* enough information to convert time offset to pcm offset */
  156391. {
  156392. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156393. return(ov_pcm_seek(vf,target));
  156394. }
  156395. }
  156396. /* page-granularity version of ov_time_seek
  156397. returns zero on success, nonzero on failure */
  156398. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156399. /* translate time to PCM position and call ov_pcm_seek */
  156400. int link=-1;
  156401. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156402. double time_total=ov_time_total(vf,-1);
  156403. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156404. if(!vf->seekable)return(OV_ENOSEEK);
  156405. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156406. /* which bitstream section does this time offset occur in? */
  156407. for(link=vf->links-1;link>=0;link--){
  156408. pcm_total-=vf->pcmlengths[link*2+1];
  156409. time_total-=ov_time_total(vf,link);
  156410. if(seconds>=time_total)break;
  156411. }
  156412. /* enough information to convert time offset to pcm offset */
  156413. {
  156414. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156415. return(ov_pcm_seek_page(vf,target));
  156416. }
  156417. }
  156418. /* tell the current stream offset cursor. Note that seek followed by
  156419. tell will likely not give the set offset due to caching */
  156420. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156421. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156422. return(vf->offset);
  156423. }
  156424. /* return PCM offset (sample) of next PCM sample to be read */
  156425. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156426. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156427. return(vf->pcm_offset);
  156428. }
  156429. /* return time offset (seconds) of next PCM sample to be read */
  156430. double ov_time_tell(OggVorbis_File *vf){
  156431. int link=0;
  156432. ogg_int64_t pcm_total=0;
  156433. double time_total=0.f;
  156434. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156435. if(vf->seekable){
  156436. pcm_total=ov_pcm_total(vf,-1);
  156437. time_total=ov_time_total(vf,-1);
  156438. /* which bitstream section does this time offset occur in? */
  156439. for(link=vf->links-1;link>=0;link--){
  156440. pcm_total-=vf->pcmlengths[link*2+1];
  156441. time_total-=ov_time_total(vf,link);
  156442. if(vf->pcm_offset>=pcm_total)break;
  156443. }
  156444. }
  156445. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156446. }
  156447. /* link: -1) return the vorbis_info struct for the bitstream section
  156448. currently being decoded
  156449. 0-n) to request information for a specific bitstream section
  156450. In the case of a non-seekable bitstream, any call returns the
  156451. current bitstream. NULL in the case that the machine is not
  156452. initialized */
  156453. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156454. if(vf->seekable){
  156455. if(link<0)
  156456. if(vf->ready_state>=STREAMSET)
  156457. return vf->vi+vf->current_link;
  156458. else
  156459. return vf->vi;
  156460. else
  156461. if(link>=vf->links)
  156462. return NULL;
  156463. else
  156464. return vf->vi+link;
  156465. }else{
  156466. return vf->vi;
  156467. }
  156468. }
  156469. /* grr, strong typing, grr, no templates/inheritence, grr */
  156470. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156471. if(vf->seekable){
  156472. if(link<0)
  156473. if(vf->ready_state>=STREAMSET)
  156474. return vf->vc+vf->current_link;
  156475. else
  156476. return vf->vc;
  156477. else
  156478. if(link>=vf->links)
  156479. return NULL;
  156480. else
  156481. return vf->vc+link;
  156482. }else{
  156483. return vf->vc;
  156484. }
  156485. }
  156486. static int host_is_big_endian() {
  156487. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156488. unsigned char *bytewise = (unsigned char *)&pattern;
  156489. if (bytewise[0] == 0xfe) return 1;
  156490. return 0;
  156491. }
  156492. /* up to this point, everything could more or less hide the multiple
  156493. logical bitstream nature of chaining from the toplevel application
  156494. if the toplevel application didn't particularly care. However, at
  156495. the point that we actually read audio back, the multiple-section
  156496. nature must surface: Multiple bitstream sections do not necessarily
  156497. have to have the same number of channels or sampling rate.
  156498. ov_read returns the sequential logical bitstream number currently
  156499. being decoded along with the PCM data in order that the toplevel
  156500. application can take action on channel/sample rate changes. This
  156501. number will be incremented even for streamed (non-seekable) streams
  156502. (for seekable streams, it represents the actual logical bitstream
  156503. index within the physical bitstream. Note that the accessor
  156504. functions above are aware of this dichotomy).
  156505. input values: buffer) a buffer to hold packed PCM data for return
  156506. length) the byte length requested to be placed into buffer
  156507. bigendianp) should the data be packed LSB first (0) or
  156508. MSB first (1)
  156509. word) word size for output. currently 1 (byte) or
  156510. 2 (16 bit short)
  156511. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156512. 0) EOF
  156513. n) number of bytes of PCM actually returned. The
  156514. below works on a packet-by-packet basis, so the
  156515. return length is not related to the 'length' passed
  156516. in, just guaranteed to fit.
  156517. *section) set to the logical bitstream number */
  156518. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156519. int bigendianp,int word,int sgned,int *bitstream){
  156520. int i,j;
  156521. int host_endian = host_is_big_endian();
  156522. float **pcm;
  156523. long samples;
  156524. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156525. while(1){
  156526. if(vf->ready_state==INITSET){
  156527. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156528. if(samples)break;
  156529. }
  156530. /* suck in another packet */
  156531. {
  156532. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156533. if(ret==OV_EOF)
  156534. return(0);
  156535. if(ret<=0)
  156536. return(ret);
  156537. }
  156538. }
  156539. if(samples>0){
  156540. /* yay! proceed to pack data into the byte buffer */
  156541. long channels=ov_info(vf,-1)->channels;
  156542. long bytespersample=word * channels;
  156543. vorbis_fpu_control fpu;
  156544. (void) fpu; // (to avoid a warning about it being unused)
  156545. if(samples>length/bytespersample)samples=length/bytespersample;
  156546. if(samples <= 0)
  156547. return OV_EINVAL;
  156548. /* a tight loop to pack each size */
  156549. {
  156550. int val;
  156551. if(word==1){
  156552. int off=(sgned?0:128);
  156553. vorbis_fpu_setround(&fpu);
  156554. for(j=0;j<samples;j++)
  156555. for(i=0;i<channels;i++){
  156556. val=vorbis_ftoi(pcm[i][j]*128.f);
  156557. if(val>127)val=127;
  156558. else if(val<-128)val=-128;
  156559. *buffer++=val+off;
  156560. }
  156561. vorbis_fpu_restore(fpu);
  156562. }else{
  156563. int off=(sgned?0:32768);
  156564. if(host_endian==bigendianp){
  156565. if(sgned){
  156566. vorbis_fpu_setround(&fpu);
  156567. for(i=0;i<channels;i++) { /* It's faster in this order */
  156568. float *src=pcm[i];
  156569. short *dest=((short *)buffer)+i;
  156570. for(j=0;j<samples;j++) {
  156571. val=vorbis_ftoi(src[j]*32768.f);
  156572. if(val>32767)val=32767;
  156573. else if(val<-32768)val=-32768;
  156574. *dest=val;
  156575. dest+=channels;
  156576. }
  156577. }
  156578. vorbis_fpu_restore(fpu);
  156579. }else{
  156580. vorbis_fpu_setround(&fpu);
  156581. for(i=0;i<channels;i++) {
  156582. float *src=pcm[i];
  156583. short *dest=((short *)buffer)+i;
  156584. for(j=0;j<samples;j++) {
  156585. val=vorbis_ftoi(src[j]*32768.f);
  156586. if(val>32767)val=32767;
  156587. else if(val<-32768)val=-32768;
  156588. *dest=val+off;
  156589. dest+=channels;
  156590. }
  156591. }
  156592. vorbis_fpu_restore(fpu);
  156593. }
  156594. }else if(bigendianp){
  156595. vorbis_fpu_setround(&fpu);
  156596. for(j=0;j<samples;j++)
  156597. for(i=0;i<channels;i++){
  156598. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156599. if(val>32767)val=32767;
  156600. else if(val<-32768)val=-32768;
  156601. val+=off;
  156602. *buffer++=(val>>8);
  156603. *buffer++=(val&0xff);
  156604. }
  156605. vorbis_fpu_restore(fpu);
  156606. }else{
  156607. int val;
  156608. vorbis_fpu_setround(&fpu);
  156609. for(j=0;j<samples;j++)
  156610. for(i=0;i<channels;i++){
  156611. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156612. if(val>32767)val=32767;
  156613. else if(val<-32768)val=-32768;
  156614. val+=off;
  156615. *buffer++=(val&0xff);
  156616. *buffer++=(val>>8);
  156617. }
  156618. vorbis_fpu_restore(fpu);
  156619. }
  156620. }
  156621. }
  156622. vorbis_synthesis_read(&vf->vd,samples);
  156623. vf->pcm_offset+=samples;
  156624. if(bitstream)*bitstream=vf->current_link;
  156625. return(samples*bytespersample);
  156626. }else{
  156627. return(samples);
  156628. }
  156629. }
  156630. /* input values: pcm_channels) a float vector per channel of output
  156631. length) the sample length being read by the app
  156632. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156633. 0) EOF
  156634. n) number of samples of PCM actually returned. The
  156635. below works on a packet-by-packet basis, so the
  156636. return length is not related to the 'length' passed
  156637. in, just guaranteed to fit.
  156638. *section) set to the logical bitstream number */
  156639. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156640. int *bitstream){
  156641. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156642. while(1){
  156643. if(vf->ready_state==INITSET){
  156644. float **pcm;
  156645. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156646. if(samples){
  156647. if(pcm_channels)*pcm_channels=pcm;
  156648. if(samples>length)samples=length;
  156649. vorbis_synthesis_read(&vf->vd,samples);
  156650. vf->pcm_offset+=samples;
  156651. if(bitstream)*bitstream=vf->current_link;
  156652. return samples;
  156653. }
  156654. }
  156655. /* suck in another packet */
  156656. {
  156657. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156658. if(ret==OV_EOF)return(0);
  156659. if(ret<=0)return(ret);
  156660. }
  156661. }
  156662. }
  156663. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156664. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156665. ogg_int64_t off);
  156666. static void _ov_splice(float **pcm,float **lappcm,
  156667. int n1, int n2,
  156668. int ch1, int ch2,
  156669. float *w1, float *w2){
  156670. int i,j;
  156671. float *w=w1;
  156672. int n=n1;
  156673. if(n1>n2){
  156674. n=n2;
  156675. w=w2;
  156676. }
  156677. /* splice */
  156678. for(j=0;j<ch1 && j<ch2;j++){
  156679. float *s=lappcm[j];
  156680. float *d=pcm[j];
  156681. for(i=0;i<n;i++){
  156682. float wd=w[i]*w[i];
  156683. float ws=1.-wd;
  156684. d[i]=d[i]*wd + s[i]*ws;
  156685. }
  156686. }
  156687. /* window from zero */
  156688. for(;j<ch2;j++){
  156689. float *d=pcm[j];
  156690. for(i=0;i<n;i++){
  156691. float wd=w[i]*w[i];
  156692. d[i]=d[i]*wd;
  156693. }
  156694. }
  156695. }
  156696. /* make sure vf is INITSET */
  156697. static int _ov_initset(OggVorbis_File *vf){
  156698. while(1){
  156699. if(vf->ready_state==INITSET)break;
  156700. /* suck in another packet */
  156701. {
  156702. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156703. if(ret<0 && ret!=OV_HOLE)return(ret);
  156704. }
  156705. }
  156706. return 0;
  156707. }
  156708. /* make sure vf is INITSET and that we have a primed buffer; if
  156709. we're crosslapping at a stream section boundary, this also makes
  156710. sure we're sanity checking against the right stream information */
  156711. static int _ov_initprime(OggVorbis_File *vf){
  156712. vorbis_dsp_state *vd=&vf->vd;
  156713. while(1){
  156714. if(vf->ready_state==INITSET)
  156715. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156716. /* suck in another packet */
  156717. {
  156718. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156719. if(ret<0 && ret!=OV_HOLE)return(ret);
  156720. }
  156721. }
  156722. return 0;
  156723. }
  156724. /* grab enough data for lapping from vf; this may be in the form of
  156725. unreturned, already-decoded pcm, remaining PCM we will need to
  156726. decode, or synthetic postextrapolation from last packets. */
  156727. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156728. float **lappcm,int lapsize){
  156729. int lapcount=0,i;
  156730. float **pcm;
  156731. /* try first to decode the lapping data */
  156732. while(lapcount<lapsize){
  156733. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156734. if(samples){
  156735. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156736. for(i=0;i<vi->channels;i++)
  156737. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156738. lapcount+=samples;
  156739. vorbis_synthesis_read(vd,samples);
  156740. }else{
  156741. /* suck in another packet */
  156742. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156743. if(ret==OV_EOF)break;
  156744. }
  156745. }
  156746. if(lapcount<lapsize){
  156747. /* failed to get lapping data from normal decode; pry it from the
  156748. postextrapolation buffering, or the second half of the MDCT
  156749. from the last packet */
  156750. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156751. if(samples==0){
  156752. for(i=0;i<vi->channels;i++)
  156753. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156754. lapcount=lapsize;
  156755. }else{
  156756. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156757. for(i=0;i<vi->channels;i++)
  156758. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156759. lapcount+=samples;
  156760. }
  156761. }
  156762. }
  156763. /* this sets up crosslapping of a sample by using trailing data from
  156764. sample 1 and lapping it into the windowing buffer of sample 2 */
  156765. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156766. vorbis_info *vi1,*vi2;
  156767. float **lappcm;
  156768. float **pcm;
  156769. float *w1,*w2;
  156770. int n1,n2,i,ret,hs1,hs2;
  156771. if(vf1==vf2)return(0); /* degenerate case */
  156772. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156773. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156774. /* the relevant overlap buffers must be pre-checked and pre-primed
  156775. before looking at settings in the event that priming would cross
  156776. a bitstream boundary. So, do it now */
  156777. ret=_ov_initset(vf1);
  156778. if(ret)return(ret);
  156779. ret=_ov_initprime(vf2);
  156780. if(ret)return(ret);
  156781. vi1=ov_info(vf1,-1);
  156782. vi2=ov_info(vf2,-1);
  156783. hs1=ov_halfrate_p(vf1);
  156784. hs2=ov_halfrate_p(vf2);
  156785. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156786. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156787. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156788. w1=vorbis_window(&vf1->vd,0);
  156789. w2=vorbis_window(&vf2->vd,0);
  156790. for(i=0;i<vi1->channels;i++)
  156791. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156792. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156793. /* have a lapping buffer from vf1; now to splice it into the lapping
  156794. buffer of vf2 */
  156795. /* consolidate and expose the buffer. */
  156796. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156797. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156798. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156799. /* splice */
  156800. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156801. /* done */
  156802. return(0);
  156803. }
  156804. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156805. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156806. vorbis_info *vi;
  156807. float **lappcm;
  156808. float **pcm;
  156809. float *w1,*w2;
  156810. int n1,n2,ch1,ch2,hs;
  156811. int i,ret;
  156812. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156813. ret=_ov_initset(vf);
  156814. if(ret)return(ret);
  156815. vi=ov_info(vf,-1);
  156816. hs=ov_halfrate_p(vf);
  156817. ch1=vi->channels;
  156818. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156819. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156820. persistent; even if the decode state
  156821. from this link gets dumped, this
  156822. window array continues to exist */
  156823. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156824. for(i=0;i<ch1;i++)
  156825. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156826. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156827. /* have lapping data; seek and prime the buffer */
  156828. ret=localseek(vf,pos);
  156829. if(ret)return ret;
  156830. ret=_ov_initprime(vf);
  156831. if(ret)return(ret);
  156832. /* Guard against cross-link changes; they're perfectly legal */
  156833. vi=ov_info(vf,-1);
  156834. ch2=vi->channels;
  156835. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156836. w2=vorbis_window(&vf->vd,0);
  156837. /* consolidate and expose the buffer. */
  156838. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156839. /* splice */
  156840. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156841. /* done */
  156842. return(0);
  156843. }
  156844. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156845. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156846. }
  156847. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156848. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156849. }
  156850. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156851. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156852. }
  156853. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156854. int (*localseek)(OggVorbis_File *,double)){
  156855. vorbis_info *vi;
  156856. float **lappcm;
  156857. float **pcm;
  156858. float *w1,*w2;
  156859. int n1,n2,ch1,ch2,hs;
  156860. int i,ret;
  156861. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156862. ret=_ov_initset(vf);
  156863. if(ret)return(ret);
  156864. vi=ov_info(vf,-1);
  156865. hs=ov_halfrate_p(vf);
  156866. ch1=vi->channels;
  156867. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156868. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156869. persistent; even if the decode state
  156870. from this link gets dumped, this
  156871. window array continues to exist */
  156872. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156873. for(i=0;i<ch1;i++)
  156874. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156875. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156876. /* have lapping data; seek and prime the buffer */
  156877. ret=localseek(vf,pos);
  156878. if(ret)return ret;
  156879. ret=_ov_initprime(vf);
  156880. if(ret)return(ret);
  156881. /* Guard against cross-link changes; they're perfectly legal */
  156882. vi=ov_info(vf,-1);
  156883. ch2=vi->channels;
  156884. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156885. w2=vorbis_window(&vf->vd,0);
  156886. /* consolidate and expose the buffer. */
  156887. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156888. /* splice */
  156889. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156890. /* done */
  156891. return(0);
  156892. }
  156893. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156894. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156895. }
  156896. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156897. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156898. }
  156899. #endif
  156900. /*** End of inlined file: vorbisfile.c ***/
  156901. /*** Start of inlined file: window.c ***/
  156902. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156903. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156904. // tasks..
  156905. #if JUCE_MSVC
  156906. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156907. #endif
  156908. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156909. #if JUCE_USE_OGGVORBIS
  156910. #include <stdlib.h>
  156911. #include <math.h>
  156912. static float vwin64[32] = {
  156913. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156914. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156915. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156916. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156917. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156918. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156919. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156920. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156921. };
  156922. static float vwin128[64] = {
  156923. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156924. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156925. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156926. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156927. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156928. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156929. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156930. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156931. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156932. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156933. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156934. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156935. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156936. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156937. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156938. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156939. };
  156940. static float vwin256[128] = {
  156941. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156942. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156943. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156944. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156945. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156946. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156947. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156948. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156949. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156950. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156951. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156952. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156953. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156954. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156955. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156956. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156957. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156958. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156959. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156960. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156961. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156962. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156963. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156964. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156965. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156966. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156967. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156968. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156969. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156970. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156971. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156972. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156973. };
  156974. static float vwin512[256] = {
  156975. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156976. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156977. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156978. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156979. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156980. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156981. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156982. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156983. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156984. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156985. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156986. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156987. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156988. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156989. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156990. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156991. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156992. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156993. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156994. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156995. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156996. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156997. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156998. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156999. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157000. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157001. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157002. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157003. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157004. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157005. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157006. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157007. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157008. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157009. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157010. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157011. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157012. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157013. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157014. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157015. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157016. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157017. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157018. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157019. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157020. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157021. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157022. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157023. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157024. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157025. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157026. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157027. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157028. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157029. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157030. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157031. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157032. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157033. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157034. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157035. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157036. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157037. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157038. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157039. };
  157040. static float vwin1024[512] = {
  157041. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157042. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157043. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157044. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157045. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157046. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157047. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157048. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157049. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157050. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157051. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157052. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157053. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157054. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157055. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157056. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157057. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157058. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157059. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157060. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157061. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157062. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157063. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157064. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157065. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157066. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157067. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157068. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157069. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157070. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157071. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157072. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157073. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157074. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157075. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157076. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157077. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157078. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157079. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157080. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157081. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157082. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157083. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157084. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157085. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157086. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157087. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157088. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157089. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157090. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157091. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157092. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157093. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157094. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157095. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157096. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157097. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157098. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157099. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157100. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157101. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157102. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157103. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157104. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157105. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157106. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157107. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157108. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157109. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157110. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157111. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157112. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157113. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157114. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157115. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157116. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157117. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157118. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157119. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157120. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157121. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157122. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157123. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157124. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157125. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157126. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157127. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157128. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157129. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157130. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157131. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157132. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157133. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157134. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157135. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157136. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157137. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157138. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157139. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157140. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157141. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157142. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157143. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157144. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157145. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157146. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157147. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157148. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157149. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157150. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157151. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157152. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157153. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157154. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157155. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157156. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157157. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157158. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157159. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157160. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157161. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157162. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157163. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157164. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157165. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157166. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157167. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157168. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157169. };
  157170. static float vwin2048[1024] = {
  157171. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157172. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157173. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157174. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157175. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157176. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157177. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157178. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157179. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157180. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157181. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157182. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157183. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157184. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157185. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157186. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157187. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157188. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157189. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157190. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157191. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157192. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157193. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157194. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157195. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157196. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157197. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157198. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157199. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157200. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157201. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157202. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157203. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157204. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157205. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157206. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157207. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157208. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157209. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157210. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157211. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157212. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157213. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157214. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157215. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157216. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157217. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157218. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157219. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157220. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157221. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157222. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157223. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157224. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157225. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157226. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157227. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157228. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157229. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157230. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157231. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157232. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157233. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157234. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157235. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157236. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157237. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157238. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157239. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157240. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157241. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157242. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157243. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157244. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157245. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157246. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157247. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157248. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157249. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157250. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157251. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157252. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157253. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157254. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157255. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157256. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157257. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157258. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157259. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157260. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157261. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157262. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157263. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157264. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157265. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157266. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157267. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157268. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157269. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157270. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157271. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157272. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157273. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157274. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157275. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157276. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157277. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157278. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157279. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157280. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157281. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157282. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157283. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157284. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157285. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157286. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157287. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157288. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157289. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157290. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157291. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157292. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157293. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157294. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157295. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157296. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157297. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157298. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157299. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157300. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157301. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157302. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157303. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157304. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157305. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157306. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157307. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157308. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157309. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157310. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157311. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157312. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157313. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157314. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157315. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157316. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157317. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157318. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157319. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157320. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157321. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157322. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157323. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157324. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157325. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157326. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157327. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157328. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157329. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157330. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157331. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157332. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157333. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157334. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157335. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157336. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157337. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157338. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157339. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157340. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157341. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157342. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157343. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157344. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157345. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157346. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157347. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157348. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157349. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157350. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157351. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157352. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157353. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157354. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157355. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157356. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157357. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157358. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157359. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157360. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157361. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157362. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157363. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157364. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157365. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157366. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157367. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157368. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157369. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157370. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157371. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157372. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157373. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157374. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157375. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157376. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157377. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157378. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157379. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157380. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157381. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157382. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157383. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157384. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157385. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157386. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157387. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157388. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157389. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157390. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157391. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157392. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157393. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157394. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157395. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157396. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157397. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157398. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157399. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157400. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157401. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157402. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157403. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157404. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157405. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157406. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157407. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157408. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157409. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157410. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157411. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157412. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157413. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157414. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157415. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157416. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157417. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157418. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157419. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157420. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157421. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157422. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157423. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157424. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157425. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157426. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157427. };
  157428. static float vwin4096[2048] = {
  157429. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157430. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157431. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157432. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157433. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157434. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157435. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157436. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157437. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157438. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157439. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157440. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157441. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157442. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157443. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157444. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157445. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157446. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157447. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157448. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157449. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157450. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157451. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157452. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157453. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157454. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157455. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157456. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157457. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157458. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157459. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157460. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157461. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157462. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157463. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157464. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157465. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157466. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157467. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157468. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157469. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157470. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157471. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157472. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157473. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157474. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157475. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157476. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157477. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157478. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157479. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157480. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157481. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157482. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157483. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157484. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157485. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157486. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157487. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157488. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157489. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157490. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157491. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157492. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157493. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157494. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157495. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157496. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157497. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157498. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157499. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157500. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157501. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157502. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157503. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157504. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157505. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157506. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157507. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157508. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157509. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157510. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157511. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157512. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157513. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157514. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157515. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157516. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157517. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157518. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157519. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157520. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157521. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157522. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157523. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157524. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157525. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157526. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157527. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157528. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157529. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157530. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157531. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157532. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157533. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157534. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157535. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157536. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157537. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157538. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157539. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157540. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157541. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157542. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157543. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157544. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157545. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157546. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157547. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157548. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157549. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157550. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157551. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157552. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157553. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157554. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157555. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157556. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157557. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157558. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157559. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157560. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157561. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157562. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157563. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157564. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157565. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157566. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157567. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157568. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157569. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157570. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157571. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157572. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157573. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157574. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157575. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157576. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157577. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157578. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157579. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157580. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157581. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157582. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157583. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157584. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157585. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157586. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157587. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157588. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157589. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157590. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157591. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157592. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157593. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157594. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157595. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157596. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157597. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157598. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157599. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157600. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157601. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157602. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157603. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157604. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157605. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157606. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157607. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157608. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157609. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157610. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157611. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157612. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157613. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157614. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157615. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157616. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157617. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157618. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157619. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157620. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157621. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157622. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157623. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157624. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157625. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157626. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157627. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157628. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157629. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157630. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157631. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157632. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157633. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157634. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157635. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157636. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157637. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157638. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157639. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157640. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157641. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157642. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157643. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157644. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157645. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157646. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157647. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157648. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157649. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157650. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157651. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157652. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157653. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157654. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157655. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157656. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157657. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157658. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157659. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157660. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157661. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157662. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157663. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157664. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157665. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157666. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157667. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157668. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157669. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157670. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157671. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157672. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157673. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157674. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157675. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157676. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157677. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157678. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157679. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157680. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157681. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157682. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157683. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157684. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157685. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157686. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157687. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157688. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157689. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157690. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157691. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157692. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157693. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157694. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157695. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157696. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157697. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157698. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157699. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157700. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157701. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157702. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157703. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157704. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157705. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157706. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157707. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157708. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157709. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157710. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157711. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157712. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157713. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157714. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157715. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157716. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157717. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157718. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157719. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157720. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157721. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157722. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157723. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157724. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157725. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157726. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157727. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157728. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157729. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157730. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157731. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157732. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157733. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157734. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157735. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157736. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157737. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157738. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157739. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157740. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157741. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157742. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157743. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157744. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157745. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157746. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157747. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157748. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157749. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157750. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157751. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157752. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157753. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157754. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157755. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157756. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157757. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157758. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157759. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157760. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157761. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157762. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157763. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157764. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157765. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157766. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157767. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157768. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157769. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157770. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157771. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157772. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157773. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157774. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157775. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157776. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157777. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157778. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157779. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157780. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157781. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157782. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157783. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157784. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157785. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157786. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157787. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157788. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157789. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157790. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157791. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157792. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157793. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157794. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157795. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157796. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157797. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157798. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157799. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157800. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157801. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157802. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157803. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157804. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157805. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157806. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157807. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157808. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157809. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157810. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157811. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157812. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157813. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157814. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157815. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157816. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157817. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157818. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157819. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157820. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157821. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157822. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157823. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157824. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157825. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157826. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157827. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157828. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157829. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157830. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157831. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157832. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157833. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157834. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157835. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157836. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157837. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157838. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157839. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157840. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157841. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157842. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157843. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157844. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157845. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157846. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157847. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157848. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157849. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157850. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157851. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157852. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157853. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157854. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157855. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157856. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157857. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157858. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157859. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157860. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157861. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157862. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157863. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157864. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157865. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157866. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157867. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157868. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157869. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157870. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157871. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157872. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157873. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157874. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157875. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157876. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157877. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157878. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157879. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157880. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157881. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157882. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157883. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157884. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157885. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157886. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157887. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157888. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157889. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157890. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157891. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157892. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157893. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157894. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157895. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157896. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157897. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157898. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157899. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157900. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157901. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157902. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157903. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157904. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157905. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157906. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157907. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157908. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157909. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157910. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157911. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157912. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157913. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157914. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157915. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157916. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157917. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157918. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157919. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157920. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157921. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157922. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157923. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157924. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157925. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157926. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157927. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157928. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157929. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157930. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157931. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157932. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157933. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157934. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157935. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157936. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157937. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157938. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157939. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157940. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157941. };
  157942. static float vwin8192[4096] = {
  157943. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157944. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157945. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157946. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157947. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157948. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157949. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157950. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157951. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157952. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157953. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157954. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157955. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157956. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157957. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157958. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157959. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157960. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157961. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157962. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157963. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157964. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157965. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157966. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157967. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157968. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157969. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157970. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157971. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157972. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157973. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157974. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157975. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157976. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157977. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157978. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157979. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157980. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157981. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157982. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157983. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157984. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157985. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157986. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157987. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157988. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157989. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157990. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157991. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157992. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157993. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157994. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157995. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157996. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157997. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157998. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157999. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158000. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158001. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158002. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158003. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158004. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158005. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158006. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158007. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158008. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158009. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158010. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158011. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158012. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158013. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158014. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158015. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158016. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158017. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158018. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158019. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158020. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158021. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158022. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158023. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158024. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158025. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158026. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158027. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158028. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158029. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158030. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158031. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158032. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158033. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158034. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158035. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158036. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158037. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158038. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158039. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158040. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158041. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158042. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158043. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158044. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158045. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158046. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158047. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158048. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158049. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158050. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158051. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158052. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158053. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158054. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158055. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158056. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158057. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158058. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158059. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158060. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158061. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158062. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158063. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158064. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158065. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158066. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158067. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158068. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158069. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158070. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158071. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158072. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158073. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158074. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158075. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158076. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158077. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158078. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158079. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158080. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158081. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158082. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158083. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158084. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158085. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158086. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158087. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158088. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158089. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158090. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158091. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158092. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158093. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158094. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158095. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158096. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158097. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158098. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158099. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158100. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158101. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158102. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158103. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158104. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158105. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158106. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158107. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158108. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158109. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158110. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158111. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158112. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158113. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158114. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158115. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158116. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158117. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158118. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158119. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158120. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158121. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158122. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158123. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158124. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158125. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158126. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158127. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158128. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158129. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158130. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158131. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158132. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158133. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158134. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158135. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158136. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158137. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158138. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158139. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158140. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158141. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158142. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158143. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158144. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158145. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158146. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158147. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158148. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158149. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158150. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158151. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158152. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158153. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158154. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158155. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158156. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158157. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158158. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158159. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158160. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158161. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158162. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158163. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158164. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158165. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158166. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158167. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158168. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158169. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158170. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158171. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158172. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158173. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158174. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158175. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158176. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158177. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158178. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158179. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158180. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158181. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158182. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158183. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158184. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158185. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158186. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158187. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158188. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158189. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158190. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158191. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158192. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158193. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158194. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158195. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158196. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158197. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158198. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158199. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158200. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158201. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158202. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158203. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158204. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158205. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158206. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158207. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158208. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158209. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158210. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158211. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158212. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158213. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158214. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158215. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158216. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158217. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158218. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158219. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158220. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158221. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158222. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158223. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158224. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158225. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158226. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158227. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158228. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158229. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158230. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158231. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158232. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158233. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158234. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158235. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158236. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158237. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158238. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158239. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158240. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158241. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158242. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158243. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158244. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158245. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158246. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158247. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158248. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158249. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158250. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158251. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158252. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158253. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158254. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158255. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158256. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158257. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158258. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158259. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158260. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158261. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158262. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158263. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158264. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158265. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158266. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158267. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158268. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158269. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158270. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158271. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158272. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158273. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158274. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158275. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158276. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158277. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158278. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158279. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158280. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158281. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158282. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158283. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158284. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158285. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158286. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158287. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158288. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158289. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158290. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158291. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158292. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158293. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158294. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158295. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158296. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158297. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158298. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158299. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158300. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158301. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158302. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158303. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158304. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158305. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158306. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158307. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158308. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158309. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158310. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158311. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158312. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158313. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158314. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158315. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158316. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158317. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158318. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158319. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158320. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158321. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158322. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158323. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158324. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158325. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158326. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158327. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158328. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158329. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158330. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158331. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158332. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158333. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158334. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158335. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158336. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158337. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158338. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158339. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158340. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158341. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158342. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158343. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158344. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158345. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158346. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158347. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158348. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158349. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158350. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158351. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158352. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158353. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158354. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158355. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158356. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158357. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158358. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158359. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158360. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158361. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158362. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158363. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158364. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158365. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158366. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158367. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158368. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158369. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158370. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158371. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158372. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158373. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158374. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158375. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158376. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158377. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158378. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158379. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158380. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158381. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158382. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158383. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158384. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158385. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158386. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158387. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158388. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158389. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158390. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158391. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158392. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158393. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158394. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158395. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158396. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158397. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158398. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158399. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158400. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158401. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158402. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158403. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158404. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158405. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158406. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158407. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158408. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158409. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158410. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158411. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158412. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158413. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158414. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158415. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158416. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158417. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158418. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158419. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158420. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158421. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158422. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158423. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158424. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158425. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158426. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158427. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158428. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158429. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158430. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158431. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158432. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158433. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158434. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158435. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158436. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158437. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158438. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158439. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158440. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158441. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158442. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158443. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158444. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158445. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158446. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158447. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158448. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158449. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158450. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158451. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158452. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158453. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158454. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158455. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158456. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158457. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158458. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158459. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158460. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158461. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158462. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158463. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158464. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158465. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158466. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158467. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158468. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158469. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158470. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158471. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158472. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158473. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158474. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158475. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158476. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158477. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158478. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158479. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158480. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158481. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158482. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158483. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158484. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158485. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158486. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158487. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158488. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158489. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158490. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158491. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158492. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158493. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158494. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158495. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158496. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158497. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158498. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158499. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158500. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158501. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158502. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158503. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158504. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158505. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158506. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158507. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158508. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158509. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158510. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158511. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158512. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158513. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158514. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158515. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158516. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158517. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158518. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158519. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158520. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158521. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158522. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158523. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158524. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158525. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158526. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158527. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158528. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158529. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158530. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158531. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158532. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158533. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158534. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158535. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158536. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158537. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158538. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158539. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158540. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158541. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158542. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158543. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158544. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158545. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158546. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158547. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158548. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158549. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158550. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158551. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158552. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158553. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158554. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158555. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158556. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158557. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158558. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158559. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158560. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158561. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158562. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158563. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158564. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158565. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158566. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158567. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158568. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158569. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158570. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158571. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158572. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158573. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158574. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158575. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158576. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158577. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158578. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158579. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158580. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158581. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158582. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158583. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158584. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158585. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158586. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158587. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158588. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158589. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158590. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158591. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158592. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158593. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158594. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158595. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158596. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158597. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158598. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158599. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158600. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158601. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158602. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158603. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158604. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158605. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158606. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158607. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158608. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158609. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158610. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158611. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158612. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158613. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158614. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158615. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158616. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158617. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158618. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158619. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158620. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158621. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158622. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158623. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158624. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158625. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158626. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158627. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158628. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158629. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158630. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158631. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158632. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158633. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158634. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158635. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158636. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158637. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158638. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158639. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158640. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158641. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158642. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158643. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158644. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158645. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158646. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158647. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158648. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158649. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158650. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158651. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158652. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158653. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158654. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158655. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158656. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158657. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158658. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158659. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158660. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158661. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158662. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158663. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158664. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158665. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158666. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158667. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158668. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158669. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158670. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158671. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158672. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158673. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158674. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158675. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158676. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158677. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158678. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158679. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158680. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158681. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158682. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158683. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158684. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158685. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158686. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158687. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158688. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158689. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158690. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158691. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158692. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158693. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158694. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158695. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158696. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158697. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158698. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158699. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158700. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158701. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158702. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158703. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158704. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158705. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158706. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158707. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158708. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158709. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158710. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158711. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158712. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158713. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158714. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158715. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158716. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158717. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158718. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158719. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158720. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158721. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158722. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158723. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158724. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158725. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158726. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158727. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158728. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158729. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158730. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158731. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158732. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158733. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158734. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158735. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158736. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158737. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158738. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158739. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158740. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158741. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158742. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158743. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158744. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158745. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158746. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158747. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158748. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158749. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158750. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158751. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158752. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158753. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158754. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158755. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158756. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158757. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158758. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158759. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158760. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158761. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158762. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158763. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158764. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158765. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158766. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158767. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158768. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158769. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158770. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158771. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158772. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158773. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158774. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158775. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158776. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158777. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158778. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158779. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158780. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158781. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158782. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158783. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158784. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158785. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158786. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158787. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158788. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158789. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158790. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158791. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158792. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158793. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158794. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158795. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158796. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158797. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158798. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158799. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158800. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158801. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158802. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158803. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158804. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158805. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158806. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158807. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158808. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158809. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158810. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158811. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158812. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158813. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158814. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158815. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158816. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158817. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158818. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158819. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158820. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158821. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158822. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158823. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158824. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158825. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158826. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158827. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158828. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158829. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158830. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158831. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158832. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158833. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158834. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158835. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158836. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158837. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158838. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158839. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158840. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158841. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158842. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158843. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158844. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158845. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158846. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158847. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158848. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158849. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158850. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158851. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158852. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158853. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158854. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158855. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158856. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158857. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158858. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158859. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158860. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158861. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158862. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158863. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158864. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158865. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158866. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158867. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158868. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158869. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158870. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158871. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158872. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158873. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158874. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158875. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158876. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158877. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158878. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158879. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158880. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158881. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158882. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158883. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158884. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158885. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158886. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158887. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158888. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158889. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158890. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158891. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158892. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158893. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158894. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158895. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158896. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158897. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158898. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158899. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158900. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158901. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158902. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158903. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158904. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158905. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158906. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158907. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158908. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158909. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158910. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158911. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158912. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158913. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158914. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158915. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158916. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158917. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158918. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158919. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158920. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158921. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158922. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158923. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158924. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158925. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158926. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158927. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158928. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158929. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158930. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158931. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158932. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158933. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158934. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158935. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158936. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158937. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158938. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158939. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158940. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158941. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158942. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158943. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158944. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158945. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158946. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158947. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158948. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158949. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158950. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158951. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158952. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158953. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158954. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158955. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158956. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158957. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158958. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158959. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158960. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158961. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158962. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158963. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158964. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158965. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158966. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158967. };
  158968. static float *vwin[8] = {
  158969. vwin64,
  158970. vwin128,
  158971. vwin256,
  158972. vwin512,
  158973. vwin1024,
  158974. vwin2048,
  158975. vwin4096,
  158976. vwin8192,
  158977. };
  158978. float *_vorbis_window_get(int n){
  158979. return vwin[n];
  158980. }
  158981. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158982. int lW,int W,int nW){
  158983. lW=(W?lW:0);
  158984. nW=(W?nW:0);
  158985. {
  158986. float *windowLW=vwin[winno[lW]];
  158987. float *windowNW=vwin[winno[nW]];
  158988. long n=blocksizes[W];
  158989. long ln=blocksizes[lW];
  158990. long rn=blocksizes[nW];
  158991. long leftbegin=n/4-ln/4;
  158992. long leftend=leftbegin+ln/2;
  158993. long rightbegin=n/2+n/4-rn/4;
  158994. long rightend=rightbegin+rn/2;
  158995. int i,p;
  158996. for(i=0;i<leftbegin;i++)
  158997. d[i]=0.f;
  158998. for(p=0;i<leftend;i++,p++)
  158999. d[i]*=windowLW[p];
  159000. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159001. d[i]*=windowNW[p];
  159002. for(;i<n;i++)
  159003. d[i]=0.f;
  159004. }
  159005. }
  159006. #endif
  159007. /*** End of inlined file: window.c ***/
  159008. #else
  159009. #include <vorbis/vorbisenc.h>
  159010. #include <vorbis/codec.h>
  159011. #include <vorbis/vorbisfile.h>
  159012. #endif
  159013. }
  159014. #undef max
  159015. #undef min
  159016. BEGIN_JUCE_NAMESPACE
  159017. static const char* const oggFormatName = "Ogg-Vorbis file";
  159018. static const char* const oggExtensions[] = { ".ogg", 0 };
  159019. class OggReader : public AudioFormatReader
  159020. {
  159021. OggVorbisNamespace::OggVorbis_File ovFile;
  159022. OggVorbisNamespace::ov_callbacks callbacks;
  159023. AudioSampleBuffer reservoir;
  159024. int reservoirStart, samplesInReservoir;
  159025. public:
  159026. OggReader (InputStream* const inp)
  159027. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159028. reservoir (2, 4096),
  159029. reservoirStart (0),
  159030. samplesInReservoir (0)
  159031. {
  159032. using namespace OggVorbisNamespace;
  159033. sampleRate = 0;
  159034. usesFloatingPointData = true;
  159035. callbacks.read_func = &oggReadCallback;
  159036. callbacks.seek_func = &oggSeekCallback;
  159037. callbacks.close_func = &oggCloseCallback;
  159038. callbacks.tell_func = &oggTellCallback;
  159039. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159040. if (err == 0)
  159041. {
  159042. vorbis_info* info = ov_info (&ovFile, -1);
  159043. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159044. numChannels = info->channels;
  159045. bitsPerSample = 16;
  159046. sampleRate = info->rate;
  159047. reservoir.setSize (numChannels,
  159048. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159049. }
  159050. }
  159051. ~OggReader()
  159052. {
  159053. OggVorbisNamespace::ov_clear (&ovFile);
  159054. }
  159055. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159056. int64 startSampleInFile, int numSamples)
  159057. {
  159058. while (numSamples > 0)
  159059. {
  159060. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159061. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159062. {
  159063. // got a few samples overlapping, so use them before seeking..
  159064. const int numToUse = jmin (numSamples, numAvailable);
  159065. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159066. if (destSamples[i] != 0)
  159067. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159068. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159069. sizeof (float) * numToUse);
  159070. startSampleInFile += numToUse;
  159071. numSamples -= numToUse;
  159072. startOffsetInDestBuffer += numToUse;
  159073. if (numSamples == 0)
  159074. break;
  159075. }
  159076. if (startSampleInFile < reservoirStart
  159077. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159078. {
  159079. // buffer miss, so refill the reservoir
  159080. int bitStream = 0;
  159081. reservoirStart = jmax (0, (int) startSampleInFile);
  159082. samplesInReservoir = reservoir.getNumSamples();
  159083. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159084. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159085. int offset = 0;
  159086. int numToRead = samplesInReservoir;
  159087. while (numToRead > 0)
  159088. {
  159089. float** dataIn = 0;
  159090. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159091. if (samps <= 0)
  159092. break;
  159093. jassert (samps <= numToRead);
  159094. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159095. {
  159096. memcpy (reservoir.getSampleData (i, offset),
  159097. dataIn[i],
  159098. sizeof (float) * samps);
  159099. }
  159100. numToRead -= samps;
  159101. offset += samps;
  159102. }
  159103. if (numToRead > 0)
  159104. reservoir.clear (offset, numToRead);
  159105. }
  159106. }
  159107. if (numSamples > 0)
  159108. {
  159109. for (int i = numDestChannels; --i >= 0;)
  159110. if (destSamples[i] != 0)
  159111. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159112. sizeof (int) * numSamples);
  159113. }
  159114. return true;
  159115. }
  159116. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159117. {
  159118. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159119. }
  159120. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159121. {
  159122. InputStream* const in = static_cast <InputStream*> (datasource);
  159123. if (whence == SEEK_CUR)
  159124. offset += in->getPosition();
  159125. else if (whence == SEEK_END)
  159126. offset += in->getTotalLength();
  159127. in->setPosition (offset);
  159128. return 0;
  159129. }
  159130. static int oggCloseCallback (void*)
  159131. {
  159132. return 0;
  159133. }
  159134. static long oggTellCallback (void* datasource)
  159135. {
  159136. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159137. }
  159138. private:
  159139. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159140. };
  159141. class OggWriter : public AudioFormatWriter
  159142. {
  159143. OggVorbisNamespace::ogg_stream_state os;
  159144. OggVorbisNamespace::ogg_page og;
  159145. OggVorbisNamespace::ogg_packet op;
  159146. OggVorbisNamespace::vorbis_info vi;
  159147. OggVorbisNamespace::vorbis_comment vc;
  159148. OggVorbisNamespace::vorbis_dsp_state vd;
  159149. OggVorbisNamespace::vorbis_block vb;
  159150. public:
  159151. bool ok;
  159152. OggWriter (OutputStream* const out,
  159153. const double sampleRate,
  159154. const int numChannels,
  159155. const int bitsPerSample,
  159156. const int qualityIndex)
  159157. : AudioFormatWriter (out, TRANS (oggFormatName),
  159158. sampleRate,
  159159. numChannels,
  159160. bitsPerSample)
  159161. {
  159162. using namespace OggVorbisNamespace;
  159163. ok = false;
  159164. vorbis_info_init (&vi);
  159165. if (vorbis_encode_init_vbr (&vi,
  159166. numChannels,
  159167. (int) sampleRate,
  159168. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159169. {
  159170. vorbis_comment_init (&vc);
  159171. if (JUCEApplication::getInstance() != 0)
  159172. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159173. vorbis_analysis_init (&vd, &vi);
  159174. vorbis_block_init (&vd, &vb);
  159175. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159176. ogg_packet header;
  159177. ogg_packet header_comm;
  159178. ogg_packet header_code;
  159179. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159180. ogg_stream_packetin (&os, &header);
  159181. ogg_stream_packetin (&os, &header_comm);
  159182. ogg_stream_packetin (&os, &header_code);
  159183. for (;;)
  159184. {
  159185. if (ogg_stream_flush (&os, &og) == 0)
  159186. break;
  159187. output->write (og.header, og.header_len);
  159188. output->write (og.body, og.body_len);
  159189. }
  159190. ok = true;
  159191. }
  159192. }
  159193. ~OggWriter()
  159194. {
  159195. using namespace OggVorbisNamespace;
  159196. if (ok)
  159197. {
  159198. // write a zero-length packet to show ogg that we're finished..
  159199. write (0, 0);
  159200. ogg_stream_clear (&os);
  159201. vorbis_block_clear (&vb);
  159202. vorbis_dsp_clear (&vd);
  159203. vorbis_comment_clear (&vc);
  159204. vorbis_info_clear (&vi);
  159205. output->flush();
  159206. }
  159207. else
  159208. {
  159209. vorbis_info_clear (&vi);
  159210. output = 0; // to stop the base class deleting this, as it needs to be returned
  159211. // to the caller of createWriter()
  159212. }
  159213. }
  159214. bool write (const int** samplesToWrite, int numSamples)
  159215. {
  159216. using namespace OggVorbisNamespace;
  159217. if (! ok)
  159218. return false;
  159219. if (numSamples > 0)
  159220. {
  159221. const double gain = 1.0 / 0x80000000u;
  159222. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159223. for (int i = numChannels; --i >= 0;)
  159224. {
  159225. float* const dst = vorbisBuffer[i];
  159226. const int* const src = samplesToWrite [i];
  159227. if (src != 0 && dst != 0)
  159228. {
  159229. for (int j = 0; j < numSamples; ++j)
  159230. dst[j] = (float) (src[j] * gain);
  159231. }
  159232. }
  159233. }
  159234. vorbis_analysis_wrote (&vd, numSamples);
  159235. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159236. {
  159237. vorbis_analysis (&vb, 0);
  159238. vorbis_bitrate_addblock (&vb);
  159239. while (vorbis_bitrate_flushpacket (&vd, &op))
  159240. {
  159241. ogg_stream_packetin (&os, &op);
  159242. for (;;)
  159243. {
  159244. if (ogg_stream_pageout (&os, &og) == 0)
  159245. break;
  159246. output->write (og.header, og.header_len);
  159247. output->write (og.body, og.body_len);
  159248. if (ogg_page_eos (&og))
  159249. break;
  159250. }
  159251. }
  159252. }
  159253. return true;
  159254. }
  159255. private:
  159256. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159257. };
  159258. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159259. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159260. {
  159261. }
  159262. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159263. {
  159264. }
  159265. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159266. {
  159267. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159268. return Array <int> (rates);
  159269. }
  159270. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159271. {
  159272. const int depths[] = { 32, 0 };
  159273. return Array <int> (depths);
  159274. }
  159275. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159276. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159277. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159278. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159279. const bool deleteStreamIfOpeningFails)
  159280. {
  159281. ScopedPointer <OggReader> r (new OggReader (in));
  159282. if (r->sampleRate != 0)
  159283. return r.release();
  159284. if (! deleteStreamIfOpeningFails)
  159285. r->input = 0;
  159286. return 0;
  159287. }
  159288. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159289. double sampleRate,
  159290. unsigned int numChannels,
  159291. int bitsPerSample,
  159292. const StringPairArray& /*metadataValues*/,
  159293. int qualityOptionIndex)
  159294. {
  159295. ScopedPointer <OggWriter> w (new OggWriter (out,
  159296. sampleRate,
  159297. numChannels,
  159298. bitsPerSample,
  159299. qualityOptionIndex));
  159300. return w->ok ? w.release() : 0;
  159301. }
  159302. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159303. {
  159304. StringArray s;
  159305. s.add ("Low Quality");
  159306. s.add ("Medium Quality");
  159307. s.add ("High Quality");
  159308. return s;
  159309. }
  159310. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159311. {
  159312. FileInputStream* const in = source.createInputStream();
  159313. if (in != 0)
  159314. {
  159315. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159316. if (r != 0)
  159317. {
  159318. const int64 numSamps = r->lengthInSamples;
  159319. r = 0;
  159320. const int64 fileNumSamps = source.getSize() / 4;
  159321. const double ratio = numSamps / (double) fileNumSamps;
  159322. if (ratio > 12.0)
  159323. return 0;
  159324. else if (ratio > 6.0)
  159325. return 1;
  159326. else
  159327. return 2;
  159328. }
  159329. }
  159330. return 1;
  159331. }
  159332. END_JUCE_NAMESPACE
  159333. #endif
  159334. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159335. #endif
  159336. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159337. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159338. #if JUCE_MSVC
  159339. #pragma warning (push)
  159340. #endif
  159341. namespace jpeglibNamespace
  159342. {
  159343. #if JUCE_INCLUDE_JPEGLIB_CODE
  159344. #if JUCE_MINGW
  159345. typedef unsigned char boolean;
  159346. #endif
  159347. #define JPEG_INTERNALS
  159348. #undef FAR
  159349. /*** Start of inlined file: jpeglib.h ***/
  159350. #ifndef JPEGLIB_H
  159351. #define JPEGLIB_H
  159352. /*
  159353. * First we include the configuration files that record how this
  159354. * installation of the JPEG library is set up. jconfig.h can be
  159355. * generated automatically for many systems. jmorecfg.h contains
  159356. * manual configuration options that most people need not worry about.
  159357. */
  159358. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159359. /*** Start of inlined file: jconfig.h ***/
  159360. /* see jconfig.doc for explanations */
  159361. // disable all the warnings under MSVC
  159362. #ifdef _MSC_VER
  159363. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159364. #endif
  159365. #ifdef __BORLANDC__
  159366. #pragma warn -8057
  159367. #pragma warn -8019
  159368. #pragma warn -8004
  159369. #pragma warn -8008
  159370. #endif
  159371. #define HAVE_PROTOTYPES
  159372. #define HAVE_UNSIGNED_CHAR
  159373. #define HAVE_UNSIGNED_SHORT
  159374. /* #define void char */
  159375. /* #define const */
  159376. #undef CHAR_IS_UNSIGNED
  159377. #define HAVE_STDDEF_H
  159378. #define HAVE_STDLIB_H
  159379. #undef NEED_BSD_STRINGS
  159380. #undef NEED_SYS_TYPES_H
  159381. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159382. #undef NEED_SHORT_EXTERNAL_NAMES
  159383. #undef INCOMPLETE_TYPES_BROKEN
  159384. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159385. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159386. typedef unsigned char boolean;
  159387. #endif
  159388. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159389. #ifdef JPEG_INTERNALS
  159390. #undef RIGHT_SHIFT_IS_UNSIGNED
  159391. #endif /* JPEG_INTERNALS */
  159392. #ifdef JPEG_CJPEG_DJPEG
  159393. #define BMP_SUPPORTED /* BMP image file format */
  159394. #define GIF_SUPPORTED /* GIF image file format */
  159395. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159396. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159397. #define TARGA_SUPPORTED /* Targa image file format */
  159398. #define TWO_FILE_COMMANDLINE /* optional */
  159399. #define USE_SETMODE /* Microsoft has setmode() */
  159400. #undef NEED_SIGNAL_CATCHER
  159401. #undef DONT_USE_B_MODE
  159402. #undef PROGRESS_REPORT /* optional */
  159403. #endif /* JPEG_CJPEG_DJPEG */
  159404. /*** End of inlined file: jconfig.h ***/
  159405. /* widely used configuration options */
  159406. #endif
  159407. /*** Start of inlined file: jmorecfg.h ***/
  159408. /*
  159409. * Define BITS_IN_JSAMPLE as either
  159410. * 8 for 8-bit sample values (the usual setting)
  159411. * 12 for 12-bit sample values
  159412. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159413. * JPEG standard, and the IJG code does not support anything else!
  159414. * We do not support run-time selection of data precision, sorry.
  159415. */
  159416. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159417. /*
  159418. * Maximum number of components (color channels) allowed in JPEG image.
  159419. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159420. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159421. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159422. * really short on memory. (Each allowed component costs a hundred or so
  159423. * bytes of storage, whether actually used in an image or not.)
  159424. */
  159425. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159426. /*
  159427. * Basic data types.
  159428. * You may need to change these if you have a machine with unusual data
  159429. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159430. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159431. * but it had better be at least 16.
  159432. */
  159433. /* Representation of a single sample (pixel element value).
  159434. * We frequently allocate large arrays of these, so it's important to keep
  159435. * them small. But if you have memory to burn and access to char or short
  159436. * arrays is very slow on your hardware, you might want to change these.
  159437. */
  159438. #if BITS_IN_JSAMPLE == 8
  159439. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159440. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159441. */
  159442. #ifdef HAVE_UNSIGNED_CHAR
  159443. typedef unsigned char JSAMPLE;
  159444. #define GETJSAMPLE(value) ((int) (value))
  159445. #else /* not HAVE_UNSIGNED_CHAR */
  159446. typedef char JSAMPLE;
  159447. #ifdef CHAR_IS_UNSIGNED
  159448. #define GETJSAMPLE(value) ((int) (value))
  159449. #else
  159450. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159451. #endif /* CHAR_IS_UNSIGNED */
  159452. #endif /* HAVE_UNSIGNED_CHAR */
  159453. #define MAXJSAMPLE 255
  159454. #define CENTERJSAMPLE 128
  159455. #endif /* BITS_IN_JSAMPLE == 8 */
  159456. #if BITS_IN_JSAMPLE == 12
  159457. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159458. * On nearly all machines "short" will do nicely.
  159459. */
  159460. typedef short JSAMPLE;
  159461. #define GETJSAMPLE(value) ((int) (value))
  159462. #define MAXJSAMPLE 4095
  159463. #define CENTERJSAMPLE 2048
  159464. #endif /* BITS_IN_JSAMPLE == 12 */
  159465. /* Representation of a DCT frequency coefficient.
  159466. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159467. * Again, we allocate large arrays of these, but you can change to int
  159468. * if you have memory to burn and "short" is really slow.
  159469. */
  159470. typedef short JCOEF;
  159471. /* Compressed datastreams are represented as arrays of JOCTET.
  159472. * These must be EXACTLY 8 bits wide, at least once they are written to
  159473. * external storage. Note that when using the stdio data source/destination
  159474. * managers, this is also the data type passed to fread/fwrite.
  159475. */
  159476. #ifdef HAVE_UNSIGNED_CHAR
  159477. typedef unsigned char JOCTET;
  159478. #define GETJOCTET(value) (value)
  159479. #else /* not HAVE_UNSIGNED_CHAR */
  159480. typedef char JOCTET;
  159481. #ifdef CHAR_IS_UNSIGNED
  159482. #define GETJOCTET(value) (value)
  159483. #else
  159484. #define GETJOCTET(value) ((value) & 0xFF)
  159485. #endif /* CHAR_IS_UNSIGNED */
  159486. #endif /* HAVE_UNSIGNED_CHAR */
  159487. /* These typedefs are used for various table entries and so forth.
  159488. * They must be at least as wide as specified; but making them too big
  159489. * won't cost a huge amount of memory, so we don't provide special
  159490. * extraction code like we did for JSAMPLE. (In other words, these
  159491. * typedefs live at a different point on the speed/space tradeoff curve.)
  159492. */
  159493. /* UINT8 must hold at least the values 0..255. */
  159494. #ifdef HAVE_UNSIGNED_CHAR
  159495. typedef unsigned char UINT8;
  159496. #else /* not HAVE_UNSIGNED_CHAR */
  159497. #ifdef CHAR_IS_UNSIGNED
  159498. typedef char UINT8;
  159499. #else /* not CHAR_IS_UNSIGNED */
  159500. typedef short UINT8;
  159501. #endif /* CHAR_IS_UNSIGNED */
  159502. #endif /* HAVE_UNSIGNED_CHAR */
  159503. /* UINT16 must hold at least the values 0..65535. */
  159504. #ifdef HAVE_UNSIGNED_SHORT
  159505. typedef unsigned short UINT16;
  159506. #else /* not HAVE_UNSIGNED_SHORT */
  159507. typedef unsigned int UINT16;
  159508. #endif /* HAVE_UNSIGNED_SHORT */
  159509. /* INT16 must hold at least the values -32768..32767. */
  159510. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159511. typedef short INT16;
  159512. #endif
  159513. /* INT32 must hold at least signed 32-bit values. */
  159514. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159515. typedef long INT32;
  159516. #endif
  159517. /* Datatype used for image dimensions. The JPEG standard only supports
  159518. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159519. * "unsigned int" is sufficient on all machines. However, if you need to
  159520. * handle larger images and you don't mind deviating from the spec, you
  159521. * can change this datatype.
  159522. */
  159523. typedef unsigned int JDIMENSION;
  159524. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159525. /* These macros are used in all function definitions and extern declarations.
  159526. * You could modify them if you need to change function linkage conventions;
  159527. * in particular, you'll need to do that to make the library a Windows DLL.
  159528. * Another application is to make all functions global for use with debuggers
  159529. * or code profilers that require it.
  159530. */
  159531. /* a function called through method pointers: */
  159532. #define METHODDEF(type) static type
  159533. /* a function used only in its module: */
  159534. #define LOCAL(type) static type
  159535. /* a function referenced thru EXTERNs: */
  159536. #define GLOBAL(type) type
  159537. /* a reference to a GLOBAL function: */
  159538. #define EXTERN(type) extern type
  159539. /* This macro is used to declare a "method", that is, a function pointer.
  159540. * We want to supply prototype parameters if the compiler can cope.
  159541. * Note that the arglist parameter must be parenthesized!
  159542. * Again, you can customize this if you need special linkage keywords.
  159543. */
  159544. #ifdef HAVE_PROTOTYPES
  159545. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159546. #else
  159547. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159548. #endif
  159549. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159550. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159551. * by just saying "FAR *" where such a pointer is needed. In a few places
  159552. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159553. */
  159554. #ifdef NEED_FAR_POINTERS
  159555. #define FAR far
  159556. #else
  159557. #define FAR
  159558. #endif
  159559. /*
  159560. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159561. * in standard header files. Or you may have conflicts with application-
  159562. * specific header files that you want to include together with these files.
  159563. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159564. */
  159565. #ifndef HAVE_BOOLEAN
  159566. typedef int boolean;
  159567. #endif
  159568. #ifndef FALSE /* in case these macros already exist */
  159569. #define FALSE 0 /* values of boolean */
  159570. #endif
  159571. #ifndef TRUE
  159572. #define TRUE 1
  159573. #endif
  159574. /*
  159575. * The remaining options affect code selection within the JPEG library,
  159576. * but they don't need to be visible to most applications using the library.
  159577. * To minimize application namespace pollution, the symbols won't be
  159578. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159579. */
  159580. #ifdef JPEG_INTERNALS
  159581. #define JPEG_INTERNAL_OPTIONS
  159582. #endif
  159583. #ifdef JPEG_INTERNAL_OPTIONS
  159584. /*
  159585. * These defines indicate whether to include various optional functions.
  159586. * Undefining some of these symbols will produce a smaller but less capable
  159587. * library. Note that you can leave certain source files out of the
  159588. * compilation/linking process if you've #undef'd the corresponding symbols.
  159589. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159590. */
  159591. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159592. /* Capability options common to encoder and decoder: */
  159593. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159594. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159595. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159596. /* Encoder capability options: */
  159597. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159598. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159599. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159600. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159601. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159602. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159603. * precision, so jchuff.c normally uses entropy optimization to compute
  159604. * usable tables for higher precision. If you don't want to do optimization,
  159605. * you'll have to supply different default Huffman tables.
  159606. * The exact same statements apply for progressive JPEG: the default tables
  159607. * don't work for progressive mode. (This may get fixed, however.)
  159608. */
  159609. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159610. /* Decoder capability options: */
  159611. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159612. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159613. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159614. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159615. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159616. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159617. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159618. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159619. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159620. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159621. /* more capability options later, no doubt */
  159622. /*
  159623. * Ordering of RGB data in scanlines passed to or from the application.
  159624. * If your application wants to deal with data in the order B,G,R, just
  159625. * change these macros. You can also deal with formats such as R,G,B,X
  159626. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159627. * the offsets will also change the order in which colormap data is organized.
  159628. * RESTRICTIONS:
  159629. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159630. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159631. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159632. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159633. * is not 3 (they don't understand about dummy color components!). So you
  159634. * can't use color quantization if you change that value.
  159635. */
  159636. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159637. #define RGB_GREEN 1 /* Offset of Green */
  159638. #define RGB_BLUE 2 /* Offset of Blue */
  159639. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159640. /* Definitions for speed-related optimizations. */
  159641. /* If your compiler supports inline functions, define INLINE
  159642. * as the inline keyword; otherwise define it as empty.
  159643. */
  159644. #ifndef INLINE
  159645. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159646. #define INLINE __inline__
  159647. #endif
  159648. #ifndef INLINE
  159649. #define INLINE /* default is to define it as empty */
  159650. #endif
  159651. #endif
  159652. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159653. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159654. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159655. */
  159656. #ifndef MULTIPLIER
  159657. #define MULTIPLIER int /* type for fastest integer multiply */
  159658. #endif
  159659. /* FAST_FLOAT should be either float or double, whichever is done faster
  159660. * by your compiler. (Note that this type is only used in the floating point
  159661. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159662. * Typically, float is faster in ANSI C compilers, while double is faster in
  159663. * pre-ANSI compilers (because they insist on converting to double anyway).
  159664. * The code below therefore chooses float if we have ANSI-style prototypes.
  159665. */
  159666. #ifndef FAST_FLOAT
  159667. #ifdef HAVE_PROTOTYPES
  159668. #define FAST_FLOAT float
  159669. #else
  159670. #define FAST_FLOAT double
  159671. #endif
  159672. #endif
  159673. #endif /* JPEG_INTERNAL_OPTIONS */
  159674. /*** End of inlined file: jmorecfg.h ***/
  159675. /* seldom changed options */
  159676. /* Version ID for the JPEG library.
  159677. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159678. */
  159679. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159680. /* Various constants determining the sizes of things.
  159681. * All of these are specified by the JPEG standard, so don't change them
  159682. * if you want to be compatible.
  159683. */
  159684. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159685. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159686. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159687. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159688. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159689. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159690. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159691. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159692. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159693. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159694. * to handle it. We even let you do this from the jconfig.h file. However,
  159695. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159696. * sometimes emits noncompliant files doesn't mean you should too.
  159697. */
  159698. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159699. #ifndef D_MAX_BLOCKS_IN_MCU
  159700. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159701. #endif
  159702. /* Data structures for images (arrays of samples and of DCT coefficients).
  159703. * On 80x86 machines, the image arrays are too big for near pointers,
  159704. * but the pointer arrays can fit in near memory.
  159705. */
  159706. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159707. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159708. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159709. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159710. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159711. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159712. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159713. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159714. /* Types for JPEG compression parameters and working tables. */
  159715. /* DCT coefficient quantization tables. */
  159716. typedef struct {
  159717. /* This array gives the coefficient quantizers in natural array order
  159718. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159719. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159720. */
  159721. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159722. /* This field is used only during compression. It's initialized FALSE when
  159723. * the table is created, and set TRUE when it's been output to the file.
  159724. * You could suppress output of a table by setting this to TRUE.
  159725. * (See jpeg_suppress_tables for an example.)
  159726. */
  159727. boolean sent_table; /* TRUE when table has been output */
  159728. } JQUANT_TBL;
  159729. /* Huffman coding tables. */
  159730. typedef struct {
  159731. /* These two fields directly represent the contents of a JPEG DHT marker */
  159732. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159733. /* length k bits; bits[0] is unused */
  159734. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159735. /* This field is used only during compression. It's initialized FALSE when
  159736. * the table is created, and set TRUE when it's been output to the file.
  159737. * You could suppress output of a table by setting this to TRUE.
  159738. * (See jpeg_suppress_tables for an example.)
  159739. */
  159740. boolean sent_table; /* TRUE when table has been output */
  159741. } JHUFF_TBL;
  159742. /* Basic info about one component (color channel). */
  159743. typedef struct {
  159744. /* These values are fixed over the whole image. */
  159745. /* For compression, they must be supplied by parameter setup; */
  159746. /* for decompression, they are read from the SOF marker. */
  159747. int component_id; /* identifier for this component (0..255) */
  159748. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159749. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159750. int v_samp_factor; /* vertical sampling factor (1..4) */
  159751. int quant_tbl_no; /* quantization table selector (0..3) */
  159752. /* These values may vary between scans. */
  159753. /* For compression, they must be supplied by parameter setup; */
  159754. /* for decompression, they are read from the SOS marker. */
  159755. /* The decompressor output side may not use these variables. */
  159756. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159757. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159758. /* Remaining fields should be treated as private by applications. */
  159759. /* These values are computed during compression or decompression startup: */
  159760. /* Component's size in DCT blocks.
  159761. * Any dummy blocks added to complete an MCU are not counted; therefore
  159762. * these values do not depend on whether a scan is interleaved or not.
  159763. */
  159764. JDIMENSION width_in_blocks;
  159765. JDIMENSION height_in_blocks;
  159766. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159767. * For decompression this is the size of the output from one DCT block,
  159768. * reflecting any scaling we choose to apply during the IDCT step.
  159769. * Values of 1,2,4,8 are likely to be supported. Note that different
  159770. * components may receive different IDCT scalings.
  159771. */
  159772. int DCT_scaled_size;
  159773. /* The downsampled dimensions are the component's actual, unpadded number
  159774. * of samples at the main buffer (preprocessing/compression interface), thus
  159775. * downsampled_width = ceil(image_width * Hi/Hmax)
  159776. * and similarly for height. For decompression, IDCT scaling is included, so
  159777. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159778. */
  159779. JDIMENSION downsampled_width; /* actual width in samples */
  159780. JDIMENSION downsampled_height; /* actual height in samples */
  159781. /* This flag is used only for decompression. In cases where some of the
  159782. * components will be ignored (eg grayscale output from YCbCr image),
  159783. * we can skip most computations for the unused components.
  159784. */
  159785. boolean component_needed; /* do we need the value of this component? */
  159786. /* These values are computed before starting a scan of the component. */
  159787. /* The decompressor output side may not use these variables. */
  159788. int MCU_width; /* number of blocks per MCU, horizontally */
  159789. int MCU_height; /* number of blocks per MCU, vertically */
  159790. int MCU_blocks; /* MCU_width * MCU_height */
  159791. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159792. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159793. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159794. /* Saved quantization table for component; NULL if none yet saved.
  159795. * See jdinput.c comments about the need for this information.
  159796. * This field is currently used only for decompression.
  159797. */
  159798. JQUANT_TBL * quant_table;
  159799. /* Private per-component storage for DCT or IDCT subsystem. */
  159800. void * dct_table;
  159801. } jpeg_component_info;
  159802. /* The script for encoding a multiple-scan file is an array of these: */
  159803. typedef struct {
  159804. int comps_in_scan; /* number of components encoded in this scan */
  159805. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159806. int Ss, Se; /* progressive JPEG spectral selection parms */
  159807. int Ah, Al; /* progressive JPEG successive approx. parms */
  159808. } jpeg_scan_info;
  159809. /* The decompressor can save APPn and COM markers in a list of these: */
  159810. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159811. struct jpeg_marker_struct {
  159812. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159813. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159814. unsigned int original_length; /* # bytes of data in the file */
  159815. unsigned int data_length; /* # bytes of data saved at data[] */
  159816. JOCTET FAR * data; /* the data contained in the marker */
  159817. /* the marker length word is not counted in data_length or original_length */
  159818. };
  159819. /* Known color spaces. */
  159820. typedef enum {
  159821. JCS_UNKNOWN, /* error/unspecified */
  159822. JCS_GRAYSCALE, /* monochrome */
  159823. JCS_RGB, /* red/green/blue */
  159824. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159825. JCS_CMYK, /* C/M/Y/K */
  159826. JCS_YCCK /* Y/Cb/Cr/K */
  159827. } J_COLOR_SPACE;
  159828. /* DCT/IDCT algorithm options. */
  159829. typedef enum {
  159830. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159831. JDCT_IFAST, /* faster, less accurate integer method */
  159832. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159833. } J_DCT_METHOD;
  159834. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159835. #define JDCT_DEFAULT JDCT_ISLOW
  159836. #endif
  159837. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159838. #define JDCT_FASTEST JDCT_IFAST
  159839. #endif
  159840. /* Dithering options for decompression. */
  159841. typedef enum {
  159842. JDITHER_NONE, /* no dithering */
  159843. JDITHER_ORDERED, /* simple ordered dither */
  159844. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159845. } J_DITHER_MODE;
  159846. /* Common fields between JPEG compression and decompression master structs. */
  159847. #define jpeg_common_fields \
  159848. struct jpeg_error_mgr * err; /* Error handler module */\
  159849. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159850. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159851. void * client_data; /* Available for use by application */\
  159852. boolean is_decompressor; /* So common code can tell which is which */\
  159853. int global_state /* For checking call sequence validity */
  159854. /* Routines that are to be used by both halves of the library are declared
  159855. * to receive a pointer to this structure. There are no actual instances of
  159856. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159857. */
  159858. struct jpeg_common_struct {
  159859. jpeg_common_fields; /* Fields common to both master struct types */
  159860. /* Additional fields follow in an actual jpeg_compress_struct or
  159861. * jpeg_decompress_struct. All three structs must agree on these
  159862. * initial fields! (This would be a lot cleaner in C++.)
  159863. */
  159864. };
  159865. typedef struct jpeg_common_struct * j_common_ptr;
  159866. typedef struct jpeg_compress_struct * j_compress_ptr;
  159867. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159868. /* Master record for a compression instance */
  159869. struct jpeg_compress_struct {
  159870. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159871. /* Destination for compressed data */
  159872. struct jpeg_destination_mgr * dest;
  159873. /* Description of source image --- these fields must be filled in by
  159874. * outer application before starting compression. in_color_space must
  159875. * be correct before you can even call jpeg_set_defaults().
  159876. */
  159877. JDIMENSION image_width; /* input image width */
  159878. JDIMENSION image_height; /* input image height */
  159879. int input_components; /* # of color components in input image */
  159880. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159881. double input_gamma; /* image gamma of input image */
  159882. /* Compression parameters --- these fields must be set before calling
  159883. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159884. * initialize everything to reasonable defaults, then changing anything
  159885. * the application specifically wants to change. That way you won't get
  159886. * burnt when new parameters are added. Also note that there are several
  159887. * helper routines to simplify changing parameters.
  159888. */
  159889. int data_precision; /* bits of precision in image data */
  159890. int num_components; /* # of color components in JPEG image */
  159891. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159892. jpeg_component_info * comp_info;
  159893. /* comp_info[i] describes component that appears i'th in SOF */
  159894. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159895. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159896. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159897. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159898. /* ptrs to Huffman coding tables, or NULL if not defined */
  159899. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159900. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159901. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159902. int num_scans; /* # of entries in scan_info array */
  159903. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159904. /* The default value of scan_info is NULL, which causes a single-scan
  159905. * sequential JPEG file to be emitted. To create a multi-scan file,
  159906. * set num_scans and scan_info to point to an array of scan definitions.
  159907. */
  159908. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159909. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159910. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159911. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159912. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159913. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159914. /* The restart interval can be specified in absolute MCUs by setting
  159915. * restart_interval, or in MCU rows by setting restart_in_rows
  159916. * (in which case the correct restart_interval will be figured
  159917. * for each scan).
  159918. */
  159919. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159920. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159921. /* Parameters controlling emission of special markers. */
  159922. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159923. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159924. UINT8 JFIF_minor_version;
  159925. /* These three values are not used by the JPEG code, merely copied */
  159926. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159927. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159928. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159929. UINT8 density_unit; /* JFIF code for pixel size units */
  159930. UINT16 X_density; /* Horizontal pixel density */
  159931. UINT16 Y_density; /* Vertical pixel density */
  159932. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159933. /* State variable: index of next scanline to be written to
  159934. * jpeg_write_scanlines(). Application may use this to control its
  159935. * processing loop, e.g., "while (next_scanline < image_height)".
  159936. */
  159937. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159938. /* Remaining fields are known throughout compressor, but generally
  159939. * should not be touched by a surrounding application.
  159940. */
  159941. /*
  159942. * These fields are computed during compression startup
  159943. */
  159944. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159945. int max_h_samp_factor; /* largest h_samp_factor */
  159946. int max_v_samp_factor; /* largest v_samp_factor */
  159947. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159948. /* The coefficient controller receives data in units of MCU rows as defined
  159949. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159950. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159951. * "iMCU" (interleaved MCU) row.
  159952. */
  159953. /*
  159954. * These fields are valid during any one scan.
  159955. * They describe the components and MCUs actually appearing in the scan.
  159956. */
  159957. int comps_in_scan; /* # of JPEG components in this scan */
  159958. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159959. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159960. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159961. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159962. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159963. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159964. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159965. /* i'th block in an MCU */
  159966. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159967. /*
  159968. * Links to compression subobjects (methods and private variables of modules)
  159969. */
  159970. struct jpeg_comp_master * master;
  159971. struct jpeg_c_main_controller * main;
  159972. struct jpeg_c_prep_controller * prep;
  159973. struct jpeg_c_coef_controller * coef;
  159974. struct jpeg_marker_writer * marker;
  159975. struct jpeg_color_converter * cconvert;
  159976. struct jpeg_downsampler * downsample;
  159977. struct jpeg_forward_dct * fdct;
  159978. struct jpeg_entropy_encoder * entropy;
  159979. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159980. int script_space_size;
  159981. };
  159982. /* Master record for a decompression instance */
  159983. struct jpeg_decompress_struct {
  159984. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159985. /* Source of compressed data */
  159986. struct jpeg_source_mgr * src;
  159987. /* Basic description of image --- filled in by jpeg_read_header(). */
  159988. /* Application may inspect these values to decide how to process image. */
  159989. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159990. JDIMENSION image_height; /* nominal image height */
  159991. int num_components; /* # of color components in JPEG image */
  159992. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159993. /* Decompression processing parameters --- these fields must be set before
  159994. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159995. * them to default values.
  159996. */
  159997. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159998. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159999. double output_gamma; /* image gamma wanted in output */
  160000. boolean buffered_image; /* TRUE=multiple output passes */
  160001. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160002. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160003. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160004. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160005. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160006. /* the following are ignored if not quantize_colors: */
  160007. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160008. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160009. int desired_number_of_colors; /* max # colors to use in created colormap */
  160010. /* these are significant only in buffered-image mode: */
  160011. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160012. boolean enable_external_quant;/* enable future use of external colormap */
  160013. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160014. /* Description of actual output image that will be returned to application.
  160015. * These fields are computed by jpeg_start_decompress().
  160016. * You can also use jpeg_calc_output_dimensions() to determine these values
  160017. * in advance of calling jpeg_start_decompress().
  160018. */
  160019. JDIMENSION output_width; /* scaled image width */
  160020. JDIMENSION output_height; /* scaled image height */
  160021. int out_color_components; /* # of color components in out_color_space */
  160022. int output_components; /* # of color components returned */
  160023. /* output_components is 1 (a colormap index) when quantizing colors;
  160024. * otherwise it equals out_color_components.
  160025. */
  160026. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160027. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160028. * high, space and time will be wasted due to unnecessary data copying.
  160029. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160030. */
  160031. /* When quantizing colors, the output colormap is described by these fields.
  160032. * The application can supply a colormap by setting colormap non-NULL before
  160033. * calling jpeg_start_decompress; otherwise a colormap is created during
  160034. * jpeg_start_decompress or jpeg_start_output.
  160035. * The map has out_color_components rows and actual_number_of_colors columns.
  160036. */
  160037. int actual_number_of_colors; /* number of entries in use */
  160038. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160039. /* State variables: these variables indicate the progress of decompression.
  160040. * The application may examine these but must not modify them.
  160041. */
  160042. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160043. * Application may use this to control its processing loop, e.g.,
  160044. * "while (output_scanline < output_height)".
  160045. */
  160046. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160047. /* Current input scan number and number of iMCU rows completed in scan.
  160048. * These indicate the progress of the decompressor input side.
  160049. */
  160050. int input_scan_number; /* Number of SOS markers seen so far */
  160051. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160052. /* The "output scan number" is the notional scan being displayed by the
  160053. * output side. The decompressor will not allow output scan/row number
  160054. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160055. */
  160056. int output_scan_number; /* Nominal scan number being displayed */
  160057. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160058. /* Current progression status. coef_bits[c][i] indicates the precision
  160059. * with which component c's DCT coefficient i (in zigzag order) is known.
  160060. * It is -1 when no data has yet been received, otherwise it is the point
  160061. * transform (shift) value for the most recent scan of the coefficient
  160062. * (thus, 0 at completion of the progression).
  160063. * This pointer is NULL when reading a non-progressive file.
  160064. */
  160065. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160066. /* Internal JPEG parameters --- the application usually need not look at
  160067. * these fields. Note that the decompressor output side may not use
  160068. * any parameters that can change between scans.
  160069. */
  160070. /* Quantization and Huffman tables are carried forward across input
  160071. * datastreams when processing abbreviated JPEG datastreams.
  160072. */
  160073. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160074. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160075. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160076. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160077. /* ptrs to Huffman coding tables, or NULL if not defined */
  160078. /* These parameters are never carried across datastreams, since they
  160079. * are given in SOF/SOS markers or defined to be reset by SOI.
  160080. */
  160081. int data_precision; /* bits of precision in image data */
  160082. jpeg_component_info * comp_info;
  160083. /* comp_info[i] describes component that appears i'th in SOF */
  160084. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160085. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160086. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160087. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160088. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160089. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160090. /* These fields record data obtained from optional markers recognized by
  160091. * the JPEG library.
  160092. */
  160093. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160094. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160095. UINT8 JFIF_major_version; /* JFIF version number */
  160096. UINT8 JFIF_minor_version;
  160097. UINT8 density_unit; /* JFIF code for pixel size units */
  160098. UINT16 X_density; /* Horizontal pixel density */
  160099. UINT16 Y_density; /* Vertical pixel density */
  160100. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160101. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160102. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160103. /* Aside from the specific data retained from APPn markers known to the
  160104. * library, the uninterpreted contents of any or all APPn and COM markers
  160105. * can be saved in a list for examination by the application.
  160106. */
  160107. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160108. /* Remaining fields are known throughout decompressor, but generally
  160109. * should not be touched by a surrounding application.
  160110. */
  160111. /*
  160112. * These fields are computed during decompression startup
  160113. */
  160114. int max_h_samp_factor; /* largest h_samp_factor */
  160115. int max_v_samp_factor; /* largest v_samp_factor */
  160116. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160117. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160118. /* The coefficient controller's input and output progress is measured in
  160119. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160120. * in fully interleaved JPEG scans, but are used whether the scan is
  160121. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160122. * rows of each component. Therefore, the IDCT output contains
  160123. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160124. */
  160125. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160126. /*
  160127. * These fields are valid during any one scan.
  160128. * They describe the components and MCUs actually appearing in the scan.
  160129. * Note that the decompressor output side must not use these fields.
  160130. */
  160131. int comps_in_scan; /* # of JPEG components in this scan */
  160132. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160133. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160134. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160135. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160136. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160137. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160138. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160139. /* i'th block in an MCU */
  160140. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160141. /* This field is shared between entropy decoder and marker parser.
  160142. * It is either zero or the code of a JPEG marker that has been
  160143. * read from the data source, but has not yet been processed.
  160144. */
  160145. int unread_marker;
  160146. /*
  160147. * Links to decompression subobjects (methods, private variables of modules)
  160148. */
  160149. struct jpeg_decomp_master * master;
  160150. struct jpeg_d_main_controller * main;
  160151. struct jpeg_d_coef_controller * coef;
  160152. struct jpeg_d_post_controller * post;
  160153. struct jpeg_input_controller * inputctl;
  160154. struct jpeg_marker_reader * marker;
  160155. struct jpeg_entropy_decoder * entropy;
  160156. struct jpeg_inverse_dct * idct;
  160157. struct jpeg_upsampler * upsample;
  160158. struct jpeg_color_deconverter * cconvert;
  160159. struct jpeg_color_quantizer * cquantize;
  160160. };
  160161. /* "Object" declarations for JPEG modules that may be supplied or called
  160162. * directly by the surrounding application.
  160163. * As with all objects in the JPEG library, these structs only define the
  160164. * publicly visible methods and state variables of a module. Additional
  160165. * private fields may exist after the public ones.
  160166. */
  160167. /* Error handler object */
  160168. struct jpeg_error_mgr {
  160169. /* Error exit handler: does not return to caller */
  160170. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160171. /* Conditionally emit a trace or warning message */
  160172. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160173. /* Routine that actually outputs a trace or error message */
  160174. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160175. /* Format a message string for the most recent JPEG error or message */
  160176. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160177. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160178. /* Reset error state variables at start of a new image */
  160179. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160180. /* The message ID code and any parameters are saved here.
  160181. * A message can have one string parameter or up to 8 int parameters.
  160182. */
  160183. int msg_code;
  160184. #define JMSG_STR_PARM_MAX 80
  160185. union {
  160186. int i[8];
  160187. char s[JMSG_STR_PARM_MAX];
  160188. } msg_parm;
  160189. /* Standard state variables for error facility */
  160190. int trace_level; /* max msg_level that will be displayed */
  160191. /* For recoverable corrupt-data errors, we emit a warning message,
  160192. * but keep going unless emit_message chooses to abort. emit_message
  160193. * should count warnings in num_warnings. The surrounding application
  160194. * can check for bad data by seeing if num_warnings is nonzero at the
  160195. * end of processing.
  160196. */
  160197. long num_warnings; /* number of corrupt-data warnings */
  160198. /* These fields point to the table(s) of error message strings.
  160199. * An application can change the table pointer to switch to a different
  160200. * message list (typically, to change the language in which errors are
  160201. * reported). Some applications may wish to add additional error codes
  160202. * that will be handled by the JPEG library error mechanism; the second
  160203. * table pointer is used for this purpose.
  160204. *
  160205. * First table includes all errors generated by JPEG library itself.
  160206. * Error code 0 is reserved for a "no such error string" message.
  160207. */
  160208. const char * const * jpeg_message_table; /* Library errors */
  160209. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160210. /* Second table can be added by application (see cjpeg/djpeg for example).
  160211. * It contains strings numbered first_addon_message..last_addon_message.
  160212. */
  160213. const char * const * addon_message_table; /* Non-library errors */
  160214. int first_addon_message; /* code for first string in addon table */
  160215. int last_addon_message; /* code for last string in addon table */
  160216. };
  160217. /* Progress monitor object */
  160218. struct jpeg_progress_mgr {
  160219. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160220. long pass_counter; /* work units completed in this pass */
  160221. long pass_limit; /* total number of work units in this pass */
  160222. int completed_passes; /* passes completed so far */
  160223. int total_passes; /* total number of passes expected */
  160224. };
  160225. /* Data destination object for compression */
  160226. struct jpeg_destination_mgr {
  160227. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160228. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160229. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160230. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160231. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160232. };
  160233. /* Data source object for decompression */
  160234. struct jpeg_source_mgr {
  160235. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160236. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160237. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160238. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160239. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160240. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160241. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160242. };
  160243. /* Memory manager object.
  160244. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160245. * and "really big" objects (virtual arrays with backing store if needed).
  160246. * The memory manager does not allow individual objects to be freed; rather,
  160247. * each created object is assigned to a pool, and whole pools can be freed
  160248. * at once. This is faster and more convenient than remembering exactly what
  160249. * to free, especially where malloc()/free() are not too speedy.
  160250. * NB: alloc routines never return NULL. They exit to error_exit if not
  160251. * successful.
  160252. */
  160253. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160254. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160255. #define JPOOL_NUMPOOLS 2
  160256. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160257. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160258. struct jpeg_memory_mgr {
  160259. /* Method pointers */
  160260. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160261. size_t sizeofobject));
  160262. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160263. size_t sizeofobject));
  160264. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160265. JDIMENSION samplesperrow,
  160266. JDIMENSION numrows));
  160267. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160268. JDIMENSION blocksperrow,
  160269. JDIMENSION numrows));
  160270. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160271. int pool_id,
  160272. boolean pre_zero,
  160273. JDIMENSION samplesperrow,
  160274. JDIMENSION numrows,
  160275. JDIMENSION maxaccess));
  160276. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160277. int pool_id,
  160278. boolean pre_zero,
  160279. JDIMENSION blocksperrow,
  160280. JDIMENSION numrows,
  160281. JDIMENSION maxaccess));
  160282. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160283. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160284. jvirt_sarray_ptr ptr,
  160285. JDIMENSION start_row,
  160286. JDIMENSION num_rows,
  160287. boolean writable));
  160288. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160289. jvirt_barray_ptr ptr,
  160290. JDIMENSION start_row,
  160291. JDIMENSION num_rows,
  160292. boolean writable));
  160293. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160294. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160295. /* Limit on memory allocation for this JPEG object. (Note that this is
  160296. * merely advisory, not a guaranteed maximum; it only affects the space
  160297. * used for virtual-array buffers.) May be changed by outer application
  160298. * after creating the JPEG object.
  160299. */
  160300. long max_memory_to_use;
  160301. /* Maximum allocation request accepted by alloc_large. */
  160302. long max_alloc_chunk;
  160303. };
  160304. /* Routine signature for application-supplied marker processing methods.
  160305. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160306. */
  160307. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160308. /* Declarations for routines called by application.
  160309. * The JPP macro hides prototype parameters from compilers that can't cope.
  160310. * Note JPP requires double parentheses.
  160311. */
  160312. #ifdef HAVE_PROTOTYPES
  160313. #define JPP(arglist) arglist
  160314. #else
  160315. #define JPP(arglist) ()
  160316. #endif
  160317. /* Short forms of external names for systems with brain-damaged linkers.
  160318. * We shorten external names to be unique in the first six letters, which
  160319. * is good enough for all known systems.
  160320. * (If your compiler itself needs names to be unique in less than 15
  160321. * characters, you are out of luck. Get a better compiler.)
  160322. */
  160323. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160324. #define jpeg_std_error jStdError
  160325. #define jpeg_CreateCompress jCreaCompress
  160326. #define jpeg_CreateDecompress jCreaDecompress
  160327. #define jpeg_destroy_compress jDestCompress
  160328. #define jpeg_destroy_decompress jDestDecompress
  160329. #define jpeg_stdio_dest jStdDest
  160330. #define jpeg_stdio_src jStdSrc
  160331. #define jpeg_set_defaults jSetDefaults
  160332. #define jpeg_set_colorspace jSetColorspace
  160333. #define jpeg_default_colorspace jDefColorspace
  160334. #define jpeg_set_quality jSetQuality
  160335. #define jpeg_set_linear_quality jSetLQuality
  160336. #define jpeg_add_quant_table jAddQuantTable
  160337. #define jpeg_quality_scaling jQualityScaling
  160338. #define jpeg_simple_progression jSimProgress
  160339. #define jpeg_suppress_tables jSuppressTables
  160340. #define jpeg_alloc_quant_table jAlcQTable
  160341. #define jpeg_alloc_huff_table jAlcHTable
  160342. #define jpeg_start_compress jStrtCompress
  160343. #define jpeg_write_scanlines jWrtScanlines
  160344. #define jpeg_finish_compress jFinCompress
  160345. #define jpeg_write_raw_data jWrtRawData
  160346. #define jpeg_write_marker jWrtMarker
  160347. #define jpeg_write_m_header jWrtMHeader
  160348. #define jpeg_write_m_byte jWrtMByte
  160349. #define jpeg_write_tables jWrtTables
  160350. #define jpeg_read_header jReadHeader
  160351. #define jpeg_start_decompress jStrtDecompress
  160352. #define jpeg_read_scanlines jReadScanlines
  160353. #define jpeg_finish_decompress jFinDecompress
  160354. #define jpeg_read_raw_data jReadRawData
  160355. #define jpeg_has_multiple_scans jHasMultScn
  160356. #define jpeg_start_output jStrtOutput
  160357. #define jpeg_finish_output jFinOutput
  160358. #define jpeg_input_complete jInComplete
  160359. #define jpeg_new_colormap jNewCMap
  160360. #define jpeg_consume_input jConsumeInput
  160361. #define jpeg_calc_output_dimensions jCalcDimensions
  160362. #define jpeg_save_markers jSaveMarkers
  160363. #define jpeg_set_marker_processor jSetMarker
  160364. #define jpeg_read_coefficients jReadCoefs
  160365. #define jpeg_write_coefficients jWrtCoefs
  160366. #define jpeg_copy_critical_parameters jCopyCrit
  160367. #define jpeg_abort_compress jAbrtCompress
  160368. #define jpeg_abort_decompress jAbrtDecompress
  160369. #define jpeg_abort jAbort
  160370. #define jpeg_destroy jDestroy
  160371. #define jpeg_resync_to_restart jResyncRestart
  160372. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160373. /* Default error-management setup */
  160374. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160375. JPP((struct jpeg_error_mgr * err));
  160376. /* Initialization of JPEG compression objects.
  160377. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160378. * names that applications should call. These expand to calls on
  160379. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160380. * passed for version mismatch checking.
  160381. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160382. */
  160383. #define jpeg_create_compress(cinfo) \
  160384. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160385. (size_t) sizeof(struct jpeg_compress_struct))
  160386. #define jpeg_create_decompress(cinfo) \
  160387. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160388. (size_t) sizeof(struct jpeg_decompress_struct))
  160389. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160390. int version, size_t structsize));
  160391. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160392. int version, size_t structsize));
  160393. /* Destruction of JPEG compression objects */
  160394. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160395. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160396. /* Standard data source and destination managers: stdio streams. */
  160397. /* Caller is responsible for opening the file before and closing after. */
  160398. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160399. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160400. /* Default parameter setup for compression */
  160401. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160402. /* Compression parameter setup aids */
  160403. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160404. J_COLOR_SPACE colorspace));
  160405. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160406. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160407. boolean force_baseline));
  160408. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160409. int scale_factor,
  160410. boolean force_baseline));
  160411. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160412. const unsigned int *basic_table,
  160413. int scale_factor,
  160414. boolean force_baseline));
  160415. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160416. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160417. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160418. boolean suppress));
  160419. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160420. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160421. /* Main entry points for compression */
  160422. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160423. boolean write_all_tables));
  160424. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160425. JSAMPARRAY scanlines,
  160426. JDIMENSION num_lines));
  160427. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160428. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160429. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160430. JSAMPIMAGE data,
  160431. JDIMENSION num_lines));
  160432. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160433. EXTERN(void) jpeg_write_marker
  160434. JPP((j_compress_ptr cinfo, int marker,
  160435. const JOCTET * dataptr, unsigned int datalen));
  160436. /* Same, but piecemeal. */
  160437. EXTERN(void) jpeg_write_m_header
  160438. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160439. EXTERN(void) jpeg_write_m_byte
  160440. JPP((j_compress_ptr cinfo, int val));
  160441. /* Alternate compression function: just write an abbreviated table file */
  160442. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160443. /* Decompression startup: read start of JPEG datastream to see what's there */
  160444. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160445. boolean require_image));
  160446. /* Return value is one of: */
  160447. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160448. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160449. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160450. /* If you pass require_image = TRUE (normal case), you need not check for
  160451. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160452. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160453. * give a suspension return (the stdio source module doesn't).
  160454. */
  160455. /* Main entry points for decompression */
  160456. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160457. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160458. JSAMPARRAY scanlines,
  160459. JDIMENSION max_lines));
  160460. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160461. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160462. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160463. JSAMPIMAGE data,
  160464. JDIMENSION max_lines));
  160465. /* Additional entry points for buffered-image mode. */
  160466. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160467. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160468. int scan_number));
  160469. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160470. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160471. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160472. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160473. /* Return value is one of: */
  160474. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160475. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160476. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160477. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160478. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160479. /* Precalculate output dimensions for current decompression parameters. */
  160480. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160481. /* Control saving of COM and APPn markers into marker_list. */
  160482. EXTERN(void) jpeg_save_markers
  160483. JPP((j_decompress_ptr cinfo, int marker_code,
  160484. unsigned int length_limit));
  160485. /* Install a special processing method for COM or APPn markers. */
  160486. EXTERN(void) jpeg_set_marker_processor
  160487. JPP((j_decompress_ptr cinfo, int marker_code,
  160488. jpeg_marker_parser_method routine));
  160489. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160490. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160491. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160492. jvirt_barray_ptr * coef_arrays));
  160493. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160494. j_compress_ptr dstinfo));
  160495. /* If you choose to abort compression or decompression before completing
  160496. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160497. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160498. * if you're done with the JPEG object, but if you want to clean it up and
  160499. * reuse it, call this:
  160500. */
  160501. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160502. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160503. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160504. * flavor of JPEG object. These may be more convenient in some places.
  160505. */
  160506. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160507. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160508. /* Default restart-marker-resync procedure for use by data source modules */
  160509. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160510. int desired));
  160511. /* These marker codes are exported since applications and data source modules
  160512. * are likely to want to use them.
  160513. */
  160514. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160515. #define JPEG_EOI 0xD9 /* EOI marker code */
  160516. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160517. #define JPEG_COM 0xFE /* COM marker code */
  160518. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160519. * for structure definitions that are never filled in, keep it quiet by
  160520. * supplying dummy definitions for the various substructures.
  160521. */
  160522. #ifdef INCOMPLETE_TYPES_BROKEN
  160523. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160524. struct jvirt_sarray_control { long dummy; };
  160525. struct jvirt_barray_control { long dummy; };
  160526. struct jpeg_comp_master { long dummy; };
  160527. struct jpeg_c_main_controller { long dummy; };
  160528. struct jpeg_c_prep_controller { long dummy; };
  160529. struct jpeg_c_coef_controller { long dummy; };
  160530. struct jpeg_marker_writer { long dummy; };
  160531. struct jpeg_color_converter { long dummy; };
  160532. struct jpeg_downsampler { long dummy; };
  160533. struct jpeg_forward_dct { long dummy; };
  160534. struct jpeg_entropy_encoder { long dummy; };
  160535. struct jpeg_decomp_master { long dummy; };
  160536. struct jpeg_d_main_controller { long dummy; };
  160537. struct jpeg_d_coef_controller { long dummy; };
  160538. struct jpeg_d_post_controller { long dummy; };
  160539. struct jpeg_input_controller { long dummy; };
  160540. struct jpeg_marker_reader { long dummy; };
  160541. struct jpeg_entropy_decoder { long dummy; };
  160542. struct jpeg_inverse_dct { long dummy; };
  160543. struct jpeg_upsampler { long dummy; };
  160544. struct jpeg_color_deconverter { long dummy; };
  160545. struct jpeg_color_quantizer { long dummy; };
  160546. #endif /* JPEG_INTERNALS */
  160547. #endif /* INCOMPLETE_TYPES_BROKEN */
  160548. /*
  160549. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160550. * The internal structure declarations are read only when that is true.
  160551. * Applications using the library should not include jpegint.h, but may wish
  160552. * to include jerror.h.
  160553. */
  160554. #ifdef JPEG_INTERNALS
  160555. /*** Start of inlined file: jpegint.h ***/
  160556. /* Declarations for both compression & decompression */
  160557. typedef enum { /* Operating modes for buffer controllers */
  160558. JBUF_PASS_THRU, /* Plain stripwise operation */
  160559. /* Remaining modes require a full-image buffer to have been created */
  160560. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160561. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160562. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160563. } J_BUF_MODE;
  160564. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160565. #define CSTATE_START 100 /* after create_compress */
  160566. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160567. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160568. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160569. #define DSTATE_START 200 /* after create_decompress */
  160570. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160571. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160572. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160573. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160574. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160575. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160576. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160577. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160578. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160579. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160580. /* Declarations for compression modules */
  160581. /* Master control module */
  160582. struct jpeg_comp_master {
  160583. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160584. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160585. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160586. /* State variables made visible to other modules */
  160587. boolean call_pass_startup; /* True if pass_startup must be called */
  160588. boolean is_last_pass; /* True during last pass */
  160589. };
  160590. /* Main buffer control (downsampled-data buffer) */
  160591. struct jpeg_c_main_controller {
  160592. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160593. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160594. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160595. JDIMENSION in_rows_avail));
  160596. };
  160597. /* Compression preprocessing (downsampling input buffer control) */
  160598. struct jpeg_c_prep_controller {
  160599. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160600. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160601. JSAMPARRAY input_buf,
  160602. JDIMENSION *in_row_ctr,
  160603. JDIMENSION in_rows_avail,
  160604. JSAMPIMAGE output_buf,
  160605. JDIMENSION *out_row_group_ctr,
  160606. JDIMENSION out_row_groups_avail));
  160607. };
  160608. /* Coefficient buffer control */
  160609. struct jpeg_c_coef_controller {
  160610. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160611. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160612. JSAMPIMAGE input_buf));
  160613. };
  160614. /* Colorspace conversion */
  160615. struct jpeg_color_converter {
  160616. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160617. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160618. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160619. JDIMENSION output_row, int num_rows));
  160620. };
  160621. /* Downsampling */
  160622. struct jpeg_downsampler {
  160623. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160624. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160625. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160626. JSAMPIMAGE output_buf,
  160627. JDIMENSION out_row_group_index));
  160628. boolean need_context_rows; /* TRUE if need rows above & below */
  160629. };
  160630. /* Forward DCT (also controls coefficient quantization) */
  160631. struct jpeg_forward_dct {
  160632. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160633. /* perhaps this should be an array??? */
  160634. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160635. jpeg_component_info * compptr,
  160636. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160637. JDIMENSION start_row, JDIMENSION start_col,
  160638. JDIMENSION num_blocks));
  160639. };
  160640. /* Entropy encoding */
  160641. struct jpeg_entropy_encoder {
  160642. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160643. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160644. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160645. };
  160646. /* Marker writing */
  160647. struct jpeg_marker_writer {
  160648. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160649. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160650. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160651. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160652. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160653. /* These routines are exported to allow insertion of extra markers */
  160654. /* Probably only COM and APPn markers should be written this way */
  160655. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160656. unsigned int datalen));
  160657. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160658. };
  160659. /* Declarations for decompression modules */
  160660. /* Master control module */
  160661. struct jpeg_decomp_master {
  160662. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160663. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160664. /* State variables made visible to other modules */
  160665. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160666. };
  160667. /* Input control module */
  160668. struct jpeg_input_controller {
  160669. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160670. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160671. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160672. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160673. /* State variables made visible to other modules */
  160674. boolean has_multiple_scans; /* True if file has multiple scans */
  160675. boolean eoi_reached; /* True when EOI has been consumed */
  160676. };
  160677. /* Main buffer control (downsampled-data buffer) */
  160678. struct jpeg_d_main_controller {
  160679. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160680. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160681. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160682. JDIMENSION out_rows_avail));
  160683. };
  160684. /* Coefficient buffer control */
  160685. struct jpeg_d_coef_controller {
  160686. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160687. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160688. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160689. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160690. JSAMPIMAGE output_buf));
  160691. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160692. jvirt_barray_ptr *coef_arrays;
  160693. };
  160694. /* Decompression postprocessing (color quantization buffer control) */
  160695. struct jpeg_d_post_controller {
  160696. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160697. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160698. JSAMPIMAGE input_buf,
  160699. JDIMENSION *in_row_group_ctr,
  160700. JDIMENSION in_row_groups_avail,
  160701. JSAMPARRAY output_buf,
  160702. JDIMENSION *out_row_ctr,
  160703. JDIMENSION out_rows_avail));
  160704. };
  160705. /* Marker reading & parsing */
  160706. struct jpeg_marker_reader {
  160707. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160708. /* Read markers until SOS or EOI.
  160709. * Returns same codes as are defined for jpeg_consume_input:
  160710. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160711. */
  160712. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160713. /* Read a restart marker --- exported for use by entropy decoder only */
  160714. jpeg_marker_parser_method read_restart_marker;
  160715. /* State of marker reader --- nominally internal, but applications
  160716. * supplying COM or APPn handlers might like to know the state.
  160717. */
  160718. boolean saw_SOI; /* found SOI? */
  160719. boolean saw_SOF; /* found SOF? */
  160720. int next_restart_num; /* next restart number expected (0-7) */
  160721. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160722. };
  160723. /* Entropy decoding */
  160724. struct jpeg_entropy_decoder {
  160725. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160726. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160727. JBLOCKROW *MCU_data));
  160728. /* This is here to share code between baseline and progressive decoders; */
  160729. /* other modules probably should not use it */
  160730. boolean insufficient_data; /* set TRUE after emitting warning */
  160731. };
  160732. /* Inverse DCT (also performs dequantization) */
  160733. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160734. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160735. JCOEFPTR coef_block,
  160736. JSAMPARRAY output_buf, JDIMENSION output_col));
  160737. struct jpeg_inverse_dct {
  160738. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160739. /* It is useful to allow each component to have a separate IDCT method. */
  160740. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160741. };
  160742. /* Upsampling (note that upsampler must also call color converter) */
  160743. struct jpeg_upsampler {
  160744. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160745. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160746. JSAMPIMAGE input_buf,
  160747. JDIMENSION *in_row_group_ctr,
  160748. JDIMENSION in_row_groups_avail,
  160749. JSAMPARRAY output_buf,
  160750. JDIMENSION *out_row_ctr,
  160751. JDIMENSION out_rows_avail));
  160752. boolean need_context_rows; /* TRUE if need rows above & below */
  160753. };
  160754. /* Colorspace conversion */
  160755. struct jpeg_color_deconverter {
  160756. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160757. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160758. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160759. JSAMPARRAY output_buf, int num_rows));
  160760. };
  160761. /* Color quantization or color precision reduction */
  160762. struct jpeg_color_quantizer {
  160763. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160764. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160765. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160766. int num_rows));
  160767. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160768. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160769. };
  160770. /* Miscellaneous useful macros */
  160771. #undef MAX
  160772. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160773. #undef MIN
  160774. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160775. /* We assume that right shift corresponds to signed division by 2 with
  160776. * rounding towards minus infinity. This is correct for typical "arithmetic
  160777. * shift" instructions that shift in copies of the sign bit. But some
  160778. * C compilers implement >> with an unsigned shift. For these machines you
  160779. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160780. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160781. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160782. * included in the variables of any routine using RIGHT_SHIFT.
  160783. */
  160784. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160785. #define SHIFT_TEMPS INT32 shift_temp;
  160786. #define RIGHT_SHIFT(x,shft) \
  160787. ((shift_temp = (x)) < 0 ? \
  160788. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160789. (shift_temp >> (shft)))
  160790. #else
  160791. #define SHIFT_TEMPS
  160792. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160793. #endif
  160794. /* Short forms of external names for systems with brain-damaged linkers. */
  160795. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160796. #define jinit_compress_master jICompress
  160797. #define jinit_c_master_control jICMaster
  160798. #define jinit_c_main_controller jICMainC
  160799. #define jinit_c_prep_controller jICPrepC
  160800. #define jinit_c_coef_controller jICCoefC
  160801. #define jinit_color_converter jICColor
  160802. #define jinit_downsampler jIDownsampler
  160803. #define jinit_forward_dct jIFDCT
  160804. #define jinit_huff_encoder jIHEncoder
  160805. #define jinit_phuff_encoder jIPHEncoder
  160806. #define jinit_marker_writer jIMWriter
  160807. #define jinit_master_decompress jIDMaster
  160808. #define jinit_d_main_controller jIDMainC
  160809. #define jinit_d_coef_controller jIDCoefC
  160810. #define jinit_d_post_controller jIDPostC
  160811. #define jinit_input_controller jIInCtlr
  160812. #define jinit_marker_reader jIMReader
  160813. #define jinit_huff_decoder jIHDecoder
  160814. #define jinit_phuff_decoder jIPHDecoder
  160815. #define jinit_inverse_dct jIIDCT
  160816. #define jinit_upsampler jIUpsampler
  160817. #define jinit_color_deconverter jIDColor
  160818. #define jinit_1pass_quantizer jI1Quant
  160819. #define jinit_2pass_quantizer jI2Quant
  160820. #define jinit_merged_upsampler jIMUpsampler
  160821. #define jinit_memory_mgr jIMemMgr
  160822. #define jdiv_round_up jDivRound
  160823. #define jround_up jRound
  160824. #define jcopy_sample_rows jCopySamples
  160825. #define jcopy_block_row jCopyBlocks
  160826. #define jzero_far jZeroFar
  160827. #define jpeg_zigzag_order jZIGTable
  160828. #define jpeg_natural_order jZAGTable
  160829. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160830. /* Compression module initialization routines */
  160831. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160832. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160833. boolean transcode_only));
  160834. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160835. boolean need_full_buffer));
  160836. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160837. boolean need_full_buffer));
  160838. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160839. boolean need_full_buffer));
  160840. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160841. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160842. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160843. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160844. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160845. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160846. /* Decompression module initialization routines */
  160847. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160848. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160849. boolean need_full_buffer));
  160850. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160851. boolean need_full_buffer));
  160852. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160853. boolean need_full_buffer));
  160854. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160855. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160856. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160857. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160858. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160859. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160860. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160861. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160862. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160863. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160864. /* Memory manager initialization */
  160865. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160866. /* Utility routines in jutils.c */
  160867. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160868. EXTERN(long) jround_up JPP((long a, long b));
  160869. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160870. JSAMPARRAY output_array, int dest_row,
  160871. int num_rows, JDIMENSION num_cols));
  160872. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160873. JDIMENSION num_blocks));
  160874. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160875. /* Constant tables in jutils.c */
  160876. #if 0 /* This table is not actually needed in v6a */
  160877. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160878. #endif
  160879. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160880. /* Suppress undefined-structure complaints if necessary. */
  160881. #ifdef INCOMPLETE_TYPES_BROKEN
  160882. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160883. struct jvirt_sarray_control { long dummy; };
  160884. struct jvirt_barray_control { long dummy; };
  160885. #endif
  160886. #endif /* INCOMPLETE_TYPES_BROKEN */
  160887. /*** End of inlined file: jpegint.h ***/
  160888. /* fetch private declarations */
  160889. /*** Start of inlined file: jerror.h ***/
  160890. /*
  160891. * To define the enum list of message codes, include this file without
  160892. * defining macro JMESSAGE. To create a message string table, include it
  160893. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160894. */
  160895. #ifndef JMESSAGE
  160896. #ifndef JERROR_H
  160897. /* First time through, define the enum list */
  160898. #define JMAKE_ENUM_LIST
  160899. #else
  160900. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160901. #define JMESSAGE(code,string)
  160902. #endif /* JERROR_H */
  160903. #endif /* JMESSAGE */
  160904. #ifdef JMAKE_ENUM_LIST
  160905. typedef enum {
  160906. #define JMESSAGE(code,string) code ,
  160907. #endif /* JMAKE_ENUM_LIST */
  160908. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160909. /* For maintenance convenience, list is alphabetical by message code name */
  160910. JMESSAGE(JERR_ARITH_NOTIMPL,
  160911. "Sorry, there are legal restrictions on arithmetic coding")
  160912. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160913. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160914. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160915. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160916. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160917. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160918. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160919. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160920. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160921. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160922. JMESSAGE(JERR_BAD_LIB_VERSION,
  160923. "Wrong JPEG library version: library is %d, caller expects %d")
  160924. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160925. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160926. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160927. JMESSAGE(JERR_BAD_PROGRESSION,
  160928. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160929. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160930. "Invalid progressive parameters at scan script entry %d")
  160931. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160932. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160933. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160934. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160935. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160936. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160937. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160938. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160939. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160940. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160941. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160942. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160943. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160944. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160945. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160946. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160947. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160948. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160949. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160950. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160951. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160952. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160953. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160954. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160955. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160956. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160957. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160958. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160959. "Cannot transcode due to multiple use of quantization table %d")
  160960. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160961. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160962. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160963. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160964. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160965. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160966. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160967. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160968. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160969. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160970. JMESSAGE(JERR_QUANT_COMPONENTS,
  160971. "Cannot quantize more than %d color components")
  160972. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160973. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160974. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160975. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160976. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160977. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160978. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160979. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160980. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160981. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160982. JMESSAGE(JERR_TFILE_WRITE,
  160983. "Write failed on temporary file --- out of disk space?")
  160984. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160985. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160986. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160987. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160988. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160989. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160990. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160991. JMESSAGE(JMSG_VERSION, JVERSION)
  160992. JMESSAGE(JTRC_16BIT_TABLES,
  160993. "Caution: quantization tables are too coarse for baseline JPEG")
  160994. JMESSAGE(JTRC_ADOBE,
  160995. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160996. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160997. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160998. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160999. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161000. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161001. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161002. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161003. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161004. JMESSAGE(JTRC_EOI, "End Of Image")
  161005. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161006. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161007. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161008. "Warning: thumbnail image size does not match data length %u")
  161009. JMESSAGE(JTRC_JFIF_EXTENSION,
  161010. "JFIF extension marker: type 0x%02x, length %u")
  161011. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161012. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161013. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161014. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161015. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161016. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161017. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161018. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161019. JMESSAGE(JTRC_RST, "RST%d")
  161020. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161021. "Smoothing not supported with nonstandard sampling ratios")
  161022. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161023. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161024. JMESSAGE(JTRC_SOI, "Start of Image")
  161025. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161026. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161027. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161028. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161029. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161030. JMESSAGE(JTRC_THUMB_JPEG,
  161031. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161032. JMESSAGE(JTRC_THUMB_PALETTE,
  161033. "JFIF extension marker: palette thumbnail image, length %u")
  161034. JMESSAGE(JTRC_THUMB_RGB,
  161035. "JFIF extension marker: RGB thumbnail image, length %u")
  161036. JMESSAGE(JTRC_UNKNOWN_IDS,
  161037. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161038. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161039. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161040. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161041. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161042. "Inconsistent progression sequence for component %d coefficient %d")
  161043. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161044. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161045. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161046. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161047. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161048. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161049. JMESSAGE(JWRN_MUST_RESYNC,
  161050. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161051. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161052. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161053. #ifdef JMAKE_ENUM_LIST
  161054. JMSG_LASTMSGCODE
  161055. } J_MESSAGE_CODE;
  161056. #undef JMAKE_ENUM_LIST
  161057. #endif /* JMAKE_ENUM_LIST */
  161058. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161059. #undef JMESSAGE
  161060. #ifndef JERROR_H
  161061. #define JERROR_H
  161062. /* Macros to simplify using the error and trace message stuff */
  161063. /* The first parameter is either type of cinfo pointer */
  161064. /* Fatal errors (print message and exit) */
  161065. #define ERREXIT(cinfo,code) \
  161066. ((cinfo)->err->msg_code = (code), \
  161067. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161068. #define ERREXIT1(cinfo,code,p1) \
  161069. ((cinfo)->err->msg_code = (code), \
  161070. (cinfo)->err->msg_parm.i[0] = (p1), \
  161071. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161072. #define ERREXIT2(cinfo,code,p1,p2) \
  161073. ((cinfo)->err->msg_code = (code), \
  161074. (cinfo)->err->msg_parm.i[0] = (p1), \
  161075. (cinfo)->err->msg_parm.i[1] = (p2), \
  161076. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161077. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161078. ((cinfo)->err->msg_code = (code), \
  161079. (cinfo)->err->msg_parm.i[0] = (p1), \
  161080. (cinfo)->err->msg_parm.i[1] = (p2), \
  161081. (cinfo)->err->msg_parm.i[2] = (p3), \
  161082. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161083. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161084. ((cinfo)->err->msg_code = (code), \
  161085. (cinfo)->err->msg_parm.i[0] = (p1), \
  161086. (cinfo)->err->msg_parm.i[1] = (p2), \
  161087. (cinfo)->err->msg_parm.i[2] = (p3), \
  161088. (cinfo)->err->msg_parm.i[3] = (p4), \
  161089. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161090. #define ERREXITS(cinfo,code,str) \
  161091. ((cinfo)->err->msg_code = (code), \
  161092. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161093. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161094. #define MAKESTMT(stuff) do { stuff } while (0)
  161095. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161096. #define WARNMS(cinfo,code) \
  161097. ((cinfo)->err->msg_code = (code), \
  161098. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161099. #define WARNMS1(cinfo,code,p1) \
  161100. ((cinfo)->err->msg_code = (code), \
  161101. (cinfo)->err->msg_parm.i[0] = (p1), \
  161102. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161103. #define WARNMS2(cinfo,code,p1,p2) \
  161104. ((cinfo)->err->msg_code = (code), \
  161105. (cinfo)->err->msg_parm.i[0] = (p1), \
  161106. (cinfo)->err->msg_parm.i[1] = (p2), \
  161107. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161108. /* Informational/debugging messages */
  161109. #define TRACEMS(cinfo,lvl,code) \
  161110. ((cinfo)->err->msg_code = (code), \
  161111. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161112. #define TRACEMS1(cinfo,lvl,code,p1) \
  161113. ((cinfo)->err->msg_code = (code), \
  161114. (cinfo)->err->msg_parm.i[0] = (p1), \
  161115. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161116. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161117. ((cinfo)->err->msg_code = (code), \
  161118. (cinfo)->err->msg_parm.i[0] = (p1), \
  161119. (cinfo)->err->msg_parm.i[1] = (p2), \
  161120. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161121. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161122. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161123. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161124. (cinfo)->err->msg_code = (code); \
  161125. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161126. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161127. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161128. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161129. (cinfo)->err->msg_code = (code); \
  161130. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161131. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161132. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161133. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161134. _mp[4] = (p5); \
  161135. (cinfo)->err->msg_code = (code); \
  161136. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161137. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161138. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161139. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161140. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161141. (cinfo)->err->msg_code = (code); \
  161142. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161143. #define TRACEMSS(cinfo,lvl,code,str) \
  161144. ((cinfo)->err->msg_code = (code), \
  161145. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161146. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161147. #endif /* JERROR_H */
  161148. /*** End of inlined file: jerror.h ***/
  161149. /* fetch error codes too */
  161150. #endif
  161151. #endif /* JPEGLIB_H */
  161152. /*** End of inlined file: jpeglib.h ***/
  161153. /*** Start of inlined file: jcapimin.c ***/
  161154. #define JPEG_INTERNALS
  161155. /*** Start of inlined file: jinclude.h ***/
  161156. /* Include auto-config file to find out which system include files we need. */
  161157. #ifndef __jinclude_h__
  161158. #define __jinclude_h__
  161159. /*** Start of inlined file: jconfig.h ***/
  161160. /* see jconfig.doc for explanations */
  161161. // disable all the warnings under MSVC
  161162. #ifdef _MSC_VER
  161163. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161164. #endif
  161165. #ifdef __BORLANDC__
  161166. #pragma warn -8057
  161167. #pragma warn -8019
  161168. #pragma warn -8004
  161169. #pragma warn -8008
  161170. #endif
  161171. #define HAVE_PROTOTYPES
  161172. #define HAVE_UNSIGNED_CHAR
  161173. #define HAVE_UNSIGNED_SHORT
  161174. /* #define void char */
  161175. /* #define const */
  161176. #undef CHAR_IS_UNSIGNED
  161177. #define HAVE_STDDEF_H
  161178. #define HAVE_STDLIB_H
  161179. #undef NEED_BSD_STRINGS
  161180. #undef NEED_SYS_TYPES_H
  161181. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161182. #undef NEED_SHORT_EXTERNAL_NAMES
  161183. #undef INCOMPLETE_TYPES_BROKEN
  161184. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161185. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161186. typedef unsigned char boolean;
  161187. #endif
  161188. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161189. #ifdef JPEG_INTERNALS
  161190. #undef RIGHT_SHIFT_IS_UNSIGNED
  161191. #endif /* JPEG_INTERNALS */
  161192. #ifdef JPEG_CJPEG_DJPEG
  161193. #define BMP_SUPPORTED /* BMP image file format */
  161194. #define GIF_SUPPORTED /* GIF image file format */
  161195. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161196. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161197. #define TARGA_SUPPORTED /* Targa image file format */
  161198. #define TWO_FILE_COMMANDLINE /* optional */
  161199. #define USE_SETMODE /* Microsoft has setmode() */
  161200. #undef NEED_SIGNAL_CATCHER
  161201. #undef DONT_USE_B_MODE
  161202. #undef PROGRESS_REPORT /* optional */
  161203. #endif /* JPEG_CJPEG_DJPEG */
  161204. /*** End of inlined file: jconfig.h ***/
  161205. /* auto configuration options */
  161206. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161207. /*
  161208. * We need the NULL macro and size_t typedef.
  161209. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161210. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161211. * pull in <sys/types.h> as well.
  161212. * Note that the core JPEG library does not require <stdio.h>;
  161213. * only the default error handler and data source/destination modules do.
  161214. * But we must pull it in because of the references to FILE in jpeglib.h.
  161215. * You can remove those references if you want to compile without <stdio.h>.
  161216. */
  161217. #ifdef HAVE_STDDEF_H
  161218. #include <stddef.h>
  161219. #endif
  161220. #ifdef HAVE_STDLIB_H
  161221. #include <stdlib.h>
  161222. #endif
  161223. #ifdef NEED_SYS_TYPES_H
  161224. #include <sys/types.h>
  161225. #endif
  161226. #include <stdio.h>
  161227. /*
  161228. * We need memory copying and zeroing functions, plus strncpy().
  161229. * ANSI and System V implementations declare these in <string.h>.
  161230. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161231. * Some systems may declare memset and memcpy in <memory.h>.
  161232. *
  161233. * NOTE: we assume the size parameters to these functions are of type size_t.
  161234. * Change the casts in these macros if not!
  161235. */
  161236. #ifdef NEED_BSD_STRINGS
  161237. #include <strings.h>
  161238. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161239. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161240. #else /* not BSD, assume ANSI/SysV string lib */
  161241. #include <string.h>
  161242. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161243. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161244. #endif
  161245. /*
  161246. * In ANSI C, and indeed any rational implementation, size_t is also the
  161247. * type returned by sizeof(). However, it seems there are some irrational
  161248. * implementations out there, in which sizeof() returns an int even though
  161249. * size_t is defined as long or unsigned long. To ensure consistent results
  161250. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161251. */
  161252. #define SIZEOF(object) ((size_t) sizeof(object))
  161253. /*
  161254. * The modules that use fread() and fwrite() always invoke them through
  161255. * these macros. On some systems you may need to twiddle the argument casts.
  161256. * CAUTION: argument order is different from underlying functions!
  161257. */
  161258. #define JFREAD(file,buf,sizeofbuf) \
  161259. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161260. #define JFWRITE(file,buf,sizeofbuf) \
  161261. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161262. typedef enum { /* JPEG marker codes */
  161263. M_SOF0 = 0xc0,
  161264. M_SOF1 = 0xc1,
  161265. M_SOF2 = 0xc2,
  161266. M_SOF3 = 0xc3,
  161267. M_SOF5 = 0xc5,
  161268. M_SOF6 = 0xc6,
  161269. M_SOF7 = 0xc7,
  161270. M_JPG = 0xc8,
  161271. M_SOF9 = 0xc9,
  161272. M_SOF10 = 0xca,
  161273. M_SOF11 = 0xcb,
  161274. M_SOF13 = 0xcd,
  161275. M_SOF14 = 0xce,
  161276. M_SOF15 = 0xcf,
  161277. M_DHT = 0xc4,
  161278. M_DAC = 0xcc,
  161279. M_RST0 = 0xd0,
  161280. M_RST1 = 0xd1,
  161281. M_RST2 = 0xd2,
  161282. M_RST3 = 0xd3,
  161283. M_RST4 = 0xd4,
  161284. M_RST5 = 0xd5,
  161285. M_RST6 = 0xd6,
  161286. M_RST7 = 0xd7,
  161287. M_SOI = 0xd8,
  161288. M_EOI = 0xd9,
  161289. M_SOS = 0xda,
  161290. M_DQT = 0xdb,
  161291. M_DNL = 0xdc,
  161292. M_DRI = 0xdd,
  161293. M_DHP = 0xde,
  161294. M_EXP = 0xdf,
  161295. M_APP0 = 0xe0,
  161296. M_APP1 = 0xe1,
  161297. M_APP2 = 0xe2,
  161298. M_APP3 = 0xe3,
  161299. M_APP4 = 0xe4,
  161300. M_APP5 = 0xe5,
  161301. M_APP6 = 0xe6,
  161302. M_APP7 = 0xe7,
  161303. M_APP8 = 0xe8,
  161304. M_APP9 = 0xe9,
  161305. M_APP10 = 0xea,
  161306. M_APP11 = 0xeb,
  161307. M_APP12 = 0xec,
  161308. M_APP13 = 0xed,
  161309. M_APP14 = 0xee,
  161310. M_APP15 = 0xef,
  161311. M_JPG0 = 0xf0,
  161312. M_JPG13 = 0xfd,
  161313. M_COM = 0xfe,
  161314. M_TEM = 0x01,
  161315. M_ERROR = 0x100
  161316. } JPEG_MARKER;
  161317. /*
  161318. * Figure F.12: extend sign bit.
  161319. * On some machines, a shift and add will be faster than a table lookup.
  161320. */
  161321. #ifdef AVOID_TABLES
  161322. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161323. #else
  161324. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161325. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161326. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161327. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161328. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161329. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161330. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161331. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161332. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161333. #endif /* AVOID_TABLES */
  161334. #endif
  161335. /*** End of inlined file: jinclude.h ***/
  161336. /*
  161337. * Initialization of a JPEG compression object.
  161338. * The error manager must already be set up (in case memory manager fails).
  161339. */
  161340. GLOBAL(void)
  161341. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161342. {
  161343. int i;
  161344. /* Guard against version mismatches between library and caller. */
  161345. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161346. if (version != JPEG_LIB_VERSION)
  161347. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161348. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161349. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161350. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161351. /* For debugging purposes, we zero the whole master structure.
  161352. * But the application has already set the err pointer, and may have set
  161353. * client_data, so we have to save and restore those fields.
  161354. * Note: if application hasn't set client_data, tools like Purify may
  161355. * complain here.
  161356. */
  161357. {
  161358. struct jpeg_error_mgr * err = cinfo->err;
  161359. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161360. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161361. cinfo->err = err;
  161362. cinfo->client_data = client_data;
  161363. }
  161364. cinfo->is_decompressor = FALSE;
  161365. /* Initialize a memory manager instance for this object */
  161366. jinit_memory_mgr((j_common_ptr) cinfo);
  161367. /* Zero out pointers to permanent structures. */
  161368. cinfo->progress = NULL;
  161369. cinfo->dest = NULL;
  161370. cinfo->comp_info = NULL;
  161371. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161372. cinfo->quant_tbl_ptrs[i] = NULL;
  161373. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161374. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161375. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161376. }
  161377. cinfo->script_space = NULL;
  161378. cinfo->input_gamma = 1.0; /* in case application forgets */
  161379. /* OK, I'm ready */
  161380. cinfo->global_state = CSTATE_START;
  161381. }
  161382. /*
  161383. * Destruction of a JPEG compression object
  161384. */
  161385. GLOBAL(void)
  161386. jpeg_destroy_compress (j_compress_ptr cinfo)
  161387. {
  161388. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161389. }
  161390. /*
  161391. * Abort processing of a JPEG compression operation,
  161392. * but don't destroy the object itself.
  161393. */
  161394. GLOBAL(void)
  161395. jpeg_abort_compress (j_compress_ptr cinfo)
  161396. {
  161397. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161398. }
  161399. /*
  161400. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161401. * Marks all currently defined tables as already written (if suppress)
  161402. * or not written (if !suppress). This will control whether they get emitted
  161403. * by a subsequent jpeg_start_compress call.
  161404. *
  161405. * This routine is exported for use by applications that want to produce
  161406. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161407. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161408. * jcparam.o would be linked whether the application used it or not.
  161409. */
  161410. GLOBAL(void)
  161411. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161412. {
  161413. int i;
  161414. JQUANT_TBL * qtbl;
  161415. JHUFF_TBL * htbl;
  161416. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161417. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161418. qtbl->sent_table = suppress;
  161419. }
  161420. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161421. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161422. htbl->sent_table = suppress;
  161423. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161424. htbl->sent_table = suppress;
  161425. }
  161426. }
  161427. /*
  161428. * Finish JPEG compression.
  161429. *
  161430. * If a multipass operating mode was selected, this may do a great deal of
  161431. * work including most of the actual output.
  161432. */
  161433. GLOBAL(void)
  161434. jpeg_finish_compress (j_compress_ptr cinfo)
  161435. {
  161436. JDIMENSION iMCU_row;
  161437. if (cinfo->global_state == CSTATE_SCANNING ||
  161438. cinfo->global_state == CSTATE_RAW_OK) {
  161439. /* Terminate first pass */
  161440. if (cinfo->next_scanline < cinfo->image_height)
  161441. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161442. (*cinfo->master->finish_pass) (cinfo);
  161443. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161444. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161445. /* Perform any remaining passes */
  161446. while (! cinfo->master->is_last_pass) {
  161447. (*cinfo->master->prepare_for_pass) (cinfo);
  161448. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161449. if (cinfo->progress != NULL) {
  161450. cinfo->progress->pass_counter = (long) iMCU_row;
  161451. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161452. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161453. }
  161454. /* We bypass the main controller and invoke coef controller directly;
  161455. * all work is being done from the coefficient buffer.
  161456. */
  161457. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161458. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161459. }
  161460. (*cinfo->master->finish_pass) (cinfo);
  161461. }
  161462. /* Write EOI, do final cleanup */
  161463. (*cinfo->marker->write_file_trailer) (cinfo);
  161464. (*cinfo->dest->term_destination) (cinfo);
  161465. /* We can use jpeg_abort to release memory and reset global_state */
  161466. jpeg_abort((j_common_ptr) cinfo);
  161467. }
  161468. /*
  161469. * Write a special marker.
  161470. * This is only recommended for writing COM or APPn markers.
  161471. * Must be called after jpeg_start_compress() and before
  161472. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161473. */
  161474. GLOBAL(void)
  161475. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161476. const JOCTET *dataptr, unsigned int datalen)
  161477. {
  161478. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161479. if (cinfo->next_scanline != 0 ||
  161480. (cinfo->global_state != CSTATE_SCANNING &&
  161481. cinfo->global_state != CSTATE_RAW_OK &&
  161482. cinfo->global_state != CSTATE_WRCOEFS))
  161483. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161484. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161485. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161486. while (datalen--) {
  161487. (*write_marker_byte) (cinfo, *dataptr);
  161488. dataptr++;
  161489. }
  161490. }
  161491. /* Same, but piecemeal. */
  161492. GLOBAL(void)
  161493. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161494. {
  161495. if (cinfo->next_scanline != 0 ||
  161496. (cinfo->global_state != CSTATE_SCANNING &&
  161497. cinfo->global_state != CSTATE_RAW_OK &&
  161498. cinfo->global_state != CSTATE_WRCOEFS))
  161499. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161500. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161501. }
  161502. GLOBAL(void)
  161503. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161504. {
  161505. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161506. }
  161507. /*
  161508. * Alternate compression function: just write an abbreviated table file.
  161509. * Before calling this, all parameters and a data destination must be set up.
  161510. *
  161511. * To produce a pair of files containing abbreviated tables and abbreviated
  161512. * image data, one would proceed as follows:
  161513. *
  161514. * initialize JPEG object
  161515. * set JPEG parameters
  161516. * set destination to table file
  161517. * jpeg_write_tables(cinfo);
  161518. * set destination to image file
  161519. * jpeg_start_compress(cinfo, FALSE);
  161520. * write data...
  161521. * jpeg_finish_compress(cinfo);
  161522. *
  161523. * jpeg_write_tables has the side effect of marking all tables written
  161524. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161525. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161526. */
  161527. GLOBAL(void)
  161528. jpeg_write_tables (j_compress_ptr cinfo)
  161529. {
  161530. if (cinfo->global_state != CSTATE_START)
  161531. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161532. /* (Re)initialize error mgr and destination modules */
  161533. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161534. (*cinfo->dest->init_destination) (cinfo);
  161535. /* Initialize the marker writer ... bit of a crock to do it here. */
  161536. jinit_marker_writer(cinfo);
  161537. /* Write them tables! */
  161538. (*cinfo->marker->write_tables_only) (cinfo);
  161539. /* And clean up. */
  161540. (*cinfo->dest->term_destination) (cinfo);
  161541. /*
  161542. * In library releases up through v6a, we called jpeg_abort() here to free
  161543. * any working memory allocated by the destination manager and marker
  161544. * writer. Some applications had a problem with that: they allocated space
  161545. * of their own from the library memory manager, and didn't want it to go
  161546. * away during write_tables. So now we do nothing. This will cause a
  161547. * memory leak if an app calls write_tables repeatedly without doing a full
  161548. * compression cycle or otherwise resetting the JPEG object. However, that
  161549. * seems less bad than unexpectedly freeing memory in the normal case.
  161550. * An app that prefers the old behavior can call jpeg_abort for itself after
  161551. * each call to jpeg_write_tables().
  161552. */
  161553. }
  161554. /*** End of inlined file: jcapimin.c ***/
  161555. /*** Start of inlined file: jcapistd.c ***/
  161556. #define JPEG_INTERNALS
  161557. /*
  161558. * Compression initialization.
  161559. * Before calling this, all parameters and a data destination must be set up.
  161560. *
  161561. * We require a write_all_tables parameter as a failsafe check when writing
  161562. * multiple datastreams from the same compression object. Since prior runs
  161563. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161564. * would emit an abbreviated stream (no tables) by default. This may be what
  161565. * is wanted, but for safety's sake it should not be the default behavior:
  161566. * programmers should have to make a deliberate choice to emit abbreviated
  161567. * images. Therefore the documentation and examples should encourage people
  161568. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161569. * wrong thing.
  161570. */
  161571. GLOBAL(void)
  161572. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161573. {
  161574. if (cinfo->global_state != CSTATE_START)
  161575. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161576. if (write_all_tables)
  161577. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161578. /* (Re)initialize error mgr and destination modules */
  161579. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161580. (*cinfo->dest->init_destination) (cinfo);
  161581. /* Perform master selection of active modules */
  161582. jinit_compress_master(cinfo);
  161583. /* Set up for the first pass */
  161584. (*cinfo->master->prepare_for_pass) (cinfo);
  161585. /* Ready for application to drive first pass through jpeg_write_scanlines
  161586. * or jpeg_write_raw_data.
  161587. */
  161588. cinfo->next_scanline = 0;
  161589. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161590. }
  161591. /*
  161592. * Write some scanlines of data to the JPEG compressor.
  161593. *
  161594. * The return value will be the number of lines actually written.
  161595. * This should be less than the supplied num_lines only in case that
  161596. * the data destination module has requested suspension of the compressor,
  161597. * or if more than image_height scanlines are passed in.
  161598. *
  161599. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161600. * this likely signals an application programmer error. However,
  161601. * excess scanlines passed in the last valid call are *silently* ignored,
  161602. * so that the application need not adjust num_lines for end-of-image
  161603. * when using a multiple-scanline buffer.
  161604. */
  161605. GLOBAL(JDIMENSION)
  161606. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161607. JDIMENSION num_lines)
  161608. {
  161609. JDIMENSION row_ctr, rows_left;
  161610. if (cinfo->global_state != CSTATE_SCANNING)
  161611. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161612. if (cinfo->next_scanline >= cinfo->image_height)
  161613. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161614. /* Call progress monitor hook if present */
  161615. if (cinfo->progress != NULL) {
  161616. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161617. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161618. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161619. }
  161620. /* Give master control module another chance if this is first call to
  161621. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161622. * delayed so that application can write COM, etc, markers between
  161623. * jpeg_start_compress and jpeg_write_scanlines.
  161624. */
  161625. if (cinfo->master->call_pass_startup)
  161626. (*cinfo->master->pass_startup) (cinfo);
  161627. /* Ignore any extra scanlines at bottom of image. */
  161628. rows_left = cinfo->image_height - cinfo->next_scanline;
  161629. if (num_lines > rows_left)
  161630. num_lines = rows_left;
  161631. row_ctr = 0;
  161632. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161633. cinfo->next_scanline += row_ctr;
  161634. return row_ctr;
  161635. }
  161636. /*
  161637. * Alternate entry point to write raw data.
  161638. * Processes exactly one iMCU row per call, unless suspended.
  161639. */
  161640. GLOBAL(JDIMENSION)
  161641. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161642. JDIMENSION num_lines)
  161643. {
  161644. JDIMENSION lines_per_iMCU_row;
  161645. if (cinfo->global_state != CSTATE_RAW_OK)
  161646. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161647. if (cinfo->next_scanline >= cinfo->image_height) {
  161648. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161649. return 0;
  161650. }
  161651. /* Call progress monitor hook if present */
  161652. if (cinfo->progress != NULL) {
  161653. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161654. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161655. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161656. }
  161657. /* Give master control module another chance if this is first call to
  161658. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161659. * delayed so that application can write COM, etc, markers between
  161660. * jpeg_start_compress and jpeg_write_raw_data.
  161661. */
  161662. if (cinfo->master->call_pass_startup)
  161663. (*cinfo->master->pass_startup) (cinfo);
  161664. /* Verify that at least one iMCU row has been passed. */
  161665. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161666. if (num_lines < lines_per_iMCU_row)
  161667. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161668. /* Directly compress the row. */
  161669. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161670. /* If compressor did not consume the whole row, suspend processing. */
  161671. return 0;
  161672. }
  161673. /* OK, we processed one iMCU row. */
  161674. cinfo->next_scanline += lines_per_iMCU_row;
  161675. return lines_per_iMCU_row;
  161676. }
  161677. /*** End of inlined file: jcapistd.c ***/
  161678. /*** Start of inlined file: jccoefct.c ***/
  161679. #define JPEG_INTERNALS
  161680. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161681. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161682. * step is run during the first pass, and subsequent passes need only read
  161683. * the buffered coefficients.
  161684. */
  161685. #ifdef ENTROPY_OPT_SUPPORTED
  161686. #define FULL_COEF_BUFFER_SUPPORTED
  161687. #else
  161688. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161689. #define FULL_COEF_BUFFER_SUPPORTED
  161690. #endif
  161691. #endif
  161692. /* Private buffer controller object */
  161693. typedef struct {
  161694. struct jpeg_c_coef_controller pub; /* public fields */
  161695. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161696. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161697. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161698. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161699. /* For single-pass compression, it's sufficient to buffer just one MCU
  161700. * (although this may prove a bit slow in practice). We allocate a
  161701. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161702. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161703. * it's not really very big; this is to keep the module interfaces unchanged
  161704. * when a large coefficient buffer is necessary.)
  161705. * In multi-pass modes, this array points to the current MCU's blocks
  161706. * within the virtual arrays.
  161707. */
  161708. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161709. /* In multi-pass modes, we need a virtual block array for each component. */
  161710. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161711. } my_coef_controller;
  161712. typedef my_coef_controller * my_coef_ptr;
  161713. /* Forward declarations */
  161714. METHODDEF(boolean) compress_data
  161715. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161716. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161717. METHODDEF(boolean) compress_first_pass
  161718. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161719. METHODDEF(boolean) compress_output
  161720. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161721. #endif
  161722. LOCAL(void)
  161723. start_iMCU_row (j_compress_ptr cinfo)
  161724. /* Reset within-iMCU-row counters for a new row */
  161725. {
  161726. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161727. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161728. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161729. * But at the bottom of the image, process only what's left.
  161730. */
  161731. if (cinfo->comps_in_scan > 1) {
  161732. coef->MCU_rows_per_iMCU_row = 1;
  161733. } else {
  161734. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161735. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161736. else
  161737. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161738. }
  161739. coef->mcu_ctr = 0;
  161740. coef->MCU_vert_offset = 0;
  161741. }
  161742. /*
  161743. * Initialize for a processing pass.
  161744. */
  161745. METHODDEF(void)
  161746. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161747. {
  161748. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161749. coef->iMCU_row_num = 0;
  161750. start_iMCU_row(cinfo);
  161751. switch (pass_mode) {
  161752. case JBUF_PASS_THRU:
  161753. if (coef->whole_image[0] != NULL)
  161754. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161755. coef->pub.compress_data = compress_data;
  161756. break;
  161757. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161758. case JBUF_SAVE_AND_PASS:
  161759. if (coef->whole_image[0] == NULL)
  161760. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161761. coef->pub.compress_data = compress_first_pass;
  161762. break;
  161763. case JBUF_CRANK_DEST:
  161764. if (coef->whole_image[0] == NULL)
  161765. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161766. coef->pub.compress_data = compress_output;
  161767. break;
  161768. #endif
  161769. default:
  161770. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161771. break;
  161772. }
  161773. }
  161774. /*
  161775. * Process some data in the single-pass case.
  161776. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161777. * per call, ie, v_samp_factor block rows for each component in the image.
  161778. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161779. *
  161780. * NB: input_buf contains a plane for each component in image,
  161781. * which we index according to the component's SOF position.
  161782. */
  161783. METHODDEF(boolean)
  161784. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161785. {
  161786. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161787. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161788. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161789. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161790. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161791. JDIMENSION ypos, xpos;
  161792. jpeg_component_info *compptr;
  161793. /* Loop to write as much as one whole iMCU row */
  161794. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161795. yoffset++) {
  161796. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161797. MCU_col_num++) {
  161798. /* Determine where data comes from in input_buf and do the DCT thing.
  161799. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161800. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161801. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161802. * specially. The data in them does not matter for image reconstruction,
  161803. * so we fill them with values that will encode to the smallest amount of
  161804. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161805. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161806. */
  161807. blkn = 0;
  161808. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161809. compptr = cinfo->cur_comp_info[ci];
  161810. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161811. : compptr->last_col_width;
  161812. xpos = MCU_col_num * compptr->MCU_sample_width;
  161813. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161814. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161815. if (coef->iMCU_row_num < last_iMCU_row ||
  161816. yoffset+yindex < compptr->last_row_height) {
  161817. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161818. input_buf[compptr->component_index],
  161819. coef->MCU_buffer[blkn],
  161820. ypos, xpos, (JDIMENSION) blockcnt);
  161821. if (blockcnt < compptr->MCU_width) {
  161822. /* Create some dummy blocks at the right edge of the image. */
  161823. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161824. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161825. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161826. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161827. }
  161828. }
  161829. } else {
  161830. /* Create a row of dummy blocks at the bottom of the image. */
  161831. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161832. compptr->MCU_width * SIZEOF(JBLOCK));
  161833. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161834. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161835. }
  161836. }
  161837. blkn += compptr->MCU_width;
  161838. ypos += DCTSIZE;
  161839. }
  161840. }
  161841. /* Try to write the MCU. In event of a suspension failure, we will
  161842. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161843. */
  161844. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161845. /* Suspension forced; update state counters and exit */
  161846. coef->MCU_vert_offset = yoffset;
  161847. coef->mcu_ctr = MCU_col_num;
  161848. return FALSE;
  161849. }
  161850. }
  161851. /* Completed an MCU row, but perhaps not an iMCU row */
  161852. coef->mcu_ctr = 0;
  161853. }
  161854. /* Completed the iMCU row, advance counters for next one */
  161855. coef->iMCU_row_num++;
  161856. start_iMCU_row(cinfo);
  161857. return TRUE;
  161858. }
  161859. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161860. /*
  161861. * Process some data in the first pass of a multi-pass case.
  161862. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161863. * per call, ie, v_samp_factor block rows for each component in the image.
  161864. * This amount of data is read from the source buffer, DCT'd and quantized,
  161865. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161866. * as needed at the right and lower edges. (The dummy blocks are constructed
  161867. * in the virtual arrays, which have been padded appropriately.) This makes
  161868. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161869. *
  161870. * We must also emit the data to the entropy encoder. This is conveniently
  161871. * done by calling compress_output() after we've loaded the current strip
  161872. * of the virtual arrays.
  161873. *
  161874. * NB: input_buf contains a plane for each component in image. All
  161875. * components are DCT'd and loaded into the virtual arrays in this pass.
  161876. * However, it may be that only a subset of the components are emitted to
  161877. * the entropy encoder during this first pass; be careful about looking
  161878. * at the scan-dependent variables (MCU dimensions, etc).
  161879. */
  161880. METHODDEF(boolean)
  161881. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161882. {
  161883. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161884. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161885. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161886. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161887. JCOEF lastDC;
  161888. jpeg_component_info *compptr;
  161889. JBLOCKARRAY buffer;
  161890. JBLOCKROW thisblockrow, lastblockrow;
  161891. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161892. ci++, compptr++) {
  161893. /* Align the virtual buffer for this component. */
  161894. buffer = (*cinfo->mem->access_virt_barray)
  161895. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161896. coef->iMCU_row_num * compptr->v_samp_factor,
  161897. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161898. /* Count non-dummy DCT block rows in this iMCU row. */
  161899. if (coef->iMCU_row_num < last_iMCU_row)
  161900. block_rows = compptr->v_samp_factor;
  161901. else {
  161902. /* NB: can't use last_row_height here, since may not be set! */
  161903. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161904. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161905. }
  161906. blocks_across = compptr->width_in_blocks;
  161907. h_samp_factor = compptr->h_samp_factor;
  161908. /* Count number of dummy blocks to be added at the right margin. */
  161909. ndummy = (int) (blocks_across % h_samp_factor);
  161910. if (ndummy > 0)
  161911. ndummy = h_samp_factor - ndummy;
  161912. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161913. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161914. */
  161915. for (block_row = 0; block_row < block_rows; block_row++) {
  161916. thisblockrow = buffer[block_row];
  161917. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161918. input_buf[ci], thisblockrow,
  161919. (JDIMENSION) (block_row * DCTSIZE),
  161920. (JDIMENSION) 0, blocks_across);
  161921. if (ndummy > 0) {
  161922. /* Create dummy blocks at the right edge of the image. */
  161923. thisblockrow += blocks_across; /* => first dummy block */
  161924. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161925. lastDC = thisblockrow[-1][0];
  161926. for (bi = 0; bi < ndummy; bi++) {
  161927. thisblockrow[bi][0] = lastDC;
  161928. }
  161929. }
  161930. }
  161931. /* If at end of image, create dummy block rows as needed.
  161932. * The tricky part here is that within each MCU, we want the DC values
  161933. * of the dummy blocks to match the last real block's DC value.
  161934. * This squeezes a few more bytes out of the resulting file...
  161935. */
  161936. if (coef->iMCU_row_num == last_iMCU_row) {
  161937. blocks_across += ndummy; /* include lower right corner */
  161938. MCUs_across = blocks_across / h_samp_factor;
  161939. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161940. block_row++) {
  161941. thisblockrow = buffer[block_row];
  161942. lastblockrow = buffer[block_row-1];
  161943. jzero_far((void FAR *) thisblockrow,
  161944. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161945. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161946. lastDC = lastblockrow[h_samp_factor-1][0];
  161947. for (bi = 0; bi < h_samp_factor; bi++) {
  161948. thisblockrow[bi][0] = lastDC;
  161949. }
  161950. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161951. lastblockrow += h_samp_factor;
  161952. }
  161953. }
  161954. }
  161955. }
  161956. /* NB: compress_output will increment iMCU_row_num if successful.
  161957. * A suspension return will result in redoing all the work above next time.
  161958. */
  161959. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161960. return compress_output(cinfo, input_buf);
  161961. }
  161962. /*
  161963. * Process some data in subsequent passes of a multi-pass case.
  161964. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161965. * per call, ie, v_samp_factor block rows for each component in the scan.
  161966. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161967. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161968. *
  161969. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161970. */
  161971. METHODDEF(boolean)
  161972. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161973. {
  161974. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161975. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161976. int blkn, ci, xindex, yindex, yoffset;
  161977. JDIMENSION start_col;
  161978. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161979. JBLOCKROW buffer_ptr;
  161980. jpeg_component_info *compptr;
  161981. /* Align the virtual buffers for the components used in this scan.
  161982. * NB: during first pass, this is safe only because the buffers will
  161983. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161984. */
  161985. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161986. compptr = cinfo->cur_comp_info[ci];
  161987. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161988. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161989. coef->iMCU_row_num * compptr->v_samp_factor,
  161990. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161991. }
  161992. /* Loop to process one whole iMCU row */
  161993. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161994. yoffset++) {
  161995. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161996. MCU_col_num++) {
  161997. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161998. blkn = 0; /* index of current DCT block within MCU */
  161999. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162000. compptr = cinfo->cur_comp_info[ci];
  162001. start_col = MCU_col_num * compptr->MCU_width;
  162002. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162003. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162004. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162005. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162006. }
  162007. }
  162008. }
  162009. /* Try to write the MCU. */
  162010. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162011. /* Suspension forced; update state counters and exit */
  162012. coef->MCU_vert_offset = yoffset;
  162013. coef->mcu_ctr = MCU_col_num;
  162014. return FALSE;
  162015. }
  162016. }
  162017. /* Completed an MCU row, but perhaps not an iMCU row */
  162018. coef->mcu_ctr = 0;
  162019. }
  162020. /* Completed the iMCU row, advance counters for next one */
  162021. coef->iMCU_row_num++;
  162022. start_iMCU_row(cinfo);
  162023. return TRUE;
  162024. }
  162025. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162026. /*
  162027. * Initialize coefficient buffer controller.
  162028. */
  162029. GLOBAL(void)
  162030. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162031. {
  162032. my_coef_ptr coef;
  162033. coef = (my_coef_ptr)
  162034. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162035. SIZEOF(my_coef_controller));
  162036. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162037. coef->pub.start_pass = start_pass_coef;
  162038. /* Create the coefficient buffer. */
  162039. if (need_full_buffer) {
  162040. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162041. /* Allocate a full-image virtual array for each component, */
  162042. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162043. int ci;
  162044. jpeg_component_info *compptr;
  162045. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162046. ci++, compptr++) {
  162047. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162048. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162049. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162050. (long) compptr->h_samp_factor),
  162051. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162052. (long) compptr->v_samp_factor),
  162053. (JDIMENSION) compptr->v_samp_factor);
  162054. }
  162055. #else
  162056. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162057. #endif
  162058. } else {
  162059. /* We only need a single-MCU buffer. */
  162060. JBLOCKROW buffer;
  162061. int i;
  162062. buffer = (JBLOCKROW)
  162063. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162064. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162065. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162066. coef->MCU_buffer[i] = buffer + i;
  162067. }
  162068. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162069. }
  162070. }
  162071. /*** End of inlined file: jccoefct.c ***/
  162072. /*** Start of inlined file: jccolor.c ***/
  162073. #define JPEG_INTERNALS
  162074. /* Private subobject */
  162075. typedef struct {
  162076. struct jpeg_color_converter pub; /* public fields */
  162077. /* Private state for RGB->YCC conversion */
  162078. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162079. } my_color_converter;
  162080. typedef my_color_converter * my_cconvert_ptr;
  162081. /**************** RGB -> YCbCr conversion: most common case **************/
  162082. /*
  162083. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162084. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162085. * The conversion equations to be implemented are therefore
  162086. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162087. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162088. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162089. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162090. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162091. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162092. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162093. * were not represented exactly. Now we sacrifice exact representation of
  162094. * maximum red and maximum blue in order to get exact grayscales.
  162095. *
  162096. * To avoid floating-point arithmetic, we represent the fractional constants
  162097. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162098. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162099. *
  162100. * For even more speed, we avoid doing any multiplications in the inner loop
  162101. * by precalculating the constants times R,G,B for all possible values.
  162102. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162103. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162104. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162105. * colorspace anyway.
  162106. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162107. * in the tables to save adding them separately in the inner loop.
  162108. */
  162109. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162110. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162111. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162112. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162113. /* We allocate one big table and divide it up into eight parts, instead of
  162114. * doing eight alloc_small requests. This lets us use a single table base
  162115. * address, which can be held in a register in the inner loops on many
  162116. * machines (more than can hold all eight addresses, anyway).
  162117. */
  162118. #define R_Y_OFF 0 /* offset to R => Y section */
  162119. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162120. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162121. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162122. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162123. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162124. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162125. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162126. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162127. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162128. /*
  162129. * Initialize for RGB->YCC colorspace conversion.
  162130. */
  162131. METHODDEF(void)
  162132. rgb_ycc_start (j_compress_ptr cinfo)
  162133. {
  162134. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162135. INT32 * rgb_ycc_tab;
  162136. INT32 i;
  162137. /* Allocate and fill in the conversion tables. */
  162138. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162139. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162140. (TABLE_SIZE * SIZEOF(INT32)));
  162141. for (i = 0; i <= MAXJSAMPLE; i++) {
  162142. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162143. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162144. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162145. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162146. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162147. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162148. * This ensures that the maximum output will round to MAXJSAMPLE
  162149. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162150. */
  162151. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162152. /* B=>Cb and R=>Cr tables are the same
  162153. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162154. */
  162155. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162156. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162157. }
  162158. }
  162159. /*
  162160. * Convert some rows of samples to the JPEG colorspace.
  162161. *
  162162. * Note that we change from the application's interleaved-pixel format
  162163. * to our internal noninterleaved, one-plane-per-component format.
  162164. * The input buffer is therefore three times as wide as the output buffer.
  162165. *
  162166. * A starting row offset is provided only for the output buffer. The caller
  162167. * can easily adjust the passed input_buf value to accommodate any row
  162168. * offset required on that side.
  162169. */
  162170. METHODDEF(void)
  162171. rgb_ycc_convert (j_compress_ptr cinfo,
  162172. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162173. JDIMENSION output_row, int num_rows)
  162174. {
  162175. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162176. register int r, g, b;
  162177. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162178. register JSAMPROW inptr;
  162179. register JSAMPROW outptr0, outptr1, outptr2;
  162180. register JDIMENSION col;
  162181. JDIMENSION num_cols = cinfo->image_width;
  162182. while (--num_rows >= 0) {
  162183. inptr = *input_buf++;
  162184. outptr0 = output_buf[0][output_row];
  162185. outptr1 = output_buf[1][output_row];
  162186. outptr2 = output_buf[2][output_row];
  162187. output_row++;
  162188. for (col = 0; col < num_cols; col++) {
  162189. r = GETJSAMPLE(inptr[RGB_RED]);
  162190. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162191. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162192. inptr += RGB_PIXELSIZE;
  162193. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162194. * must be too; we do not need an explicit range-limiting operation.
  162195. * Hence the value being shifted is never negative, and we don't
  162196. * need the general RIGHT_SHIFT macro.
  162197. */
  162198. /* Y */
  162199. outptr0[col] = (JSAMPLE)
  162200. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162201. >> SCALEBITS);
  162202. /* Cb */
  162203. outptr1[col] = (JSAMPLE)
  162204. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162205. >> SCALEBITS);
  162206. /* Cr */
  162207. outptr2[col] = (JSAMPLE)
  162208. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162209. >> SCALEBITS);
  162210. }
  162211. }
  162212. }
  162213. /**************** Cases other than RGB -> YCbCr **************/
  162214. /*
  162215. * Convert some rows of samples to the JPEG colorspace.
  162216. * This version handles RGB->grayscale conversion, which is the same
  162217. * as the RGB->Y portion of RGB->YCbCr.
  162218. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162219. */
  162220. METHODDEF(void)
  162221. rgb_gray_convert (j_compress_ptr cinfo,
  162222. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162223. JDIMENSION output_row, int num_rows)
  162224. {
  162225. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162226. register int r, g, b;
  162227. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162228. register JSAMPROW inptr;
  162229. register JSAMPROW outptr;
  162230. register JDIMENSION col;
  162231. JDIMENSION num_cols = cinfo->image_width;
  162232. while (--num_rows >= 0) {
  162233. inptr = *input_buf++;
  162234. outptr = output_buf[0][output_row];
  162235. output_row++;
  162236. for (col = 0; col < num_cols; col++) {
  162237. r = GETJSAMPLE(inptr[RGB_RED]);
  162238. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162239. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162240. inptr += RGB_PIXELSIZE;
  162241. /* Y */
  162242. outptr[col] = (JSAMPLE)
  162243. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162244. >> SCALEBITS);
  162245. }
  162246. }
  162247. }
  162248. /*
  162249. * Convert some rows of samples to the JPEG colorspace.
  162250. * This version handles Adobe-style CMYK->YCCK conversion,
  162251. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162252. * conversion as above, while passing K (black) unchanged.
  162253. * We assume rgb_ycc_start has been called.
  162254. */
  162255. METHODDEF(void)
  162256. cmyk_ycck_convert (j_compress_ptr cinfo,
  162257. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162258. JDIMENSION output_row, int num_rows)
  162259. {
  162260. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162261. register int r, g, b;
  162262. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162263. register JSAMPROW inptr;
  162264. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162265. register JDIMENSION col;
  162266. JDIMENSION num_cols = cinfo->image_width;
  162267. while (--num_rows >= 0) {
  162268. inptr = *input_buf++;
  162269. outptr0 = output_buf[0][output_row];
  162270. outptr1 = output_buf[1][output_row];
  162271. outptr2 = output_buf[2][output_row];
  162272. outptr3 = output_buf[3][output_row];
  162273. output_row++;
  162274. for (col = 0; col < num_cols; col++) {
  162275. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162276. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162277. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162278. /* K passes through as-is */
  162279. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162280. inptr += 4;
  162281. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162282. * must be too; we do not need an explicit range-limiting operation.
  162283. * Hence the value being shifted is never negative, and we don't
  162284. * need the general RIGHT_SHIFT macro.
  162285. */
  162286. /* Y */
  162287. outptr0[col] = (JSAMPLE)
  162288. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162289. >> SCALEBITS);
  162290. /* Cb */
  162291. outptr1[col] = (JSAMPLE)
  162292. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162293. >> SCALEBITS);
  162294. /* Cr */
  162295. outptr2[col] = (JSAMPLE)
  162296. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162297. >> SCALEBITS);
  162298. }
  162299. }
  162300. }
  162301. /*
  162302. * Convert some rows of samples to the JPEG colorspace.
  162303. * This version handles grayscale output with no conversion.
  162304. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162305. */
  162306. METHODDEF(void)
  162307. grayscale_convert (j_compress_ptr cinfo,
  162308. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162309. JDIMENSION output_row, int num_rows)
  162310. {
  162311. register JSAMPROW inptr;
  162312. register JSAMPROW outptr;
  162313. register JDIMENSION col;
  162314. JDIMENSION num_cols = cinfo->image_width;
  162315. int instride = cinfo->input_components;
  162316. while (--num_rows >= 0) {
  162317. inptr = *input_buf++;
  162318. outptr = output_buf[0][output_row];
  162319. output_row++;
  162320. for (col = 0; col < num_cols; col++) {
  162321. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162322. inptr += instride;
  162323. }
  162324. }
  162325. }
  162326. /*
  162327. * Convert some rows of samples to the JPEG colorspace.
  162328. * This version handles multi-component colorspaces without conversion.
  162329. * We assume input_components == num_components.
  162330. */
  162331. METHODDEF(void)
  162332. null_convert (j_compress_ptr cinfo,
  162333. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162334. JDIMENSION output_row, int num_rows)
  162335. {
  162336. register JSAMPROW inptr;
  162337. register JSAMPROW outptr;
  162338. register JDIMENSION col;
  162339. register int ci;
  162340. int nc = cinfo->num_components;
  162341. JDIMENSION num_cols = cinfo->image_width;
  162342. while (--num_rows >= 0) {
  162343. /* It seems fastest to make a separate pass for each component. */
  162344. for (ci = 0; ci < nc; ci++) {
  162345. inptr = *input_buf;
  162346. outptr = output_buf[ci][output_row];
  162347. for (col = 0; col < num_cols; col++) {
  162348. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162349. inptr += nc;
  162350. }
  162351. }
  162352. input_buf++;
  162353. output_row++;
  162354. }
  162355. }
  162356. /*
  162357. * Empty method for start_pass.
  162358. */
  162359. METHODDEF(void)
  162360. null_method (j_compress_ptr)
  162361. {
  162362. /* no work needed */
  162363. }
  162364. /*
  162365. * Module initialization routine for input colorspace conversion.
  162366. */
  162367. GLOBAL(void)
  162368. jinit_color_converter (j_compress_ptr cinfo)
  162369. {
  162370. my_cconvert_ptr cconvert;
  162371. cconvert = (my_cconvert_ptr)
  162372. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162373. SIZEOF(my_color_converter));
  162374. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162375. /* set start_pass to null method until we find out differently */
  162376. cconvert->pub.start_pass = null_method;
  162377. /* Make sure input_components agrees with in_color_space */
  162378. switch (cinfo->in_color_space) {
  162379. case JCS_GRAYSCALE:
  162380. if (cinfo->input_components != 1)
  162381. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162382. break;
  162383. case JCS_RGB:
  162384. #if RGB_PIXELSIZE != 3
  162385. if (cinfo->input_components != RGB_PIXELSIZE)
  162386. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162387. break;
  162388. #endif /* else share code with YCbCr */
  162389. case JCS_YCbCr:
  162390. if (cinfo->input_components != 3)
  162391. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162392. break;
  162393. case JCS_CMYK:
  162394. case JCS_YCCK:
  162395. if (cinfo->input_components != 4)
  162396. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162397. break;
  162398. default: /* JCS_UNKNOWN can be anything */
  162399. if (cinfo->input_components < 1)
  162400. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162401. break;
  162402. }
  162403. /* Check num_components, set conversion method based on requested space */
  162404. switch (cinfo->jpeg_color_space) {
  162405. case JCS_GRAYSCALE:
  162406. if (cinfo->num_components != 1)
  162407. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162408. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162409. cconvert->pub.color_convert = grayscale_convert;
  162410. else if (cinfo->in_color_space == JCS_RGB) {
  162411. cconvert->pub.start_pass = rgb_ycc_start;
  162412. cconvert->pub.color_convert = rgb_gray_convert;
  162413. } else if (cinfo->in_color_space == JCS_YCbCr)
  162414. cconvert->pub.color_convert = grayscale_convert;
  162415. else
  162416. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162417. break;
  162418. case JCS_RGB:
  162419. if (cinfo->num_components != 3)
  162420. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162421. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162422. cconvert->pub.color_convert = null_convert;
  162423. else
  162424. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162425. break;
  162426. case JCS_YCbCr:
  162427. if (cinfo->num_components != 3)
  162428. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162429. if (cinfo->in_color_space == JCS_RGB) {
  162430. cconvert->pub.start_pass = rgb_ycc_start;
  162431. cconvert->pub.color_convert = rgb_ycc_convert;
  162432. } else if (cinfo->in_color_space == JCS_YCbCr)
  162433. cconvert->pub.color_convert = null_convert;
  162434. else
  162435. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162436. break;
  162437. case JCS_CMYK:
  162438. if (cinfo->num_components != 4)
  162439. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162440. if (cinfo->in_color_space == JCS_CMYK)
  162441. cconvert->pub.color_convert = null_convert;
  162442. else
  162443. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162444. break;
  162445. case JCS_YCCK:
  162446. if (cinfo->num_components != 4)
  162447. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162448. if (cinfo->in_color_space == JCS_CMYK) {
  162449. cconvert->pub.start_pass = rgb_ycc_start;
  162450. cconvert->pub.color_convert = cmyk_ycck_convert;
  162451. } else if (cinfo->in_color_space == JCS_YCCK)
  162452. cconvert->pub.color_convert = null_convert;
  162453. else
  162454. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162455. break;
  162456. default: /* allow null conversion of JCS_UNKNOWN */
  162457. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162458. cinfo->num_components != cinfo->input_components)
  162459. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162460. cconvert->pub.color_convert = null_convert;
  162461. break;
  162462. }
  162463. }
  162464. /*** End of inlined file: jccolor.c ***/
  162465. #undef FIX
  162466. /*** Start of inlined file: jcdctmgr.c ***/
  162467. #define JPEG_INTERNALS
  162468. /*** Start of inlined file: jdct.h ***/
  162469. /*
  162470. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162471. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162472. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162473. * implementations use an array of type FAST_FLOAT, instead.)
  162474. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162475. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162476. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162477. * convention improves accuracy in integer implementations and saves some
  162478. * work in floating-point ones.
  162479. * Quantization of the output coefficients is done by jcdctmgr.c.
  162480. */
  162481. #ifndef __jdct_h__
  162482. #define __jdct_h__
  162483. #if BITS_IN_JSAMPLE == 8
  162484. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162485. #else
  162486. typedef INT32 DCTELEM; /* must have 32 bits */
  162487. #endif
  162488. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162489. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162490. /*
  162491. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162492. * to an output sample array. The routine must dequantize the input data as
  162493. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162494. * pointed to by compptr->dct_table. The output data is to be placed into the
  162495. * sample array starting at a specified column. (Any row offset needed will
  162496. * be applied to the array pointer before it is passed to the IDCT code.)
  162497. * Note that the number of samples emitted by the IDCT routine is
  162498. * DCT_scaled_size * DCT_scaled_size.
  162499. */
  162500. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162501. /*
  162502. * Each IDCT routine has its own ideas about the best dct_table element type.
  162503. */
  162504. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162505. #if BITS_IN_JSAMPLE == 8
  162506. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162507. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162508. #else
  162509. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162510. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162511. #endif
  162512. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162513. /*
  162514. * Each IDCT routine is responsible for range-limiting its results and
  162515. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162516. * be quite far out of range if the input data is corrupt, so a bulletproof
  162517. * range-limiting step is required. We use a mask-and-table-lookup method
  162518. * to do the combined operations quickly. See the comments with
  162519. * prepare_range_limit_table (in jdmaster.c) for more info.
  162520. */
  162521. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162522. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162523. /* Short forms of external names for systems with brain-damaged linkers. */
  162524. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162525. #define jpeg_fdct_islow jFDislow
  162526. #define jpeg_fdct_ifast jFDifast
  162527. #define jpeg_fdct_float jFDfloat
  162528. #define jpeg_idct_islow jRDislow
  162529. #define jpeg_idct_ifast jRDifast
  162530. #define jpeg_idct_float jRDfloat
  162531. #define jpeg_idct_4x4 jRD4x4
  162532. #define jpeg_idct_2x2 jRD2x2
  162533. #define jpeg_idct_1x1 jRD1x1
  162534. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162535. /* Extern declarations for the forward and inverse DCT routines. */
  162536. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162537. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162538. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162539. EXTERN(void) jpeg_idct_islow
  162540. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162541. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162542. EXTERN(void) jpeg_idct_ifast
  162543. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162544. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162545. EXTERN(void) jpeg_idct_float
  162546. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162547. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162548. EXTERN(void) jpeg_idct_4x4
  162549. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162550. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162551. EXTERN(void) jpeg_idct_2x2
  162552. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162553. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162554. EXTERN(void) jpeg_idct_1x1
  162555. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162556. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162557. /*
  162558. * Macros for handling fixed-point arithmetic; these are used by many
  162559. * but not all of the DCT/IDCT modules.
  162560. *
  162561. * All values are expected to be of type INT32.
  162562. * Fractional constants are scaled left by CONST_BITS bits.
  162563. * CONST_BITS is defined within each module using these macros,
  162564. * and may differ from one module to the next.
  162565. */
  162566. #define ONE ((INT32) 1)
  162567. #define CONST_SCALE (ONE << CONST_BITS)
  162568. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162569. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162570. * thus causing a lot of useless floating-point operations at run time.
  162571. */
  162572. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162573. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162574. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162575. * the fudge factor is correct for either sign of X.
  162576. */
  162577. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162578. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162579. * This macro is used only when the two inputs will actually be no more than
  162580. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162581. * full 32x32 multiply. This provides a useful speedup on many machines.
  162582. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162583. * in C, but some C compilers will do the right thing if you provide the
  162584. * correct combination of casts.
  162585. */
  162586. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162587. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162588. #endif
  162589. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162590. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162591. #endif
  162592. #ifndef MULTIPLY16C16 /* default definition */
  162593. #define MULTIPLY16C16(var,const) ((var) * (const))
  162594. #endif
  162595. /* Same except both inputs are variables. */
  162596. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162597. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162598. #endif
  162599. #ifndef MULTIPLY16V16 /* default definition */
  162600. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162601. #endif
  162602. #endif
  162603. /*** End of inlined file: jdct.h ***/
  162604. /* Private declarations for DCT subsystem */
  162605. /* Private subobject for this module */
  162606. typedef struct {
  162607. struct jpeg_forward_dct pub; /* public fields */
  162608. /* Pointer to the DCT routine actually in use */
  162609. forward_DCT_method_ptr do_dct;
  162610. /* The actual post-DCT divisors --- not identical to the quant table
  162611. * entries, because of scaling (especially for an unnormalized DCT).
  162612. * Each table is given in normal array order.
  162613. */
  162614. DCTELEM * divisors[NUM_QUANT_TBLS];
  162615. #ifdef DCT_FLOAT_SUPPORTED
  162616. /* Same as above for the floating-point case. */
  162617. float_DCT_method_ptr do_float_dct;
  162618. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162619. #endif
  162620. } my_fdct_controller;
  162621. typedef my_fdct_controller * my_fdct_ptr;
  162622. /*
  162623. * Initialize for a processing pass.
  162624. * Verify that all referenced Q-tables are present, and set up
  162625. * the divisor table for each one.
  162626. * In the current implementation, DCT of all components is done during
  162627. * the first pass, even if only some components will be output in the
  162628. * first scan. Hence all components should be examined here.
  162629. */
  162630. METHODDEF(void)
  162631. start_pass_fdctmgr (j_compress_ptr cinfo)
  162632. {
  162633. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162634. int ci, qtblno, i;
  162635. jpeg_component_info *compptr;
  162636. JQUANT_TBL * qtbl;
  162637. DCTELEM * dtbl;
  162638. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162639. ci++, compptr++) {
  162640. qtblno = compptr->quant_tbl_no;
  162641. /* Make sure specified quantization table is present */
  162642. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162643. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162644. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162645. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162646. /* Compute divisors for this quant table */
  162647. /* We may do this more than once for same table, but it's not a big deal */
  162648. switch (cinfo->dct_method) {
  162649. #ifdef DCT_ISLOW_SUPPORTED
  162650. case JDCT_ISLOW:
  162651. /* For LL&M IDCT method, divisors are equal to raw quantization
  162652. * coefficients multiplied by 8 (to counteract scaling).
  162653. */
  162654. if (fdct->divisors[qtblno] == NULL) {
  162655. fdct->divisors[qtblno] = (DCTELEM *)
  162656. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162657. DCTSIZE2 * SIZEOF(DCTELEM));
  162658. }
  162659. dtbl = fdct->divisors[qtblno];
  162660. for (i = 0; i < DCTSIZE2; i++) {
  162661. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162662. }
  162663. break;
  162664. #endif
  162665. #ifdef DCT_IFAST_SUPPORTED
  162666. case JDCT_IFAST:
  162667. {
  162668. /* For AA&N IDCT method, divisors are equal to quantization
  162669. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162670. * scalefactor[0] = 1
  162671. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162672. * We apply a further scale factor of 8.
  162673. */
  162674. #define CONST_BITS 14
  162675. static const INT16 aanscales[DCTSIZE2] = {
  162676. /* precomputed values scaled up by 14 bits */
  162677. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162678. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162679. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162680. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162681. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162682. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162683. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162684. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162685. };
  162686. SHIFT_TEMPS
  162687. if (fdct->divisors[qtblno] == NULL) {
  162688. fdct->divisors[qtblno] = (DCTELEM *)
  162689. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162690. DCTSIZE2 * SIZEOF(DCTELEM));
  162691. }
  162692. dtbl = fdct->divisors[qtblno];
  162693. for (i = 0; i < DCTSIZE2; i++) {
  162694. dtbl[i] = (DCTELEM)
  162695. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162696. (INT32) aanscales[i]),
  162697. CONST_BITS-3);
  162698. }
  162699. }
  162700. break;
  162701. #endif
  162702. #ifdef DCT_FLOAT_SUPPORTED
  162703. case JDCT_FLOAT:
  162704. {
  162705. /* For float AA&N IDCT method, divisors are equal to quantization
  162706. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162707. * scalefactor[0] = 1
  162708. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162709. * We apply a further scale factor of 8.
  162710. * What's actually stored is 1/divisor so that the inner loop can
  162711. * use a multiplication rather than a division.
  162712. */
  162713. FAST_FLOAT * fdtbl;
  162714. int row, col;
  162715. static const double aanscalefactor[DCTSIZE] = {
  162716. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162717. 1.0, 0.785694958, 0.541196100, 0.275899379
  162718. };
  162719. if (fdct->float_divisors[qtblno] == NULL) {
  162720. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162721. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162722. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162723. }
  162724. fdtbl = fdct->float_divisors[qtblno];
  162725. i = 0;
  162726. for (row = 0; row < DCTSIZE; row++) {
  162727. for (col = 0; col < DCTSIZE; col++) {
  162728. fdtbl[i] = (FAST_FLOAT)
  162729. (1.0 / (((double) qtbl->quantval[i] *
  162730. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162731. i++;
  162732. }
  162733. }
  162734. }
  162735. break;
  162736. #endif
  162737. default:
  162738. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162739. break;
  162740. }
  162741. }
  162742. }
  162743. /*
  162744. * Perform forward DCT on one or more blocks of a component.
  162745. *
  162746. * The input samples are taken from the sample_data[] array starting at
  162747. * position start_row/start_col, and moving to the right for any additional
  162748. * blocks. The quantized coefficients are returned in coef_blocks[].
  162749. */
  162750. METHODDEF(void)
  162751. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162752. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162753. JDIMENSION start_row, JDIMENSION start_col,
  162754. JDIMENSION num_blocks)
  162755. /* This version is used for integer DCT implementations. */
  162756. {
  162757. /* This routine is heavily used, so it's worth coding it tightly. */
  162758. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162759. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162760. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162761. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162762. JDIMENSION bi;
  162763. sample_data += start_row; /* fold in the vertical offset once */
  162764. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162765. /* Load data into workspace, applying unsigned->signed conversion */
  162766. { register DCTELEM *workspaceptr;
  162767. register JSAMPROW elemptr;
  162768. register int elemr;
  162769. workspaceptr = workspace;
  162770. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162771. elemptr = sample_data[elemr] + start_col;
  162772. #if DCTSIZE == 8 /* unroll the inner loop */
  162773. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162774. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162775. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162776. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162777. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162778. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162779. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162780. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162781. #else
  162782. { register int elemc;
  162783. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162784. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162785. }
  162786. }
  162787. #endif
  162788. }
  162789. }
  162790. /* Perform the DCT */
  162791. (*do_dct) (workspace);
  162792. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162793. { register DCTELEM temp, qval;
  162794. register int i;
  162795. register JCOEFPTR output_ptr = coef_blocks[bi];
  162796. for (i = 0; i < DCTSIZE2; i++) {
  162797. qval = divisors[i];
  162798. temp = workspace[i];
  162799. /* Divide the coefficient value by qval, ensuring proper rounding.
  162800. * Since C does not specify the direction of rounding for negative
  162801. * quotients, we have to force the dividend positive for portability.
  162802. *
  162803. * In most files, at least half of the output values will be zero
  162804. * (at default quantization settings, more like three-quarters...)
  162805. * so we should ensure that this case is fast. On many machines,
  162806. * a comparison is enough cheaper than a divide to make a special test
  162807. * a win. Since both inputs will be nonnegative, we need only test
  162808. * for a < b to discover whether a/b is 0.
  162809. * If your machine's division is fast enough, define FAST_DIVIDE.
  162810. */
  162811. #ifdef FAST_DIVIDE
  162812. #define DIVIDE_BY(a,b) a /= b
  162813. #else
  162814. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162815. #endif
  162816. if (temp < 0) {
  162817. temp = -temp;
  162818. temp += qval>>1; /* for rounding */
  162819. DIVIDE_BY(temp, qval);
  162820. temp = -temp;
  162821. } else {
  162822. temp += qval>>1; /* for rounding */
  162823. DIVIDE_BY(temp, qval);
  162824. }
  162825. output_ptr[i] = (JCOEF) temp;
  162826. }
  162827. }
  162828. }
  162829. }
  162830. #ifdef DCT_FLOAT_SUPPORTED
  162831. METHODDEF(void)
  162832. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162833. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162834. JDIMENSION start_row, JDIMENSION start_col,
  162835. JDIMENSION num_blocks)
  162836. /* This version is used for floating-point DCT implementations. */
  162837. {
  162838. /* This routine is heavily used, so it's worth coding it tightly. */
  162839. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162840. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162841. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162842. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162843. JDIMENSION bi;
  162844. sample_data += start_row; /* fold in the vertical offset once */
  162845. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162846. /* Load data into workspace, applying unsigned->signed conversion */
  162847. { register FAST_FLOAT *workspaceptr;
  162848. register JSAMPROW elemptr;
  162849. register int elemr;
  162850. workspaceptr = workspace;
  162851. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162852. elemptr = sample_data[elemr] + start_col;
  162853. #if DCTSIZE == 8 /* unroll the inner loop */
  162854. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162855. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162856. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162857. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162858. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162859. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162860. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162861. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162862. #else
  162863. { register int elemc;
  162864. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162865. *workspaceptr++ = (FAST_FLOAT)
  162866. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162867. }
  162868. }
  162869. #endif
  162870. }
  162871. }
  162872. /* Perform the DCT */
  162873. (*do_dct) (workspace);
  162874. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162875. { register FAST_FLOAT temp;
  162876. register int i;
  162877. register JCOEFPTR output_ptr = coef_blocks[bi];
  162878. for (i = 0; i < DCTSIZE2; i++) {
  162879. /* Apply the quantization and scaling factor */
  162880. temp = workspace[i] * divisors[i];
  162881. /* Round to nearest integer.
  162882. * Since C does not specify the direction of rounding for negative
  162883. * quotients, we have to force the dividend positive for portability.
  162884. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162885. * code should work for either 16-bit or 32-bit ints.
  162886. */
  162887. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162888. }
  162889. }
  162890. }
  162891. }
  162892. #endif /* DCT_FLOAT_SUPPORTED */
  162893. /*
  162894. * Initialize FDCT manager.
  162895. */
  162896. GLOBAL(void)
  162897. jinit_forward_dct (j_compress_ptr cinfo)
  162898. {
  162899. my_fdct_ptr fdct;
  162900. int i;
  162901. fdct = (my_fdct_ptr)
  162902. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162903. SIZEOF(my_fdct_controller));
  162904. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162905. fdct->pub.start_pass = start_pass_fdctmgr;
  162906. switch (cinfo->dct_method) {
  162907. #ifdef DCT_ISLOW_SUPPORTED
  162908. case JDCT_ISLOW:
  162909. fdct->pub.forward_DCT = forward_DCT;
  162910. fdct->do_dct = jpeg_fdct_islow;
  162911. break;
  162912. #endif
  162913. #ifdef DCT_IFAST_SUPPORTED
  162914. case JDCT_IFAST:
  162915. fdct->pub.forward_DCT = forward_DCT;
  162916. fdct->do_dct = jpeg_fdct_ifast;
  162917. break;
  162918. #endif
  162919. #ifdef DCT_FLOAT_SUPPORTED
  162920. case JDCT_FLOAT:
  162921. fdct->pub.forward_DCT = forward_DCT_float;
  162922. fdct->do_float_dct = jpeg_fdct_float;
  162923. break;
  162924. #endif
  162925. default:
  162926. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162927. break;
  162928. }
  162929. /* Mark divisor tables unallocated */
  162930. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162931. fdct->divisors[i] = NULL;
  162932. #ifdef DCT_FLOAT_SUPPORTED
  162933. fdct->float_divisors[i] = NULL;
  162934. #endif
  162935. }
  162936. }
  162937. /*** End of inlined file: jcdctmgr.c ***/
  162938. #undef CONST_BITS
  162939. /*** Start of inlined file: jchuff.c ***/
  162940. #define JPEG_INTERNALS
  162941. /*** Start of inlined file: jchuff.h ***/
  162942. /* The legal range of a DCT coefficient is
  162943. * -1024 .. +1023 for 8-bit data;
  162944. * -16384 .. +16383 for 12-bit data.
  162945. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162946. */
  162947. #ifndef _jchuff_h_
  162948. #define _jchuff_h_
  162949. #if BITS_IN_JSAMPLE == 8
  162950. #define MAX_COEF_BITS 10
  162951. #else
  162952. #define MAX_COEF_BITS 14
  162953. #endif
  162954. /* Derived data constructed for each Huffman table */
  162955. typedef struct {
  162956. unsigned int ehufco[256]; /* code for each symbol */
  162957. char ehufsi[256]; /* length of code for each symbol */
  162958. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162959. } c_derived_tbl;
  162960. /* Short forms of external names for systems with brain-damaged linkers. */
  162961. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162962. #define jpeg_make_c_derived_tbl jMkCDerived
  162963. #define jpeg_gen_optimal_table jGenOptTbl
  162964. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162965. /* Expand a Huffman table definition into the derived format */
  162966. EXTERN(void) jpeg_make_c_derived_tbl
  162967. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162968. c_derived_tbl ** pdtbl));
  162969. /* Generate an optimal table definition given the specified counts */
  162970. EXTERN(void) jpeg_gen_optimal_table
  162971. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162972. #endif
  162973. /*** End of inlined file: jchuff.h ***/
  162974. /* Declarations shared with jcphuff.c */
  162975. /* Expanded entropy encoder object for Huffman encoding.
  162976. *
  162977. * The savable_state subrecord contains fields that change within an MCU,
  162978. * but must not be updated permanently until we complete the MCU.
  162979. */
  162980. typedef struct {
  162981. INT32 put_buffer; /* current bit-accumulation buffer */
  162982. int put_bits; /* # of bits now in it */
  162983. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162984. } savable_state;
  162985. /* This macro is to work around compilers with missing or broken
  162986. * structure assignment. You'll need to fix this code if you have
  162987. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162988. */
  162989. #ifndef NO_STRUCT_ASSIGN
  162990. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162991. #else
  162992. #if MAX_COMPS_IN_SCAN == 4
  162993. #define ASSIGN_STATE(dest,src) \
  162994. ((dest).put_buffer = (src).put_buffer, \
  162995. (dest).put_bits = (src).put_bits, \
  162996. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162997. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162998. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162999. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163000. #endif
  163001. #endif
  163002. typedef struct {
  163003. struct jpeg_entropy_encoder pub; /* public fields */
  163004. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163005. /* These fields are NOT loaded into local working state. */
  163006. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163007. int next_restart_num; /* next restart number to write (0-7) */
  163008. /* Pointers to derived tables (these workspaces have image lifespan) */
  163009. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163010. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163011. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163012. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163013. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163014. #endif
  163015. } huff_entropy_encoder;
  163016. typedef huff_entropy_encoder * huff_entropy_ptr;
  163017. /* Working state while writing an MCU.
  163018. * This struct contains all the fields that are needed by subroutines.
  163019. */
  163020. typedef struct {
  163021. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163022. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163023. savable_state cur; /* Current bit buffer & DC state */
  163024. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163025. } working_state;
  163026. /* Forward declarations */
  163027. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163028. JBLOCKROW *MCU_data));
  163029. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163030. #ifdef ENTROPY_OPT_SUPPORTED
  163031. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163032. JBLOCKROW *MCU_data));
  163033. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163034. #endif
  163035. /*
  163036. * Initialize for a Huffman-compressed scan.
  163037. * If gather_statistics is TRUE, we do not output anything during the scan,
  163038. * just count the Huffman symbols used and generate Huffman code tables.
  163039. */
  163040. METHODDEF(void)
  163041. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163042. {
  163043. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163044. int ci, dctbl, actbl;
  163045. jpeg_component_info * compptr;
  163046. if (gather_statistics) {
  163047. #ifdef ENTROPY_OPT_SUPPORTED
  163048. entropy->pub.encode_mcu = encode_mcu_gather;
  163049. entropy->pub.finish_pass = finish_pass_gather;
  163050. #else
  163051. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163052. #endif
  163053. } else {
  163054. entropy->pub.encode_mcu = encode_mcu_huff;
  163055. entropy->pub.finish_pass = finish_pass_huff;
  163056. }
  163057. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163058. compptr = cinfo->cur_comp_info[ci];
  163059. dctbl = compptr->dc_tbl_no;
  163060. actbl = compptr->ac_tbl_no;
  163061. if (gather_statistics) {
  163062. #ifdef ENTROPY_OPT_SUPPORTED
  163063. /* Check for invalid table indexes */
  163064. /* (make_c_derived_tbl does this in the other path) */
  163065. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163066. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163067. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163068. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163069. /* Allocate and zero the statistics tables */
  163070. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163071. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163072. entropy->dc_count_ptrs[dctbl] = (long *)
  163073. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163074. 257 * SIZEOF(long));
  163075. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163076. if (entropy->ac_count_ptrs[actbl] == NULL)
  163077. entropy->ac_count_ptrs[actbl] = (long *)
  163078. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163079. 257 * SIZEOF(long));
  163080. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163081. #endif
  163082. } else {
  163083. /* Compute derived values for Huffman tables */
  163084. /* We may do this more than once for a table, but it's not expensive */
  163085. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163086. & entropy->dc_derived_tbls[dctbl]);
  163087. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163088. & entropy->ac_derived_tbls[actbl]);
  163089. }
  163090. /* Initialize DC predictions to 0 */
  163091. entropy->saved.last_dc_val[ci] = 0;
  163092. }
  163093. /* Initialize bit buffer to empty */
  163094. entropy->saved.put_buffer = 0;
  163095. entropy->saved.put_bits = 0;
  163096. /* Initialize restart stuff */
  163097. entropy->restarts_to_go = cinfo->restart_interval;
  163098. entropy->next_restart_num = 0;
  163099. }
  163100. /*
  163101. * Compute the derived values for a Huffman table.
  163102. * This routine also performs some validation checks on the table.
  163103. *
  163104. * Note this is also used by jcphuff.c.
  163105. */
  163106. GLOBAL(void)
  163107. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163108. c_derived_tbl ** pdtbl)
  163109. {
  163110. JHUFF_TBL *htbl;
  163111. c_derived_tbl *dtbl;
  163112. int p, i, l, lastp, si, maxsymbol;
  163113. char huffsize[257];
  163114. unsigned int huffcode[257];
  163115. unsigned int code;
  163116. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163117. * paralleling the order of the symbols themselves in htbl->huffval[].
  163118. */
  163119. /* Find the input Huffman table */
  163120. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163121. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163122. htbl =
  163123. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163124. if (htbl == NULL)
  163125. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163126. /* Allocate a workspace if we haven't already done so. */
  163127. if (*pdtbl == NULL)
  163128. *pdtbl = (c_derived_tbl *)
  163129. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163130. SIZEOF(c_derived_tbl));
  163131. dtbl = *pdtbl;
  163132. /* Figure C.1: make table of Huffman code length for each symbol */
  163133. p = 0;
  163134. for (l = 1; l <= 16; l++) {
  163135. i = (int) htbl->bits[l];
  163136. if (i < 0 || p + i > 256) /* protect against table overrun */
  163137. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163138. while (i--)
  163139. huffsize[p++] = (char) l;
  163140. }
  163141. huffsize[p] = 0;
  163142. lastp = p;
  163143. /* Figure C.2: generate the codes themselves */
  163144. /* We also validate that the counts represent a legal Huffman code tree. */
  163145. code = 0;
  163146. si = huffsize[0];
  163147. p = 0;
  163148. while (huffsize[p]) {
  163149. while (((int) huffsize[p]) == si) {
  163150. huffcode[p++] = code;
  163151. code++;
  163152. }
  163153. /* code is now 1 more than the last code used for codelength si; but
  163154. * it must still fit in si bits, since no code is allowed to be all ones.
  163155. */
  163156. if (((INT32) code) >= (((INT32) 1) << si))
  163157. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163158. code <<= 1;
  163159. si++;
  163160. }
  163161. /* Figure C.3: generate encoding tables */
  163162. /* These are code and size indexed by symbol value */
  163163. /* Set all codeless symbols to have code length 0;
  163164. * this lets us detect duplicate VAL entries here, and later
  163165. * allows emit_bits to detect any attempt to emit such symbols.
  163166. */
  163167. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163168. /* This is also a convenient place to check for out-of-range
  163169. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163170. * but only 0..15 for DC. (We could constrain them further
  163171. * based on data depth and mode, but this seems enough.)
  163172. */
  163173. maxsymbol = isDC ? 15 : 255;
  163174. for (p = 0; p < lastp; p++) {
  163175. i = htbl->huffval[p];
  163176. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163177. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163178. dtbl->ehufco[i] = huffcode[p];
  163179. dtbl->ehufsi[i] = huffsize[p];
  163180. }
  163181. }
  163182. /* Outputting bytes to the file */
  163183. /* Emit a byte, taking 'action' if must suspend. */
  163184. #define emit_byte(state,val,action) \
  163185. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163186. if (--(state)->free_in_buffer == 0) \
  163187. if (! dump_buffer(state)) \
  163188. { action; } }
  163189. LOCAL(boolean)
  163190. dump_buffer (working_state * state)
  163191. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163192. {
  163193. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163194. if (! (*dest->empty_output_buffer) (state->cinfo))
  163195. return FALSE;
  163196. /* After a successful buffer dump, must reset buffer pointers */
  163197. state->next_output_byte = dest->next_output_byte;
  163198. state->free_in_buffer = dest->free_in_buffer;
  163199. return TRUE;
  163200. }
  163201. /* Outputting bits to the file */
  163202. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163203. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163204. * in one call, and we never retain more than 7 bits in put_buffer
  163205. * between calls, so 24 bits are sufficient.
  163206. */
  163207. INLINE
  163208. LOCAL(boolean)
  163209. emit_bits (working_state * state, unsigned int code, int size)
  163210. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163211. {
  163212. /* This routine is heavily used, so it's worth coding tightly. */
  163213. register INT32 put_buffer = (INT32) code;
  163214. register int put_bits = state->cur.put_bits;
  163215. /* if size is 0, caller used an invalid Huffman table entry */
  163216. if (size == 0)
  163217. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163218. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163219. put_bits += size; /* new number of bits in buffer */
  163220. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163221. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163222. while (put_bits >= 8) {
  163223. int c = (int) ((put_buffer >> 16) & 0xFF);
  163224. emit_byte(state, c, return FALSE);
  163225. if (c == 0xFF) { /* need to stuff a zero byte? */
  163226. emit_byte(state, 0, return FALSE);
  163227. }
  163228. put_buffer <<= 8;
  163229. put_bits -= 8;
  163230. }
  163231. state->cur.put_buffer = put_buffer; /* update state variables */
  163232. state->cur.put_bits = put_bits;
  163233. return TRUE;
  163234. }
  163235. LOCAL(boolean)
  163236. flush_bits (working_state * state)
  163237. {
  163238. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163239. return FALSE;
  163240. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163241. state->cur.put_bits = 0;
  163242. return TRUE;
  163243. }
  163244. /* Encode a single block's worth of coefficients */
  163245. LOCAL(boolean)
  163246. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163247. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163248. {
  163249. register int temp, temp2;
  163250. register int nbits;
  163251. register int k, r, i;
  163252. /* Encode the DC coefficient difference per section F.1.2.1 */
  163253. temp = temp2 = block[0] - last_dc_val;
  163254. if (temp < 0) {
  163255. temp = -temp; /* temp is abs value of input */
  163256. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163257. /* This code assumes we are on a two's complement machine */
  163258. temp2--;
  163259. }
  163260. /* Find the number of bits needed for the magnitude of the coefficient */
  163261. nbits = 0;
  163262. while (temp) {
  163263. nbits++;
  163264. temp >>= 1;
  163265. }
  163266. /* Check for out-of-range coefficient values.
  163267. * Since we're encoding a difference, the range limit is twice as much.
  163268. */
  163269. if (nbits > MAX_COEF_BITS+1)
  163270. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163271. /* Emit the Huffman-coded symbol for the number of bits */
  163272. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163273. return FALSE;
  163274. /* Emit that number of bits of the value, if positive, */
  163275. /* or the complement of its magnitude, if negative. */
  163276. if (nbits) /* emit_bits rejects calls with size 0 */
  163277. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163278. return FALSE;
  163279. /* Encode the AC coefficients per section F.1.2.2 */
  163280. r = 0; /* r = run length of zeros */
  163281. for (k = 1; k < DCTSIZE2; k++) {
  163282. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163283. r++;
  163284. } else {
  163285. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163286. while (r > 15) {
  163287. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163288. return FALSE;
  163289. r -= 16;
  163290. }
  163291. temp2 = temp;
  163292. if (temp < 0) {
  163293. temp = -temp; /* temp is abs value of input */
  163294. /* This code assumes we are on a two's complement machine */
  163295. temp2--;
  163296. }
  163297. /* Find the number of bits needed for the magnitude of the coefficient */
  163298. nbits = 1; /* there must be at least one 1 bit */
  163299. while ((temp >>= 1))
  163300. nbits++;
  163301. /* Check for out-of-range coefficient values */
  163302. if (nbits > MAX_COEF_BITS)
  163303. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163304. /* Emit Huffman symbol for run length / number of bits */
  163305. i = (r << 4) + nbits;
  163306. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163307. return FALSE;
  163308. /* Emit that number of bits of the value, if positive, */
  163309. /* or the complement of its magnitude, if negative. */
  163310. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163311. return FALSE;
  163312. r = 0;
  163313. }
  163314. }
  163315. /* If the last coef(s) were zero, emit an end-of-block code */
  163316. if (r > 0)
  163317. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163318. return FALSE;
  163319. return TRUE;
  163320. }
  163321. /*
  163322. * Emit a restart marker & resynchronize predictions.
  163323. */
  163324. LOCAL(boolean)
  163325. emit_restart (working_state * state, int restart_num)
  163326. {
  163327. int ci;
  163328. if (! flush_bits(state))
  163329. return FALSE;
  163330. emit_byte(state, 0xFF, return FALSE);
  163331. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163332. /* Re-initialize DC predictions to 0 */
  163333. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163334. state->cur.last_dc_val[ci] = 0;
  163335. /* The restart counter is not updated until we successfully write the MCU. */
  163336. return TRUE;
  163337. }
  163338. /*
  163339. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163340. */
  163341. METHODDEF(boolean)
  163342. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163343. {
  163344. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163345. working_state state;
  163346. int blkn, ci;
  163347. jpeg_component_info * compptr;
  163348. /* Load up working state */
  163349. state.next_output_byte = cinfo->dest->next_output_byte;
  163350. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163351. ASSIGN_STATE(state.cur, entropy->saved);
  163352. state.cinfo = cinfo;
  163353. /* Emit restart marker if needed */
  163354. if (cinfo->restart_interval) {
  163355. if (entropy->restarts_to_go == 0)
  163356. if (! emit_restart(&state, entropy->next_restart_num))
  163357. return FALSE;
  163358. }
  163359. /* Encode the MCU data blocks */
  163360. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163361. ci = cinfo->MCU_membership[blkn];
  163362. compptr = cinfo->cur_comp_info[ci];
  163363. if (! encode_one_block(&state,
  163364. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163365. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163366. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163367. return FALSE;
  163368. /* Update last_dc_val */
  163369. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163370. }
  163371. /* Completed MCU, so update state */
  163372. cinfo->dest->next_output_byte = state.next_output_byte;
  163373. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163374. ASSIGN_STATE(entropy->saved, state.cur);
  163375. /* Update restart-interval state too */
  163376. if (cinfo->restart_interval) {
  163377. if (entropy->restarts_to_go == 0) {
  163378. entropy->restarts_to_go = cinfo->restart_interval;
  163379. entropy->next_restart_num++;
  163380. entropy->next_restart_num &= 7;
  163381. }
  163382. entropy->restarts_to_go--;
  163383. }
  163384. return TRUE;
  163385. }
  163386. /*
  163387. * Finish up at the end of a Huffman-compressed scan.
  163388. */
  163389. METHODDEF(void)
  163390. finish_pass_huff (j_compress_ptr cinfo)
  163391. {
  163392. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163393. working_state state;
  163394. /* Load up working state ... flush_bits needs it */
  163395. state.next_output_byte = cinfo->dest->next_output_byte;
  163396. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163397. ASSIGN_STATE(state.cur, entropy->saved);
  163398. state.cinfo = cinfo;
  163399. /* Flush out the last data */
  163400. if (! flush_bits(&state))
  163401. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163402. /* Update state */
  163403. cinfo->dest->next_output_byte = state.next_output_byte;
  163404. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163405. ASSIGN_STATE(entropy->saved, state.cur);
  163406. }
  163407. /*
  163408. * Huffman coding optimization.
  163409. *
  163410. * We first scan the supplied data and count the number of uses of each symbol
  163411. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163412. * Then we build a Huffman coding tree for the observed counts.
  163413. * Symbols which are not needed at all for the particular image are not
  163414. * assigned any code, which saves space in the DHT marker as well as in
  163415. * the compressed data.
  163416. */
  163417. #ifdef ENTROPY_OPT_SUPPORTED
  163418. /* Process a single block's worth of coefficients */
  163419. LOCAL(void)
  163420. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163421. long dc_counts[], long ac_counts[])
  163422. {
  163423. register int temp;
  163424. register int nbits;
  163425. register int k, r;
  163426. /* Encode the DC coefficient difference per section F.1.2.1 */
  163427. temp = block[0] - last_dc_val;
  163428. if (temp < 0)
  163429. temp = -temp;
  163430. /* Find the number of bits needed for the magnitude of the coefficient */
  163431. nbits = 0;
  163432. while (temp) {
  163433. nbits++;
  163434. temp >>= 1;
  163435. }
  163436. /* Check for out-of-range coefficient values.
  163437. * Since we're encoding a difference, the range limit is twice as much.
  163438. */
  163439. if (nbits > MAX_COEF_BITS+1)
  163440. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163441. /* Count the Huffman symbol for the number of bits */
  163442. dc_counts[nbits]++;
  163443. /* Encode the AC coefficients per section F.1.2.2 */
  163444. r = 0; /* r = run length of zeros */
  163445. for (k = 1; k < DCTSIZE2; k++) {
  163446. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163447. r++;
  163448. } else {
  163449. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163450. while (r > 15) {
  163451. ac_counts[0xF0]++;
  163452. r -= 16;
  163453. }
  163454. /* Find the number of bits needed for the magnitude of the coefficient */
  163455. if (temp < 0)
  163456. temp = -temp;
  163457. /* Find the number of bits needed for the magnitude of the coefficient */
  163458. nbits = 1; /* there must be at least one 1 bit */
  163459. while ((temp >>= 1))
  163460. nbits++;
  163461. /* Check for out-of-range coefficient values */
  163462. if (nbits > MAX_COEF_BITS)
  163463. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163464. /* Count Huffman symbol for run length / number of bits */
  163465. ac_counts[(r << 4) + nbits]++;
  163466. r = 0;
  163467. }
  163468. }
  163469. /* If the last coef(s) were zero, emit an end-of-block code */
  163470. if (r > 0)
  163471. ac_counts[0]++;
  163472. }
  163473. /*
  163474. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163475. * No data is actually output, so no suspension return is possible.
  163476. */
  163477. METHODDEF(boolean)
  163478. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163479. {
  163480. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163481. int blkn, ci;
  163482. jpeg_component_info * compptr;
  163483. /* Take care of restart intervals if needed */
  163484. if (cinfo->restart_interval) {
  163485. if (entropy->restarts_to_go == 0) {
  163486. /* Re-initialize DC predictions to 0 */
  163487. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163488. entropy->saved.last_dc_val[ci] = 0;
  163489. /* Update restart state */
  163490. entropy->restarts_to_go = cinfo->restart_interval;
  163491. }
  163492. entropy->restarts_to_go--;
  163493. }
  163494. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163495. ci = cinfo->MCU_membership[blkn];
  163496. compptr = cinfo->cur_comp_info[ci];
  163497. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163498. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163499. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163500. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163501. }
  163502. return TRUE;
  163503. }
  163504. /*
  163505. * Generate the best Huffman code table for the given counts, fill htbl.
  163506. * Note this is also used by jcphuff.c.
  163507. *
  163508. * The JPEG standard requires that no symbol be assigned a codeword of all
  163509. * one bits (so that padding bits added at the end of a compressed segment
  163510. * can't look like a valid code). Because of the canonical ordering of
  163511. * codewords, this just means that there must be an unused slot in the
  163512. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163513. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163514. * with count 1. In theory that's not optimal; giving it count zero but
  163515. * including it in the symbol set anyway should give a better Huffman code.
  163516. * But the theoretically better code actually seems to come out worse in
  163517. * practice, because it produces more all-ones bytes (which incur stuffed
  163518. * zero bytes in the final file). In any case the difference is tiny.
  163519. *
  163520. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163521. * If some symbols have a very small but nonzero probability, the Huffman tree
  163522. * must be adjusted to meet the code length restriction. We currently use
  163523. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163524. * optimal; it may not choose the best possible limited-length code. But
  163525. * typically only very-low-frequency symbols will be given less-than-optimal
  163526. * lengths, so the code is almost optimal. Experimental comparisons against
  163527. * an optimal limited-length-code algorithm indicate that the difference is
  163528. * microscopic --- usually less than a hundredth of a percent of total size.
  163529. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163530. */
  163531. GLOBAL(void)
  163532. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163533. {
  163534. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163535. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163536. int codesize[257]; /* codesize[k] = code length of symbol k */
  163537. int others[257]; /* next symbol in current branch of tree */
  163538. int c1, c2;
  163539. int p, i, j;
  163540. long v;
  163541. /* This algorithm is explained in section K.2 of the JPEG standard */
  163542. MEMZERO(bits, SIZEOF(bits));
  163543. MEMZERO(codesize, SIZEOF(codesize));
  163544. for (i = 0; i < 257; i++)
  163545. others[i] = -1; /* init links to empty */
  163546. freq[256] = 1; /* make sure 256 has a nonzero count */
  163547. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163548. * that no real symbol is given code-value of all ones, because 256
  163549. * will be placed last in the largest codeword category.
  163550. */
  163551. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163552. for (;;) {
  163553. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163554. /* In case of ties, take the larger symbol number */
  163555. c1 = -1;
  163556. v = 1000000000L;
  163557. for (i = 0; i <= 256; i++) {
  163558. if (freq[i] && freq[i] <= v) {
  163559. v = freq[i];
  163560. c1 = i;
  163561. }
  163562. }
  163563. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163564. /* In case of ties, take the larger symbol number */
  163565. c2 = -1;
  163566. v = 1000000000L;
  163567. for (i = 0; i <= 256; i++) {
  163568. if (freq[i] && freq[i] <= v && i != c1) {
  163569. v = freq[i];
  163570. c2 = i;
  163571. }
  163572. }
  163573. /* Done if we've merged everything into one frequency */
  163574. if (c2 < 0)
  163575. break;
  163576. /* Else merge the two counts/trees */
  163577. freq[c1] += freq[c2];
  163578. freq[c2] = 0;
  163579. /* Increment the codesize of everything in c1's tree branch */
  163580. codesize[c1]++;
  163581. while (others[c1] >= 0) {
  163582. c1 = others[c1];
  163583. codesize[c1]++;
  163584. }
  163585. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163586. /* Increment the codesize of everything in c2's tree branch */
  163587. codesize[c2]++;
  163588. while (others[c2] >= 0) {
  163589. c2 = others[c2];
  163590. codesize[c2]++;
  163591. }
  163592. }
  163593. /* Now count the number of symbols of each code length */
  163594. for (i = 0; i <= 256; i++) {
  163595. if (codesize[i]) {
  163596. /* The JPEG standard seems to think that this can't happen, */
  163597. /* but I'm paranoid... */
  163598. if (codesize[i] > MAX_CLEN)
  163599. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163600. bits[codesize[i]]++;
  163601. }
  163602. }
  163603. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163604. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163605. * Here is what the JPEG spec says about how this next bit works:
  163606. * Since symbols are paired for the longest Huffman code, the symbols are
  163607. * removed from this length category two at a time. The prefix for the pair
  163608. * (which is one bit shorter) is allocated to one of the pair; then,
  163609. * skipping the BITS entry for that prefix length, a code word from the next
  163610. * shortest nonzero BITS entry is converted into a prefix for two code words
  163611. * one bit longer.
  163612. */
  163613. for (i = MAX_CLEN; i > 16; i--) {
  163614. while (bits[i] > 0) {
  163615. j = i - 2; /* find length of new prefix to be used */
  163616. while (bits[j] == 0)
  163617. j--;
  163618. bits[i] -= 2; /* remove two symbols */
  163619. bits[i-1]++; /* one goes in this length */
  163620. bits[j+1] += 2; /* two new symbols in this length */
  163621. bits[j]--; /* symbol of this length is now a prefix */
  163622. }
  163623. }
  163624. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163625. while (bits[i] == 0) /* find largest codelength still in use */
  163626. i--;
  163627. bits[i]--;
  163628. /* Return final symbol counts (only for lengths 0..16) */
  163629. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163630. /* Return a list of the symbols sorted by code length */
  163631. /* It's not real clear to me why we don't need to consider the codelength
  163632. * changes made above, but the JPEG spec seems to think this works.
  163633. */
  163634. p = 0;
  163635. for (i = 1; i <= MAX_CLEN; i++) {
  163636. for (j = 0; j <= 255; j++) {
  163637. if (codesize[j] == i) {
  163638. htbl->huffval[p] = (UINT8) j;
  163639. p++;
  163640. }
  163641. }
  163642. }
  163643. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163644. htbl->sent_table = FALSE;
  163645. }
  163646. /*
  163647. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163648. */
  163649. METHODDEF(void)
  163650. finish_pass_gather (j_compress_ptr cinfo)
  163651. {
  163652. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163653. int ci, dctbl, actbl;
  163654. jpeg_component_info * compptr;
  163655. JHUFF_TBL **htblptr;
  163656. boolean did_dc[NUM_HUFF_TBLS];
  163657. boolean did_ac[NUM_HUFF_TBLS];
  163658. /* It's important not to apply jpeg_gen_optimal_table more than once
  163659. * per table, because it clobbers the input frequency counts!
  163660. */
  163661. MEMZERO(did_dc, SIZEOF(did_dc));
  163662. MEMZERO(did_ac, SIZEOF(did_ac));
  163663. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163664. compptr = cinfo->cur_comp_info[ci];
  163665. dctbl = compptr->dc_tbl_no;
  163666. actbl = compptr->ac_tbl_no;
  163667. if (! did_dc[dctbl]) {
  163668. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163669. if (*htblptr == NULL)
  163670. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163671. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163672. did_dc[dctbl] = TRUE;
  163673. }
  163674. if (! did_ac[actbl]) {
  163675. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163676. if (*htblptr == NULL)
  163677. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163678. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163679. did_ac[actbl] = TRUE;
  163680. }
  163681. }
  163682. }
  163683. #endif /* ENTROPY_OPT_SUPPORTED */
  163684. /*
  163685. * Module initialization routine for Huffman entropy encoding.
  163686. */
  163687. GLOBAL(void)
  163688. jinit_huff_encoder (j_compress_ptr cinfo)
  163689. {
  163690. huff_entropy_ptr entropy;
  163691. int i;
  163692. entropy = (huff_entropy_ptr)
  163693. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163694. SIZEOF(huff_entropy_encoder));
  163695. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163696. entropy->pub.start_pass = start_pass_huff;
  163697. /* Mark tables unallocated */
  163698. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163699. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163700. #ifdef ENTROPY_OPT_SUPPORTED
  163701. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163702. #endif
  163703. }
  163704. }
  163705. /*** End of inlined file: jchuff.c ***/
  163706. #undef emit_byte
  163707. /*** Start of inlined file: jcinit.c ***/
  163708. #define JPEG_INTERNALS
  163709. /*
  163710. * Master selection of compression modules.
  163711. * This is done once at the start of processing an image. We determine
  163712. * which modules will be used and give them appropriate initialization calls.
  163713. */
  163714. GLOBAL(void)
  163715. jinit_compress_master (j_compress_ptr cinfo)
  163716. {
  163717. /* Initialize master control (includes parameter checking/processing) */
  163718. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163719. /* Preprocessing */
  163720. if (! cinfo->raw_data_in) {
  163721. jinit_color_converter(cinfo);
  163722. jinit_downsampler(cinfo);
  163723. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163724. }
  163725. /* Forward DCT */
  163726. jinit_forward_dct(cinfo);
  163727. /* Entropy encoding: either Huffman or arithmetic coding. */
  163728. if (cinfo->arith_code) {
  163729. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163730. } else {
  163731. if (cinfo->progressive_mode) {
  163732. #ifdef C_PROGRESSIVE_SUPPORTED
  163733. jinit_phuff_encoder(cinfo);
  163734. #else
  163735. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163736. #endif
  163737. } else
  163738. jinit_huff_encoder(cinfo);
  163739. }
  163740. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163741. jinit_c_coef_controller(cinfo,
  163742. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163743. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163744. jinit_marker_writer(cinfo);
  163745. /* We can now tell the memory manager to allocate virtual arrays. */
  163746. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163747. /* Write the datastream header (SOI) immediately.
  163748. * Frame and scan headers are postponed till later.
  163749. * This lets application insert special markers after the SOI.
  163750. */
  163751. (*cinfo->marker->write_file_header) (cinfo);
  163752. }
  163753. /*** End of inlined file: jcinit.c ***/
  163754. /*** Start of inlined file: jcmainct.c ***/
  163755. #define JPEG_INTERNALS
  163756. /* Note: currently, there is no operating mode in which a full-image buffer
  163757. * is needed at this step. If there were, that mode could not be used with
  163758. * "raw data" input, since this module is bypassed in that case. However,
  163759. * we've left the code here for possible use in special applications.
  163760. */
  163761. #undef FULL_MAIN_BUFFER_SUPPORTED
  163762. /* Private buffer controller object */
  163763. typedef struct {
  163764. struct jpeg_c_main_controller pub; /* public fields */
  163765. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163766. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163767. boolean suspended; /* remember if we suspended output */
  163768. J_BUF_MODE pass_mode; /* current operating mode */
  163769. /* If using just a strip buffer, this points to the entire set of buffers
  163770. * (we allocate one for each component). In the full-image case, this
  163771. * points to the currently accessible strips of the virtual arrays.
  163772. */
  163773. JSAMPARRAY buffer[MAX_COMPONENTS];
  163774. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163775. /* If using full-image storage, this array holds pointers to virtual-array
  163776. * control blocks for each component. Unused if not full-image storage.
  163777. */
  163778. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163779. #endif
  163780. } my_main_controller;
  163781. typedef my_main_controller * my_main_ptr;
  163782. /* Forward declarations */
  163783. METHODDEF(void) process_data_simple_main
  163784. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163785. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163786. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163787. METHODDEF(void) process_data_buffer_main
  163788. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163789. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163790. #endif
  163791. /*
  163792. * Initialize for a processing pass.
  163793. */
  163794. METHODDEF(void)
  163795. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163796. {
  163797. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163798. /* Do nothing in raw-data mode. */
  163799. if (cinfo->raw_data_in)
  163800. return;
  163801. main_->cur_iMCU_row = 0; /* initialize counters */
  163802. main_->rowgroup_ctr = 0;
  163803. main_->suspended = FALSE;
  163804. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163805. switch (pass_mode) {
  163806. case JBUF_PASS_THRU:
  163807. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163808. if (main_->whole_image[0] != NULL)
  163809. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163810. #endif
  163811. main_->pub.process_data = process_data_simple_main;
  163812. break;
  163813. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163814. case JBUF_SAVE_SOURCE:
  163815. case JBUF_CRANK_DEST:
  163816. case JBUF_SAVE_AND_PASS:
  163817. if (main_->whole_image[0] == NULL)
  163818. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163819. main_->pub.process_data = process_data_buffer_main;
  163820. break;
  163821. #endif
  163822. default:
  163823. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163824. break;
  163825. }
  163826. }
  163827. /*
  163828. * Process some data.
  163829. * This routine handles the simple pass-through mode,
  163830. * where we have only a strip buffer.
  163831. */
  163832. METHODDEF(void)
  163833. process_data_simple_main (j_compress_ptr cinfo,
  163834. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163835. JDIMENSION in_rows_avail)
  163836. {
  163837. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163838. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163839. /* Read input data if we haven't filled the main buffer yet */
  163840. if (main_->rowgroup_ctr < DCTSIZE)
  163841. (*cinfo->prep->pre_process_data) (cinfo,
  163842. input_buf, in_row_ctr, in_rows_avail,
  163843. main_->buffer, &main_->rowgroup_ctr,
  163844. (JDIMENSION) DCTSIZE);
  163845. /* If we don't have a full iMCU row buffered, return to application for
  163846. * more data. Note that preprocessor will always pad to fill the iMCU row
  163847. * at the bottom of the image.
  163848. */
  163849. if (main_->rowgroup_ctr != DCTSIZE)
  163850. return;
  163851. /* Send the completed row to the compressor */
  163852. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163853. /* If compressor did not consume the whole row, then we must need to
  163854. * suspend processing and return to the application. In this situation
  163855. * we pretend we didn't yet consume the last input row; otherwise, if
  163856. * it happened to be the last row of the image, the application would
  163857. * think we were done.
  163858. */
  163859. if (! main_->suspended) {
  163860. (*in_row_ctr)--;
  163861. main_->suspended = TRUE;
  163862. }
  163863. return;
  163864. }
  163865. /* We did finish the row. Undo our little suspension hack if a previous
  163866. * call suspended; then mark the main buffer empty.
  163867. */
  163868. if (main_->suspended) {
  163869. (*in_row_ctr)++;
  163870. main_->suspended = FALSE;
  163871. }
  163872. main_->rowgroup_ctr = 0;
  163873. main_->cur_iMCU_row++;
  163874. }
  163875. }
  163876. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163877. /*
  163878. * Process some data.
  163879. * This routine handles all of the modes that use a full-size buffer.
  163880. */
  163881. METHODDEF(void)
  163882. process_data_buffer_main (j_compress_ptr cinfo,
  163883. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163884. JDIMENSION in_rows_avail)
  163885. {
  163886. my_main_ptr main = (my_main_ptr) cinfo->main;
  163887. int ci;
  163888. jpeg_component_info *compptr;
  163889. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163890. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163891. /* Realign the virtual buffers if at the start of an iMCU row. */
  163892. if (main->rowgroup_ctr == 0) {
  163893. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163894. ci++, compptr++) {
  163895. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163896. ((j_common_ptr) cinfo, main->whole_image[ci],
  163897. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163898. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163899. }
  163900. /* In a read pass, pretend we just read some source data. */
  163901. if (! writing) {
  163902. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163903. main->rowgroup_ctr = DCTSIZE;
  163904. }
  163905. }
  163906. /* If a write pass, read input data until the current iMCU row is full. */
  163907. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163908. if (writing) {
  163909. (*cinfo->prep->pre_process_data) (cinfo,
  163910. input_buf, in_row_ctr, in_rows_avail,
  163911. main->buffer, &main->rowgroup_ctr,
  163912. (JDIMENSION) DCTSIZE);
  163913. /* Return to application if we need more data to fill the iMCU row. */
  163914. if (main->rowgroup_ctr < DCTSIZE)
  163915. return;
  163916. }
  163917. /* Emit data, unless this is a sink-only pass. */
  163918. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163919. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163920. /* If compressor did not consume the whole row, then we must need to
  163921. * suspend processing and return to the application. In this situation
  163922. * we pretend we didn't yet consume the last input row; otherwise, if
  163923. * it happened to be the last row of the image, the application would
  163924. * think we were done.
  163925. */
  163926. if (! main->suspended) {
  163927. (*in_row_ctr)--;
  163928. main->suspended = TRUE;
  163929. }
  163930. return;
  163931. }
  163932. /* We did finish the row. Undo our little suspension hack if a previous
  163933. * call suspended; then mark the main buffer empty.
  163934. */
  163935. if (main->suspended) {
  163936. (*in_row_ctr)++;
  163937. main->suspended = FALSE;
  163938. }
  163939. }
  163940. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163941. main->rowgroup_ctr = 0;
  163942. main->cur_iMCU_row++;
  163943. }
  163944. }
  163945. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163946. /*
  163947. * Initialize main buffer controller.
  163948. */
  163949. GLOBAL(void)
  163950. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163951. {
  163952. my_main_ptr main_;
  163953. int ci;
  163954. jpeg_component_info *compptr;
  163955. main_ = (my_main_ptr)
  163956. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163957. SIZEOF(my_main_controller));
  163958. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163959. main_->pub.start_pass = start_pass_main;
  163960. /* We don't need to create a buffer in raw-data mode. */
  163961. if (cinfo->raw_data_in)
  163962. return;
  163963. /* Create the buffer. It holds downsampled data, so each component
  163964. * may be of a different size.
  163965. */
  163966. if (need_full_buffer) {
  163967. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163968. /* Allocate a full-image virtual array for each component */
  163969. /* Note we pad the bottom to a multiple of the iMCU height */
  163970. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163971. ci++, compptr++) {
  163972. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163973. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163974. compptr->width_in_blocks * DCTSIZE,
  163975. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163976. (long) compptr->v_samp_factor) * DCTSIZE,
  163977. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163978. }
  163979. #else
  163980. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163981. #endif
  163982. } else {
  163983. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163984. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163985. #endif
  163986. /* Allocate a strip buffer for each component */
  163987. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163988. ci++, compptr++) {
  163989. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163990. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163991. compptr->width_in_blocks * DCTSIZE,
  163992. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163993. }
  163994. }
  163995. }
  163996. /*** End of inlined file: jcmainct.c ***/
  163997. /*** Start of inlined file: jcmarker.c ***/
  163998. #define JPEG_INTERNALS
  163999. /* Private state */
  164000. typedef struct {
  164001. struct jpeg_marker_writer pub; /* public fields */
  164002. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164003. } my_marker_writer;
  164004. typedef my_marker_writer * my_marker_ptr;
  164005. /*
  164006. * Basic output routines.
  164007. *
  164008. * Note that we do not support suspension while writing a marker.
  164009. * Therefore, an application using suspension must ensure that there is
  164010. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164011. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164012. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164013. * modes are not supported at all with suspension, so those two are the only
  164014. * points where markers will be written.
  164015. */
  164016. LOCAL(void)
  164017. emit_byte (j_compress_ptr cinfo, int val)
  164018. /* Emit a byte */
  164019. {
  164020. struct jpeg_destination_mgr * dest = cinfo->dest;
  164021. *(dest->next_output_byte)++ = (JOCTET) val;
  164022. if (--dest->free_in_buffer == 0) {
  164023. if (! (*dest->empty_output_buffer) (cinfo))
  164024. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164025. }
  164026. }
  164027. LOCAL(void)
  164028. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164029. /* Emit a marker code */
  164030. {
  164031. emit_byte(cinfo, 0xFF);
  164032. emit_byte(cinfo, (int) mark);
  164033. }
  164034. LOCAL(void)
  164035. emit_2bytes (j_compress_ptr cinfo, int value)
  164036. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164037. {
  164038. emit_byte(cinfo, (value >> 8) & 0xFF);
  164039. emit_byte(cinfo, value & 0xFF);
  164040. }
  164041. /*
  164042. * Routines to write specific marker types.
  164043. */
  164044. LOCAL(int)
  164045. emit_dqt (j_compress_ptr cinfo, int index)
  164046. /* Emit a DQT marker */
  164047. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164048. {
  164049. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164050. int prec;
  164051. int i;
  164052. if (qtbl == NULL)
  164053. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164054. prec = 0;
  164055. for (i = 0; i < DCTSIZE2; i++) {
  164056. if (qtbl->quantval[i] > 255)
  164057. prec = 1;
  164058. }
  164059. if (! qtbl->sent_table) {
  164060. emit_marker(cinfo, M_DQT);
  164061. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164062. emit_byte(cinfo, index + (prec<<4));
  164063. for (i = 0; i < DCTSIZE2; i++) {
  164064. /* The table entries must be emitted in zigzag order. */
  164065. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164066. if (prec)
  164067. emit_byte(cinfo, (int) (qval >> 8));
  164068. emit_byte(cinfo, (int) (qval & 0xFF));
  164069. }
  164070. qtbl->sent_table = TRUE;
  164071. }
  164072. return prec;
  164073. }
  164074. LOCAL(void)
  164075. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164076. /* Emit a DHT marker */
  164077. {
  164078. JHUFF_TBL * htbl;
  164079. int length, i;
  164080. if (is_ac) {
  164081. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164082. index += 0x10; /* output index has AC bit set */
  164083. } else {
  164084. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164085. }
  164086. if (htbl == NULL)
  164087. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164088. if (! htbl->sent_table) {
  164089. emit_marker(cinfo, M_DHT);
  164090. length = 0;
  164091. for (i = 1; i <= 16; i++)
  164092. length += htbl->bits[i];
  164093. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164094. emit_byte(cinfo, index);
  164095. for (i = 1; i <= 16; i++)
  164096. emit_byte(cinfo, htbl->bits[i]);
  164097. for (i = 0; i < length; i++)
  164098. emit_byte(cinfo, htbl->huffval[i]);
  164099. htbl->sent_table = TRUE;
  164100. }
  164101. }
  164102. LOCAL(void)
  164103. emit_dac (j_compress_ptr)
  164104. /* Emit a DAC marker */
  164105. /* Since the useful info is so small, we want to emit all the tables in */
  164106. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164107. {
  164108. #ifdef C_ARITH_CODING_SUPPORTED
  164109. char dc_in_use[NUM_ARITH_TBLS];
  164110. char ac_in_use[NUM_ARITH_TBLS];
  164111. int length, i;
  164112. jpeg_component_info *compptr;
  164113. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164114. dc_in_use[i] = ac_in_use[i] = 0;
  164115. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164116. compptr = cinfo->cur_comp_info[i];
  164117. dc_in_use[compptr->dc_tbl_no] = 1;
  164118. ac_in_use[compptr->ac_tbl_no] = 1;
  164119. }
  164120. length = 0;
  164121. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164122. length += dc_in_use[i] + ac_in_use[i];
  164123. emit_marker(cinfo, M_DAC);
  164124. emit_2bytes(cinfo, length*2 + 2);
  164125. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164126. if (dc_in_use[i]) {
  164127. emit_byte(cinfo, i);
  164128. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164129. }
  164130. if (ac_in_use[i]) {
  164131. emit_byte(cinfo, i + 0x10);
  164132. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164133. }
  164134. }
  164135. #endif /* C_ARITH_CODING_SUPPORTED */
  164136. }
  164137. LOCAL(void)
  164138. emit_dri (j_compress_ptr cinfo)
  164139. /* Emit a DRI marker */
  164140. {
  164141. emit_marker(cinfo, M_DRI);
  164142. emit_2bytes(cinfo, 4); /* fixed length */
  164143. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164144. }
  164145. LOCAL(void)
  164146. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164147. /* Emit a SOF marker */
  164148. {
  164149. int ci;
  164150. jpeg_component_info *compptr;
  164151. emit_marker(cinfo, code);
  164152. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164153. /* Make sure image isn't bigger than SOF field can handle */
  164154. if ((long) cinfo->image_height > 65535L ||
  164155. (long) cinfo->image_width > 65535L)
  164156. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164157. emit_byte(cinfo, cinfo->data_precision);
  164158. emit_2bytes(cinfo, (int) cinfo->image_height);
  164159. emit_2bytes(cinfo, (int) cinfo->image_width);
  164160. emit_byte(cinfo, cinfo->num_components);
  164161. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164162. ci++, compptr++) {
  164163. emit_byte(cinfo, compptr->component_id);
  164164. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164165. emit_byte(cinfo, compptr->quant_tbl_no);
  164166. }
  164167. }
  164168. LOCAL(void)
  164169. emit_sos (j_compress_ptr cinfo)
  164170. /* Emit a SOS marker */
  164171. {
  164172. int i, td, ta;
  164173. jpeg_component_info *compptr;
  164174. emit_marker(cinfo, M_SOS);
  164175. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164176. emit_byte(cinfo, cinfo->comps_in_scan);
  164177. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164178. compptr = cinfo->cur_comp_info[i];
  164179. emit_byte(cinfo, compptr->component_id);
  164180. td = compptr->dc_tbl_no;
  164181. ta = compptr->ac_tbl_no;
  164182. if (cinfo->progressive_mode) {
  164183. /* Progressive mode: only DC or only AC tables are used in one scan;
  164184. * furthermore, Huffman coding of DC refinement uses no table at all.
  164185. * We emit 0 for unused field(s); this is recommended by the P&M text
  164186. * but does not seem to be specified in the standard.
  164187. */
  164188. if (cinfo->Ss == 0) {
  164189. ta = 0; /* DC scan */
  164190. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164191. td = 0; /* no DC table either */
  164192. } else {
  164193. td = 0; /* AC scan */
  164194. }
  164195. }
  164196. emit_byte(cinfo, (td << 4) + ta);
  164197. }
  164198. emit_byte(cinfo, cinfo->Ss);
  164199. emit_byte(cinfo, cinfo->Se);
  164200. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164201. }
  164202. LOCAL(void)
  164203. emit_jfif_app0 (j_compress_ptr cinfo)
  164204. /* Emit a JFIF-compliant APP0 marker */
  164205. {
  164206. /*
  164207. * Length of APP0 block (2 bytes)
  164208. * Block ID (4 bytes - ASCII "JFIF")
  164209. * Zero byte (1 byte to terminate the ID string)
  164210. * Version Major, Minor (2 bytes - major first)
  164211. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164212. * Xdpu (2 bytes - dots per unit horizontal)
  164213. * Ydpu (2 bytes - dots per unit vertical)
  164214. * Thumbnail X size (1 byte)
  164215. * Thumbnail Y size (1 byte)
  164216. */
  164217. emit_marker(cinfo, M_APP0);
  164218. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164219. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164220. emit_byte(cinfo, 0x46);
  164221. emit_byte(cinfo, 0x49);
  164222. emit_byte(cinfo, 0x46);
  164223. emit_byte(cinfo, 0);
  164224. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164225. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164226. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164227. emit_2bytes(cinfo, (int) cinfo->X_density);
  164228. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164229. emit_byte(cinfo, 0); /* No thumbnail image */
  164230. emit_byte(cinfo, 0);
  164231. }
  164232. LOCAL(void)
  164233. emit_adobe_app14 (j_compress_ptr cinfo)
  164234. /* Emit an Adobe APP14 marker */
  164235. {
  164236. /*
  164237. * Length of APP14 block (2 bytes)
  164238. * Block ID (5 bytes - ASCII "Adobe")
  164239. * Version Number (2 bytes - currently 100)
  164240. * Flags0 (2 bytes - currently 0)
  164241. * Flags1 (2 bytes - currently 0)
  164242. * Color transform (1 byte)
  164243. *
  164244. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164245. * now in circulation seem to use Version = 100, so that's what we write.
  164246. *
  164247. * We write the color transform byte as 1 if the JPEG color space is
  164248. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164249. * whether the encoder performed a transformation, which is pretty useless.
  164250. */
  164251. emit_marker(cinfo, M_APP14);
  164252. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164253. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164254. emit_byte(cinfo, 0x64);
  164255. emit_byte(cinfo, 0x6F);
  164256. emit_byte(cinfo, 0x62);
  164257. emit_byte(cinfo, 0x65);
  164258. emit_2bytes(cinfo, 100); /* Version */
  164259. emit_2bytes(cinfo, 0); /* Flags0 */
  164260. emit_2bytes(cinfo, 0); /* Flags1 */
  164261. switch (cinfo->jpeg_color_space) {
  164262. case JCS_YCbCr:
  164263. emit_byte(cinfo, 1); /* Color transform = 1 */
  164264. break;
  164265. case JCS_YCCK:
  164266. emit_byte(cinfo, 2); /* Color transform = 2 */
  164267. break;
  164268. default:
  164269. emit_byte(cinfo, 0); /* Color transform = 0 */
  164270. break;
  164271. }
  164272. }
  164273. /*
  164274. * These routines allow writing an arbitrary marker with parameters.
  164275. * The only intended use is to emit COM or APPn markers after calling
  164276. * write_file_header and before calling write_frame_header.
  164277. * Other uses are not guaranteed to produce desirable results.
  164278. * Counting the parameter bytes properly is the caller's responsibility.
  164279. */
  164280. METHODDEF(void)
  164281. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164282. /* Emit an arbitrary marker header */
  164283. {
  164284. if (datalen > (unsigned int) 65533) /* safety check */
  164285. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164286. emit_marker(cinfo, (JPEG_MARKER) marker);
  164287. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164288. }
  164289. METHODDEF(void)
  164290. write_marker_byte (j_compress_ptr cinfo, int val)
  164291. /* Emit one byte of marker parameters following write_marker_header */
  164292. {
  164293. emit_byte(cinfo, val);
  164294. }
  164295. /*
  164296. * Write datastream header.
  164297. * This consists of an SOI and optional APPn markers.
  164298. * We recommend use of the JFIF marker, but not the Adobe marker,
  164299. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164300. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164301. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164302. * Note that an application can write additional header markers after
  164303. * jpeg_start_compress returns.
  164304. */
  164305. METHODDEF(void)
  164306. write_file_header (j_compress_ptr cinfo)
  164307. {
  164308. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164309. emit_marker(cinfo, M_SOI); /* first the SOI */
  164310. /* SOI is defined to reset restart interval to 0 */
  164311. marker->last_restart_interval = 0;
  164312. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164313. emit_jfif_app0(cinfo);
  164314. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164315. emit_adobe_app14(cinfo);
  164316. }
  164317. /*
  164318. * Write frame header.
  164319. * This consists of DQT and SOFn markers.
  164320. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164321. * This avoids compatibility problems with incorrect implementations that
  164322. * try to error-check the quant table numbers as soon as they see the SOF.
  164323. */
  164324. METHODDEF(void)
  164325. write_frame_header (j_compress_ptr cinfo)
  164326. {
  164327. int ci, prec;
  164328. boolean is_baseline;
  164329. jpeg_component_info *compptr;
  164330. /* Emit DQT for each quantization table.
  164331. * Note that emit_dqt() suppresses any duplicate tables.
  164332. */
  164333. prec = 0;
  164334. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164335. ci++, compptr++) {
  164336. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164337. }
  164338. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164339. /* Check for a non-baseline specification.
  164340. * Note we assume that Huffman table numbers won't be changed later.
  164341. */
  164342. if (cinfo->arith_code || cinfo->progressive_mode ||
  164343. cinfo->data_precision != 8) {
  164344. is_baseline = FALSE;
  164345. } else {
  164346. is_baseline = TRUE;
  164347. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164348. ci++, compptr++) {
  164349. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164350. is_baseline = FALSE;
  164351. }
  164352. if (prec && is_baseline) {
  164353. is_baseline = FALSE;
  164354. /* If it's baseline except for quantizer size, warn the user */
  164355. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164356. }
  164357. }
  164358. /* Emit the proper SOF marker */
  164359. if (cinfo->arith_code) {
  164360. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164361. } else {
  164362. if (cinfo->progressive_mode)
  164363. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164364. else if (is_baseline)
  164365. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164366. else
  164367. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164368. }
  164369. }
  164370. /*
  164371. * Write scan header.
  164372. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164373. * Compressed data will be written following the SOS.
  164374. */
  164375. METHODDEF(void)
  164376. write_scan_header (j_compress_ptr cinfo)
  164377. {
  164378. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164379. int i;
  164380. jpeg_component_info *compptr;
  164381. if (cinfo->arith_code) {
  164382. /* Emit arith conditioning info. We may have some duplication
  164383. * if the file has multiple scans, but it's so small it's hardly
  164384. * worth worrying about.
  164385. */
  164386. emit_dac(cinfo);
  164387. } else {
  164388. /* Emit Huffman tables.
  164389. * Note that emit_dht() suppresses any duplicate tables.
  164390. */
  164391. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164392. compptr = cinfo->cur_comp_info[i];
  164393. if (cinfo->progressive_mode) {
  164394. /* Progressive mode: only DC or only AC tables are used in one scan */
  164395. if (cinfo->Ss == 0) {
  164396. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164397. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164398. } else {
  164399. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164400. }
  164401. } else {
  164402. /* Sequential mode: need both DC and AC tables */
  164403. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164404. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164405. }
  164406. }
  164407. }
  164408. /* Emit DRI if required --- note that DRI value could change for each scan.
  164409. * We avoid wasting space with unnecessary DRIs, however.
  164410. */
  164411. if (cinfo->restart_interval != marker->last_restart_interval) {
  164412. emit_dri(cinfo);
  164413. marker->last_restart_interval = cinfo->restart_interval;
  164414. }
  164415. emit_sos(cinfo);
  164416. }
  164417. /*
  164418. * Write datastream trailer.
  164419. */
  164420. METHODDEF(void)
  164421. write_file_trailer (j_compress_ptr cinfo)
  164422. {
  164423. emit_marker(cinfo, M_EOI);
  164424. }
  164425. /*
  164426. * Write an abbreviated table-specification datastream.
  164427. * This consists of SOI, DQT and DHT tables, and EOI.
  164428. * Any table that is defined and not marked sent_table = TRUE will be
  164429. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164430. */
  164431. METHODDEF(void)
  164432. write_tables_only (j_compress_ptr cinfo)
  164433. {
  164434. int i;
  164435. emit_marker(cinfo, M_SOI);
  164436. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164437. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164438. (void) emit_dqt(cinfo, i);
  164439. }
  164440. if (! cinfo->arith_code) {
  164441. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164442. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164443. emit_dht(cinfo, i, FALSE);
  164444. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164445. emit_dht(cinfo, i, TRUE);
  164446. }
  164447. }
  164448. emit_marker(cinfo, M_EOI);
  164449. }
  164450. /*
  164451. * Initialize the marker writer module.
  164452. */
  164453. GLOBAL(void)
  164454. jinit_marker_writer (j_compress_ptr cinfo)
  164455. {
  164456. my_marker_ptr marker;
  164457. /* Create the subobject */
  164458. marker = (my_marker_ptr)
  164459. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164460. SIZEOF(my_marker_writer));
  164461. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164462. /* Initialize method pointers */
  164463. marker->pub.write_file_header = write_file_header;
  164464. marker->pub.write_frame_header = write_frame_header;
  164465. marker->pub.write_scan_header = write_scan_header;
  164466. marker->pub.write_file_trailer = write_file_trailer;
  164467. marker->pub.write_tables_only = write_tables_only;
  164468. marker->pub.write_marker_header = write_marker_header;
  164469. marker->pub.write_marker_byte = write_marker_byte;
  164470. /* Initialize private state */
  164471. marker->last_restart_interval = 0;
  164472. }
  164473. /*** End of inlined file: jcmarker.c ***/
  164474. /*** Start of inlined file: jcmaster.c ***/
  164475. #define JPEG_INTERNALS
  164476. /* Private state */
  164477. typedef enum {
  164478. main_pass, /* input data, also do first output step */
  164479. huff_opt_pass, /* Huffman code optimization pass */
  164480. output_pass /* data output pass */
  164481. } c_pass_type;
  164482. typedef struct {
  164483. struct jpeg_comp_master pub; /* public fields */
  164484. c_pass_type pass_type; /* the type of the current pass */
  164485. int pass_number; /* # of passes completed */
  164486. int total_passes; /* total # of passes needed */
  164487. int scan_number; /* current index in scan_info[] */
  164488. } my_comp_master;
  164489. typedef my_comp_master * my_master_ptr;
  164490. /*
  164491. * Support routines that do various essential calculations.
  164492. */
  164493. LOCAL(void)
  164494. initial_setup (j_compress_ptr cinfo)
  164495. /* Do computations that are needed before master selection phase */
  164496. {
  164497. int ci;
  164498. jpeg_component_info *compptr;
  164499. long samplesperrow;
  164500. JDIMENSION jd_samplesperrow;
  164501. /* Sanity check on image dimensions */
  164502. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164503. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164504. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164505. /* Make sure image isn't bigger than I can handle */
  164506. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164507. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164508. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164509. /* Width of an input scanline must be representable as JDIMENSION. */
  164510. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164511. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164512. if ((long) jd_samplesperrow != samplesperrow)
  164513. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164514. /* For now, precision must match compiled-in value... */
  164515. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164516. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164517. /* Check that number of components won't exceed internal array sizes */
  164518. if (cinfo->num_components > MAX_COMPONENTS)
  164519. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164520. MAX_COMPONENTS);
  164521. /* Compute maximum sampling factors; check factor validity */
  164522. cinfo->max_h_samp_factor = 1;
  164523. cinfo->max_v_samp_factor = 1;
  164524. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164525. ci++, compptr++) {
  164526. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164527. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164528. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164529. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164530. compptr->h_samp_factor);
  164531. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164532. compptr->v_samp_factor);
  164533. }
  164534. /* Compute dimensions of components */
  164535. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164536. ci++, compptr++) {
  164537. /* Fill in the correct component_index value; don't rely on application */
  164538. compptr->component_index = ci;
  164539. /* For compression, we never do DCT scaling. */
  164540. compptr->DCT_scaled_size = DCTSIZE;
  164541. /* Size in DCT blocks */
  164542. compptr->width_in_blocks = (JDIMENSION)
  164543. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164544. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164545. compptr->height_in_blocks = (JDIMENSION)
  164546. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164547. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164548. /* Size in samples */
  164549. compptr->downsampled_width = (JDIMENSION)
  164550. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164551. (long) cinfo->max_h_samp_factor);
  164552. compptr->downsampled_height = (JDIMENSION)
  164553. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164554. (long) cinfo->max_v_samp_factor);
  164555. /* Mark component needed (this flag isn't actually used for compression) */
  164556. compptr->component_needed = TRUE;
  164557. }
  164558. /* Compute number of fully interleaved MCU rows (number of times that
  164559. * main controller will call coefficient controller).
  164560. */
  164561. cinfo->total_iMCU_rows = (JDIMENSION)
  164562. jdiv_round_up((long) cinfo->image_height,
  164563. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164564. }
  164565. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164566. LOCAL(void)
  164567. validate_script (j_compress_ptr cinfo)
  164568. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164569. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164570. */
  164571. {
  164572. const jpeg_scan_info * scanptr;
  164573. int scanno, ncomps, ci, coefi, thisi;
  164574. int Ss, Se, Ah, Al;
  164575. boolean component_sent[MAX_COMPONENTS];
  164576. #ifdef C_PROGRESSIVE_SUPPORTED
  164577. int * last_bitpos_ptr;
  164578. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164579. /* -1 until that coefficient has been seen; then last Al for it */
  164580. #endif
  164581. if (cinfo->num_scans <= 0)
  164582. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164583. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164584. * for progressive JPEG, no scan can have this.
  164585. */
  164586. scanptr = cinfo->scan_info;
  164587. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164588. #ifdef C_PROGRESSIVE_SUPPORTED
  164589. cinfo->progressive_mode = TRUE;
  164590. last_bitpos_ptr = & last_bitpos[0][0];
  164591. for (ci = 0; ci < cinfo->num_components; ci++)
  164592. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164593. *last_bitpos_ptr++ = -1;
  164594. #else
  164595. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164596. #endif
  164597. } else {
  164598. cinfo->progressive_mode = FALSE;
  164599. for (ci = 0; ci < cinfo->num_components; ci++)
  164600. component_sent[ci] = FALSE;
  164601. }
  164602. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164603. /* Validate component indexes */
  164604. ncomps = scanptr->comps_in_scan;
  164605. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164606. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164607. for (ci = 0; ci < ncomps; ci++) {
  164608. thisi = scanptr->component_index[ci];
  164609. if (thisi < 0 || thisi >= cinfo->num_components)
  164610. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164611. /* Components must appear in SOF order within each scan */
  164612. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164613. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164614. }
  164615. /* Validate progression parameters */
  164616. Ss = scanptr->Ss;
  164617. Se = scanptr->Se;
  164618. Ah = scanptr->Ah;
  164619. Al = scanptr->Al;
  164620. if (cinfo->progressive_mode) {
  164621. #ifdef C_PROGRESSIVE_SUPPORTED
  164622. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164623. * seems wrong: the upper bound ought to depend on data precision.
  164624. * Perhaps they really meant 0..N+1 for N-bit precision.
  164625. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164626. * out-of-range reconstructed DC values during the first DC scan,
  164627. * which might cause problems for some decoders.
  164628. */
  164629. #if BITS_IN_JSAMPLE == 8
  164630. #define MAX_AH_AL 10
  164631. #else
  164632. #define MAX_AH_AL 13
  164633. #endif
  164634. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164635. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164636. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164637. if (Ss == 0) {
  164638. if (Se != 0) /* DC and AC together not OK */
  164639. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164640. } else {
  164641. if (ncomps != 1) /* AC scans must be for only one component */
  164642. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164643. }
  164644. for (ci = 0; ci < ncomps; ci++) {
  164645. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164646. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164647. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164648. for (coefi = Ss; coefi <= Se; coefi++) {
  164649. if (last_bitpos_ptr[coefi] < 0) {
  164650. /* first scan of this coefficient */
  164651. if (Ah != 0)
  164652. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164653. } else {
  164654. /* not first scan */
  164655. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164656. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164657. }
  164658. last_bitpos_ptr[coefi] = Al;
  164659. }
  164660. }
  164661. #endif
  164662. } else {
  164663. /* For sequential JPEG, all progression parameters must be these: */
  164664. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164665. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164666. /* Make sure components are not sent twice */
  164667. for (ci = 0; ci < ncomps; ci++) {
  164668. thisi = scanptr->component_index[ci];
  164669. if (component_sent[thisi])
  164670. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164671. component_sent[thisi] = TRUE;
  164672. }
  164673. }
  164674. }
  164675. /* Now verify that everything got sent. */
  164676. if (cinfo->progressive_mode) {
  164677. #ifdef C_PROGRESSIVE_SUPPORTED
  164678. /* For progressive mode, we only check that at least some DC data
  164679. * got sent for each component; the spec does not require that all bits
  164680. * of all coefficients be transmitted. Would it be wiser to enforce
  164681. * transmission of all coefficient bits??
  164682. */
  164683. for (ci = 0; ci < cinfo->num_components; ci++) {
  164684. if (last_bitpos[ci][0] < 0)
  164685. ERREXIT(cinfo, JERR_MISSING_DATA);
  164686. }
  164687. #endif
  164688. } else {
  164689. for (ci = 0; ci < cinfo->num_components; ci++) {
  164690. if (! component_sent[ci])
  164691. ERREXIT(cinfo, JERR_MISSING_DATA);
  164692. }
  164693. }
  164694. }
  164695. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164696. LOCAL(void)
  164697. select_scan_parameters (j_compress_ptr cinfo)
  164698. /* Set up the scan parameters for the current scan */
  164699. {
  164700. int ci;
  164701. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164702. if (cinfo->scan_info != NULL) {
  164703. /* Prepare for current scan --- the script is already validated */
  164704. my_master_ptr master = (my_master_ptr) cinfo->master;
  164705. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164706. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164707. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164708. cinfo->cur_comp_info[ci] =
  164709. &cinfo->comp_info[scanptr->component_index[ci]];
  164710. }
  164711. cinfo->Ss = scanptr->Ss;
  164712. cinfo->Se = scanptr->Se;
  164713. cinfo->Ah = scanptr->Ah;
  164714. cinfo->Al = scanptr->Al;
  164715. }
  164716. else
  164717. #endif
  164718. {
  164719. /* Prepare for single sequential-JPEG scan containing all components */
  164720. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164721. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164722. MAX_COMPS_IN_SCAN);
  164723. cinfo->comps_in_scan = cinfo->num_components;
  164724. for (ci = 0; ci < cinfo->num_components; ci++) {
  164725. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164726. }
  164727. cinfo->Ss = 0;
  164728. cinfo->Se = DCTSIZE2-1;
  164729. cinfo->Ah = 0;
  164730. cinfo->Al = 0;
  164731. }
  164732. }
  164733. LOCAL(void)
  164734. per_scan_setup (j_compress_ptr cinfo)
  164735. /* Do computations that are needed before processing a JPEG scan */
  164736. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164737. {
  164738. int ci, mcublks, tmp;
  164739. jpeg_component_info *compptr;
  164740. if (cinfo->comps_in_scan == 1) {
  164741. /* Noninterleaved (single-component) scan */
  164742. compptr = cinfo->cur_comp_info[0];
  164743. /* Overall image size in MCUs */
  164744. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164745. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164746. /* For noninterleaved scan, always one block per MCU */
  164747. compptr->MCU_width = 1;
  164748. compptr->MCU_height = 1;
  164749. compptr->MCU_blocks = 1;
  164750. compptr->MCU_sample_width = DCTSIZE;
  164751. compptr->last_col_width = 1;
  164752. /* For noninterleaved scans, it is convenient to define last_row_height
  164753. * as the number of block rows present in the last iMCU row.
  164754. */
  164755. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164756. if (tmp == 0) tmp = compptr->v_samp_factor;
  164757. compptr->last_row_height = tmp;
  164758. /* Prepare array describing MCU composition */
  164759. cinfo->blocks_in_MCU = 1;
  164760. cinfo->MCU_membership[0] = 0;
  164761. } else {
  164762. /* Interleaved (multi-component) scan */
  164763. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164764. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164765. MAX_COMPS_IN_SCAN);
  164766. /* Overall image size in MCUs */
  164767. cinfo->MCUs_per_row = (JDIMENSION)
  164768. jdiv_round_up((long) cinfo->image_width,
  164769. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164770. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164771. jdiv_round_up((long) cinfo->image_height,
  164772. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164773. cinfo->blocks_in_MCU = 0;
  164774. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164775. compptr = cinfo->cur_comp_info[ci];
  164776. /* Sampling factors give # of blocks of component in each MCU */
  164777. compptr->MCU_width = compptr->h_samp_factor;
  164778. compptr->MCU_height = compptr->v_samp_factor;
  164779. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164780. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164781. /* Figure number of non-dummy blocks in last MCU column & row */
  164782. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164783. if (tmp == 0) tmp = compptr->MCU_width;
  164784. compptr->last_col_width = tmp;
  164785. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164786. if (tmp == 0) tmp = compptr->MCU_height;
  164787. compptr->last_row_height = tmp;
  164788. /* Prepare array describing MCU composition */
  164789. mcublks = compptr->MCU_blocks;
  164790. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164791. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164792. while (mcublks-- > 0) {
  164793. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164794. }
  164795. }
  164796. }
  164797. /* Convert restart specified in rows to actual MCU count. */
  164798. /* Note that count must fit in 16 bits, so we provide limiting. */
  164799. if (cinfo->restart_in_rows > 0) {
  164800. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164801. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164802. }
  164803. }
  164804. /*
  164805. * Per-pass setup.
  164806. * This is called at the beginning of each pass. We determine which modules
  164807. * will be active during this pass and give them appropriate start_pass calls.
  164808. * We also set is_last_pass to indicate whether any more passes will be
  164809. * required.
  164810. */
  164811. METHODDEF(void)
  164812. prepare_for_pass (j_compress_ptr cinfo)
  164813. {
  164814. my_master_ptr master = (my_master_ptr) cinfo->master;
  164815. switch (master->pass_type) {
  164816. case main_pass:
  164817. /* Initial pass: will collect input data, and do either Huffman
  164818. * optimization or data output for the first scan.
  164819. */
  164820. select_scan_parameters(cinfo);
  164821. per_scan_setup(cinfo);
  164822. if (! cinfo->raw_data_in) {
  164823. (*cinfo->cconvert->start_pass) (cinfo);
  164824. (*cinfo->downsample->start_pass) (cinfo);
  164825. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164826. }
  164827. (*cinfo->fdct->start_pass) (cinfo);
  164828. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164829. (*cinfo->coef->start_pass) (cinfo,
  164830. (master->total_passes > 1 ?
  164831. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164832. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164833. if (cinfo->optimize_coding) {
  164834. /* No immediate data output; postpone writing frame/scan headers */
  164835. master->pub.call_pass_startup = FALSE;
  164836. } else {
  164837. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164838. master->pub.call_pass_startup = TRUE;
  164839. }
  164840. break;
  164841. #ifdef ENTROPY_OPT_SUPPORTED
  164842. case huff_opt_pass:
  164843. /* Do Huffman optimization for a scan after the first one. */
  164844. select_scan_parameters(cinfo);
  164845. per_scan_setup(cinfo);
  164846. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164847. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164848. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164849. master->pub.call_pass_startup = FALSE;
  164850. break;
  164851. }
  164852. /* Special case: Huffman DC refinement scans need no Huffman table
  164853. * and therefore we can skip the optimization pass for them.
  164854. */
  164855. master->pass_type = output_pass;
  164856. master->pass_number++;
  164857. /*FALLTHROUGH*/
  164858. #endif
  164859. case output_pass:
  164860. /* Do a data-output pass. */
  164861. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164862. if (! cinfo->optimize_coding) {
  164863. select_scan_parameters(cinfo);
  164864. per_scan_setup(cinfo);
  164865. }
  164866. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164867. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164868. /* We emit frame/scan headers now */
  164869. if (master->scan_number == 0)
  164870. (*cinfo->marker->write_frame_header) (cinfo);
  164871. (*cinfo->marker->write_scan_header) (cinfo);
  164872. master->pub.call_pass_startup = FALSE;
  164873. break;
  164874. default:
  164875. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164876. }
  164877. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164878. /* Set up progress monitor's pass info if present */
  164879. if (cinfo->progress != NULL) {
  164880. cinfo->progress->completed_passes = master->pass_number;
  164881. cinfo->progress->total_passes = master->total_passes;
  164882. }
  164883. }
  164884. /*
  164885. * Special start-of-pass hook.
  164886. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164887. * In single-pass processing, we need this hook because we don't want to
  164888. * write frame/scan headers during jpeg_start_compress; we want to let the
  164889. * application write COM markers etc. between jpeg_start_compress and the
  164890. * jpeg_write_scanlines loop.
  164891. * In multi-pass processing, this routine is not used.
  164892. */
  164893. METHODDEF(void)
  164894. pass_startup (j_compress_ptr cinfo)
  164895. {
  164896. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164897. (*cinfo->marker->write_frame_header) (cinfo);
  164898. (*cinfo->marker->write_scan_header) (cinfo);
  164899. }
  164900. /*
  164901. * Finish up at end of pass.
  164902. */
  164903. METHODDEF(void)
  164904. finish_pass_master (j_compress_ptr cinfo)
  164905. {
  164906. my_master_ptr master = (my_master_ptr) cinfo->master;
  164907. /* The entropy coder always needs an end-of-pass call,
  164908. * either to analyze statistics or to flush its output buffer.
  164909. */
  164910. (*cinfo->entropy->finish_pass) (cinfo);
  164911. /* Update state for next pass */
  164912. switch (master->pass_type) {
  164913. case main_pass:
  164914. /* next pass is either output of scan 0 (after optimization)
  164915. * or output of scan 1 (if no optimization).
  164916. */
  164917. master->pass_type = output_pass;
  164918. if (! cinfo->optimize_coding)
  164919. master->scan_number++;
  164920. break;
  164921. case huff_opt_pass:
  164922. /* next pass is always output of current scan */
  164923. master->pass_type = output_pass;
  164924. break;
  164925. case output_pass:
  164926. /* next pass is either optimization or output of next scan */
  164927. if (cinfo->optimize_coding)
  164928. master->pass_type = huff_opt_pass;
  164929. master->scan_number++;
  164930. break;
  164931. }
  164932. master->pass_number++;
  164933. }
  164934. /*
  164935. * Initialize master compression control.
  164936. */
  164937. GLOBAL(void)
  164938. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164939. {
  164940. my_master_ptr master;
  164941. master = (my_master_ptr)
  164942. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164943. SIZEOF(my_comp_master));
  164944. cinfo->master = (struct jpeg_comp_master *) master;
  164945. master->pub.prepare_for_pass = prepare_for_pass;
  164946. master->pub.pass_startup = pass_startup;
  164947. master->pub.finish_pass = finish_pass_master;
  164948. master->pub.is_last_pass = FALSE;
  164949. /* Validate parameters, determine derived values */
  164950. initial_setup(cinfo);
  164951. if (cinfo->scan_info != NULL) {
  164952. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164953. validate_script(cinfo);
  164954. #else
  164955. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164956. #endif
  164957. } else {
  164958. cinfo->progressive_mode = FALSE;
  164959. cinfo->num_scans = 1;
  164960. }
  164961. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164962. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164963. /* Initialize my private state */
  164964. if (transcode_only) {
  164965. /* no main pass in transcoding */
  164966. if (cinfo->optimize_coding)
  164967. master->pass_type = huff_opt_pass;
  164968. else
  164969. master->pass_type = output_pass;
  164970. } else {
  164971. /* for normal compression, first pass is always this type: */
  164972. master->pass_type = main_pass;
  164973. }
  164974. master->scan_number = 0;
  164975. master->pass_number = 0;
  164976. if (cinfo->optimize_coding)
  164977. master->total_passes = cinfo->num_scans * 2;
  164978. else
  164979. master->total_passes = cinfo->num_scans;
  164980. }
  164981. /*** End of inlined file: jcmaster.c ***/
  164982. /*** Start of inlined file: jcomapi.c ***/
  164983. #define JPEG_INTERNALS
  164984. /*
  164985. * Abort processing of a JPEG compression or decompression operation,
  164986. * but don't destroy the object itself.
  164987. *
  164988. * For this, we merely clean up all the nonpermanent memory pools.
  164989. * Note that temp files (virtual arrays) are not allowed to belong to
  164990. * the permanent pool, so we will be able to close all temp files here.
  164991. * Closing a data source or destination, if necessary, is the application's
  164992. * responsibility.
  164993. */
  164994. GLOBAL(void)
  164995. jpeg_abort (j_common_ptr cinfo)
  164996. {
  164997. int pool;
  164998. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164999. if (cinfo->mem == NULL)
  165000. return;
  165001. /* Releasing pools in reverse order might help avoid fragmentation
  165002. * with some (brain-damaged) malloc libraries.
  165003. */
  165004. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165005. (*cinfo->mem->free_pool) (cinfo, pool);
  165006. }
  165007. /* Reset overall state for possible reuse of object */
  165008. if (cinfo->is_decompressor) {
  165009. cinfo->global_state = DSTATE_START;
  165010. /* Try to keep application from accessing now-deleted marker list.
  165011. * A bit kludgy to do it here, but this is the most central place.
  165012. */
  165013. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165014. } else {
  165015. cinfo->global_state = CSTATE_START;
  165016. }
  165017. }
  165018. /*
  165019. * Destruction of a JPEG object.
  165020. *
  165021. * Everything gets deallocated except the master jpeg_compress_struct itself
  165022. * and the error manager struct. Both of these are supplied by the application
  165023. * and must be freed, if necessary, by the application. (Often they are on
  165024. * the stack and so don't need to be freed anyway.)
  165025. * Closing a data source or destination, if necessary, is the application's
  165026. * responsibility.
  165027. */
  165028. GLOBAL(void)
  165029. jpeg_destroy (j_common_ptr cinfo)
  165030. {
  165031. /* We need only tell the memory manager to release everything. */
  165032. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165033. if (cinfo->mem != NULL)
  165034. (*cinfo->mem->self_destruct) (cinfo);
  165035. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165036. cinfo->global_state = 0; /* mark it destroyed */
  165037. }
  165038. /*
  165039. * Convenience routines for allocating quantization and Huffman tables.
  165040. * (Would jutils.c be a more reasonable place to put these?)
  165041. */
  165042. GLOBAL(JQUANT_TBL *)
  165043. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165044. {
  165045. JQUANT_TBL *tbl;
  165046. tbl = (JQUANT_TBL *)
  165047. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165048. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165049. return tbl;
  165050. }
  165051. GLOBAL(JHUFF_TBL *)
  165052. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165053. {
  165054. JHUFF_TBL *tbl;
  165055. tbl = (JHUFF_TBL *)
  165056. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165057. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165058. return tbl;
  165059. }
  165060. /*** End of inlined file: jcomapi.c ***/
  165061. /*** Start of inlined file: jcparam.c ***/
  165062. #define JPEG_INTERNALS
  165063. /*
  165064. * Quantization table setup routines
  165065. */
  165066. GLOBAL(void)
  165067. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165068. const unsigned int *basic_table,
  165069. int scale_factor, boolean force_baseline)
  165070. /* Define a quantization table equal to the basic_table times
  165071. * a scale factor (given as a percentage).
  165072. * If force_baseline is TRUE, the computed quantization table entries
  165073. * are limited to 1..255 for JPEG baseline compatibility.
  165074. */
  165075. {
  165076. JQUANT_TBL ** qtblptr;
  165077. int i;
  165078. long temp;
  165079. /* Safety check to ensure start_compress not called yet. */
  165080. if (cinfo->global_state != CSTATE_START)
  165081. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165082. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165083. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165084. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165085. if (*qtblptr == NULL)
  165086. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165087. for (i = 0; i < DCTSIZE2; i++) {
  165088. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165089. /* limit the values to the valid range */
  165090. if (temp <= 0L) temp = 1L;
  165091. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165092. if (force_baseline && temp > 255L)
  165093. temp = 255L; /* limit to baseline range if requested */
  165094. (*qtblptr)->quantval[i] = (UINT16) temp;
  165095. }
  165096. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165097. (*qtblptr)->sent_table = FALSE;
  165098. }
  165099. GLOBAL(void)
  165100. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165101. boolean force_baseline)
  165102. /* Set or change the 'quality' (quantization) setting, using default tables
  165103. * and a straight percentage-scaling quality scale. In most cases it's better
  165104. * to use jpeg_set_quality (below); this entry point is provided for
  165105. * applications that insist on a linear percentage scaling.
  165106. */
  165107. {
  165108. /* These are the sample quantization tables given in JPEG spec section K.1.
  165109. * The spec says that the values given produce "good" quality, and
  165110. * when divided by 2, "very good" quality.
  165111. */
  165112. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165113. 16, 11, 10, 16, 24, 40, 51, 61,
  165114. 12, 12, 14, 19, 26, 58, 60, 55,
  165115. 14, 13, 16, 24, 40, 57, 69, 56,
  165116. 14, 17, 22, 29, 51, 87, 80, 62,
  165117. 18, 22, 37, 56, 68, 109, 103, 77,
  165118. 24, 35, 55, 64, 81, 104, 113, 92,
  165119. 49, 64, 78, 87, 103, 121, 120, 101,
  165120. 72, 92, 95, 98, 112, 100, 103, 99
  165121. };
  165122. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165123. 17, 18, 24, 47, 99, 99, 99, 99,
  165124. 18, 21, 26, 66, 99, 99, 99, 99,
  165125. 24, 26, 56, 99, 99, 99, 99, 99,
  165126. 47, 66, 99, 99, 99, 99, 99, 99,
  165127. 99, 99, 99, 99, 99, 99, 99, 99,
  165128. 99, 99, 99, 99, 99, 99, 99, 99,
  165129. 99, 99, 99, 99, 99, 99, 99, 99,
  165130. 99, 99, 99, 99, 99, 99, 99, 99
  165131. };
  165132. /* Set up two quantization tables using the specified scaling */
  165133. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165134. scale_factor, force_baseline);
  165135. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165136. scale_factor, force_baseline);
  165137. }
  165138. GLOBAL(int)
  165139. jpeg_quality_scaling (int quality)
  165140. /* Convert a user-specified quality rating to a percentage scaling factor
  165141. * for an underlying quantization table, using our recommended scaling curve.
  165142. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165143. */
  165144. {
  165145. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165146. if (quality <= 0) quality = 1;
  165147. if (quality > 100) quality = 100;
  165148. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165149. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165150. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165151. * to make all the table entries 1 (hence, minimum quantization loss).
  165152. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165153. */
  165154. if (quality < 50)
  165155. quality = 5000 / quality;
  165156. else
  165157. quality = 200 - quality*2;
  165158. return quality;
  165159. }
  165160. GLOBAL(void)
  165161. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165162. /* Set or change the 'quality' (quantization) setting, using default tables.
  165163. * This is the standard quality-adjusting entry point for typical user
  165164. * interfaces; only those who want detailed control over quantization tables
  165165. * would use the preceding three routines directly.
  165166. */
  165167. {
  165168. /* Convert user 0-100 rating to percentage scaling */
  165169. quality = jpeg_quality_scaling(quality);
  165170. /* Set up standard quality tables */
  165171. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165172. }
  165173. /*
  165174. * Huffman table setup routines
  165175. */
  165176. LOCAL(void)
  165177. add_huff_table (j_compress_ptr cinfo,
  165178. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165179. /* Define a Huffman table */
  165180. {
  165181. int nsymbols, len;
  165182. if (*htblptr == NULL)
  165183. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165184. /* Copy the number-of-symbols-of-each-code-length counts */
  165185. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165186. /* Validate the counts. We do this here mainly so we can copy the right
  165187. * number of symbols from the val[] array, without risking marching off
  165188. * the end of memory. jchuff.c will do a more thorough test later.
  165189. */
  165190. nsymbols = 0;
  165191. for (len = 1; len <= 16; len++)
  165192. nsymbols += bits[len];
  165193. if (nsymbols < 1 || nsymbols > 256)
  165194. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165195. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165196. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165197. (*htblptr)->sent_table = FALSE;
  165198. }
  165199. LOCAL(void)
  165200. std_huff_tables (j_compress_ptr cinfo)
  165201. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165202. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165203. {
  165204. static const UINT8 bits_dc_luminance[17] =
  165205. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165206. static const UINT8 val_dc_luminance[] =
  165207. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165208. static const UINT8 bits_dc_chrominance[17] =
  165209. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165210. static const UINT8 val_dc_chrominance[] =
  165211. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165212. static const UINT8 bits_ac_luminance[17] =
  165213. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165214. static const UINT8 val_ac_luminance[] =
  165215. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165216. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165217. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165218. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165219. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165220. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165221. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165222. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165223. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165224. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165225. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165226. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165227. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165228. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165229. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165230. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165231. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165232. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165233. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165234. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165235. 0xf9, 0xfa };
  165236. static const UINT8 bits_ac_chrominance[17] =
  165237. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165238. static const UINT8 val_ac_chrominance[] =
  165239. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165240. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165241. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165242. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165243. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165244. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165245. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165246. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165247. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165248. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165249. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165250. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165251. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165252. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165253. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165254. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165255. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165256. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165257. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165258. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165259. 0xf9, 0xfa };
  165260. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165261. bits_dc_luminance, val_dc_luminance);
  165262. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165263. bits_ac_luminance, val_ac_luminance);
  165264. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165265. bits_dc_chrominance, val_dc_chrominance);
  165266. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165267. bits_ac_chrominance, val_ac_chrominance);
  165268. }
  165269. /*
  165270. * Default parameter setup for compression.
  165271. *
  165272. * Applications that don't choose to use this routine must do their
  165273. * own setup of all these parameters. Alternately, you can call this
  165274. * to establish defaults and then alter parameters selectively. This
  165275. * is the recommended approach since, if we add any new parameters,
  165276. * your code will still work (they'll be set to reasonable defaults).
  165277. */
  165278. GLOBAL(void)
  165279. jpeg_set_defaults (j_compress_ptr cinfo)
  165280. {
  165281. int i;
  165282. /* Safety check to ensure start_compress not called yet. */
  165283. if (cinfo->global_state != CSTATE_START)
  165284. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165285. /* Allocate comp_info array large enough for maximum component count.
  165286. * Array is made permanent in case application wants to compress
  165287. * multiple images at same param settings.
  165288. */
  165289. if (cinfo->comp_info == NULL)
  165290. cinfo->comp_info = (jpeg_component_info *)
  165291. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165292. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165293. /* Initialize everything not dependent on the color space */
  165294. cinfo->data_precision = BITS_IN_JSAMPLE;
  165295. /* Set up two quantization tables using default quality of 75 */
  165296. jpeg_set_quality(cinfo, 75, TRUE);
  165297. /* Set up two Huffman tables */
  165298. std_huff_tables(cinfo);
  165299. /* Initialize default arithmetic coding conditioning */
  165300. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165301. cinfo->arith_dc_L[i] = 0;
  165302. cinfo->arith_dc_U[i] = 1;
  165303. cinfo->arith_ac_K[i] = 5;
  165304. }
  165305. /* Default is no multiple-scan output */
  165306. cinfo->scan_info = NULL;
  165307. cinfo->num_scans = 0;
  165308. /* Expect normal source image, not raw downsampled data */
  165309. cinfo->raw_data_in = FALSE;
  165310. /* Use Huffman coding, not arithmetic coding, by default */
  165311. cinfo->arith_code = FALSE;
  165312. /* By default, don't do extra passes to optimize entropy coding */
  165313. cinfo->optimize_coding = FALSE;
  165314. /* The standard Huffman tables are only valid for 8-bit data precision.
  165315. * If the precision is higher, force optimization on so that usable
  165316. * tables will be computed. This test can be removed if default tables
  165317. * are supplied that are valid for the desired precision.
  165318. */
  165319. if (cinfo->data_precision > 8)
  165320. cinfo->optimize_coding = TRUE;
  165321. /* By default, use the simpler non-cosited sampling alignment */
  165322. cinfo->CCIR601_sampling = FALSE;
  165323. /* No input smoothing */
  165324. cinfo->smoothing_factor = 0;
  165325. /* DCT algorithm preference */
  165326. cinfo->dct_method = JDCT_DEFAULT;
  165327. /* No restart markers */
  165328. cinfo->restart_interval = 0;
  165329. cinfo->restart_in_rows = 0;
  165330. /* Fill in default JFIF marker parameters. Note that whether the marker
  165331. * will actually be written is determined by jpeg_set_colorspace.
  165332. *
  165333. * By default, the library emits JFIF version code 1.01.
  165334. * An application that wants to emit JFIF 1.02 extension markers should set
  165335. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165336. * to 1.02, but there may still be some decoders in use that will complain
  165337. * about that; saying 1.01 should minimize compatibility problems.
  165338. */
  165339. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165340. cinfo->JFIF_minor_version = 1;
  165341. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165342. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165343. cinfo->Y_density = 1;
  165344. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165345. jpeg_default_colorspace(cinfo);
  165346. }
  165347. /*
  165348. * Select an appropriate JPEG colorspace for in_color_space.
  165349. */
  165350. GLOBAL(void)
  165351. jpeg_default_colorspace (j_compress_ptr cinfo)
  165352. {
  165353. switch (cinfo->in_color_space) {
  165354. case JCS_GRAYSCALE:
  165355. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165356. break;
  165357. case JCS_RGB:
  165358. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165359. break;
  165360. case JCS_YCbCr:
  165361. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165362. break;
  165363. case JCS_CMYK:
  165364. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165365. break;
  165366. case JCS_YCCK:
  165367. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165368. break;
  165369. case JCS_UNKNOWN:
  165370. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165371. break;
  165372. default:
  165373. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165374. }
  165375. }
  165376. /*
  165377. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165378. */
  165379. GLOBAL(void)
  165380. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165381. {
  165382. jpeg_component_info * compptr;
  165383. int ci;
  165384. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165385. (compptr = &cinfo->comp_info[index], \
  165386. compptr->component_id = (id), \
  165387. compptr->h_samp_factor = (hsamp), \
  165388. compptr->v_samp_factor = (vsamp), \
  165389. compptr->quant_tbl_no = (quant), \
  165390. compptr->dc_tbl_no = (dctbl), \
  165391. compptr->ac_tbl_no = (actbl) )
  165392. /* Safety check to ensure start_compress not called yet. */
  165393. if (cinfo->global_state != CSTATE_START)
  165394. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165395. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165396. * tables 1 for chrominance components.
  165397. */
  165398. cinfo->jpeg_color_space = colorspace;
  165399. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165400. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165401. switch (colorspace) {
  165402. case JCS_GRAYSCALE:
  165403. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165404. cinfo->num_components = 1;
  165405. /* JFIF specifies component ID 1 */
  165406. SET_COMP(0, 1, 1,1, 0, 0,0);
  165407. break;
  165408. case JCS_RGB:
  165409. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165410. cinfo->num_components = 3;
  165411. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165412. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165413. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165414. break;
  165415. case JCS_YCbCr:
  165416. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165417. cinfo->num_components = 3;
  165418. /* JFIF specifies component IDs 1,2,3 */
  165419. /* We default to 2x2 subsamples of chrominance */
  165420. SET_COMP(0, 1, 2,2, 0, 0,0);
  165421. SET_COMP(1, 2, 1,1, 1, 1,1);
  165422. SET_COMP(2, 3, 1,1, 1, 1,1);
  165423. break;
  165424. case JCS_CMYK:
  165425. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165426. cinfo->num_components = 4;
  165427. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165428. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165429. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165430. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165431. break;
  165432. case JCS_YCCK:
  165433. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165434. cinfo->num_components = 4;
  165435. SET_COMP(0, 1, 2,2, 0, 0,0);
  165436. SET_COMP(1, 2, 1,1, 1, 1,1);
  165437. SET_COMP(2, 3, 1,1, 1, 1,1);
  165438. SET_COMP(3, 4, 2,2, 0, 0,0);
  165439. break;
  165440. case JCS_UNKNOWN:
  165441. cinfo->num_components = cinfo->input_components;
  165442. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165443. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165444. MAX_COMPONENTS);
  165445. for (ci = 0; ci < cinfo->num_components; ci++) {
  165446. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165447. }
  165448. break;
  165449. default:
  165450. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165451. }
  165452. }
  165453. #ifdef C_PROGRESSIVE_SUPPORTED
  165454. LOCAL(jpeg_scan_info *)
  165455. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165456. int Ss, int Se, int Ah, int Al)
  165457. /* Support routine: generate one scan for specified component */
  165458. {
  165459. scanptr->comps_in_scan = 1;
  165460. scanptr->component_index[0] = ci;
  165461. scanptr->Ss = Ss;
  165462. scanptr->Se = Se;
  165463. scanptr->Ah = Ah;
  165464. scanptr->Al = Al;
  165465. scanptr++;
  165466. return scanptr;
  165467. }
  165468. LOCAL(jpeg_scan_info *)
  165469. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165470. int Ss, int Se, int Ah, int Al)
  165471. /* Support routine: generate one scan for each component */
  165472. {
  165473. int ci;
  165474. for (ci = 0; ci < ncomps; ci++) {
  165475. scanptr->comps_in_scan = 1;
  165476. scanptr->component_index[0] = ci;
  165477. scanptr->Ss = Ss;
  165478. scanptr->Se = Se;
  165479. scanptr->Ah = Ah;
  165480. scanptr->Al = Al;
  165481. scanptr++;
  165482. }
  165483. return scanptr;
  165484. }
  165485. LOCAL(jpeg_scan_info *)
  165486. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165487. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165488. {
  165489. int ci;
  165490. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165491. /* Single interleaved DC scan */
  165492. scanptr->comps_in_scan = ncomps;
  165493. for (ci = 0; ci < ncomps; ci++)
  165494. scanptr->component_index[ci] = ci;
  165495. scanptr->Ss = scanptr->Se = 0;
  165496. scanptr->Ah = Ah;
  165497. scanptr->Al = Al;
  165498. scanptr++;
  165499. } else {
  165500. /* Noninterleaved DC scan for each component */
  165501. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165502. }
  165503. return scanptr;
  165504. }
  165505. /*
  165506. * Create a recommended progressive-JPEG script.
  165507. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165508. */
  165509. GLOBAL(void)
  165510. jpeg_simple_progression (j_compress_ptr cinfo)
  165511. {
  165512. int ncomps = cinfo->num_components;
  165513. int nscans;
  165514. jpeg_scan_info * scanptr;
  165515. /* Safety check to ensure start_compress not called yet. */
  165516. if (cinfo->global_state != CSTATE_START)
  165517. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165518. /* Figure space needed for script. Calculation must match code below! */
  165519. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165520. /* Custom script for YCbCr color images. */
  165521. nscans = 10;
  165522. } else {
  165523. /* All-purpose script for other color spaces. */
  165524. if (ncomps > MAX_COMPS_IN_SCAN)
  165525. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165526. else
  165527. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165528. }
  165529. /* Allocate space for script.
  165530. * We need to put it in the permanent pool in case the application performs
  165531. * multiple compressions without changing the settings. To avoid a memory
  165532. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165533. * object, we try to re-use previously allocated space, and we allocate
  165534. * enough space to handle YCbCr even if initially asked for grayscale.
  165535. */
  165536. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165537. cinfo->script_space_size = MAX(nscans, 10);
  165538. cinfo->script_space = (jpeg_scan_info *)
  165539. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165540. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165541. }
  165542. scanptr = cinfo->script_space;
  165543. cinfo->scan_info = scanptr;
  165544. cinfo->num_scans = nscans;
  165545. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165546. /* Custom script for YCbCr color images. */
  165547. /* Initial DC scan */
  165548. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165549. /* Initial AC scan: get some luma data out in a hurry */
  165550. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165551. /* Chroma data is too small to be worth expending many scans on */
  165552. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165553. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165554. /* Complete spectral selection for luma AC */
  165555. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165556. /* Refine next bit of luma AC */
  165557. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165558. /* Finish DC successive approximation */
  165559. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165560. /* Finish AC successive approximation */
  165561. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165562. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165563. /* Luma bottom bit comes last since it's usually largest scan */
  165564. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165565. } else {
  165566. /* All-purpose script for other color spaces. */
  165567. /* Successive approximation first pass */
  165568. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165569. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165570. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165571. /* Successive approximation second pass */
  165572. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165573. /* Successive approximation final pass */
  165574. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165575. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165576. }
  165577. }
  165578. #endif /* C_PROGRESSIVE_SUPPORTED */
  165579. /*** End of inlined file: jcparam.c ***/
  165580. /*** Start of inlined file: jcphuff.c ***/
  165581. #define JPEG_INTERNALS
  165582. #ifdef C_PROGRESSIVE_SUPPORTED
  165583. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165584. typedef struct {
  165585. struct jpeg_entropy_encoder pub; /* public fields */
  165586. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165587. boolean gather_statistics;
  165588. /* Bit-level coding status.
  165589. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165590. */
  165591. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165592. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165593. INT32 put_buffer; /* current bit-accumulation buffer */
  165594. int put_bits; /* # of bits now in it */
  165595. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165596. /* Coding status for DC components */
  165597. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165598. /* Coding status for AC components */
  165599. int ac_tbl_no; /* the table number of the single component */
  165600. unsigned int EOBRUN; /* run length of EOBs */
  165601. unsigned int BE; /* # of buffered correction bits before MCU */
  165602. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165603. /* packing correction bits tightly would save some space but cost time... */
  165604. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165605. int next_restart_num; /* next restart number to write (0-7) */
  165606. /* Pointers to derived tables (these workspaces have image lifespan).
  165607. * Since any one scan codes only DC or only AC, we only need one set
  165608. * of tables, not one for DC and one for AC.
  165609. */
  165610. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165611. /* Statistics tables for optimization; again, one set is enough */
  165612. long * count_ptrs[NUM_HUFF_TBLS];
  165613. } phuff_entropy_encoder;
  165614. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165615. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165616. * buffer can hold. Larger sizes may slightly improve compression, but
  165617. * 1000 is already well into the realm of overkill.
  165618. * The minimum safe size is 64 bits.
  165619. */
  165620. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165621. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165622. * We assume that int right shift is unsigned if INT32 right shift is,
  165623. * which should be safe.
  165624. */
  165625. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165626. #define ISHIFT_TEMPS int ishift_temp;
  165627. #define IRIGHT_SHIFT(x,shft) \
  165628. ((ishift_temp = (x)) < 0 ? \
  165629. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165630. (ishift_temp >> (shft)))
  165631. #else
  165632. #define ISHIFT_TEMPS
  165633. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165634. #endif
  165635. /* Forward declarations */
  165636. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165637. JBLOCKROW *MCU_data));
  165638. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165639. JBLOCKROW *MCU_data));
  165640. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165641. JBLOCKROW *MCU_data));
  165642. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165643. JBLOCKROW *MCU_data));
  165644. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165645. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165646. /*
  165647. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165648. */
  165649. METHODDEF(void)
  165650. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165651. {
  165652. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165653. boolean is_DC_band;
  165654. int ci, tbl;
  165655. jpeg_component_info * compptr;
  165656. entropy->cinfo = cinfo;
  165657. entropy->gather_statistics = gather_statistics;
  165658. is_DC_band = (cinfo->Ss == 0);
  165659. /* We assume jcmaster.c already validated the scan parameters. */
  165660. /* Select execution routines */
  165661. if (cinfo->Ah == 0) {
  165662. if (is_DC_band)
  165663. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165664. else
  165665. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165666. } else {
  165667. if (is_DC_band)
  165668. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165669. else {
  165670. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165671. /* AC refinement needs a correction bit buffer */
  165672. if (entropy->bit_buffer == NULL)
  165673. entropy->bit_buffer = (char *)
  165674. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165675. MAX_CORR_BITS * SIZEOF(char));
  165676. }
  165677. }
  165678. if (gather_statistics)
  165679. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165680. else
  165681. entropy->pub.finish_pass = finish_pass_phuff;
  165682. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165683. * for AC coefficients.
  165684. */
  165685. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165686. compptr = cinfo->cur_comp_info[ci];
  165687. /* Initialize DC predictions to 0 */
  165688. entropy->last_dc_val[ci] = 0;
  165689. /* Get table index */
  165690. if (is_DC_band) {
  165691. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165692. continue;
  165693. tbl = compptr->dc_tbl_no;
  165694. } else {
  165695. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165696. }
  165697. if (gather_statistics) {
  165698. /* Check for invalid table index */
  165699. /* (make_c_derived_tbl does this in the other path) */
  165700. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165701. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165702. /* Allocate and zero the statistics tables */
  165703. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165704. if (entropy->count_ptrs[tbl] == NULL)
  165705. entropy->count_ptrs[tbl] = (long *)
  165706. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165707. 257 * SIZEOF(long));
  165708. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165709. } else {
  165710. /* Compute derived values for Huffman table */
  165711. /* We may do this more than once for a table, but it's not expensive */
  165712. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165713. & entropy->derived_tbls[tbl]);
  165714. }
  165715. }
  165716. /* Initialize AC stuff */
  165717. entropy->EOBRUN = 0;
  165718. entropy->BE = 0;
  165719. /* Initialize bit buffer to empty */
  165720. entropy->put_buffer = 0;
  165721. entropy->put_bits = 0;
  165722. /* Initialize restart stuff */
  165723. entropy->restarts_to_go = cinfo->restart_interval;
  165724. entropy->next_restart_num = 0;
  165725. }
  165726. /* Outputting bytes to the file.
  165727. * NB: these must be called only when actually outputting,
  165728. * that is, entropy->gather_statistics == FALSE.
  165729. */
  165730. /* Emit a byte */
  165731. #define emit_byte(entropy,val) \
  165732. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165733. if (--(entropy)->free_in_buffer == 0) \
  165734. dump_buffer_p(entropy); }
  165735. LOCAL(void)
  165736. dump_buffer_p (phuff_entropy_ptr entropy)
  165737. /* Empty the output buffer; we do not support suspension in this module. */
  165738. {
  165739. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165740. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165741. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165742. /* After a successful buffer dump, must reset buffer pointers */
  165743. entropy->next_output_byte = dest->next_output_byte;
  165744. entropy->free_in_buffer = dest->free_in_buffer;
  165745. }
  165746. /* Outputting bits to the file */
  165747. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165748. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165749. * in one call, and we never retain more than 7 bits in put_buffer
  165750. * between calls, so 24 bits are sufficient.
  165751. */
  165752. INLINE
  165753. LOCAL(void)
  165754. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165755. /* Emit some bits, unless we are in gather mode */
  165756. {
  165757. /* This routine is heavily used, so it's worth coding tightly. */
  165758. register INT32 put_buffer = (INT32) code;
  165759. register int put_bits = entropy->put_bits;
  165760. /* if size is 0, caller used an invalid Huffman table entry */
  165761. if (size == 0)
  165762. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165763. if (entropy->gather_statistics)
  165764. return; /* do nothing if we're only getting stats */
  165765. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165766. put_bits += size; /* new number of bits in buffer */
  165767. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165768. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165769. while (put_bits >= 8) {
  165770. int c = (int) ((put_buffer >> 16) & 0xFF);
  165771. emit_byte(entropy, c);
  165772. if (c == 0xFF) { /* need to stuff a zero byte? */
  165773. emit_byte(entropy, 0);
  165774. }
  165775. put_buffer <<= 8;
  165776. put_bits -= 8;
  165777. }
  165778. entropy->put_buffer = put_buffer; /* update variables */
  165779. entropy->put_bits = put_bits;
  165780. }
  165781. LOCAL(void)
  165782. flush_bits_p (phuff_entropy_ptr entropy)
  165783. {
  165784. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165785. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165786. entropy->put_bits = 0;
  165787. }
  165788. /*
  165789. * Emit (or just count) a Huffman symbol.
  165790. */
  165791. INLINE
  165792. LOCAL(void)
  165793. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165794. {
  165795. if (entropy->gather_statistics)
  165796. entropy->count_ptrs[tbl_no][symbol]++;
  165797. else {
  165798. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165799. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165800. }
  165801. }
  165802. /*
  165803. * Emit bits from a correction bit buffer.
  165804. */
  165805. LOCAL(void)
  165806. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165807. unsigned int nbits)
  165808. {
  165809. if (entropy->gather_statistics)
  165810. return; /* no real work */
  165811. while (nbits > 0) {
  165812. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165813. bufstart++;
  165814. nbits--;
  165815. }
  165816. }
  165817. /*
  165818. * Emit any pending EOBRUN symbol.
  165819. */
  165820. LOCAL(void)
  165821. emit_eobrun (phuff_entropy_ptr entropy)
  165822. {
  165823. register int temp, nbits;
  165824. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165825. temp = entropy->EOBRUN;
  165826. nbits = 0;
  165827. while ((temp >>= 1))
  165828. nbits++;
  165829. /* safety check: shouldn't happen given limited correction-bit buffer */
  165830. if (nbits > 14)
  165831. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165832. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165833. if (nbits)
  165834. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165835. entropy->EOBRUN = 0;
  165836. /* Emit any buffered correction bits */
  165837. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165838. entropy->BE = 0;
  165839. }
  165840. }
  165841. /*
  165842. * Emit a restart marker & resynchronize predictions.
  165843. */
  165844. LOCAL(void)
  165845. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165846. {
  165847. int ci;
  165848. emit_eobrun(entropy);
  165849. if (! entropy->gather_statistics) {
  165850. flush_bits_p(entropy);
  165851. emit_byte(entropy, 0xFF);
  165852. emit_byte(entropy, JPEG_RST0 + restart_num);
  165853. }
  165854. if (entropy->cinfo->Ss == 0) {
  165855. /* Re-initialize DC predictions to 0 */
  165856. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165857. entropy->last_dc_val[ci] = 0;
  165858. } else {
  165859. /* Re-initialize all AC-related fields to 0 */
  165860. entropy->EOBRUN = 0;
  165861. entropy->BE = 0;
  165862. }
  165863. }
  165864. /*
  165865. * MCU encoding for DC initial scan (either spectral selection,
  165866. * or first pass of successive approximation).
  165867. */
  165868. METHODDEF(boolean)
  165869. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165870. {
  165871. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165872. register int temp, temp2;
  165873. register int nbits;
  165874. int blkn, ci;
  165875. int Al = cinfo->Al;
  165876. JBLOCKROW block;
  165877. jpeg_component_info * compptr;
  165878. ISHIFT_TEMPS
  165879. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165880. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165881. /* Emit restart marker if needed */
  165882. if (cinfo->restart_interval)
  165883. if (entropy->restarts_to_go == 0)
  165884. emit_restart_p(entropy, entropy->next_restart_num);
  165885. /* Encode the MCU data blocks */
  165886. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165887. block = MCU_data[blkn];
  165888. ci = cinfo->MCU_membership[blkn];
  165889. compptr = cinfo->cur_comp_info[ci];
  165890. /* Compute the DC value after the required point transform by Al.
  165891. * This is simply an arithmetic right shift.
  165892. */
  165893. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165894. /* DC differences are figured on the point-transformed values. */
  165895. temp = temp2 - entropy->last_dc_val[ci];
  165896. entropy->last_dc_val[ci] = temp2;
  165897. /* Encode the DC coefficient difference per section G.1.2.1 */
  165898. temp2 = temp;
  165899. if (temp < 0) {
  165900. temp = -temp; /* temp is abs value of input */
  165901. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165902. /* This code assumes we are on a two's complement machine */
  165903. temp2--;
  165904. }
  165905. /* Find the number of bits needed for the magnitude of the coefficient */
  165906. nbits = 0;
  165907. while (temp) {
  165908. nbits++;
  165909. temp >>= 1;
  165910. }
  165911. /* Check for out-of-range coefficient values.
  165912. * Since we're encoding a difference, the range limit is twice as much.
  165913. */
  165914. if (nbits > MAX_COEF_BITS+1)
  165915. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165916. /* Count/emit the Huffman-coded symbol for the number of bits */
  165917. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165918. /* Emit that number of bits of the value, if positive, */
  165919. /* or the complement of its magnitude, if negative. */
  165920. if (nbits) /* emit_bits rejects calls with size 0 */
  165921. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165922. }
  165923. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165924. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165925. /* Update restart-interval state too */
  165926. if (cinfo->restart_interval) {
  165927. if (entropy->restarts_to_go == 0) {
  165928. entropy->restarts_to_go = cinfo->restart_interval;
  165929. entropy->next_restart_num++;
  165930. entropy->next_restart_num &= 7;
  165931. }
  165932. entropy->restarts_to_go--;
  165933. }
  165934. return TRUE;
  165935. }
  165936. /*
  165937. * MCU encoding for AC initial scan (either spectral selection,
  165938. * or first pass of successive approximation).
  165939. */
  165940. METHODDEF(boolean)
  165941. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165942. {
  165943. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165944. register int temp, temp2;
  165945. register int nbits;
  165946. register int r, k;
  165947. int Se = cinfo->Se;
  165948. int Al = cinfo->Al;
  165949. JBLOCKROW block;
  165950. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165951. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165952. /* Emit restart marker if needed */
  165953. if (cinfo->restart_interval)
  165954. if (entropy->restarts_to_go == 0)
  165955. emit_restart_p(entropy, entropy->next_restart_num);
  165956. /* Encode the MCU data block */
  165957. block = MCU_data[0];
  165958. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165959. r = 0; /* r = run length of zeros */
  165960. for (k = cinfo->Ss; k <= Se; k++) {
  165961. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165962. r++;
  165963. continue;
  165964. }
  165965. /* We must apply the point transform by Al. For AC coefficients this
  165966. * is an integer division with rounding towards 0. To do this portably
  165967. * in C, we shift after obtaining the absolute value; so the code is
  165968. * interwoven with finding the abs value (temp) and output bits (temp2).
  165969. */
  165970. if (temp < 0) {
  165971. temp = -temp; /* temp is abs value of input */
  165972. temp >>= Al; /* apply the point transform */
  165973. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165974. temp2 = ~temp;
  165975. } else {
  165976. temp >>= Al; /* apply the point transform */
  165977. temp2 = temp;
  165978. }
  165979. /* Watch out for case that nonzero coef is zero after point transform */
  165980. if (temp == 0) {
  165981. r++;
  165982. continue;
  165983. }
  165984. /* Emit any pending EOBRUN */
  165985. if (entropy->EOBRUN > 0)
  165986. emit_eobrun(entropy);
  165987. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165988. while (r > 15) {
  165989. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165990. r -= 16;
  165991. }
  165992. /* Find the number of bits needed for the magnitude of the coefficient */
  165993. nbits = 1; /* there must be at least one 1 bit */
  165994. while ((temp >>= 1))
  165995. nbits++;
  165996. /* Check for out-of-range coefficient values */
  165997. if (nbits > MAX_COEF_BITS)
  165998. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165999. /* Count/emit Huffman symbol for run length / number of bits */
  166000. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166001. /* Emit that number of bits of the value, if positive, */
  166002. /* or the complement of its magnitude, if negative. */
  166003. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166004. r = 0; /* reset zero run length */
  166005. }
  166006. if (r > 0) { /* If there are trailing zeroes, */
  166007. entropy->EOBRUN++; /* count an EOB */
  166008. if (entropy->EOBRUN == 0x7FFF)
  166009. emit_eobrun(entropy); /* force it out to avoid overflow */
  166010. }
  166011. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166012. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166013. /* Update restart-interval state too */
  166014. if (cinfo->restart_interval) {
  166015. if (entropy->restarts_to_go == 0) {
  166016. entropy->restarts_to_go = cinfo->restart_interval;
  166017. entropy->next_restart_num++;
  166018. entropy->next_restart_num &= 7;
  166019. }
  166020. entropy->restarts_to_go--;
  166021. }
  166022. return TRUE;
  166023. }
  166024. /*
  166025. * MCU encoding for DC successive approximation refinement scan.
  166026. * Note: we assume such scans can be multi-component, although the spec
  166027. * is not very clear on the point.
  166028. */
  166029. METHODDEF(boolean)
  166030. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166031. {
  166032. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166033. register int temp;
  166034. int blkn;
  166035. int Al = cinfo->Al;
  166036. JBLOCKROW block;
  166037. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166038. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166039. /* Emit restart marker if needed */
  166040. if (cinfo->restart_interval)
  166041. if (entropy->restarts_to_go == 0)
  166042. emit_restart_p(entropy, entropy->next_restart_num);
  166043. /* Encode the MCU data blocks */
  166044. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166045. block = MCU_data[blkn];
  166046. /* We simply emit the Al'th bit of the DC coefficient value. */
  166047. temp = (*block)[0];
  166048. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166049. }
  166050. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166051. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166052. /* Update restart-interval state too */
  166053. if (cinfo->restart_interval) {
  166054. if (entropy->restarts_to_go == 0) {
  166055. entropy->restarts_to_go = cinfo->restart_interval;
  166056. entropy->next_restart_num++;
  166057. entropy->next_restart_num &= 7;
  166058. }
  166059. entropy->restarts_to_go--;
  166060. }
  166061. return TRUE;
  166062. }
  166063. /*
  166064. * MCU encoding for AC successive approximation refinement scan.
  166065. */
  166066. METHODDEF(boolean)
  166067. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166068. {
  166069. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166070. register int temp;
  166071. register int r, k;
  166072. int EOB;
  166073. char *BR_buffer;
  166074. unsigned int BR;
  166075. int Se = cinfo->Se;
  166076. int Al = cinfo->Al;
  166077. JBLOCKROW block;
  166078. int absvalues[DCTSIZE2];
  166079. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166080. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166081. /* Emit restart marker if needed */
  166082. if (cinfo->restart_interval)
  166083. if (entropy->restarts_to_go == 0)
  166084. emit_restart_p(entropy, entropy->next_restart_num);
  166085. /* Encode the MCU data block */
  166086. block = MCU_data[0];
  166087. /* It is convenient to make a pre-pass to determine the transformed
  166088. * coefficients' absolute values and the EOB position.
  166089. */
  166090. EOB = 0;
  166091. for (k = cinfo->Ss; k <= Se; k++) {
  166092. temp = (*block)[jpeg_natural_order[k]];
  166093. /* We must apply the point transform by Al. For AC coefficients this
  166094. * is an integer division with rounding towards 0. To do this portably
  166095. * in C, we shift after obtaining the absolute value.
  166096. */
  166097. if (temp < 0)
  166098. temp = -temp; /* temp is abs value of input */
  166099. temp >>= Al; /* apply the point transform */
  166100. absvalues[k] = temp; /* save abs value for main pass */
  166101. if (temp == 1)
  166102. EOB = k; /* EOB = index of last newly-nonzero coef */
  166103. }
  166104. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166105. r = 0; /* r = run length of zeros */
  166106. BR = 0; /* BR = count of buffered bits added now */
  166107. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166108. for (k = cinfo->Ss; k <= Se; k++) {
  166109. if ((temp = absvalues[k]) == 0) {
  166110. r++;
  166111. continue;
  166112. }
  166113. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166114. while (r > 15 && k <= EOB) {
  166115. /* emit any pending EOBRUN and the BE correction bits */
  166116. emit_eobrun(entropy);
  166117. /* Emit ZRL */
  166118. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166119. r -= 16;
  166120. /* Emit buffered correction bits that must be associated with ZRL */
  166121. emit_buffered_bits(entropy, BR_buffer, BR);
  166122. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166123. BR = 0;
  166124. }
  166125. /* If the coef was previously nonzero, it only needs a correction bit.
  166126. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166127. * that we also need to test r > 15. But if r > 15, we can only get here
  166128. * if k > EOB, which implies that this coefficient is not 1.
  166129. */
  166130. if (temp > 1) {
  166131. /* The correction bit is the next bit of the absolute value. */
  166132. BR_buffer[BR++] = (char) (temp & 1);
  166133. continue;
  166134. }
  166135. /* Emit any pending EOBRUN and the BE correction bits */
  166136. emit_eobrun(entropy);
  166137. /* Count/emit Huffman symbol for run length / number of bits */
  166138. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166139. /* Emit output bit for newly-nonzero coef */
  166140. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166141. emit_bits_p(entropy, (unsigned int) temp, 1);
  166142. /* Emit buffered correction bits that must be associated with this code */
  166143. emit_buffered_bits(entropy, BR_buffer, BR);
  166144. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166145. BR = 0;
  166146. r = 0; /* reset zero run length */
  166147. }
  166148. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166149. entropy->EOBRUN++; /* count an EOB */
  166150. entropy->BE += BR; /* concat my correction bits to older ones */
  166151. /* We force out the EOB if we risk either:
  166152. * 1. overflow of the EOB counter;
  166153. * 2. overflow of the correction bit buffer during the next MCU.
  166154. */
  166155. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166156. emit_eobrun(entropy);
  166157. }
  166158. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166159. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166160. /* Update restart-interval state too */
  166161. if (cinfo->restart_interval) {
  166162. if (entropy->restarts_to_go == 0) {
  166163. entropy->restarts_to_go = cinfo->restart_interval;
  166164. entropy->next_restart_num++;
  166165. entropy->next_restart_num &= 7;
  166166. }
  166167. entropy->restarts_to_go--;
  166168. }
  166169. return TRUE;
  166170. }
  166171. /*
  166172. * Finish up at the end of a Huffman-compressed progressive scan.
  166173. */
  166174. METHODDEF(void)
  166175. finish_pass_phuff (j_compress_ptr cinfo)
  166176. {
  166177. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166178. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166179. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166180. /* Flush out any buffered data */
  166181. emit_eobrun(entropy);
  166182. flush_bits_p(entropy);
  166183. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166184. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166185. }
  166186. /*
  166187. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166188. */
  166189. METHODDEF(void)
  166190. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166191. {
  166192. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166193. boolean is_DC_band;
  166194. int ci, tbl;
  166195. jpeg_component_info * compptr;
  166196. JHUFF_TBL **htblptr;
  166197. boolean did[NUM_HUFF_TBLS];
  166198. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166199. emit_eobrun(entropy);
  166200. is_DC_band = (cinfo->Ss == 0);
  166201. /* It's important not to apply jpeg_gen_optimal_table more than once
  166202. * per table, because it clobbers the input frequency counts!
  166203. */
  166204. MEMZERO(did, SIZEOF(did));
  166205. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166206. compptr = cinfo->cur_comp_info[ci];
  166207. if (is_DC_band) {
  166208. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166209. continue;
  166210. tbl = compptr->dc_tbl_no;
  166211. } else {
  166212. tbl = compptr->ac_tbl_no;
  166213. }
  166214. if (! did[tbl]) {
  166215. if (is_DC_band)
  166216. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166217. else
  166218. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166219. if (*htblptr == NULL)
  166220. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166221. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166222. did[tbl] = TRUE;
  166223. }
  166224. }
  166225. }
  166226. /*
  166227. * Module initialization routine for progressive Huffman entropy encoding.
  166228. */
  166229. GLOBAL(void)
  166230. jinit_phuff_encoder (j_compress_ptr cinfo)
  166231. {
  166232. phuff_entropy_ptr entropy;
  166233. int i;
  166234. entropy = (phuff_entropy_ptr)
  166235. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166236. SIZEOF(phuff_entropy_encoder));
  166237. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166238. entropy->pub.start_pass = start_pass_phuff;
  166239. /* Mark tables unallocated */
  166240. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166241. entropy->derived_tbls[i] = NULL;
  166242. entropy->count_ptrs[i] = NULL;
  166243. }
  166244. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166245. }
  166246. #endif /* C_PROGRESSIVE_SUPPORTED */
  166247. /*** End of inlined file: jcphuff.c ***/
  166248. /*** Start of inlined file: jcprepct.c ***/
  166249. #define JPEG_INTERNALS
  166250. /* At present, jcsample.c can request context rows only for smoothing.
  166251. * In the future, we might also need context rows for CCIR601 sampling
  166252. * or other more-complex downsampling procedures. The code to support
  166253. * context rows should be compiled only if needed.
  166254. */
  166255. #ifdef INPUT_SMOOTHING_SUPPORTED
  166256. #define CONTEXT_ROWS_SUPPORTED
  166257. #endif
  166258. /*
  166259. * For the simple (no-context-row) case, we just need to buffer one
  166260. * row group's worth of pixels for the downsampling step. At the bottom of
  166261. * the image, we pad to a full row group by replicating the last pixel row.
  166262. * The downsampler's last output row is then replicated if needed to pad
  166263. * out to a full iMCU row.
  166264. *
  166265. * When providing context rows, we must buffer three row groups' worth of
  166266. * pixels. Three row groups are physically allocated, but the row pointer
  166267. * arrays are made five row groups high, with the extra pointers above and
  166268. * below "wrapping around" to point to the last and first real row groups.
  166269. * This allows the downsampler to access the proper context rows.
  166270. * At the top and bottom of the image, we create dummy context rows by
  166271. * copying the first or last real pixel row. This copying could be avoided
  166272. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166273. * trouble on the compression side.
  166274. */
  166275. /* Private buffer controller object */
  166276. typedef struct {
  166277. struct jpeg_c_prep_controller pub; /* public fields */
  166278. /* Downsampling input buffer. This buffer holds color-converted data
  166279. * until we have enough to do a downsample step.
  166280. */
  166281. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166282. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166283. int next_buf_row; /* index of next row to store in color_buf */
  166284. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166285. int this_row_group; /* starting row index of group to process */
  166286. int next_buf_stop; /* downsample when we reach this index */
  166287. #endif
  166288. } my_prep_controller;
  166289. typedef my_prep_controller * my_prep_ptr;
  166290. /*
  166291. * Initialize for a processing pass.
  166292. */
  166293. METHODDEF(void)
  166294. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166295. {
  166296. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166297. if (pass_mode != JBUF_PASS_THRU)
  166298. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166299. /* Initialize total-height counter for detecting bottom of image */
  166300. prep->rows_to_go = cinfo->image_height;
  166301. /* Mark the conversion buffer empty */
  166302. prep->next_buf_row = 0;
  166303. #ifdef CONTEXT_ROWS_SUPPORTED
  166304. /* Preset additional state variables for context mode.
  166305. * These aren't used in non-context mode, so we needn't test which mode.
  166306. */
  166307. prep->this_row_group = 0;
  166308. /* Set next_buf_stop to stop after two row groups have been read in. */
  166309. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166310. #endif
  166311. }
  166312. /*
  166313. * Expand an image vertically from height input_rows to height output_rows,
  166314. * by duplicating the bottom row.
  166315. */
  166316. LOCAL(void)
  166317. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166318. int input_rows, int output_rows)
  166319. {
  166320. register int row;
  166321. for (row = input_rows; row < output_rows; row++) {
  166322. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166323. 1, num_cols);
  166324. }
  166325. }
  166326. /*
  166327. * Process some data in the simple no-context case.
  166328. *
  166329. * Preprocessor output data is counted in "row groups". A row group
  166330. * is defined to be v_samp_factor sample rows of each component.
  166331. * Downsampling will produce this much data from each max_v_samp_factor
  166332. * input rows.
  166333. */
  166334. METHODDEF(void)
  166335. pre_process_data (j_compress_ptr cinfo,
  166336. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166337. JDIMENSION in_rows_avail,
  166338. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166339. JDIMENSION out_row_groups_avail)
  166340. {
  166341. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166342. int numrows, ci;
  166343. JDIMENSION inrows;
  166344. jpeg_component_info * compptr;
  166345. while (*in_row_ctr < in_rows_avail &&
  166346. *out_row_group_ctr < out_row_groups_avail) {
  166347. /* Do color conversion to fill the conversion buffer. */
  166348. inrows = in_rows_avail - *in_row_ctr;
  166349. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166350. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166351. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166352. prep->color_buf,
  166353. (JDIMENSION) prep->next_buf_row,
  166354. numrows);
  166355. *in_row_ctr += numrows;
  166356. prep->next_buf_row += numrows;
  166357. prep->rows_to_go -= numrows;
  166358. /* If at bottom of image, pad to fill the conversion buffer. */
  166359. if (prep->rows_to_go == 0 &&
  166360. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166361. for (ci = 0; ci < cinfo->num_components; ci++) {
  166362. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166363. prep->next_buf_row, cinfo->max_v_samp_factor);
  166364. }
  166365. prep->next_buf_row = cinfo->max_v_samp_factor;
  166366. }
  166367. /* If we've filled the conversion buffer, empty it. */
  166368. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166369. (*cinfo->downsample->downsample) (cinfo,
  166370. prep->color_buf, (JDIMENSION) 0,
  166371. output_buf, *out_row_group_ctr);
  166372. prep->next_buf_row = 0;
  166373. (*out_row_group_ctr)++;
  166374. }
  166375. /* If at bottom of image, pad the output to a full iMCU height.
  166376. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166377. */
  166378. if (prep->rows_to_go == 0 &&
  166379. *out_row_group_ctr < out_row_groups_avail) {
  166380. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166381. ci++, compptr++) {
  166382. expand_bottom_edge(output_buf[ci],
  166383. compptr->width_in_blocks * DCTSIZE,
  166384. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166385. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166386. }
  166387. *out_row_group_ctr = out_row_groups_avail;
  166388. break; /* can exit outer loop without test */
  166389. }
  166390. }
  166391. }
  166392. #ifdef CONTEXT_ROWS_SUPPORTED
  166393. /*
  166394. * Process some data in the context case.
  166395. */
  166396. METHODDEF(void)
  166397. pre_process_context (j_compress_ptr cinfo,
  166398. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166399. JDIMENSION in_rows_avail,
  166400. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166401. JDIMENSION out_row_groups_avail)
  166402. {
  166403. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166404. int numrows, ci;
  166405. int buf_height = cinfo->max_v_samp_factor * 3;
  166406. JDIMENSION inrows;
  166407. while (*out_row_group_ctr < out_row_groups_avail) {
  166408. if (*in_row_ctr < in_rows_avail) {
  166409. /* Do color conversion to fill the conversion buffer. */
  166410. inrows = in_rows_avail - *in_row_ctr;
  166411. numrows = prep->next_buf_stop - prep->next_buf_row;
  166412. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166413. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166414. prep->color_buf,
  166415. (JDIMENSION) prep->next_buf_row,
  166416. numrows);
  166417. /* Pad at top of image, if first time through */
  166418. if (prep->rows_to_go == cinfo->image_height) {
  166419. for (ci = 0; ci < cinfo->num_components; ci++) {
  166420. int row;
  166421. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166422. jcopy_sample_rows(prep->color_buf[ci], 0,
  166423. prep->color_buf[ci], -row,
  166424. 1, cinfo->image_width);
  166425. }
  166426. }
  166427. }
  166428. *in_row_ctr += numrows;
  166429. prep->next_buf_row += numrows;
  166430. prep->rows_to_go -= numrows;
  166431. } else {
  166432. /* Return for more data, unless we are at the bottom of the image. */
  166433. if (prep->rows_to_go != 0)
  166434. break;
  166435. /* When at bottom of image, pad to fill the conversion buffer. */
  166436. if (prep->next_buf_row < prep->next_buf_stop) {
  166437. for (ci = 0; ci < cinfo->num_components; ci++) {
  166438. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166439. prep->next_buf_row, prep->next_buf_stop);
  166440. }
  166441. prep->next_buf_row = prep->next_buf_stop;
  166442. }
  166443. }
  166444. /* If we've gotten enough data, downsample a row group. */
  166445. if (prep->next_buf_row == prep->next_buf_stop) {
  166446. (*cinfo->downsample->downsample) (cinfo,
  166447. prep->color_buf,
  166448. (JDIMENSION) prep->this_row_group,
  166449. output_buf, *out_row_group_ctr);
  166450. (*out_row_group_ctr)++;
  166451. /* Advance pointers with wraparound as necessary. */
  166452. prep->this_row_group += cinfo->max_v_samp_factor;
  166453. if (prep->this_row_group >= buf_height)
  166454. prep->this_row_group = 0;
  166455. if (prep->next_buf_row >= buf_height)
  166456. prep->next_buf_row = 0;
  166457. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166458. }
  166459. }
  166460. }
  166461. /*
  166462. * Create the wrapped-around downsampling input buffer needed for context mode.
  166463. */
  166464. LOCAL(void)
  166465. create_context_buffer (j_compress_ptr cinfo)
  166466. {
  166467. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166468. int rgroup_height = cinfo->max_v_samp_factor;
  166469. int ci, i;
  166470. jpeg_component_info * compptr;
  166471. JSAMPARRAY true_buffer, fake_buffer;
  166472. /* Grab enough space for fake row pointers for all the components;
  166473. * we need five row groups' worth of pointers for each component.
  166474. */
  166475. fake_buffer = (JSAMPARRAY)
  166476. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166477. (cinfo->num_components * 5 * rgroup_height) *
  166478. SIZEOF(JSAMPROW));
  166479. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166480. ci++, compptr++) {
  166481. /* Allocate the actual buffer space (3 row groups) for this component.
  166482. * We make the buffer wide enough to allow the downsampler to edge-expand
  166483. * horizontally within the buffer, if it so chooses.
  166484. */
  166485. true_buffer = (*cinfo->mem->alloc_sarray)
  166486. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166487. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166488. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166489. (JDIMENSION) (3 * rgroup_height));
  166490. /* Copy true buffer row pointers into the middle of the fake row array */
  166491. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166492. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166493. /* Fill in the above and below wraparound pointers */
  166494. for (i = 0; i < rgroup_height; i++) {
  166495. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166496. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166497. }
  166498. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166499. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166500. }
  166501. }
  166502. #endif /* CONTEXT_ROWS_SUPPORTED */
  166503. /*
  166504. * Initialize preprocessing controller.
  166505. */
  166506. GLOBAL(void)
  166507. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166508. {
  166509. my_prep_ptr prep;
  166510. int ci;
  166511. jpeg_component_info * compptr;
  166512. if (need_full_buffer) /* safety check */
  166513. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166514. prep = (my_prep_ptr)
  166515. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166516. SIZEOF(my_prep_controller));
  166517. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166518. prep->pub.start_pass = start_pass_prep;
  166519. /* Allocate the color conversion buffer.
  166520. * We make the buffer wide enough to allow the downsampler to edge-expand
  166521. * horizontally within the buffer, if it so chooses.
  166522. */
  166523. if (cinfo->downsample->need_context_rows) {
  166524. /* Set up to provide context rows */
  166525. #ifdef CONTEXT_ROWS_SUPPORTED
  166526. prep->pub.pre_process_data = pre_process_context;
  166527. create_context_buffer(cinfo);
  166528. #else
  166529. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166530. #endif
  166531. } else {
  166532. /* No context, just make it tall enough for one row group */
  166533. prep->pub.pre_process_data = pre_process_data;
  166534. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166535. ci++, compptr++) {
  166536. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166537. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166538. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166539. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166540. (JDIMENSION) cinfo->max_v_samp_factor);
  166541. }
  166542. }
  166543. }
  166544. /*** End of inlined file: jcprepct.c ***/
  166545. /*** Start of inlined file: jcsample.c ***/
  166546. #define JPEG_INTERNALS
  166547. /* Pointer to routine to downsample a single component */
  166548. typedef JMETHOD(void, downsample1_ptr,
  166549. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166550. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166551. /* Private subobject */
  166552. typedef struct {
  166553. struct jpeg_downsampler pub; /* public fields */
  166554. /* Downsampling method pointers, one per component */
  166555. downsample1_ptr methods[MAX_COMPONENTS];
  166556. } my_downsampler;
  166557. typedef my_downsampler * my_downsample_ptr;
  166558. /*
  166559. * Initialize for a downsampling pass.
  166560. */
  166561. METHODDEF(void)
  166562. start_pass_downsample (j_compress_ptr)
  166563. {
  166564. /* no work for now */
  166565. }
  166566. /*
  166567. * Expand a component horizontally from width input_cols to width output_cols,
  166568. * by duplicating the rightmost samples.
  166569. */
  166570. LOCAL(void)
  166571. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166572. JDIMENSION input_cols, JDIMENSION output_cols)
  166573. {
  166574. register JSAMPROW ptr;
  166575. register JSAMPLE pixval;
  166576. register int count;
  166577. int row;
  166578. int numcols = (int) (output_cols - input_cols);
  166579. if (numcols > 0) {
  166580. for (row = 0; row < num_rows; row++) {
  166581. ptr = image_data[row] + input_cols;
  166582. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166583. for (count = numcols; count > 0; count--)
  166584. *ptr++ = pixval;
  166585. }
  166586. }
  166587. }
  166588. /*
  166589. * Do downsampling for a whole row group (all components).
  166590. *
  166591. * In this version we simply downsample each component independently.
  166592. */
  166593. METHODDEF(void)
  166594. sep_downsample (j_compress_ptr cinfo,
  166595. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166596. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166597. {
  166598. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166599. int ci;
  166600. jpeg_component_info * compptr;
  166601. JSAMPARRAY in_ptr, out_ptr;
  166602. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166603. ci++, compptr++) {
  166604. in_ptr = input_buf[ci] + in_row_index;
  166605. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166606. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166607. }
  166608. }
  166609. /*
  166610. * Downsample pixel values of a single component.
  166611. * One row group is processed per call.
  166612. * This version handles arbitrary integral sampling ratios, without smoothing.
  166613. * Note that this version is not actually used for customary sampling ratios.
  166614. */
  166615. METHODDEF(void)
  166616. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166617. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166618. {
  166619. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166620. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166621. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166622. JSAMPROW inptr, outptr;
  166623. INT32 outvalue;
  166624. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166625. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166626. numpix = h_expand * v_expand;
  166627. numpix2 = numpix/2;
  166628. /* Expand input data enough to let all the output samples be generated
  166629. * by the standard loop. Special-casing padded output would be more
  166630. * efficient.
  166631. */
  166632. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166633. cinfo->image_width, output_cols * h_expand);
  166634. inrow = 0;
  166635. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166636. outptr = output_data[outrow];
  166637. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166638. outcol++, outcol_h += h_expand) {
  166639. outvalue = 0;
  166640. for (v = 0; v < v_expand; v++) {
  166641. inptr = input_data[inrow+v] + outcol_h;
  166642. for (h = 0; h < h_expand; h++) {
  166643. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166644. }
  166645. }
  166646. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166647. }
  166648. inrow += v_expand;
  166649. }
  166650. }
  166651. /*
  166652. * Downsample pixel values of a single component.
  166653. * This version handles the special case of a full-size component,
  166654. * without smoothing.
  166655. */
  166656. METHODDEF(void)
  166657. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166658. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166659. {
  166660. /* Copy the data */
  166661. jcopy_sample_rows(input_data, 0, output_data, 0,
  166662. cinfo->max_v_samp_factor, cinfo->image_width);
  166663. /* Edge-expand */
  166664. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166665. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166666. }
  166667. /*
  166668. * Downsample pixel values of a single component.
  166669. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166670. * without smoothing.
  166671. *
  166672. * A note about the "bias" calculations: when rounding fractional values to
  166673. * integer, we do not want to always round 0.5 up to the next integer.
  166674. * If we did that, we'd introduce a noticeable bias towards larger values.
  166675. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166676. * alternate pixel locations (a simple ordered dither pattern).
  166677. */
  166678. METHODDEF(void)
  166679. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166680. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166681. {
  166682. int outrow;
  166683. JDIMENSION outcol;
  166684. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166685. register JSAMPROW inptr, outptr;
  166686. register int bias;
  166687. /* Expand input data enough to let all the output samples be generated
  166688. * by the standard loop. Special-casing padded output would be more
  166689. * efficient.
  166690. */
  166691. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166692. cinfo->image_width, output_cols * 2);
  166693. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166694. outptr = output_data[outrow];
  166695. inptr = input_data[outrow];
  166696. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166697. for (outcol = 0; outcol < output_cols; outcol++) {
  166698. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166699. + bias) >> 1);
  166700. bias ^= 1; /* 0=>1, 1=>0 */
  166701. inptr += 2;
  166702. }
  166703. }
  166704. }
  166705. /*
  166706. * Downsample pixel values of a single component.
  166707. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166708. * without smoothing.
  166709. */
  166710. METHODDEF(void)
  166711. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166712. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166713. {
  166714. int inrow, outrow;
  166715. JDIMENSION outcol;
  166716. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166717. register JSAMPROW inptr0, inptr1, outptr;
  166718. register int bias;
  166719. /* Expand input data enough to let all the output samples be generated
  166720. * by the standard loop. Special-casing padded output would be more
  166721. * efficient.
  166722. */
  166723. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166724. cinfo->image_width, output_cols * 2);
  166725. inrow = 0;
  166726. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166727. outptr = output_data[outrow];
  166728. inptr0 = input_data[inrow];
  166729. inptr1 = input_data[inrow+1];
  166730. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166731. for (outcol = 0; outcol < output_cols; outcol++) {
  166732. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166733. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166734. + bias) >> 2);
  166735. bias ^= 3; /* 1=>2, 2=>1 */
  166736. inptr0 += 2; inptr1 += 2;
  166737. }
  166738. inrow += 2;
  166739. }
  166740. }
  166741. #ifdef INPUT_SMOOTHING_SUPPORTED
  166742. /*
  166743. * Downsample pixel values of a single component.
  166744. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166745. * with smoothing. One row of context is required.
  166746. */
  166747. METHODDEF(void)
  166748. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166749. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166750. {
  166751. int inrow, outrow;
  166752. JDIMENSION colctr;
  166753. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166754. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166755. INT32 membersum, neighsum, memberscale, neighscale;
  166756. /* Expand input data enough to let all the output samples be generated
  166757. * by the standard loop. Special-casing padded output would be more
  166758. * efficient.
  166759. */
  166760. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166761. cinfo->image_width, output_cols * 2);
  166762. /* We don't bother to form the individual "smoothed" input pixel values;
  166763. * we can directly compute the output which is the average of the four
  166764. * smoothed values. Each of the four member pixels contributes a fraction
  166765. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166766. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166767. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166768. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166769. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166770. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166771. * factors are scaled by 2^16 = 65536.
  166772. * Also recall that SF = smoothing_factor / 1024.
  166773. */
  166774. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166775. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166776. inrow = 0;
  166777. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166778. outptr = output_data[outrow];
  166779. inptr0 = input_data[inrow];
  166780. inptr1 = input_data[inrow+1];
  166781. above_ptr = input_data[inrow-1];
  166782. below_ptr = input_data[inrow+2];
  166783. /* Special case for first column: pretend column -1 is same as column 0 */
  166784. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166785. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166786. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166787. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166788. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166789. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166790. neighsum += neighsum;
  166791. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166792. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166793. membersum = membersum * memberscale + neighsum * neighscale;
  166794. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166795. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166796. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166797. /* sum of pixels directly mapped to this output element */
  166798. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166799. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166800. /* sum of edge-neighbor pixels */
  166801. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166802. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166803. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166804. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166805. /* The edge-neighbors count twice as much as corner-neighbors */
  166806. neighsum += neighsum;
  166807. /* Add in the corner-neighbors */
  166808. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166809. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166810. /* form final output scaled up by 2^16 */
  166811. membersum = membersum * memberscale + neighsum * neighscale;
  166812. /* round, descale and output it */
  166813. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166814. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166815. }
  166816. /* Special case for last column */
  166817. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166818. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166819. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166820. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166821. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166822. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166823. neighsum += neighsum;
  166824. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166825. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166826. membersum = membersum * memberscale + neighsum * neighscale;
  166827. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166828. inrow += 2;
  166829. }
  166830. }
  166831. /*
  166832. * Downsample pixel values of a single component.
  166833. * This version handles the special case of a full-size component,
  166834. * with smoothing. One row of context is required.
  166835. */
  166836. METHODDEF(void)
  166837. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166838. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166839. {
  166840. int outrow;
  166841. JDIMENSION colctr;
  166842. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166843. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166844. INT32 membersum, neighsum, memberscale, neighscale;
  166845. int colsum, lastcolsum, nextcolsum;
  166846. /* Expand input data enough to let all the output samples be generated
  166847. * by the standard loop. Special-casing padded output would be more
  166848. * efficient.
  166849. */
  166850. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166851. cinfo->image_width, output_cols);
  166852. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166853. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166854. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166855. * Also recall that SF = smoothing_factor / 1024.
  166856. */
  166857. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166858. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166859. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166860. outptr = output_data[outrow];
  166861. inptr = input_data[outrow];
  166862. above_ptr = input_data[outrow-1];
  166863. below_ptr = input_data[outrow+1];
  166864. /* Special case for first column */
  166865. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166866. GETJSAMPLE(*inptr);
  166867. membersum = GETJSAMPLE(*inptr++);
  166868. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166869. GETJSAMPLE(*inptr);
  166870. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166871. membersum = membersum * memberscale + neighsum * neighscale;
  166872. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166873. lastcolsum = colsum; colsum = nextcolsum;
  166874. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166875. membersum = GETJSAMPLE(*inptr++);
  166876. above_ptr++; below_ptr++;
  166877. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166878. GETJSAMPLE(*inptr);
  166879. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166880. membersum = membersum * memberscale + neighsum * neighscale;
  166881. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166882. lastcolsum = colsum; colsum = nextcolsum;
  166883. }
  166884. /* Special case for last column */
  166885. membersum = GETJSAMPLE(*inptr);
  166886. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166887. membersum = membersum * memberscale + neighsum * neighscale;
  166888. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166889. }
  166890. }
  166891. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166892. /*
  166893. * Module initialization routine for downsampling.
  166894. * Note that we must select a routine for each component.
  166895. */
  166896. GLOBAL(void)
  166897. jinit_downsampler (j_compress_ptr cinfo)
  166898. {
  166899. my_downsample_ptr downsample;
  166900. int ci;
  166901. jpeg_component_info * compptr;
  166902. boolean smoothok = TRUE;
  166903. downsample = (my_downsample_ptr)
  166904. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166905. SIZEOF(my_downsampler));
  166906. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166907. downsample->pub.start_pass = start_pass_downsample;
  166908. downsample->pub.downsample = sep_downsample;
  166909. downsample->pub.need_context_rows = FALSE;
  166910. if (cinfo->CCIR601_sampling)
  166911. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166912. /* Verify we can handle the sampling factors, and set up method pointers */
  166913. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166914. ci++, compptr++) {
  166915. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166916. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166917. #ifdef INPUT_SMOOTHING_SUPPORTED
  166918. if (cinfo->smoothing_factor) {
  166919. downsample->methods[ci] = fullsize_smooth_downsample;
  166920. downsample->pub.need_context_rows = TRUE;
  166921. } else
  166922. #endif
  166923. downsample->methods[ci] = fullsize_downsample;
  166924. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166925. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166926. smoothok = FALSE;
  166927. downsample->methods[ci] = h2v1_downsample;
  166928. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166929. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166930. #ifdef INPUT_SMOOTHING_SUPPORTED
  166931. if (cinfo->smoothing_factor) {
  166932. downsample->methods[ci] = h2v2_smooth_downsample;
  166933. downsample->pub.need_context_rows = TRUE;
  166934. } else
  166935. #endif
  166936. downsample->methods[ci] = h2v2_downsample;
  166937. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166938. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166939. smoothok = FALSE;
  166940. downsample->methods[ci] = int_downsample;
  166941. } else
  166942. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166943. }
  166944. #ifdef INPUT_SMOOTHING_SUPPORTED
  166945. if (cinfo->smoothing_factor && !smoothok)
  166946. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166947. #endif
  166948. }
  166949. /*** End of inlined file: jcsample.c ***/
  166950. /*** Start of inlined file: jctrans.c ***/
  166951. #define JPEG_INTERNALS
  166952. /* Forward declarations */
  166953. LOCAL(void) transencode_master_selection
  166954. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166955. LOCAL(void) transencode_coef_controller
  166956. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166957. /*
  166958. * Compression initialization for writing raw-coefficient data.
  166959. * Before calling this, all parameters and a data destination must be set up.
  166960. * Call jpeg_finish_compress() to actually write the data.
  166961. *
  166962. * The number of passed virtual arrays must match cinfo->num_components.
  166963. * Note that the virtual arrays need not be filled or even realized at
  166964. * the time write_coefficients is called; indeed, if the virtual arrays
  166965. * were requested from this compression object's memory manager, they
  166966. * typically will be realized during this routine and filled afterwards.
  166967. */
  166968. GLOBAL(void)
  166969. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166970. {
  166971. if (cinfo->global_state != CSTATE_START)
  166972. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166973. /* Mark all tables to be written */
  166974. jpeg_suppress_tables(cinfo, FALSE);
  166975. /* (Re)initialize error mgr and destination modules */
  166976. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166977. (*cinfo->dest->init_destination) (cinfo);
  166978. /* Perform master selection of active modules */
  166979. transencode_master_selection(cinfo, coef_arrays);
  166980. /* Wait for jpeg_finish_compress() call */
  166981. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166982. cinfo->global_state = CSTATE_WRCOEFS;
  166983. }
  166984. /*
  166985. * Initialize the compression object with default parameters,
  166986. * then copy from the source object all parameters needed for lossless
  166987. * transcoding. Parameters that can be varied without loss (such as
  166988. * scan script and Huffman optimization) are left in their default states.
  166989. */
  166990. GLOBAL(void)
  166991. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166992. j_compress_ptr dstinfo)
  166993. {
  166994. JQUANT_TBL ** qtblptr;
  166995. jpeg_component_info *incomp, *outcomp;
  166996. JQUANT_TBL *c_quant, *slot_quant;
  166997. int tblno, ci, coefi;
  166998. /* Safety check to ensure start_compress not called yet. */
  166999. if (dstinfo->global_state != CSTATE_START)
  167000. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167001. /* Copy fundamental image dimensions */
  167002. dstinfo->image_width = srcinfo->image_width;
  167003. dstinfo->image_height = srcinfo->image_height;
  167004. dstinfo->input_components = srcinfo->num_components;
  167005. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167006. /* Initialize all parameters to default values */
  167007. jpeg_set_defaults(dstinfo);
  167008. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167009. * Fix it to get the right header markers for the image colorspace.
  167010. */
  167011. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167012. dstinfo->data_precision = srcinfo->data_precision;
  167013. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167014. /* Copy the source's quantization tables. */
  167015. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167016. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167017. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167018. if (*qtblptr == NULL)
  167019. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167020. MEMCOPY((*qtblptr)->quantval,
  167021. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167022. SIZEOF((*qtblptr)->quantval));
  167023. (*qtblptr)->sent_table = FALSE;
  167024. }
  167025. }
  167026. /* Copy the source's per-component info.
  167027. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167028. */
  167029. dstinfo->num_components = srcinfo->num_components;
  167030. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167031. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167032. MAX_COMPONENTS);
  167033. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167034. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167035. outcomp->component_id = incomp->component_id;
  167036. outcomp->h_samp_factor = incomp->h_samp_factor;
  167037. outcomp->v_samp_factor = incomp->v_samp_factor;
  167038. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167039. /* Make sure saved quantization table for component matches the qtable
  167040. * slot. If not, the input file re-used this qtable slot.
  167041. * IJG encoder currently cannot duplicate this.
  167042. */
  167043. tblno = outcomp->quant_tbl_no;
  167044. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167045. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167046. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167047. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167048. c_quant = incomp->quant_table;
  167049. if (c_quant != NULL) {
  167050. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167051. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167052. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167053. }
  167054. }
  167055. /* Note: we do not copy the source's Huffman table assignments;
  167056. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167057. */
  167058. }
  167059. /* Also copy JFIF version and resolution information, if available.
  167060. * Strictly speaking this isn't "critical" info, but it's nearly
  167061. * always appropriate to copy it if available. In particular,
  167062. * if the application chooses to copy JFIF 1.02 extension markers from
  167063. * the source file, we need to copy the version to make sure we don't
  167064. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167065. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167066. */
  167067. if (srcinfo->saw_JFIF_marker) {
  167068. if (srcinfo->JFIF_major_version == 1) {
  167069. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167070. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167071. }
  167072. dstinfo->density_unit = srcinfo->density_unit;
  167073. dstinfo->X_density = srcinfo->X_density;
  167074. dstinfo->Y_density = srcinfo->Y_density;
  167075. }
  167076. }
  167077. /*
  167078. * Master selection of compression modules for transcoding.
  167079. * This substitutes for jcinit.c's initialization of the full compressor.
  167080. */
  167081. LOCAL(void)
  167082. transencode_master_selection (j_compress_ptr cinfo,
  167083. jvirt_barray_ptr * coef_arrays)
  167084. {
  167085. /* Although we don't actually use input_components for transcoding,
  167086. * jcmaster.c's initial_setup will complain if input_components is 0.
  167087. */
  167088. cinfo->input_components = 1;
  167089. /* Initialize master control (includes parameter checking/processing) */
  167090. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167091. /* Entropy encoding: either Huffman or arithmetic coding. */
  167092. if (cinfo->arith_code) {
  167093. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167094. } else {
  167095. if (cinfo->progressive_mode) {
  167096. #ifdef C_PROGRESSIVE_SUPPORTED
  167097. jinit_phuff_encoder(cinfo);
  167098. #else
  167099. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167100. #endif
  167101. } else
  167102. jinit_huff_encoder(cinfo);
  167103. }
  167104. /* We need a special coefficient buffer controller. */
  167105. transencode_coef_controller(cinfo, coef_arrays);
  167106. jinit_marker_writer(cinfo);
  167107. /* We can now tell the memory manager to allocate virtual arrays. */
  167108. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167109. /* Write the datastream header (SOI, JFIF) immediately.
  167110. * Frame and scan headers are postponed till later.
  167111. * This lets application insert special markers after the SOI.
  167112. */
  167113. (*cinfo->marker->write_file_header) (cinfo);
  167114. }
  167115. /*
  167116. * The rest of this file is a special implementation of the coefficient
  167117. * buffer controller. This is similar to jccoefct.c, but it handles only
  167118. * output from presupplied virtual arrays. Furthermore, we generate any
  167119. * dummy padding blocks on-the-fly rather than expecting them to be present
  167120. * in the arrays.
  167121. */
  167122. /* Private buffer controller object */
  167123. typedef struct {
  167124. struct jpeg_c_coef_controller pub; /* public fields */
  167125. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167126. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167127. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167128. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167129. /* Virtual block array for each component. */
  167130. jvirt_barray_ptr * whole_image;
  167131. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167132. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167133. } my_coef_controller2;
  167134. typedef my_coef_controller2 * my_coef_ptr2;
  167135. LOCAL(void)
  167136. start_iMCU_row2 (j_compress_ptr cinfo)
  167137. /* Reset within-iMCU-row counters for a new row */
  167138. {
  167139. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167140. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167141. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167142. * But at the bottom of the image, process only what's left.
  167143. */
  167144. if (cinfo->comps_in_scan > 1) {
  167145. coef->MCU_rows_per_iMCU_row = 1;
  167146. } else {
  167147. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167148. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167149. else
  167150. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167151. }
  167152. coef->mcu_ctr = 0;
  167153. coef->MCU_vert_offset = 0;
  167154. }
  167155. /*
  167156. * Initialize for a processing pass.
  167157. */
  167158. METHODDEF(void)
  167159. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167160. {
  167161. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167162. if (pass_mode != JBUF_CRANK_DEST)
  167163. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167164. coef->iMCU_row_num = 0;
  167165. start_iMCU_row2(cinfo);
  167166. }
  167167. /*
  167168. * Process some data.
  167169. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167170. * per call, ie, v_samp_factor block rows for each component in the scan.
  167171. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167172. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167173. *
  167174. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167175. */
  167176. METHODDEF(boolean)
  167177. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167178. {
  167179. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167180. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167181. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167182. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167183. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167184. JDIMENSION start_col;
  167185. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167186. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167187. JBLOCKROW buffer_ptr;
  167188. jpeg_component_info *compptr;
  167189. /* Align the virtual buffers for the components used in this scan. */
  167190. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167191. compptr = cinfo->cur_comp_info[ci];
  167192. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167193. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167194. coef->iMCU_row_num * compptr->v_samp_factor,
  167195. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167196. }
  167197. /* Loop to process one whole iMCU row */
  167198. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167199. yoffset++) {
  167200. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167201. MCU_col_num++) {
  167202. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167203. blkn = 0; /* index of current DCT block within MCU */
  167204. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167205. compptr = cinfo->cur_comp_info[ci];
  167206. start_col = MCU_col_num * compptr->MCU_width;
  167207. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167208. : compptr->last_col_width;
  167209. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167210. if (coef->iMCU_row_num < last_iMCU_row ||
  167211. yindex+yoffset < compptr->last_row_height) {
  167212. /* Fill in pointers to real blocks in this row */
  167213. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167214. for (xindex = 0; xindex < blockcnt; xindex++)
  167215. MCU_buffer[blkn++] = buffer_ptr++;
  167216. } else {
  167217. /* At bottom of image, need a whole row of dummy blocks */
  167218. xindex = 0;
  167219. }
  167220. /* Fill in any dummy blocks needed in this row.
  167221. * Dummy blocks are filled in the same way as in jccoefct.c:
  167222. * all zeroes in the AC entries, DC entries equal to previous
  167223. * block's DC value. The init routine has already zeroed the
  167224. * AC entries, so we need only set the DC entries correctly.
  167225. */
  167226. for (; xindex < compptr->MCU_width; xindex++) {
  167227. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167228. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167229. blkn++;
  167230. }
  167231. }
  167232. }
  167233. /* Try to write the MCU. */
  167234. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167235. /* Suspension forced; update state counters and exit */
  167236. coef->MCU_vert_offset = yoffset;
  167237. coef->mcu_ctr = MCU_col_num;
  167238. return FALSE;
  167239. }
  167240. }
  167241. /* Completed an MCU row, but perhaps not an iMCU row */
  167242. coef->mcu_ctr = 0;
  167243. }
  167244. /* Completed the iMCU row, advance counters for next one */
  167245. coef->iMCU_row_num++;
  167246. start_iMCU_row2(cinfo);
  167247. return TRUE;
  167248. }
  167249. /*
  167250. * Initialize coefficient buffer controller.
  167251. *
  167252. * Each passed coefficient array must be the right size for that
  167253. * coefficient: width_in_blocks wide and height_in_blocks high,
  167254. * with unitheight at least v_samp_factor.
  167255. */
  167256. LOCAL(void)
  167257. transencode_coef_controller (j_compress_ptr cinfo,
  167258. jvirt_barray_ptr * coef_arrays)
  167259. {
  167260. my_coef_ptr2 coef;
  167261. JBLOCKROW buffer;
  167262. int i;
  167263. coef = (my_coef_ptr2)
  167264. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167265. SIZEOF(my_coef_controller2));
  167266. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167267. coef->pub.start_pass = start_pass_coef2;
  167268. coef->pub.compress_data = compress_output2;
  167269. /* Save pointer to virtual arrays */
  167270. coef->whole_image = coef_arrays;
  167271. /* Allocate and pre-zero space for dummy DCT blocks. */
  167272. buffer = (JBLOCKROW)
  167273. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167274. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167275. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167276. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167277. coef->dummy_buffer[i] = buffer + i;
  167278. }
  167279. }
  167280. /*** End of inlined file: jctrans.c ***/
  167281. /*** Start of inlined file: jdapistd.c ***/
  167282. #define JPEG_INTERNALS
  167283. /* Forward declarations */
  167284. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167285. /*
  167286. * Decompression initialization.
  167287. * jpeg_read_header must be completed before calling this.
  167288. *
  167289. * If a multipass operating mode was selected, this will do all but the
  167290. * last pass, and thus may take a great deal of time.
  167291. *
  167292. * Returns FALSE if suspended. The return value need be inspected only if
  167293. * a suspending data source is used.
  167294. */
  167295. GLOBAL(boolean)
  167296. jpeg_start_decompress (j_decompress_ptr cinfo)
  167297. {
  167298. if (cinfo->global_state == DSTATE_READY) {
  167299. /* First call: initialize master control, select active modules */
  167300. jinit_master_decompress(cinfo);
  167301. if (cinfo->buffered_image) {
  167302. /* No more work here; expecting jpeg_start_output next */
  167303. cinfo->global_state = DSTATE_BUFIMAGE;
  167304. return TRUE;
  167305. }
  167306. cinfo->global_state = DSTATE_PRELOAD;
  167307. }
  167308. if (cinfo->global_state == DSTATE_PRELOAD) {
  167309. /* If file has multiple scans, absorb them all into the coef buffer */
  167310. if (cinfo->inputctl->has_multiple_scans) {
  167311. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167312. for (;;) {
  167313. int retcode;
  167314. /* Call progress monitor hook if present */
  167315. if (cinfo->progress != NULL)
  167316. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167317. /* Absorb some more input */
  167318. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167319. if (retcode == JPEG_SUSPENDED)
  167320. return FALSE;
  167321. if (retcode == JPEG_REACHED_EOI)
  167322. break;
  167323. /* Advance progress counter if appropriate */
  167324. if (cinfo->progress != NULL &&
  167325. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167326. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167327. /* jdmaster underestimated number of scans; ratchet up one scan */
  167328. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167329. }
  167330. }
  167331. }
  167332. #else
  167333. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167334. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167335. }
  167336. cinfo->output_scan_number = cinfo->input_scan_number;
  167337. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167338. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167339. /* Perform any dummy output passes, and set up for the final pass */
  167340. return output_pass_setup(cinfo);
  167341. }
  167342. /*
  167343. * Set up for an output pass, and perform any dummy pass(es) needed.
  167344. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167345. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167346. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167347. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167348. */
  167349. LOCAL(boolean)
  167350. output_pass_setup (j_decompress_ptr cinfo)
  167351. {
  167352. if (cinfo->global_state != DSTATE_PRESCAN) {
  167353. /* First call: do pass setup */
  167354. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167355. cinfo->output_scanline = 0;
  167356. cinfo->global_state = DSTATE_PRESCAN;
  167357. }
  167358. /* Loop over any required dummy passes */
  167359. while (cinfo->master->is_dummy_pass) {
  167360. #ifdef QUANT_2PASS_SUPPORTED
  167361. /* Crank through the dummy pass */
  167362. while (cinfo->output_scanline < cinfo->output_height) {
  167363. JDIMENSION last_scanline;
  167364. /* Call progress monitor hook if present */
  167365. if (cinfo->progress != NULL) {
  167366. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167367. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167368. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167369. }
  167370. /* Process some data */
  167371. last_scanline = cinfo->output_scanline;
  167372. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167373. &cinfo->output_scanline, (JDIMENSION) 0);
  167374. if (cinfo->output_scanline == last_scanline)
  167375. return FALSE; /* No progress made, must suspend */
  167376. }
  167377. /* Finish up dummy pass, and set up for another one */
  167378. (*cinfo->master->finish_output_pass) (cinfo);
  167379. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167380. cinfo->output_scanline = 0;
  167381. #else
  167382. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167383. #endif /* QUANT_2PASS_SUPPORTED */
  167384. }
  167385. /* Ready for application to drive output pass through
  167386. * jpeg_read_scanlines or jpeg_read_raw_data.
  167387. */
  167388. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167389. return TRUE;
  167390. }
  167391. /*
  167392. * Read some scanlines of data from the JPEG decompressor.
  167393. *
  167394. * The return value will be the number of lines actually read.
  167395. * This may be less than the number requested in several cases,
  167396. * including bottom of image, data source suspension, and operating
  167397. * modes that emit multiple scanlines at a time.
  167398. *
  167399. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167400. * this likely signals an application programmer error. However,
  167401. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167402. */
  167403. GLOBAL(JDIMENSION)
  167404. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167405. JDIMENSION max_lines)
  167406. {
  167407. JDIMENSION row_ctr;
  167408. if (cinfo->global_state != DSTATE_SCANNING)
  167409. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167410. if (cinfo->output_scanline >= cinfo->output_height) {
  167411. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167412. return 0;
  167413. }
  167414. /* Call progress monitor hook if present */
  167415. if (cinfo->progress != NULL) {
  167416. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167417. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167418. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167419. }
  167420. /* Process some data */
  167421. row_ctr = 0;
  167422. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167423. cinfo->output_scanline += row_ctr;
  167424. return row_ctr;
  167425. }
  167426. /*
  167427. * Alternate entry point to read raw data.
  167428. * Processes exactly one iMCU row per call, unless suspended.
  167429. */
  167430. GLOBAL(JDIMENSION)
  167431. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167432. JDIMENSION max_lines)
  167433. {
  167434. JDIMENSION lines_per_iMCU_row;
  167435. if (cinfo->global_state != DSTATE_RAW_OK)
  167436. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167437. if (cinfo->output_scanline >= cinfo->output_height) {
  167438. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167439. return 0;
  167440. }
  167441. /* Call progress monitor hook if present */
  167442. if (cinfo->progress != NULL) {
  167443. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167444. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167445. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167446. }
  167447. /* Verify that at least one iMCU row can be returned. */
  167448. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167449. if (max_lines < lines_per_iMCU_row)
  167450. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167451. /* Decompress directly into user's buffer. */
  167452. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167453. return 0; /* suspension forced, can do nothing more */
  167454. /* OK, we processed one iMCU row. */
  167455. cinfo->output_scanline += lines_per_iMCU_row;
  167456. return lines_per_iMCU_row;
  167457. }
  167458. /* Additional entry points for buffered-image mode. */
  167459. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167460. /*
  167461. * Initialize for an output pass in buffered-image mode.
  167462. */
  167463. GLOBAL(boolean)
  167464. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167465. {
  167466. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167467. cinfo->global_state != DSTATE_PRESCAN)
  167468. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167469. /* Limit scan number to valid range */
  167470. if (scan_number <= 0)
  167471. scan_number = 1;
  167472. if (cinfo->inputctl->eoi_reached &&
  167473. scan_number > cinfo->input_scan_number)
  167474. scan_number = cinfo->input_scan_number;
  167475. cinfo->output_scan_number = scan_number;
  167476. /* Perform any dummy output passes, and set up for the real pass */
  167477. return output_pass_setup(cinfo);
  167478. }
  167479. /*
  167480. * Finish up after an output pass in buffered-image mode.
  167481. *
  167482. * Returns FALSE if suspended. The return value need be inspected only if
  167483. * a suspending data source is used.
  167484. */
  167485. GLOBAL(boolean)
  167486. jpeg_finish_output (j_decompress_ptr cinfo)
  167487. {
  167488. if ((cinfo->global_state == DSTATE_SCANNING ||
  167489. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167490. /* Terminate this pass. */
  167491. /* We do not require the whole pass to have been completed. */
  167492. (*cinfo->master->finish_output_pass) (cinfo);
  167493. cinfo->global_state = DSTATE_BUFPOST;
  167494. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167495. /* BUFPOST = repeat call after a suspension, anything else is error */
  167496. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167497. }
  167498. /* Read markers looking for SOS or EOI */
  167499. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167500. ! cinfo->inputctl->eoi_reached) {
  167501. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167502. return FALSE; /* Suspend, come back later */
  167503. }
  167504. cinfo->global_state = DSTATE_BUFIMAGE;
  167505. return TRUE;
  167506. }
  167507. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167508. /*** End of inlined file: jdapistd.c ***/
  167509. /*** Start of inlined file: jdapimin.c ***/
  167510. #define JPEG_INTERNALS
  167511. /*
  167512. * Initialization of a JPEG decompression object.
  167513. * The error manager must already be set up (in case memory manager fails).
  167514. */
  167515. GLOBAL(void)
  167516. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167517. {
  167518. int i;
  167519. /* Guard against version mismatches between library and caller. */
  167520. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167521. if (version != JPEG_LIB_VERSION)
  167522. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167523. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167524. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167525. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167526. /* For debugging purposes, we zero the whole master structure.
  167527. * But the application has already set the err pointer, and may have set
  167528. * client_data, so we have to save and restore those fields.
  167529. * Note: if application hasn't set client_data, tools like Purify may
  167530. * complain here.
  167531. */
  167532. {
  167533. struct jpeg_error_mgr * err = cinfo->err;
  167534. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167535. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167536. cinfo->err = err;
  167537. cinfo->client_data = client_data;
  167538. }
  167539. cinfo->is_decompressor = TRUE;
  167540. /* Initialize a memory manager instance for this object */
  167541. jinit_memory_mgr((j_common_ptr) cinfo);
  167542. /* Zero out pointers to permanent structures. */
  167543. cinfo->progress = NULL;
  167544. cinfo->src = NULL;
  167545. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167546. cinfo->quant_tbl_ptrs[i] = NULL;
  167547. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167548. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167549. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167550. }
  167551. /* Initialize marker processor so application can override methods
  167552. * for COM, APPn markers before calling jpeg_read_header.
  167553. */
  167554. cinfo->marker_list = NULL;
  167555. jinit_marker_reader(cinfo);
  167556. /* And initialize the overall input controller. */
  167557. jinit_input_controller(cinfo);
  167558. /* OK, I'm ready */
  167559. cinfo->global_state = DSTATE_START;
  167560. }
  167561. /*
  167562. * Destruction of a JPEG decompression object
  167563. */
  167564. GLOBAL(void)
  167565. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167566. {
  167567. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167568. }
  167569. /*
  167570. * Abort processing of a JPEG decompression operation,
  167571. * but don't destroy the object itself.
  167572. */
  167573. GLOBAL(void)
  167574. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167575. {
  167576. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167577. }
  167578. /*
  167579. * Set default decompression parameters.
  167580. */
  167581. LOCAL(void)
  167582. default_decompress_parms (j_decompress_ptr cinfo)
  167583. {
  167584. /* Guess the input colorspace, and set output colorspace accordingly. */
  167585. /* (Wish JPEG committee had provided a real way to specify this...) */
  167586. /* Note application may override our guesses. */
  167587. switch (cinfo->num_components) {
  167588. case 1:
  167589. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167590. cinfo->out_color_space = JCS_GRAYSCALE;
  167591. break;
  167592. case 3:
  167593. if (cinfo->saw_JFIF_marker) {
  167594. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167595. } else if (cinfo->saw_Adobe_marker) {
  167596. switch (cinfo->Adobe_transform) {
  167597. case 0:
  167598. cinfo->jpeg_color_space = JCS_RGB;
  167599. break;
  167600. case 1:
  167601. cinfo->jpeg_color_space = JCS_YCbCr;
  167602. break;
  167603. default:
  167604. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167605. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167606. break;
  167607. }
  167608. } else {
  167609. /* Saw no special markers, try to guess from the component IDs */
  167610. int cid0 = cinfo->comp_info[0].component_id;
  167611. int cid1 = cinfo->comp_info[1].component_id;
  167612. int cid2 = cinfo->comp_info[2].component_id;
  167613. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167614. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167615. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167616. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167617. else {
  167618. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167619. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167620. }
  167621. }
  167622. /* Always guess RGB is proper output colorspace. */
  167623. cinfo->out_color_space = JCS_RGB;
  167624. break;
  167625. case 4:
  167626. if (cinfo->saw_Adobe_marker) {
  167627. switch (cinfo->Adobe_transform) {
  167628. case 0:
  167629. cinfo->jpeg_color_space = JCS_CMYK;
  167630. break;
  167631. case 2:
  167632. cinfo->jpeg_color_space = JCS_YCCK;
  167633. break;
  167634. default:
  167635. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167636. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167637. break;
  167638. }
  167639. } else {
  167640. /* No special markers, assume straight CMYK. */
  167641. cinfo->jpeg_color_space = JCS_CMYK;
  167642. }
  167643. cinfo->out_color_space = JCS_CMYK;
  167644. break;
  167645. default:
  167646. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167647. cinfo->out_color_space = JCS_UNKNOWN;
  167648. break;
  167649. }
  167650. /* Set defaults for other decompression parameters. */
  167651. cinfo->scale_num = 1; /* 1:1 scaling */
  167652. cinfo->scale_denom = 1;
  167653. cinfo->output_gamma = 1.0;
  167654. cinfo->buffered_image = FALSE;
  167655. cinfo->raw_data_out = FALSE;
  167656. cinfo->dct_method = JDCT_DEFAULT;
  167657. cinfo->do_fancy_upsampling = TRUE;
  167658. cinfo->do_block_smoothing = TRUE;
  167659. cinfo->quantize_colors = FALSE;
  167660. /* We set these in case application only sets quantize_colors. */
  167661. cinfo->dither_mode = JDITHER_FS;
  167662. #ifdef QUANT_2PASS_SUPPORTED
  167663. cinfo->two_pass_quantize = TRUE;
  167664. #else
  167665. cinfo->two_pass_quantize = FALSE;
  167666. #endif
  167667. cinfo->desired_number_of_colors = 256;
  167668. cinfo->colormap = NULL;
  167669. /* Initialize for no mode change in buffered-image mode. */
  167670. cinfo->enable_1pass_quant = FALSE;
  167671. cinfo->enable_external_quant = FALSE;
  167672. cinfo->enable_2pass_quant = FALSE;
  167673. }
  167674. /*
  167675. * Decompression startup: read start of JPEG datastream to see what's there.
  167676. * Need only initialize JPEG object and supply a data source before calling.
  167677. *
  167678. * This routine will read as far as the first SOS marker (ie, actual start of
  167679. * compressed data), and will save all tables and parameters in the JPEG
  167680. * object. It will also initialize the decompression parameters to default
  167681. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167682. * adjust the decompression parameters and then call jpeg_start_decompress.
  167683. * (Or, if the application only wanted to determine the image parameters,
  167684. * the data need not be decompressed. In that case, call jpeg_abort or
  167685. * jpeg_destroy to release any temporary space.)
  167686. * If an abbreviated (tables only) datastream is presented, the routine will
  167687. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167688. * re-use the JPEG object to read the abbreviated image datastream(s).
  167689. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167690. * The JPEG_SUSPENDED return code only occurs if the data source module
  167691. * requests suspension of the decompressor. In this case the application
  167692. * should load more source data and then re-call jpeg_read_header to resume
  167693. * processing.
  167694. * If a non-suspending data source is used and require_image is TRUE, then the
  167695. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167696. *
  167697. * This routine is now just a front end to jpeg_consume_input, with some
  167698. * extra error checking.
  167699. */
  167700. GLOBAL(int)
  167701. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167702. {
  167703. int retcode;
  167704. if (cinfo->global_state != DSTATE_START &&
  167705. cinfo->global_state != DSTATE_INHEADER)
  167706. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167707. retcode = jpeg_consume_input(cinfo);
  167708. switch (retcode) {
  167709. case JPEG_REACHED_SOS:
  167710. retcode = JPEG_HEADER_OK;
  167711. break;
  167712. case JPEG_REACHED_EOI:
  167713. if (require_image) /* Complain if application wanted an image */
  167714. ERREXIT(cinfo, JERR_NO_IMAGE);
  167715. /* Reset to start state; it would be safer to require the application to
  167716. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167717. * A side effect is to free any temporary memory (there shouldn't be any).
  167718. */
  167719. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167720. retcode = JPEG_HEADER_TABLES_ONLY;
  167721. break;
  167722. case JPEG_SUSPENDED:
  167723. /* no work */
  167724. break;
  167725. }
  167726. return retcode;
  167727. }
  167728. /*
  167729. * Consume data in advance of what the decompressor requires.
  167730. * This can be called at any time once the decompressor object has
  167731. * been created and a data source has been set up.
  167732. *
  167733. * This routine is essentially a state machine that handles a couple
  167734. * of critical state-transition actions, namely initial setup and
  167735. * transition from header scanning to ready-for-start_decompress.
  167736. * All the actual input is done via the input controller's consume_input
  167737. * method.
  167738. */
  167739. GLOBAL(int)
  167740. jpeg_consume_input (j_decompress_ptr cinfo)
  167741. {
  167742. int retcode = JPEG_SUSPENDED;
  167743. /* NB: every possible DSTATE value should be listed in this switch */
  167744. switch (cinfo->global_state) {
  167745. case DSTATE_START:
  167746. /* Start-of-datastream actions: reset appropriate modules */
  167747. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167748. /* Initialize application's data source module */
  167749. (*cinfo->src->init_source) (cinfo);
  167750. cinfo->global_state = DSTATE_INHEADER;
  167751. /*FALLTHROUGH*/
  167752. case DSTATE_INHEADER:
  167753. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167754. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167755. /* Set up default parameters based on header data */
  167756. default_decompress_parms(cinfo);
  167757. /* Set global state: ready for start_decompress */
  167758. cinfo->global_state = DSTATE_READY;
  167759. }
  167760. break;
  167761. case DSTATE_READY:
  167762. /* Can't advance past first SOS until start_decompress is called */
  167763. retcode = JPEG_REACHED_SOS;
  167764. break;
  167765. case DSTATE_PRELOAD:
  167766. case DSTATE_PRESCAN:
  167767. case DSTATE_SCANNING:
  167768. case DSTATE_RAW_OK:
  167769. case DSTATE_BUFIMAGE:
  167770. case DSTATE_BUFPOST:
  167771. case DSTATE_STOPPING:
  167772. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167773. break;
  167774. default:
  167775. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167776. }
  167777. return retcode;
  167778. }
  167779. /*
  167780. * Have we finished reading the input file?
  167781. */
  167782. GLOBAL(boolean)
  167783. jpeg_input_complete (j_decompress_ptr cinfo)
  167784. {
  167785. /* Check for valid jpeg object */
  167786. if (cinfo->global_state < DSTATE_START ||
  167787. cinfo->global_state > DSTATE_STOPPING)
  167788. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167789. return cinfo->inputctl->eoi_reached;
  167790. }
  167791. /*
  167792. * Is there more than one scan?
  167793. */
  167794. GLOBAL(boolean)
  167795. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167796. {
  167797. /* Only valid after jpeg_read_header completes */
  167798. if (cinfo->global_state < DSTATE_READY ||
  167799. cinfo->global_state > DSTATE_STOPPING)
  167800. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167801. return cinfo->inputctl->has_multiple_scans;
  167802. }
  167803. /*
  167804. * Finish JPEG decompression.
  167805. *
  167806. * This will normally just verify the file trailer and release temp storage.
  167807. *
  167808. * Returns FALSE if suspended. The return value need be inspected only if
  167809. * a suspending data source is used.
  167810. */
  167811. GLOBAL(boolean)
  167812. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167813. {
  167814. if ((cinfo->global_state == DSTATE_SCANNING ||
  167815. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167816. /* Terminate final pass of non-buffered mode */
  167817. if (cinfo->output_scanline < cinfo->output_height)
  167818. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167819. (*cinfo->master->finish_output_pass) (cinfo);
  167820. cinfo->global_state = DSTATE_STOPPING;
  167821. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167822. /* Finishing after a buffered-image operation */
  167823. cinfo->global_state = DSTATE_STOPPING;
  167824. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167825. /* STOPPING = repeat call after a suspension, anything else is error */
  167826. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167827. }
  167828. /* Read until EOI */
  167829. while (! cinfo->inputctl->eoi_reached) {
  167830. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167831. return FALSE; /* Suspend, come back later */
  167832. }
  167833. /* Do final cleanup */
  167834. (*cinfo->src->term_source) (cinfo);
  167835. /* We can use jpeg_abort to release memory and reset global_state */
  167836. jpeg_abort((j_common_ptr) cinfo);
  167837. return TRUE;
  167838. }
  167839. /*** End of inlined file: jdapimin.c ***/
  167840. /*** Start of inlined file: jdatasrc.c ***/
  167841. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167842. /*** Start of inlined file: jerror.h ***/
  167843. /*
  167844. * To define the enum list of message codes, include this file without
  167845. * defining macro JMESSAGE. To create a message string table, include it
  167846. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167847. */
  167848. #ifndef JMESSAGE
  167849. #ifndef JERROR_H
  167850. /* First time through, define the enum list */
  167851. #define JMAKE_ENUM_LIST
  167852. #else
  167853. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167854. #define JMESSAGE(code,string)
  167855. #endif /* JERROR_H */
  167856. #endif /* JMESSAGE */
  167857. #ifdef JMAKE_ENUM_LIST
  167858. typedef enum {
  167859. #define JMESSAGE(code,string) code ,
  167860. #endif /* JMAKE_ENUM_LIST */
  167861. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167862. /* For maintenance convenience, list is alphabetical by message code name */
  167863. JMESSAGE(JERR_ARITH_NOTIMPL,
  167864. "Sorry, there are legal restrictions on arithmetic coding")
  167865. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167866. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167867. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167868. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167869. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167870. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167871. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167872. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167873. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167874. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167875. JMESSAGE(JERR_BAD_LIB_VERSION,
  167876. "Wrong JPEG library version: library is %d, caller expects %d")
  167877. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167878. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167879. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167880. JMESSAGE(JERR_BAD_PROGRESSION,
  167881. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167882. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167883. "Invalid progressive parameters at scan script entry %d")
  167884. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167885. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167886. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167887. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167888. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167889. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167890. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167891. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167892. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167893. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167894. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167895. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167896. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167897. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167898. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167899. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167900. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167901. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167902. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167903. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167904. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167905. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167906. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167907. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167908. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167909. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167910. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167911. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167912. "Cannot transcode due to multiple use of quantization table %d")
  167913. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167914. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167915. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167916. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167917. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167918. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167919. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167920. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167921. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167922. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167923. JMESSAGE(JERR_QUANT_COMPONENTS,
  167924. "Cannot quantize more than %d color components")
  167925. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167926. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167927. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167928. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167929. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167930. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167931. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167932. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167933. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167934. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167935. JMESSAGE(JERR_TFILE_WRITE,
  167936. "Write failed on temporary file --- out of disk space?")
  167937. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167938. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167939. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167940. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167941. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167942. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167943. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167944. JMESSAGE(JMSG_VERSION, JVERSION)
  167945. JMESSAGE(JTRC_16BIT_TABLES,
  167946. "Caution: quantization tables are too coarse for baseline JPEG")
  167947. JMESSAGE(JTRC_ADOBE,
  167948. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167949. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167950. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167951. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167952. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167953. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167954. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167955. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167956. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167957. JMESSAGE(JTRC_EOI, "End Of Image")
  167958. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167959. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167960. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167961. "Warning: thumbnail image size does not match data length %u")
  167962. JMESSAGE(JTRC_JFIF_EXTENSION,
  167963. "JFIF extension marker: type 0x%02x, length %u")
  167964. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167965. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167966. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167967. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167968. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167969. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167970. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167971. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167972. JMESSAGE(JTRC_RST, "RST%d")
  167973. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167974. "Smoothing not supported with nonstandard sampling ratios")
  167975. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167976. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167977. JMESSAGE(JTRC_SOI, "Start of Image")
  167978. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167979. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167980. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167981. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167982. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167983. JMESSAGE(JTRC_THUMB_JPEG,
  167984. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167985. JMESSAGE(JTRC_THUMB_PALETTE,
  167986. "JFIF extension marker: palette thumbnail image, length %u")
  167987. JMESSAGE(JTRC_THUMB_RGB,
  167988. "JFIF extension marker: RGB thumbnail image, length %u")
  167989. JMESSAGE(JTRC_UNKNOWN_IDS,
  167990. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167991. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167992. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167993. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167994. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167995. "Inconsistent progression sequence for component %d coefficient %d")
  167996. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167997. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167998. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167999. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168000. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168001. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168002. JMESSAGE(JWRN_MUST_RESYNC,
  168003. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168004. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168005. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168006. #ifdef JMAKE_ENUM_LIST
  168007. JMSG_LASTMSGCODE
  168008. } J_MESSAGE_CODE;
  168009. #undef JMAKE_ENUM_LIST
  168010. #endif /* JMAKE_ENUM_LIST */
  168011. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168012. #undef JMESSAGE
  168013. #ifndef JERROR_H
  168014. #define JERROR_H
  168015. /* Macros to simplify using the error and trace message stuff */
  168016. /* The first parameter is either type of cinfo pointer */
  168017. /* Fatal errors (print message and exit) */
  168018. #define ERREXIT(cinfo,code) \
  168019. ((cinfo)->err->msg_code = (code), \
  168020. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168021. #define ERREXIT1(cinfo,code,p1) \
  168022. ((cinfo)->err->msg_code = (code), \
  168023. (cinfo)->err->msg_parm.i[0] = (p1), \
  168024. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168025. #define ERREXIT2(cinfo,code,p1,p2) \
  168026. ((cinfo)->err->msg_code = (code), \
  168027. (cinfo)->err->msg_parm.i[0] = (p1), \
  168028. (cinfo)->err->msg_parm.i[1] = (p2), \
  168029. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168030. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168031. ((cinfo)->err->msg_code = (code), \
  168032. (cinfo)->err->msg_parm.i[0] = (p1), \
  168033. (cinfo)->err->msg_parm.i[1] = (p2), \
  168034. (cinfo)->err->msg_parm.i[2] = (p3), \
  168035. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168036. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168037. ((cinfo)->err->msg_code = (code), \
  168038. (cinfo)->err->msg_parm.i[0] = (p1), \
  168039. (cinfo)->err->msg_parm.i[1] = (p2), \
  168040. (cinfo)->err->msg_parm.i[2] = (p3), \
  168041. (cinfo)->err->msg_parm.i[3] = (p4), \
  168042. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168043. #define ERREXITS(cinfo,code,str) \
  168044. ((cinfo)->err->msg_code = (code), \
  168045. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168046. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168047. #define MAKESTMT(stuff) do { stuff } while (0)
  168048. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168049. #define WARNMS(cinfo,code) \
  168050. ((cinfo)->err->msg_code = (code), \
  168051. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168052. #define WARNMS1(cinfo,code,p1) \
  168053. ((cinfo)->err->msg_code = (code), \
  168054. (cinfo)->err->msg_parm.i[0] = (p1), \
  168055. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168056. #define WARNMS2(cinfo,code,p1,p2) \
  168057. ((cinfo)->err->msg_code = (code), \
  168058. (cinfo)->err->msg_parm.i[0] = (p1), \
  168059. (cinfo)->err->msg_parm.i[1] = (p2), \
  168060. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168061. /* Informational/debugging messages */
  168062. #define TRACEMS(cinfo,lvl,code) \
  168063. ((cinfo)->err->msg_code = (code), \
  168064. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168065. #define TRACEMS1(cinfo,lvl,code,p1) \
  168066. ((cinfo)->err->msg_code = (code), \
  168067. (cinfo)->err->msg_parm.i[0] = (p1), \
  168068. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168069. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168070. ((cinfo)->err->msg_code = (code), \
  168071. (cinfo)->err->msg_parm.i[0] = (p1), \
  168072. (cinfo)->err->msg_parm.i[1] = (p2), \
  168073. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168074. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168075. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168076. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168077. (cinfo)->err->msg_code = (code); \
  168078. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168079. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168080. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168081. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168082. (cinfo)->err->msg_code = (code); \
  168083. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168084. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168085. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168086. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168087. _mp[4] = (p5); \
  168088. (cinfo)->err->msg_code = (code); \
  168089. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168090. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168091. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168092. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168093. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168094. (cinfo)->err->msg_code = (code); \
  168095. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168096. #define TRACEMSS(cinfo,lvl,code,str) \
  168097. ((cinfo)->err->msg_code = (code), \
  168098. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168099. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168100. #endif /* JERROR_H */
  168101. /*** End of inlined file: jerror.h ***/
  168102. /* Expanded data source object for stdio input */
  168103. typedef struct {
  168104. struct jpeg_source_mgr pub; /* public fields */
  168105. FILE * infile; /* source stream */
  168106. JOCTET * buffer; /* start of buffer */
  168107. boolean start_of_file; /* have we gotten any data yet? */
  168108. } my_source_mgr;
  168109. typedef my_source_mgr * my_src_ptr;
  168110. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168111. /*
  168112. * Initialize source --- called by jpeg_read_header
  168113. * before any data is actually read.
  168114. */
  168115. METHODDEF(void)
  168116. init_source (j_decompress_ptr cinfo)
  168117. {
  168118. my_src_ptr src = (my_src_ptr) cinfo->src;
  168119. /* We reset the empty-input-file flag for each image,
  168120. * but we don't clear the input buffer.
  168121. * This is correct behavior for reading a series of images from one source.
  168122. */
  168123. src->start_of_file = TRUE;
  168124. }
  168125. /*
  168126. * Fill the input buffer --- called whenever buffer is emptied.
  168127. *
  168128. * In typical applications, this should read fresh data into the buffer
  168129. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168130. * reset the pointer & count to the start of the buffer, and return TRUE
  168131. * indicating that the buffer has been reloaded. It is not necessary to
  168132. * fill the buffer entirely, only to obtain at least one more byte.
  168133. *
  168134. * There is no such thing as an EOF return. If the end of the file has been
  168135. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168136. * the buffer. In most cases, generating a warning message and inserting a
  168137. * fake EOI marker is the best course of action --- this will allow the
  168138. * decompressor to output however much of the image is there. However,
  168139. * the resulting error message is misleading if the real problem is an empty
  168140. * input file, so we handle that case specially.
  168141. *
  168142. * In applications that need to be able to suspend compression due to input
  168143. * not being available yet, a FALSE return indicates that no more data can be
  168144. * obtained right now, but more may be forthcoming later. In this situation,
  168145. * the decompressor will return to its caller (with an indication of the
  168146. * number of scanlines it has read, if any). The application should resume
  168147. * decompression after it has loaded more data into the input buffer. Note
  168148. * that there are substantial restrictions on the use of suspension --- see
  168149. * the documentation.
  168150. *
  168151. * When suspending, the decompressor will back up to a convenient restart point
  168152. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168153. * indicate where the restart point will be if the current call returns FALSE.
  168154. * Data beyond this point must be rescanned after resumption, so move it to
  168155. * the front of the buffer rather than discarding it.
  168156. */
  168157. METHODDEF(boolean)
  168158. fill_input_buffer (j_decompress_ptr cinfo)
  168159. {
  168160. my_src_ptr src = (my_src_ptr) cinfo->src;
  168161. size_t nbytes;
  168162. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168163. if (nbytes <= 0) {
  168164. if (src->start_of_file) /* Treat empty input file as fatal error */
  168165. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168166. WARNMS(cinfo, JWRN_JPEG_EOF);
  168167. /* Insert a fake EOI marker */
  168168. src->buffer[0] = (JOCTET) 0xFF;
  168169. src->buffer[1] = (JOCTET) JPEG_EOI;
  168170. nbytes = 2;
  168171. }
  168172. src->pub.next_input_byte = src->buffer;
  168173. src->pub.bytes_in_buffer = nbytes;
  168174. src->start_of_file = FALSE;
  168175. return TRUE;
  168176. }
  168177. /*
  168178. * Skip data --- used to skip over a potentially large amount of
  168179. * uninteresting data (such as an APPn marker).
  168180. *
  168181. * Writers of suspendable-input applications must note that skip_input_data
  168182. * is not granted the right to give a suspension return. If the skip extends
  168183. * beyond the data currently in the buffer, the buffer can be marked empty so
  168184. * that the next read will cause a fill_input_buffer call that can suspend.
  168185. * Arranging for additional bytes to be discarded before reloading the input
  168186. * buffer is the application writer's problem.
  168187. */
  168188. METHODDEF(void)
  168189. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168190. {
  168191. my_src_ptr src = (my_src_ptr) cinfo->src;
  168192. /* Just a dumb implementation for now. Could use fseek() except
  168193. * it doesn't work on pipes. Not clear that being smart is worth
  168194. * any trouble anyway --- large skips are infrequent.
  168195. */
  168196. if (num_bytes > 0) {
  168197. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168198. num_bytes -= (long) src->pub.bytes_in_buffer;
  168199. (void) fill_input_buffer(cinfo);
  168200. /* note we assume that fill_input_buffer will never return FALSE,
  168201. * so suspension need not be handled.
  168202. */
  168203. }
  168204. src->pub.next_input_byte += (size_t) num_bytes;
  168205. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168206. }
  168207. }
  168208. /*
  168209. * An additional method that can be provided by data source modules is the
  168210. * resync_to_restart method for error recovery in the presence of RST markers.
  168211. * For the moment, this source module just uses the default resync method
  168212. * provided by the JPEG library. That method assumes that no backtracking
  168213. * is possible.
  168214. */
  168215. /*
  168216. * Terminate source --- called by jpeg_finish_decompress
  168217. * after all data has been read. Often a no-op.
  168218. *
  168219. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168220. * application must deal with any cleanup that should happen even
  168221. * for error exit.
  168222. */
  168223. METHODDEF(void)
  168224. term_source (j_decompress_ptr)
  168225. {
  168226. /* no work necessary here */
  168227. }
  168228. /*
  168229. * Prepare for input from a stdio stream.
  168230. * The caller must have already opened the stream, and is responsible
  168231. * for closing it after finishing decompression.
  168232. */
  168233. GLOBAL(void)
  168234. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168235. {
  168236. my_src_ptr src;
  168237. /* The source object and input buffer are made permanent so that a series
  168238. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168239. * only before the first one. (If we discarded the buffer at the end of
  168240. * one image, we'd likely lose the start of the next one.)
  168241. * This makes it unsafe to use this manager and a different source
  168242. * manager serially with the same JPEG object. Caveat programmer.
  168243. */
  168244. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168245. cinfo->src = (struct jpeg_source_mgr *)
  168246. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168247. SIZEOF(my_source_mgr));
  168248. src = (my_src_ptr) cinfo->src;
  168249. src->buffer = (JOCTET *)
  168250. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168251. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168252. }
  168253. src = (my_src_ptr) cinfo->src;
  168254. src->pub.init_source = init_source;
  168255. src->pub.fill_input_buffer = fill_input_buffer;
  168256. src->pub.skip_input_data = skip_input_data;
  168257. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168258. src->pub.term_source = term_source;
  168259. src->infile = infile;
  168260. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168261. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168262. }
  168263. /*** End of inlined file: jdatasrc.c ***/
  168264. /*** Start of inlined file: jdcoefct.c ***/
  168265. #define JPEG_INTERNALS
  168266. /* Block smoothing is only applicable for progressive JPEG, so: */
  168267. #ifndef D_PROGRESSIVE_SUPPORTED
  168268. #undef BLOCK_SMOOTHING_SUPPORTED
  168269. #endif
  168270. /* Private buffer controller object */
  168271. typedef struct {
  168272. struct jpeg_d_coef_controller pub; /* public fields */
  168273. /* These variables keep track of the current location of the input side. */
  168274. /* cinfo->input_iMCU_row is also used for this. */
  168275. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168276. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168277. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168278. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168279. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168280. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168281. * and let the entropy decoder write into that workspace each time.
  168282. * (On 80x86, the workspace is FAR even though it's not really very big;
  168283. * this is to keep the module interfaces unchanged when a large coefficient
  168284. * buffer is necessary.)
  168285. * In multi-pass modes, this array points to the current MCU's blocks
  168286. * within the virtual arrays; it is used only by the input side.
  168287. */
  168288. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168289. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168290. /* In multi-pass modes, we need a virtual block array for each component. */
  168291. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168292. #endif
  168293. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168294. /* When doing block smoothing, we latch coefficient Al values here */
  168295. int * coef_bits_latch;
  168296. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168297. #endif
  168298. } my_coef_controller3;
  168299. typedef my_coef_controller3 * my_coef_ptr3;
  168300. /* Forward declarations */
  168301. METHODDEF(int) decompress_onepass
  168302. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168303. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168304. METHODDEF(int) decompress_data
  168305. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168306. #endif
  168307. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168308. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168309. METHODDEF(int) decompress_smooth_data
  168310. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168311. #endif
  168312. LOCAL(void)
  168313. start_iMCU_row3 (j_decompress_ptr cinfo)
  168314. /* Reset within-iMCU-row counters for a new row (input side) */
  168315. {
  168316. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168317. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168318. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168319. * But at the bottom of the image, process only what's left.
  168320. */
  168321. if (cinfo->comps_in_scan > 1) {
  168322. coef->MCU_rows_per_iMCU_row = 1;
  168323. } else {
  168324. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168325. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168326. else
  168327. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168328. }
  168329. coef->MCU_ctr = 0;
  168330. coef->MCU_vert_offset = 0;
  168331. }
  168332. /*
  168333. * Initialize for an input processing pass.
  168334. */
  168335. METHODDEF(void)
  168336. start_input_pass (j_decompress_ptr cinfo)
  168337. {
  168338. cinfo->input_iMCU_row = 0;
  168339. start_iMCU_row3(cinfo);
  168340. }
  168341. /*
  168342. * Initialize for an output processing pass.
  168343. */
  168344. METHODDEF(void)
  168345. start_output_pass (j_decompress_ptr cinfo)
  168346. {
  168347. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168348. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168349. /* If multipass, check to see whether to use block smoothing on this pass */
  168350. if (coef->pub.coef_arrays != NULL) {
  168351. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168352. coef->pub.decompress_data = decompress_smooth_data;
  168353. else
  168354. coef->pub.decompress_data = decompress_data;
  168355. }
  168356. #endif
  168357. cinfo->output_iMCU_row = 0;
  168358. }
  168359. /*
  168360. * Decompress and return some data in the single-pass case.
  168361. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168362. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168363. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168364. *
  168365. * NB: output_buf contains a plane for each component in image,
  168366. * which we index according to the component's SOF position.
  168367. */
  168368. METHODDEF(int)
  168369. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168370. {
  168371. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168372. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168373. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168374. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168375. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168376. JSAMPARRAY output_ptr;
  168377. JDIMENSION start_col, output_col;
  168378. jpeg_component_info *compptr;
  168379. inverse_DCT_method_ptr inverse_DCT;
  168380. /* Loop to process as much as one whole iMCU row */
  168381. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168382. yoffset++) {
  168383. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168384. MCU_col_num++) {
  168385. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168386. jzero_far((void FAR *) coef->MCU_buffer[0],
  168387. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168388. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168389. /* Suspension forced; update state counters and exit */
  168390. coef->MCU_vert_offset = yoffset;
  168391. coef->MCU_ctr = MCU_col_num;
  168392. return JPEG_SUSPENDED;
  168393. }
  168394. /* Determine where data should go in output_buf and do the IDCT thing.
  168395. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168396. * incremented past them!). Note the inner loop relies on having
  168397. * allocated the MCU_buffer[] blocks sequentially.
  168398. */
  168399. blkn = 0; /* index of current DCT block within MCU */
  168400. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168401. compptr = cinfo->cur_comp_info[ci];
  168402. /* Don't bother to IDCT an uninteresting component. */
  168403. if (! compptr->component_needed) {
  168404. blkn += compptr->MCU_blocks;
  168405. continue;
  168406. }
  168407. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168408. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168409. : compptr->last_col_width;
  168410. output_ptr = output_buf[compptr->component_index] +
  168411. yoffset * compptr->DCT_scaled_size;
  168412. start_col = MCU_col_num * compptr->MCU_sample_width;
  168413. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168414. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168415. yoffset+yindex < compptr->last_row_height) {
  168416. output_col = start_col;
  168417. for (xindex = 0; xindex < useful_width; xindex++) {
  168418. (*inverse_DCT) (cinfo, compptr,
  168419. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168420. output_ptr, output_col);
  168421. output_col += compptr->DCT_scaled_size;
  168422. }
  168423. }
  168424. blkn += compptr->MCU_width;
  168425. output_ptr += compptr->DCT_scaled_size;
  168426. }
  168427. }
  168428. }
  168429. /* Completed an MCU row, but perhaps not an iMCU row */
  168430. coef->MCU_ctr = 0;
  168431. }
  168432. /* Completed the iMCU row, advance counters for next one */
  168433. cinfo->output_iMCU_row++;
  168434. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168435. start_iMCU_row3(cinfo);
  168436. return JPEG_ROW_COMPLETED;
  168437. }
  168438. /* Completed the scan */
  168439. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168440. return JPEG_SCAN_COMPLETED;
  168441. }
  168442. /*
  168443. * Dummy consume-input routine for single-pass operation.
  168444. */
  168445. METHODDEF(int)
  168446. dummy_consume_data (j_decompress_ptr)
  168447. {
  168448. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168449. }
  168450. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168451. /*
  168452. * Consume input data and store it in the full-image coefficient buffer.
  168453. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168454. * ie, v_samp_factor block rows for each component in the scan.
  168455. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168456. */
  168457. METHODDEF(int)
  168458. consume_data (j_decompress_ptr cinfo)
  168459. {
  168460. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168461. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168462. int blkn, ci, xindex, yindex, yoffset;
  168463. JDIMENSION start_col;
  168464. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168465. JBLOCKROW buffer_ptr;
  168466. jpeg_component_info *compptr;
  168467. /* Align the virtual buffers for the components used in this scan. */
  168468. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168469. compptr = cinfo->cur_comp_info[ci];
  168470. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168471. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168472. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168473. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168474. /* Note: entropy decoder expects buffer to be zeroed,
  168475. * but this is handled automatically by the memory manager
  168476. * because we requested a pre-zeroed array.
  168477. */
  168478. }
  168479. /* Loop to process one whole iMCU row */
  168480. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168481. yoffset++) {
  168482. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168483. MCU_col_num++) {
  168484. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168485. blkn = 0; /* index of current DCT block within MCU */
  168486. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168487. compptr = cinfo->cur_comp_info[ci];
  168488. start_col = MCU_col_num * compptr->MCU_width;
  168489. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168490. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168491. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168492. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168493. }
  168494. }
  168495. }
  168496. /* Try to fetch the MCU. */
  168497. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168498. /* Suspension forced; update state counters and exit */
  168499. coef->MCU_vert_offset = yoffset;
  168500. coef->MCU_ctr = MCU_col_num;
  168501. return JPEG_SUSPENDED;
  168502. }
  168503. }
  168504. /* Completed an MCU row, but perhaps not an iMCU row */
  168505. coef->MCU_ctr = 0;
  168506. }
  168507. /* Completed the iMCU row, advance counters for next one */
  168508. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168509. start_iMCU_row3(cinfo);
  168510. return JPEG_ROW_COMPLETED;
  168511. }
  168512. /* Completed the scan */
  168513. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168514. return JPEG_SCAN_COMPLETED;
  168515. }
  168516. /*
  168517. * Decompress and return some data in the multi-pass case.
  168518. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168519. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168520. *
  168521. * NB: output_buf contains a plane for each component in image.
  168522. */
  168523. METHODDEF(int)
  168524. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168525. {
  168526. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168527. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168528. JDIMENSION block_num;
  168529. int ci, block_row, block_rows;
  168530. JBLOCKARRAY buffer;
  168531. JBLOCKROW buffer_ptr;
  168532. JSAMPARRAY output_ptr;
  168533. JDIMENSION output_col;
  168534. jpeg_component_info *compptr;
  168535. inverse_DCT_method_ptr inverse_DCT;
  168536. /* Force some input to be done if we are getting ahead of the input. */
  168537. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168538. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168539. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168540. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168541. return JPEG_SUSPENDED;
  168542. }
  168543. /* OK, output from the virtual arrays. */
  168544. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168545. ci++, compptr++) {
  168546. /* Don't bother to IDCT an uninteresting component. */
  168547. if (! compptr->component_needed)
  168548. continue;
  168549. /* Align the virtual buffer for this component. */
  168550. buffer = (*cinfo->mem->access_virt_barray)
  168551. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168552. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168553. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168554. /* Count non-dummy DCT block rows in this iMCU row. */
  168555. if (cinfo->output_iMCU_row < last_iMCU_row)
  168556. block_rows = compptr->v_samp_factor;
  168557. else {
  168558. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168559. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168560. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168561. }
  168562. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168563. output_ptr = output_buf[ci];
  168564. /* Loop over all DCT blocks to be processed. */
  168565. for (block_row = 0; block_row < block_rows; block_row++) {
  168566. buffer_ptr = buffer[block_row];
  168567. output_col = 0;
  168568. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168569. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168570. output_ptr, output_col);
  168571. buffer_ptr++;
  168572. output_col += compptr->DCT_scaled_size;
  168573. }
  168574. output_ptr += compptr->DCT_scaled_size;
  168575. }
  168576. }
  168577. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168578. return JPEG_ROW_COMPLETED;
  168579. return JPEG_SCAN_COMPLETED;
  168580. }
  168581. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168582. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168583. /*
  168584. * This code applies interblock smoothing as described by section K.8
  168585. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168586. * the DC values of a DCT block and its 8 neighboring blocks.
  168587. * We apply smoothing only for progressive JPEG decoding, and only if
  168588. * the coefficients it can estimate are not yet known to full precision.
  168589. */
  168590. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168591. #define Q01_POS 1
  168592. #define Q10_POS 8
  168593. #define Q20_POS 16
  168594. #define Q11_POS 9
  168595. #define Q02_POS 2
  168596. /*
  168597. * Determine whether block smoothing is applicable and safe.
  168598. * We also latch the current states of the coef_bits[] entries for the
  168599. * AC coefficients; otherwise, if the input side of the decompressor
  168600. * advances into a new scan, we might think the coefficients are known
  168601. * more accurately than they really are.
  168602. */
  168603. LOCAL(boolean)
  168604. smoothing_ok (j_decompress_ptr cinfo)
  168605. {
  168606. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168607. boolean smoothing_useful = FALSE;
  168608. int ci, coefi;
  168609. jpeg_component_info *compptr;
  168610. JQUANT_TBL * qtable;
  168611. int * coef_bits;
  168612. int * coef_bits_latch;
  168613. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168614. return FALSE;
  168615. /* Allocate latch area if not already done */
  168616. if (coef->coef_bits_latch == NULL)
  168617. coef->coef_bits_latch = (int *)
  168618. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168619. cinfo->num_components *
  168620. (SAVED_COEFS * SIZEOF(int)));
  168621. coef_bits_latch = coef->coef_bits_latch;
  168622. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168623. ci++, compptr++) {
  168624. /* All components' quantization values must already be latched. */
  168625. if ((qtable = compptr->quant_table) == NULL)
  168626. return FALSE;
  168627. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168628. if (qtable->quantval[0] == 0 ||
  168629. qtable->quantval[Q01_POS] == 0 ||
  168630. qtable->quantval[Q10_POS] == 0 ||
  168631. qtable->quantval[Q20_POS] == 0 ||
  168632. qtable->quantval[Q11_POS] == 0 ||
  168633. qtable->quantval[Q02_POS] == 0)
  168634. return FALSE;
  168635. /* DC values must be at least partly known for all components. */
  168636. coef_bits = cinfo->coef_bits[ci];
  168637. if (coef_bits[0] < 0)
  168638. return FALSE;
  168639. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168640. for (coefi = 1; coefi <= 5; coefi++) {
  168641. coef_bits_latch[coefi] = coef_bits[coefi];
  168642. if (coef_bits[coefi] != 0)
  168643. smoothing_useful = TRUE;
  168644. }
  168645. coef_bits_latch += SAVED_COEFS;
  168646. }
  168647. return smoothing_useful;
  168648. }
  168649. /*
  168650. * Variant of decompress_data for use when doing block smoothing.
  168651. */
  168652. METHODDEF(int)
  168653. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168654. {
  168655. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168656. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168657. JDIMENSION block_num, last_block_column;
  168658. int ci, block_row, block_rows, access_rows;
  168659. JBLOCKARRAY buffer;
  168660. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168661. JSAMPARRAY output_ptr;
  168662. JDIMENSION output_col;
  168663. jpeg_component_info *compptr;
  168664. inverse_DCT_method_ptr inverse_DCT;
  168665. boolean first_row, last_row;
  168666. JBLOCK workspace;
  168667. int *coef_bits;
  168668. JQUANT_TBL *quanttbl;
  168669. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168670. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168671. int Al, pred;
  168672. /* Force some input to be done if we are getting ahead of the input. */
  168673. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168674. ! cinfo->inputctl->eoi_reached) {
  168675. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168676. /* If input is working on current scan, we ordinarily want it to
  168677. * have completed the current row. But if input scan is DC,
  168678. * we want it to keep one row ahead so that next block row's DC
  168679. * values are up to date.
  168680. */
  168681. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168682. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168683. break;
  168684. }
  168685. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168686. return JPEG_SUSPENDED;
  168687. }
  168688. /* OK, output from the virtual arrays. */
  168689. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168690. ci++, compptr++) {
  168691. /* Don't bother to IDCT an uninteresting component. */
  168692. if (! compptr->component_needed)
  168693. continue;
  168694. /* Count non-dummy DCT block rows in this iMCU row. */
  168695. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168696. block_rows = compptr->v_samp_factor;
  168697. access_rows = block_rows * 2; /* this and next iMCU row */
  168698. last_row = FALSE;
  168699. } else {
  168700. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168701. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168702. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168703. access_rows = block_rows; /* this iMCU row only */
  168704. last_row = TRUE;
  168705. }
  168706. /* Align the virtual buffer for this component. */
  168707. if (cinfo->output_iMCU_row > 0) {
  168708. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168709. buffer = (*cinfo->mem->access_virt_barray)
  168710. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168711. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168712. (JDIMENSION) access_rows, FALSE);
  168713. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168714. first_row = FALSE;
  168715. } else {
  168716. buffer = (*cinfo->mem->access_virt_barray)
  168717. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168718. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168719. first_row = TRUE;
  168720. }
  168721. /* Fetch component-dependent info */
  168722. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168723. quanttbl = compptr->quant_table;
  168724. Q00 = quanttbl->quantval[0];
  168725. Q01 = quanttbl->quantval[Q01_POS];
  168726. Q10 = quanttbl->quantval[Q10_POS];
  168727. Q20 = quanttbl->quantval[Q20_POS];
  168728. Q11 = quanttbl->quantval[Q11_POS];
  168729. Q02 = quanttbl->quantval[Q02_POS];
  168730. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168731. output_ptr = output_buf[ci];
  168732. /* Loop over all DCT blocks to be processed. */
  168733. for (block_row = 0; block_row < block_rows; block_row++) {
  168734. buffer_ptr = buffer[block_row];
  168735. if (first_row && block_row == 0)
  168736. prev_block_row = buffer_ptr;
  168737. else
  168738. prev_block_row = buffer[block_row-1];
  168739. if (last_row && block_row == block_rows-1)
  168740. next_block_row = buffer_ptr;
  168741. else
  168742. next_block_row = buffer[block_row+1];
  168743. /* We fetch the surrounding DC values using a sliding-register approach.
  168744. * Initialize all nine here so as to do the right thing on narrow pics.
  168745. */
  168746. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168747. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168748. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168749. output_col = 0;
  168750. last_block_column = compptr->width_in_blocks - 1;
  168751. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168752. /* Fetch current DCT block into workspace so we can modify it. */
  168753. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168754. /* Update DC values */
  168755. if (block_num < last_block_column) {
  168756. DC3 = (int) prev_block_row[1][0];
  168757. DC6 = (int) buffer_ptr[1][0];
  168758. DC9 = (int) next_block_row[1][0];
  168759. }
  168760. /* Compute coefficient estimates per K.8.
  168761. * An estimate is applied only if coefficient is still zero,
  168762. * and is not known to be fully accurate.
  168763. */
  168764. /* AC01 */
  168765. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168766. num = 36 * Q00 * (DC4 - DC6);
  168767. if (num >= 0) {
  168768. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168769. if (Al > 0 && pred >= (1<<Al))
  168770. pred = (1<<Al)-1;
  168771. } else {
  168772. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168773. if (Al > 0 && pred >= (1<<Al))
  168774. pred = (1<<Al)-1;
  168775. pred = -pred;
  168776. }
  168777. workspace[1] = (JCOEF) pred;
  168778. }
  168779. /* AC10 */
  168780. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168781. num = 36 * Q00 * (DC2 - DC8);
  168782. if (num >= 0) {
  168783. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168784. if (Al > 0 && pred >= (1<<Al))
  168785. pred = (1<<Al)-1;
  168786. } else {
  168787. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168788. if (Al > 0 && pred >= (1<<Al))
  168789. pred = (1<<Al)-1;
  168790. pred = -pred;
  168791. }
  168792. workspace[8] = (JCOEF) pred;
  168793. }
  168794. /* AC20 */
  168795. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168796. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168797. if (num >= 0) {
  168798. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168799. if (Al > 0 && pred >= (1<<Al))
  168800. pred = (1<<Al)-1;
  168801. } else {
  168802. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168803. if (Al > 0 && pred >= (1<<Al))
  168804. pred = (1<<Al)-1;
  168805. pred = -pred;
  168806. }
  168807. workspace[16] = (JCOEF) pred;
  168808. }
  168809. /* AC11 */
  168810. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168811. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168812. if (num >= 0) {
  168813. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168814. if (Al > 0 && pred >= (1<<Al))
  168815. pred = (1<<Al)-1;
  168816. } else {
  168817. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168818. if (Al > 0 && pred >= (1<<Al))
  168819. pred = (1<<Al)-1;
  168820. pred = -pred;
  168821. }
  168822. workspace[9] = (JCOEF) pred;
  168823. }
  168824. /* AC02 */
  168825. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168826. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168827. if (num >= 0) {
  168828. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168829. if (Al > 0 && pred >= (1<<Al))
  168830. pred = (1<<Al)-1;
  168831. } else {
  168832. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168833. if (Al > 0 && pred >= (1<<Al))
  168834. pred = (1<<Al)-1;
  168835. pred = -pred;
  168836. }
  168837. workspace[2] = (JCOEF) pred;
  168838. }
  168839. /* OK, do the IDCT */
  168840. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168841. output_ptr, output_col);
  168842. /* Advance for next column */
  168843. DC1 = DC2; DC2 = DC3;
  168844. DC4 = DC5; DC5 = DC6;
  168845. DC7 = DC8; DC8 = DC9;
  168846. buffer_ptr++, prev_block_row++, next_block_row++;
  168847. output_col += compptr->DCT_scaled_size;
  168848. }
  168849. output_ptr += compptr->DCT_scaled_size;
  168850. }
  168851. }
  168852. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168853. return JPEG_ROW_COMPLETED;
  168854. return JPEG_SCAN_COMPLETED;
  168855. }
  168856. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168857. /*
  168858. * Initialize coefficient buffer controller.
  168859. */
  168860. GLOBAL(void)
  168861. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168862. {
  168863. my_coef_ptr3 coef;
  168864. coef = (my_coef_ptr3)
  168865. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168866. SIZEOF(my_coef_controller3));
  168867. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168868. coef->pub.start_input_pass = start_input_pass;
  168869. coef->pub.start_output_pass = start_output_pass;
  168870. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168871. coef->coef_bits_latch = NULL;
  168872. #endif
  168873. /* Create the coefficient buffer. */
  168874. if (need_full_buffer) {
  168875. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168876. /* Allocate a full-image virtual array for each component, */
  168877. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168878. /* Note we ask for a pre-zeroed array. */
  168879. int ci, access_rows;
  168880. jpeg_component_info *compptr;
  168881. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168882. ci++, compptr++) {
  168883. access_rows = compptr->v_samp_factor;
  168884. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168885. /* If block smoothing could be used, need a bigger window */
  168886. if (cinfo->progressive_mode)
  168887. access_rows *= 3;
  168888. #endif
  168889. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168890. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168891. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168892. (long) compptr->h_samp_factor),
  168893. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168894. (long) compptr->v_samp_factor),
  168895. (JDIMENSION) access_rows);
  168896. }
  168897. coef->pub.consume_data = consume_data;
  168898. coef->pub.decompress_data = decompress_data;
  168899. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168900. #else
  168901. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168902. #endif
  168903. } else {
  168904. /* We only need a single-MCU buffer. */
  168905. JBLOCKROW buffer;
  168906. int i;
  168907. buffer = (JBLOCKROW)
  168908. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168909. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168910. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168911. coef->MCU_buffer[i] = buffer + i;
  168912. }
  168913. coef->pub.consume_data = dummy_consume_data;
  168914. coef->pub.decompress_data = decompress_onepass;
  168915. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168916. }
  168917. }
  168918. /*** End of inlined file: jdcoefct.c ***/
  168919. #undef FIX
  168920. /*** Start of inlined file: jdcolor.c ***/
  168921. #define JPEG_INTERNALS
  168922. /* Private subobject */
  168923. typedef struct {
  168924. struct jpeg_color_deconverter pub; /* public fields */
  168925. /* Private state for YCC->RGB conversion */
  168926. int * Cr_r_tab; /* => table for Cr to R conversion */
  168927. int * Cb_b_tab; /* => table for Cb to B conversion */
  168928. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168929. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168930. } my_color_deconverter2;
  168931. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168932. /**************** YCbCr -> RGB conversion: most common case **************/
  168933. /*
  168934. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168935. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168936. * The conversion equations to be implemented are therefore
  168937. * R = Y + 1.40200 * Cr
  168938. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168939. * B = Y + 1.77200 * Cb
  168940. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168941. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168942. *
  168943. * To avoid floating-point arithmetic, we represent the fractional constants
  168944. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168945. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168946. * Notice that Y, being an integral input, does not contribute any fraction
  168947. * so it need not participate in the rounding.
  168948. *
  168949. * For even more speed, we avoid doing any multiplications in the inner loop
  168950. * by precalculating the constants times Cb and Cr for all possible values.
  168951. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168952. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168953. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168954. * colorspace anyway.
  168955. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168956. * values for the G calculation are left scaled up, since we must add them
  168957. * together before rounding.
  168958. */
  168959. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168960. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168961. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168962. /*
  168963. * Initialize tables for YCC->RGB colorspace conversion.
  168964. */
  168965. LOCAL(void)
  168966. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168967. {
  168968. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168969. int i;
  168970. INT32 x;
  168971. SHIFT_TEMPS
  168972. cconvert->Cr_r_tab = (int *)
  168973. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168974. (MAXJSAMPLE+1) * SIZEOF(int));
  168975. cconvert->Cb_b_tab = (int *)
  168976. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168977. (MAXJSAMPLE+1) * SIZEOF(int));
  168978. cconvert->Cr_g_tab = (INT32 *)
  168979. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168980. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168981. cconvert->Cb_g_tab = (INT32 *)
  168982. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168983. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168984. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168985. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168986. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168987. /* Cr=>R value is nearest int to 1.40200 * x */
  168988. cconvert->Cr_r_tab[i] = (int)
  168989. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168990. /* Cb=>B value is nearest int to 1.77200 * x */
  168991. cconvert->Cb_b_tab[i] = (int)
  168992. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168993. /* Cr=>G value is scaled-up -0.71414 * x */
  168994. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168995. /* Cb=>G value is scaled-up -0.34414 * x */
  168996. /* We also add in ONE_HALF so that need not do it in inner loop */
  168997. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168998. }
  168999. }
  169000. /*
  169001. * Convert some rows of samples to the output colorspace.
  169002. *
  169003. * Note that we change from noninterleaved, one-plane-per-component format
  169004. * to interleaved-pixel format. The output buffer is therefore three times
  169005. * as wide as the input buffer.
  169006. * A starting row offset is provided only for the input buffer. The caller
  169007. * can easily adjust the passed output_buf value to accommodate any row
  169008. * offset required on that side.
  169009. */
  169010. METHODDEF(void)
  169011. ycc_rgb_convert (j_decompress_ptr cinfo,
  169012. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169013. JSAMPARRAY output_buf, int num_rows)
  169014. {
  169015. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169016. register int y, cb, cr;
  169017. register JSAMPROW outptr;
  169018. register JSAMPROW inptr0, inptr1, inptr2;
  169019. register JDIMENSION col;
  169020. JDIMENSION num_cols = cinfo->output_width;
  169021. /* copy these pointers into registers if possible */
  169022. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169023. register int * Crrtab = cconvert->Cr_r_tab;
  169024. register int * Cbbtab = cconvert->Cb_b_tab;
  169025. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169026. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169027. SHIFT_TEMPS
  169028. while (--num_rows >= 0) {
  169029. inptr0 = input_buf[0][input_row];
  169030. inptr1 = input_buf[1][input_row];
  169031. inptr2 = input_buf[2][input_row];
  169032. input_row++;
  169033. outptr = *output_buf++;
  169034. for (col = 0; col < num_cols; col++) {
  169035. y = GETJSAMPLE(inptr0[col]);
  169036. cb = GETJSAMPLE(inptr1[col]);
  169037. cr = GETJSAMPLE(inptr2[col]);
  169038. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169039. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169040. outptr[RGB_GREEN] = range_limit[y +
  169041. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169042. SCALEBITS))];
  169043. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169044. outptr += RGB_PIXELSIZE;
  169045. }
  169046. }
  169047. }
  169048. /**************** Cases other than YCbCr -> RGB **************/
  169049. /*
  169050. * Color conversion for no colorspace change: just copy the data,
  169051. * converting from separate-planes to interleaved representation.
  169052. */
  169053. METHODDEF(void)
  169054. null_convert2 (j_decompress_ptr cinfo,
  169055. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169056. JSAMPARRAY output_buf, int num_rows)
  169057. {
  169058. register JSAMPROW inptr, outptr;
  169059. register JDIMENSION count;
  169060. register int num_components = cinfo->num_components;
  169061. JDIMENSION num_cols = cinfo->output_width;
  169062. int ci;
  169063. while (--num_rows >= 0) {
  169064. for (ci = 0; ci < num_components; ci++) {
  169065. inptr = input_buf[ci][input_row];
  169066. outptr = output_buf[0] + ci;
  169067. for (count = num_cols; count > 0; count--) {
  169068. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169069. outptr += num_components;
  169070. }
  169071. }
  169072. input_row++;
  169073. output_buf++;
  169074. }
  169075. }
  169076. /*
  169077. * Color conversion for grayscale: just copy the data.
  169078. * This also works for YCbCr -> grayscale conversion, in which
  169079. * we just copy the Y (luminance) component and ignore chrominance.
  169080. */
  169081. METHODDEF(void)
  169082. grayscale_convert2 (j_decompress_ptr cinfo,
  169083. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169084. JSAMPARRAY output_buf, int num_rows)
  169085. {
  169086. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169087. num_rows, cinfo->output_width);
  169088. }
  169089. /*
  169090. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169091. * This is provided to support applications that don't want to cope
  169092. * with grayscale as a separate case.
  169093. */
  169094. METHODDEF(void)
  169095. gray_rgb_convert (j_decompress_ptr cinfo,
  169096. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169097. JSAMPARRAY output_buf, int num_rows)
  169098. {
  169099. register JSAMPROW inptr, outptr;
  169100. register JDIMENSION col;
  169101. JDIMENSION num_cols = cinfo->output_width;
  169102. while (--num_rows >= 0) {
  169103. inptr = input_buf[0][input_row++];
  169104. outptr = *output_buf++;
  169105. for (col = 0; col < num_cols; col++) {
  169106. /* We can dispense with GETJSAMPLE() here */
  169107. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169108. outptr += RGB_PIXELSIZE;
  169109. }
  169110. }
  169111. }
  169112. /*
  169113. * Adobe-style YCCK->CMYK conversion.
  169114. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169115. * conversion as above, while passing K (black) unchanged.
  169116. * We assume build_ycc_rgb_table has been called.
  169117. */
  169118. METHODDEF(void)
  169119. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169120. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169121. JSAMPARRAY output_buf, int num_rows)
  169122. {
  169123. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169124. register int y, cb, cr;
  169125. register JSAMPROW outptr;
  169126. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169127. register JDIMENSION col;
  169128. JDIMENSION num_cols = cinfo->output_width;
  169129. /* copy these pointers into registers if possible */
  169130. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169131. register int * Crrtab = cconvert->Cr_r_tab;
  169132. register int * Cbbtab = cconvert->Cb_b_tab;
  169133. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169134. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169135. SHIFT_TEMPS
  169136. while (--num_rows >= 0) {
  169137. inptr0 = input_buf[0][input_row];
  169138. inptr1 = input_buf[1][input_row];
  169139. inptr2 = input_buf[2][input_row];
  169140. inptr3 = input_buf[3][input_row];
  169141. input_row++;
  169142. outptr = *output_buf++;
  169143. for (col = 0; col < num_cols; col++) {
  169144. y = GETJSAMPLE(inptr0[col]);
  169145. cb = GETJSAMPLE(inptr1[col]);
  169146. cr = GETJSAMPLE(inptr2[col]);
  169147. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169148. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169149. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169150. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169151. SCALEBITS)))];
  169152. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169153. /* K passes through unchanged */
  169154. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169155. outptr += 4;
  169156. }
  169157. }
  169158. }
  169159. /*
  169160. * Empty method for start_pass.
  169161. */
  169162. METHODDEF(void)
  169163. start_pass_dcolor (j_decompress_ptr)
  169164. {
  169165. /* no work needed */
  169166. }
  169167. /*
  169168. * Module initialization routine for output colorspace conversion.
  169169. */
  169170. GLOBAL(void)
  169171. jinit_color_deconverter (j_decompress_ptr cinfo)
  169172. {
  169173. my_cconvert_ptr2 cconvert;
  169174. int ci;
  169175. cconvert = (my_cconvert_ptr2)
  169176. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169177. SIZEOF(my_color_deconverter2));
  169178. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169179. cconvert->pub.start_pass = start_pass_dcolor;
  169180. /* Make sure num_components agrees with jpeg_color_space */
  169181. switch (cinfo->jpeg_color_space) {
  169182. case JCS_GRAYSCALE:
  169183. if (cinfo->num_components != 1)
  169184. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169185. break;
  169186. case JCS_RGB:
  169187. case JCS_YCbCr:
  169188. if (cinfo->num_components != 3)
  169189. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169190. break;
  169191. case JCS_CMYK:
  169192. case JCS_YCCK:
  169193. if (cinfo->num_components != 4)
  169194. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169195. break;
  169196. default: /* JCS_UNKNOWN can be anything */
  169197. if (cinfo->num_components < 1)
  169198. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169199. break;
  169200. }
  169201. /* Set out_color_components and conversion method based on requested space.
  169202. * Also clear the component_needed flags for any unused components,
  169203. * so that earlier pipeline stages can avoid useless computation.
  169204. */
  169205. switch (cinfo->out_color_space) {
  169206. case JCS_GRAYSCALE:
  169207. cinfo->out_color_components = 1;
  169208. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169209. cinfo->jpeg_color_space == JCS_YCbCr) {
  169210. cconvert->pub.color_convert = grayscale_convert2;
  169211. /* For color->grayscale conversion, only the Y (0) component is needed */
  169212. for (ci = 1; ci < cinfo->num_components; ci++)
  169213. cinfo->comp_info[ci].component_needed = FALSE;
  169214. } else
  169215. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169216. break;
  169217. case JCS_RGB:
  169218. cinfo->out_color_components = RGB_PIXELSIZE;
  169219. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169220. cconvert->pub.color_convert = ycc_rgb_convert;
  169221. build_ycc_rgb_table(cinfo);
  169222. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169223. cconvert->pub.color_convert = gray_rgb_convert;
  169224. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169225. cconvert->pub.color_convert = null_convert2;
  169226. } else
  169227. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169228. break;
  169229. case JCS_CMYK:
  169230. cinfo->out_color_components = 4;
  169231. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169232. cconvert->pub.color_convert = ycck_cmyk_convert;
  169233. build_ycc_rgb_table(cinfo);
  169234. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169235. cconvert->pub.color_convert = null_convert2;
  169236. } else
  169237. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169238. break;
  169239. default:
  169240. /* Permit null conversion to same output space */
  169241. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169242. cinfo->out_color_components = cinfo->num_components;
  169243. cconvert->pub.color_convert = null_convert2;
  169244. } else /* unsupported non-null conversion */
  169245. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169246. break;
  169247. }
  169248. if (cinfo->quantize_colors)
  169249. cinfo->output_components = 1; /* single colormapped output component */
  169250. else
  169251. cinfo->output_components = cinfo->out_color_components;
  169252. }
  169253. /*** End of inlined file: jdcolor.c ***/
  169254. #undef FIX
  169255. /*** Start of inlined file: jddctmgr.c ***/
  169256. #define JPEG_INTERNALS
  169257. /*
  169258. * The decompressor input side (jdinput.c) saves away the appropriate
  169259. * quantization table for each component at the start of the first scan
  169260. * involving that component. (This is necessary in order to correctly
  169261. * decode files that reuse Q-table slots.)
  169262. * When we are ready to make an output pass, the saved Q-table is converted
  169263. * to a multiplier table that will actually be used by the IDCT routine.
  169264. * The multiplier table contents are IDCT-method-dependent. To support
  169265. * application changes in IDCT method between scans, we can remake the
  169266. * multiplier tables if necessary.
  169267. * In buffered-image mode, the first output pass may occur before any data
  169268. * has been seen for some components, and thus before their Q-tables have
  169269. * been saved away. To handle this case, multiplier tables are preset
  169270. * to zeroes; the result of the IDCT will be a neutral gray level.
  169271. */
  169272. /* Private subobject for this module */
  169273. typedef struct {
  169274. struct jpeg_inverse_dct pub; /* public fields */
  169275. /* This array contains the IDCT method code that each multiplier table
  169276. * is currently set up for, or -1 if it's not yet set up.
  169277. * The actual multiplier tables are pointed to by dct_table in the
  169278. * per-component comp_info structures.
  169279. */
  169280. int cur_method[MAX_COMPONENTS];
  169281. } my_idct_controller;
  169282. typedef my_idct_controller * my_idct_ptr;
  169283. /* Allocated multiplier tables: big enough for any supported variant */
  169284. typedef union {
  169285. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169286. #ifdef DCT_IFAST_SUPPORTED
  169287. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169288. #endif
  169289. #ifdef DCT_FLOAT_SUPPORTED
  169290. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169291. #endif
  169292. } multiplier_table;
  169293. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169294. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169295. */
  169296. #ifdef DCT_ISLOW_SUPPORTED
  169297. #define PROVIDE_ISLOW_TABLES
  169298. #else
  169299. #ifdef IDCT_SCALING_SUPPORTED
  169300. #define PROVIDE_ISLOW_TABLES
  169301. #endif
  169302. #endif
  169303. /*
  169304. * Prepare for an output pass.
  169305. * Here we select the proper IDCT routine for each component and build
  169306. * a matching multiplier table.
  169307. */
  169308. METHODDEF(void)
  169309. start_pass (j_decompress_ptr cinfo)
  169310. {
  169311. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169312. int ci, i;
  169313. jpeg_component_info *compptr;
  169314. int method = 0;
  169315. inverse_DCT_method_ptr method_ptr = NULL;
  169316. JQUANT_TBL * qtbl;
  169317. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169318. ci++, compptr++) {
  169319. /* Select the proper IDCT routine for this component's scaling */
  169320. switch (compptr->DCT_scaled_size) {
  169321. #ifdef IDCT_SCALING_SUPPORTED
  169322. case 1:
  169323. method_ptr = jpeg_idct_1x1;
  169324. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169325. break;
  169326. case 2:
  169327. method_ptr = jpeg_idct_2x2;
  169328. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169329. break;
  169330. case 4:
  169331. method_ptr = jpeg_idct_4x4;
  169332. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169333. break;
  169334. #endif
  169335. case DCTSIZE:
  169336. switch (cinfo->dct_method) {
  169337. #ifdef DCT_ISLOW_SUPPORTED
  169338. case JDCT_ISLOW:
  169339. method_ptr = jpeg_idct_islow;
  169340. method = JDCT_ISLOW;
  169341. break;
  169342. #endif
  169343. #ifdef DCT_IFAST_SUPPORTED
  169344. case JDCT_IFAST:
  169345. method_ptr = jpeg_idct_ifast;
  169346. method = JDCT_IFAST;
  169347. break;
  169348. #endif
  169349. #ifdef DCT_FLOAT_SUPPORTED
  169350. case JDCT_FLOAT:
  169351. method_ptr = jpeg_idct_float;
  169352. method = JDCT_FLOAT;
  169353. break;
  169354. #endif
  169355. default:
  169356. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169357. break;
  169358. }
  169359. break;
  169360. default:
  169361. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169362. break;
  169363. }
  169364. idct->pub.inverse_DCT[ci] = method_ptr;
  169365. /* Create multiplier table from quant table.
  169366. * However, we can skip this if the component is uninteresting
  169367. * or if we already built the table. Also, if no quant table
  169368. * has yet been saved for the component, we leave the
  169369. * multiplier table all-zero; we'll be reading zeroes from the
  169370. * coefficient controller's buffer anyway.
  169371. */
  169372. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169373. continue;
  169374. qtbl = compptr->quant_table;
  169375. if (qtbl == NULL) /* happens if no data yet for component */
  169376. continue;
  169377. idct->cur_method[ci] = method;
  169378. switch (method) {
  169379. #ifdef PROVIDE_ISLOW_TABLES
  169380. case JDCT_ISLOW:
  169381. {
  169382. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169383. * coefficients, but are stored as ints to ensure access efficiency.
  169384. */
  169385. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169386. for (i = 0; i < DCTSIZE2; i++) {
  169387. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169388. }
  169389. }
  169390. break;
  169391. #endif
  169392. #ifdef DCT_IFAST_SUPPORTED
  169393. case JDCT_IFAST:
  169394. {
  169395. /* For AA&N IDCT method, multipliers are equal to quantization
  169396. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169397. * scalefactor[0] = 1
  169398. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169399. * For integer operation, the multiplier table is to be scaled by
  169400. * IFAST_SCALE_BITS.
  169401. */
  169402. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169403. #define CONST_BITS 14
  169404. static const INT16 aanscales[DCTSIZE2] = {
  169405. /* precomputed values scaled up by 14 bits */
  169406. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169407. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169408. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169409. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169410. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169411. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169412. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169413. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169414. };
  169415. SHIFT_TEMPS
  169416. for (i = 0; i < DCTSIZE2; i++) {
  169417. ifmtbl[i] = (IFAST_MULT_TYPE)
  169418. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169419. (INT32) aanscales[i]),
  169420. CONST_BITS-IFAST_SCALE_BITS);
  169421. }
  169422. }
  169423. break;
  169424. #endif
  169425. #ifdef DCT_FLOAT_SUPPORTED
  169426. case JDCT_FLOAT:
  169427. {
  169428. /* For float AA&N IDCT method, multipliers are equal to quantization
  169429. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169430. * scalefactor[0] = 1
  169431. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169432. */
  169433. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169434. int row, col;
  169435. static const double aanscalefactor[DCTSIZE] = {
  169436. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169437. 1.0, 0.785694958, 0.541196100, 0.275899379
  169438. };
  169439. i = 0;
  169440. for (row = 0; row < DCTSIZE; row++) {
  169441. for (col = 0; col < DCTSIZE; col++) {
  169442. fmtbl[i] = (FLOAT_MULT_TYPE)
  169443. ((double) qtbl->quantval[i] *
  169444. aanscalefactor[row] * aanscalefactor[col]);
  169445. i++;
  169446. }
  169447. }
  169448. }
  169449. break;
  169450. #endif
  169451. default:
  169452. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169453. break;
  169454. }
  169455. }
  169456. }
  169457. /*
  169458. * Initialize IDCT manager.
  169459. */
  169460. GLOBAL(void)
  169461. jinit_inverse_dct (j_decompress_ptr cinfo)
  169462. {
  169463. my_idct_ptr idct;
  169464. int ci;
  169465. jpeg_component_info *compptr;
  169466. idct = (my_idct_ptr)
  169467. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169468. SIZEOF(my_idct_controller));
  169469. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169470. idct->pub.start_pass = start_pass;
  169471. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169472. ci++, compptr++) {
  169473. /* Allocate and pre-zero a multiplier table for each component */
  169474. compptr->dct_table =
  169475. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169476. SIZEOF(multiplier_table));
  169477. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169478. /* Mark multiplier table not yet set up for any method */
  169479. idct->cur_method[ci] = -1;
  169480. }
  169481. }
  169482. /*** End of inlined file: jddctmgr.c ***/
  169483. #undef CONST_BITS
  169484. #undef ASSIGN_STATE
  169485. /*** Start of inlined file: jdhuff.c ***/
  169486. #define JPEG_INTERNALS
  169487. /*** Start of inlined file: jdhuff.h ***/
  169488. /* Short forms of external names for systems with brain-damaged linkers. */
  169489. #ifndef __jdhuff_h__
  169490. #define __jdhuff_h__
  169491. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169492. #define jpeg_make_d_derived_tbl jMkDDerived
  169493. #define jpeg_fill_bit_buffer jFilBitBuf
  169494. #define jpeg_huff_decode jHufDecode
  169495. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169496. /* Derived data constructed for each Huffman table */
  169497. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169498. typedef struct {
  169499. /* Basic tables: (element [0] of each array is unused) */
  169500. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169501. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169502. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169503. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169504. * the smallest code of length k; so given a code of length k, the
  169505. * corresponding symbol is huffval[code + valoffset[k]]
  169506. */
  169507. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169508. JHUFF_TBL *pub;
  169509. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169510. * the input data stream. If the next Huffman code is no more
  169511. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169512. * the corresponding symbol directly from these tables.
  169513. */
  169514. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169515. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169516. } d_derived_tbl;
  169517. /* Expand a Huffman table definition into the derived format */
  169518. EXTERN(void) jpeg_make_d_derived_tbl
  169519. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169520. d_derived_tbl ** pdtbl));
  169521. /*
  169522. * Fetching the next N bits from the input stream is a time-critical operation
  169523. * for the Huffman decoders. We implement it with a combination of inline
  169524. * macros and out-of-line subroutines. Note that N (the number of bits
  169525. * demanded at one time) never exceeds 15 for JPEG use.
  169526. *
  169527. * We read source bytes into get_buffer and dole out bits as needed.
  169528. * If get_buffer already contains enough bits, they are fetched in-line
  169529. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169530. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169531. * as full as possible (not just to the number of bits needed; this
  169532. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169533. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169534. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169535. * at least the requested number of bits --- dummy zeroes are inserted if
  169536. * necessary.
  169537. */
  169538. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169539. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169540. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169541. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169542. * appropriately should be a win. Unfortunately we can't define the size
  169543. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169544. * because not all machines measure sizeof in 8-bit bytes.
  169545. */
  169546. typedef struct { /* Bitreading state saved across MCUs */
  169547. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169548. int bits_left; /* # of unused bits in it */
  169549. } bitread_perm_state;
  169550. typedef struct { /* Bitreading working state within an MCU */
  169551. /* Current data source location */
  169552. /* We need a copy, rather than munging the original, in case of suspension */
  169553. const JOCTET * next_input_byte; /* => next byte to read from source */
  169554. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169555. /* Bit input buffer --- note these values are kept in register variables,
  169556. * not in this struct, inside the inner loops.
  169557. */
  169558. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169559. int bits_left; /* # of unused bits in it */
  169560. /* Pointer needed by jpeg_fill_bit_buffer. */
  169561. j_decompress_ptr cinfo; /* back link to decompress master record */
  169562. } bitread_working_state;
  169563. /* Macros to declare and load/save bitread local variables. */
  169564. #define BITREAD_STATE_VARS \
  169565. register bit_buf_type get_buffer; \
  169566. register int bits_left; \
  169567. bitread_working_state br_state
  169568. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169569. br_state.cinfo = cinfop; \
  169570. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169571. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169572. get_buffer = permstate.get_buffer; \
  169573. bits_left = permstate.bits_left;
  169574. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169575. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169576. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169577. permstate.get_buffer = get_buffer; \
  169578. permstate.bits_left = bits_left
  169579. /*
  169580. * These macros provide the in-line portion of bit fetching.
  169581. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169582. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169583. * The variables get_buffer and bits_left are assumed to be locals,
  169584. * but the state struct might not be (jpeg_huff_decode needs this).
  169585. * CHECK_BIT_BUFFER(state,n,action);
  169586. * Ensure there are N bits in get_buffer; if suspend, take action.
  169587. * val = GET_BITS(n);
  169588. * Fetch next N bits.
  169589. * val = PEEK_BITS(n);
  169590. * Fetch next N bits without removing them from the buffer.
  169591. * DROP_BITS(n);
  169592. * Discard next N bits.
  169593. * The value N should be a simple variable, not an expression, because it
  169594. * is evaluated multiple times.
  169595. */
  169596. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169597. { if (bits_left < (nbits)) { \
  169598. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169599. { action; } \
  169600. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169601. #define GET_BITS(nbits) \
  169602. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169603. #define PEEK_BITS(nbits) \
  169604. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169605. #define DROP_BITS(nbits) \
  169606. (bits_left -= (nbits))
  169607. /* Load up the bit buffer to a depth of at least nbits */
  169608. EXTERN(boolean) jpeg_fill_bit_buffer
  169609. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169610. register int bits_left, int nbits));
  169611. /*
  169612. * Code for extracting next Huffman-coded symbol from input bit stream.
  169613. * Again, this is time-critical and we make the main paths be macros.
  169614. *
  169615. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169616. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169617. * or fewer bits long. The few overlength codes are handled with a loop,
  169618. * which need not be inline code.
  169619. *
  169620. * Notes about the HUFF_DECODE macro:
  169621. * 1. Near the end of the data segment, we may fail to get enough bits
  169622. * for a lookahead. In that case, we do it the hard way.
  169623. * 2. If the lookahead table contains no entry, the next code must be
  169624. * more than HUFF_LOOKAHEAD bits long.
  169625. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169626. */
  169627. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169628. { register int nb, look; \
  169629. if (bits_left < HUFF_LOOKAHEAD) { \
  169630. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169631. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169632. if (bits_left < HUFF_LOOKAHEAD) { \
  169633. nb = 1; goto slowlabel; \
  169634. } \
  169635. } \
  169636. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169637. if ((nb = htbl->look_nbits[look]) != 0) { \
  169638. DROP_BITS(nb); \
  169639. result = htbl->look_sym[look]; \
  169640. } else { \
  169641. nb = HUFF_LOOKAHEAD+1; \
  169642. slowlabel: \
  169643. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169644. { failaction; } \
  169645. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169646. } \
  169647. }
  169648. /* Out-of-line case for Huffman code fetching */
  169649. EXTERN(int) jpeg_huff_decode
  169650. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169651. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169652. #endif
  169653. /*** End of inlined file: jdhuff.h ***/
  169654. /* Declarations shared with jdphuff.c */
  169655. /*
  169656. * Expanded entropy decoder object for Huffman decoding.
  169657. *
  169658. * The savable_state subrecord contains fields that change within an MCU,
  169659. * but must not be updated permanently until we complete the MCU.
  169660. */
  169661. typedef struct {
  169662. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169663. } savable_state2;
  169664. /* This macro is to work around compilers with missing or broken
  169665. * structure assignment. You'll need to fix this code if you have
  169666. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169667. */
  169668. #ifndef NO_STRUCT_ASSIGN
  169669. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169670. #else
  169671. #if MAX_COMPS_IN_SCAN == 4
  169672. #define ASSIGN_STATE(dest,src) \
  169673. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169674. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169675. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169676. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169677. #endif
  169678. #endif
  169679. typedef struct {
  169680. struct jpeg_entropy_decoder pub; /* public fields */
  169681. /* These fields are loaded into local variables at start of each MCU.
  169682. * In case of suspension, we exit WITHOUT updating them.
  169683. */
  169684. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169685. savable_state2 saved; /* Other state at start of MCU */
  169686. /* These fields are NOT loaded into local working state. */
  169687. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169688. /* Pointers to derived tables (these workspaces have image lifespan) */
  169689. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169690. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169691. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169692. /* Pointers to derived tables to be used for each block within an MCU */
  169693. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169694. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169695. /* Whether we care about the DC and AC coefficient values for each block */
  169696. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169697. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169698. } huff_entropy_decoder2;
  169699. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169700. /*
  169701. * Initialize for a Huffman-compressed scan.
  169702. */
  169703. METHODDEF(void)
  169704. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169705. {
  169706. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169707. int ci, blkn, dctbl, actbl;
  169708. jpeg_component_info * compptr;
  169709. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169710. * This ought to be an error condition, but we make it a warning because
  169711. * there are some baseline files out there with all zeroes in these bytes.
  169712. */
  169713. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169714. cinfo->Ah != 0 || cinfo->Al != 0)
  169715. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169716. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169717. compptr = cinfo->cur_comp_info[ci];
  169718. dctbl = compptr->dc_tbl_no;
  169719. actbl = compptr->ac_tbl_no;
  169720. /* Compute derived values for Huffman tables */
  169721. /* We may do this more than once for a table, but it's not expensive */
  169722. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169723. & entropy->dc_derived_tbls[dctbl]);
  169724. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169725. & entropy->ac_derived_tbls[actbl]);
  169726. /* Initialize DC predictions to 0 */
  169727. entropy->saved.last_dc_val[ci] = 0;
  169728. }
  169729. /* Precalculate decoding info for each block in an MCU of this scan */
  169730. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169731. ci = cinfo->MCU_membership[blkn];
  169732. compptr = cinfo->cur_comp_info[ci];
  169733. /* Precalculate which table to use for each block */
  169734. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169735. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169736. /* Decide whether we really care about the coefficient values */
  169737. if (compptr->component_needed) {
  169738. entropy->dc_needed[blkn] = TRUE;
  169739. /* we don't need the ACs if producing a 1/8th-size image */
  169740. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169741. } else {
  169742. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169743. }
  169744. }
  169745. /* Initialize bitread state variables */
  169746. entropy->bitstate.bits_left = 0;
  169747. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169748. entropy->pub.insufficient_data = FALSE;
  169749. /* Initialize restart counter */
  169750. entropy->restarts_to_go = cinfo->restart_interval;
  169751. }
  169752. /*
  169753. * Compute the derived values for a Huffman table.
  169754. * This routine also performs some validation checks on the table.
  169755. *
  169756. * Note this is also used by jdphuff.c.
  169757. */
  169758. GLOBAL(void)
  169759. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169760. d_derived_tbl ** pdtbl)
  169761. {
  169762. JHUFF_TBL *htbl;
  169763. d_derived_tbl *dtbl;
  169764. int p, i, l, si, numsymbols;
  169765. int lookbits, ctr;
  169766. char huffsize[257];
  169767. unsigned int huffcode[257];
  169768. unsigned int code;
  169769. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169770. * paralleling the order of the symbols themselves in htbl->huffval[].
  169771. */
  169772. /* Find the input Huffman table */
  169773. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169774. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169775. htbl =
  169776. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169777. if (htbl == NULL)
  169778. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169779. /* Allocate a workspace if we haven't already done so. */
  169780. if (*pdtbl == NULL)
  169781. *pdtbl = (d_derived_tbl *)
  169782. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169783. SIZEOF(d_derived_tbl));
  169784. dtbl = *pdtbl;
  169785. dtbl->pub = htbl; /* fill in back link */
  169786. /* Figure C.1: make table of Huffman code length for each symbol */
  169787. p = 0;
  169788. for (l = 1; l <= 16; l++) {
  169789. i = (int) htbl->bits[l];
  169790. if (i < 0 || p + i > 256) /* protect against table overrun */
  169791. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169792. while (i--)
  169793. huffsize[p++] = (char) l;
  169794. }
  169795. huffsize[p] = 0;
  169796. numsymbols = p;
  169797. /* Figure C.2: generate the codes themselves */
  169798. /* We also validate that the counts represent a legal Huffman code tree. */
  169799. code = 0;
  169800. si = huffsize[0];
  169801. p = 0;
  169802. while (huffsize[p]) {
  169803. while (((int) huffsize[p]) == si) {
  169804. huffcode[p++] = code;
  169805. code++;
  169806. }
  169807. /* code is now 1 more than the last code used for codelength si; but
  169808. * it must still fit in si bits, since no code is allowed to be all ones.
  169809. */
  169810. if (((INT32) code) >= (((INT32) 1) << si))
  169811. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169812. code <<= 1;
  169813. si++;
  169814. }
  169815. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169816. p = 0;
  169817. for (l = 1; l <= 16; l++) {
  169818. if (htbl->bits[l]) {
  169819. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169820. * minus the minimum code of length l
  169821. */
  169822. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169823. p += htbl->bits[l];
  169824. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169825. } else {
  169826. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169827. }
  169828. }
  169829. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169830. /* Compute lookahead tables to speed up decoding.
  169831. * First we set all the table entries to 0, indicating "too long";
  169832. * then we iterate through the Huffman codes that are short enough and
  169833. * fill in all the entries that correspond to bit sequences starting
  169834. * with that code.
  169835. */
  169836. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169837. p = 0;
  169838. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169839. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169840. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169841. /* Generate left-justified code followed by all possible bit sequences */
  169842. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169843. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169844. dtbl->look_nbits[lookbits] = l;
  169845. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169846. lookbits++;
  169847. }
  169848. }
  169849. }
  169850. /* Validate symbols as being reasonable.
  169851. * For AC tables, we make no check, but accept all byte values 0..255.
  169852. * For DC tables, we require the symbols to be in range 0..15.
  169853. * (Tighter bounds could be applied depending on the data depth and mode,
  169854. * but this is sufficient to ensure safe decoding.)
  169855. */
  169856. if (isDC) {
  169857. for (i = 0; i < numsymbols; i++) {
  169858. int sym = htbl->huffval[i];
  169859. if (sym < 0 || sym > 15)
  169860. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169861. }
  169862. }
  169863. }
  169864. /*
  169865. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169866. * See jdhuff.h for info about usage.
  169867. * Note: current values of get_buffer and bits_left are passed as parameters,
  169868. * but are returned in the corresponding fields of the state struct.
  169869. *
  169870. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169871. * of get_buffer to be used. (On machines with wider words, an even larger
  169872. * buffer could be used.) However, on some machines 32-bit shifts are
  169873. * quite slow and take time proportional to the number of places shifted.
  169874. * (This is true with most PC compilers, for instance.) In this case it may
  169875. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169876. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169877. */
  169878. #ifdef SLOW_SHIFT_32
  169879. #define MIN_GET_BITS 15 /* minimum allowable value */
  169880. #else
  169881. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169882. #endif
  169883. GLOBAL(boolean)
  169884. jpeg_fill_bit_buffer (bitread_working_state * state,
  169885. register bit_buf_type get_buffer, register int bits_left,
  169886. int nbits)
  169887. /* Load up the bit buffer to a depth of at least nbits */
  169888. {
  169889. /* Copy heavily used state fields into locals (hopefully registers) */
  169890. register const JOCTET * next_input_byte = state->next_input_byte;
  169891. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169892. j_decompress_ptr cinfo = state->cinfo;
  169893. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169894. /* (It is assumed that no request will be for more than that many bits.) */
  169895. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169896. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169897. while (bits_left < MIN_GET_BITS) {
  169898. register int c;
  169899. /* Attempt to read a byte */
  169900. if (bytes_in_buffer == 0) {
  169901. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169902. return FALSE;
  169903. next_input_byte = cinfo->src->next_input_byte;
  169904. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169905. }
  169906. bytes_in_buffer--;
  169907. c = GETJOCTET(*next_input_byte++);
  169908. /* If it's 0xFF, check and discard stuffed zero byte */
  169909. if (c == 0xFF) {
  169910. /* Loop here to discard any padding FF's on terminating marker,
  169911. * so that we can save a valid unread_marker value. NOTE: we will
  169912. * accept multiple FF's followed by a 0 as meaning a single FF data
  169913. * byte. This data pattern is not valid according to the standard.
  169914. */
  169915. do {
  169916. if (bytes_in_buffer == 0) {
  169917. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169918. return FALSE;
  169919. next_input_byte = cinfo->src->next_input_byte;
  169920. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169921. }
  169922. bytes_in_buffer--;
  169923. c = GETJOCTET(*next_input_byte++);
  169924. } while (c == 0xFF);
  169925. if (c == 0) {
  169926. /* Found FF/00, which represents an FF data byte */
  169927. c = 0xFF;
  169928. } else {
  169929. /* Oops, it's actually a marker indicating end of compressed data.
  169930. * Save the marker code for later use.
  169931. * Fine point: it might appear that we should save the marker into
  169932. * bitread working state, not straight into permanent state. But
  169933. * once we have hit a marker, we cannot need to suspend within the
  169934. * current MCU, because we will read no more bytes from the data
  169935. * source. So it is OK to update permanent state right away.
  169936. */
  169937. cinfo->unread_marker = c;
  169938. /* See if we need to insert some fake zero bits. */
  169939. goto no_more_bytes;
  169940. }
  169941. }
  169942. /* OK, load c into get_buffer */
  169943. get_buffer = (get_buffer << 8) | c;
  169944. bits_left += 8;
  169945. } /* end while */
  169946. } else {
  169947. no_more_bytes:
  169948. /* We get here if we've read the marker that terminates the compressed
  169949. * data segment. There should be enough bits in the buffer register
  169950. * to satisfy the request; if so, no problem.
  169951. */
  169952. if (nbits > bits_left) {
  169953. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169954. * the data stream, so that we can produce some kind of image.
  169955. * We use a nonvolatile flag to ensure that only one warning message
  169956. * appears per data segment.
  169957. */
  169958. if (! cinfo->entropy->insufficient_data) {
  169959. WARNMS(cinfo, JWRN_HIT_MARKER);
  169960. cinfo->entropy->insufficient_data = TRUE;
  169961. }
  169962. /* Fill the buffer with zero bits */
  169963. get_buffer <<= MIN_GET_BITS - bits_left;
  169964. bits_left = MIN_GET_BITS;
  169965. }
  169966. }
  169967. /* Unload the local registers */
  169968. state->next_input_byte = next_input_byte;
  169969. state->bytes_in_buffer = bytes_in_buffer;
  169970. state->get_buffer = get_buffer;
  169971. state->bits_left = bits_left;
  169972. return TRUE;
  169973. }
  169974. /*
  169975. * Out-of-line code for Huffman code decoding.
  169976. * See jdhuff.h for info about usage.
  169977. */
  169978. GLOBAL(int)
  169979. jpeg_huff_decode (bitread_working_state * state,
  169980. register bit_buf_type get_buffer, register int bits_left,
  169981. d_derived_tbl * htbl, int min_bits)
  169982. {
  169983. register int l = min_bits;
  169984. register INT32 code;
  169985. /* HUFF_DECODE has determined that the code is at least min_bits */
  169986. /* bits long, so fetch that many bits in one swoop. */
  169987. CHECK_BIT_BUFFER(*state, l, return -1);
  169988. code = GET_BITS(l);
  169989. /* Collect the rest of the Huffman code one bit at a time. */
  169990. /* This is per Figure F.16 in the JPEG spec. */
  169991. while (code > htbl->maxcode[l]) {
  169992. code <<= 1;
  169993. CHECK_BIT_BUFFER(*state, 1, return -1);
  169994. code |= GET_BITS(1);
  169995. l++;
  169996. }
  169997. /* Unload the local registers */
  169998. state->get_buffer = get_buffer;
  169999. state->bits_left = bits_left;
  170000. /* With garbage input we may reach the sentinel value l = 17. */
  170001. if (l > 16) {
  170002. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170003. return 0; /* fake a zero as the safest result */
  170004. }
  170005. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170006. }
  170007. /*
  170008. * Check for a restart marker & resynchronize decoder.
  170009. * Returns FALSE if must suspend.
  170010. */
  170011. LOCAL(boolean)
  170012. process_restart (j_decompress_ptr cinfo)
  170013. {
  170014. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170015. int ci;
  170016. /* Throw away any unused bits remaining in bit buffer; */
  170017. /* include any full bytes in next_marker's count of discarded bytes */
  170018. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170019. entropy->bitstate.bits_left = 0;
  170020. /* Advance past the RSTn marker */
  170021. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170022. return FALSE;
  170023. /* Re-initialize DC predictions to 0 */
  170024. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170025. entropy->saved.last_dc_val[ci] = 0;
  170026. /* Reset restart counter */
  170027. entropy->restarts_to_go = cinfo->restart_interval;
  170028. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170029. * against a marker. In that case we will end up treating the next data
  170030. * segment as empty, and we can avoid producing bogus output pixels by
  170031. * leaving the flag set.
  170032. */
  170033. if (cinfo->unread_marker == 0)
  170034. entropy->pub.insufficient_data = FALSE;
  170035. return TRUE;
  170036. }
  170037. /*
  170038. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170039. * The coefficients are reordered from zigzag order into natural array order,
  170040. * but are not dequantized.
  170041. *
  170042. * The i'th block of the MCU is stored into the block pointed to by
  170043. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170044. * (Wholesale zeroing is usually a little faster than retail...)
  170045. *
  170046. * Returns FALSE if data source requested suspension. In that case no
  170047. * changes have been made to permanent state. (Exception: some output
  170048. * coefficients may already have been assigned. This is harmless for
  170049. * this module, since we'll just re-assign them on the next call.)
  170050. */
  170051. METHODDEF(boolean)
  170052. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170053. {
  170054. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170055. int blkn;
  170056. BITREAD_STATE_VARS;
  170057. savable_state2 state;
  170058. /* Process restart marker if needed; may have to suspend */
  170059. if (cinfo->restart_interval) {
  170060. if (entropy->restarts_to_go == 0)
  170061. if (! process_restart(cinfo))
  170062. return FALSE;
  170063. }
  170064. /* If we've run out of data, just leave the MCU set to zeroes.
  170065. * This way, we return uniform gray for the remainder of the segment.
  170066. */
  170067. if (! entropy->pub.insufficient_data) {
  170068. /* Load up working state */
  170069. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170070. ASSIGN_STATE(state, entropy->saved);
  170071. /* Outer loop handles each block in the MCU */
  170072. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170073. JBLOCKROW block = MCU_data[blkn];
  170074. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170075. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170076. register int s, k, r;
  170077. /* Decode a single block's worth of coefficients */
  170078. /* Section F.2.2.1: decode the DC coefficient difference */
  170079. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170080. if (s) {
  170081. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170082. r = GET_BITS(s);
  170083. s = HUFF_EXTEND(r, s);
  170084. }
  170085. if (entropy->dc_needed[blkn]) {
  170086. /* Convert DC difference to actual value, update last_dc_val */
  170087. int ci = cinfo->MCU_membership[blkn];
  170088. s += state.last_dc_val[ci];
  170089. state.last_dc_val[ci] = s;
  170090. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170091. (*block)[0] = (JCOEF) s;
  170092. }
  170093. if (entropy->ac_needed[blkn]) {
  170094. /* Section F.2.2.2: decode the AC coefficients */
  170095. /* Since zeroes are skipped, output area must be cleared beforehand */
  170096. for (k = 1; k < DCTSIZE2; k++) {
  170097. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170098. r = s >> 4;
  170099. s &= 15;
  170100. if (s) {
  170101. k += r;
  170102. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170103. r = GET_BITS(s);
  170104. s = HUFF_EXTEND(r, s);
  170105. /* Output coefficient in natural (dezigzagged) order.
  170106. * Note: the extra entries in jpeg_natural_order[] will save us
  170107. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170108. */
  170109. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170110. } else {
  170111. if (r != 15)
  170112. break;
  170113. k += 15;
  170114. }
  170115. }
  170116. } else {
  170117. /* Section F.2.2.2: decode the AC coefficients */
  170118. /* In this path we just discard the values */
  170119. for (k = 1; k < DCTSIZE2; k++) {
  170120. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170121. r = s >> 4;
  170122. s &= 15;
  170123. if (s) {
  170124. k += r;
  170125. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170126. DROP_BITS(s);
  170127. } else {
  170128. if (r != 15)
  170129. break;
  170130. k += 15;
  170131. }
  170132. }
  170133. }
  170134. }
  170135. /* Completed MCU, so update state */
  170136. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170137. ASSIGN_STATE(entropy->saved, state);
  170138. }
  170139. /* Account for restart interval (no-op if not using restarts) */
  170140. entropy->restarts_to_go--;
  170141. return TRUE;
  170142. }
  170143. /*
  170144. * Module initialization routine for Huffman entropy decoding.
  170145. */
  170146. GLOBAL(void)
  170147. jinit_huff_decoder (j_decompress_ptr cinfo)
  170148. {
  170149. huff_entropy_ptr2 entropy;
  170150. int i;
  170151. entropy = (huff_entropy_ptr2)
  170152. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170153. SIZEOF(huff_entropy_decoder2));
  170154. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170155. entropy->pub.start_pass = start_pass_huff_decoder;
  170156. entropy->pub.decode_mcu = decode_mcu;
  170157. /* Mark tables unallocated */
  170158. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170159. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170160. }
  170161. }
  170162. /*** End of inlined file: jdhuff.c ***/
  170163. /*** Start of inlined file: jdinput.c ***/
  170164. #define JPEG_INTERNALS
  170165. /* Private state */
  170166. typedef struct {
  170167. struct jpeg_input_controller pub; /* public fields */
  170168. boolean inheaders; /* TRUE until first SOS is reached */
  170169. } my_input_controller;
  170170. typedef my_input_controller * my_inputctl_ptr;
  170171. /* Forward declarations */
  170172. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170173. /*
  170174. * Routines to calculate various quantities related to the size of the image.
  170175. */
  170176. LOCAL(void)
  170177. initial_setup2 (j_decompress_ptr cinfo)
  170178. /* Called once, when first SOS marker is reached */
  170179. {
  170180. int ci;
  170181. jpeg_component_info *compptr;
  170182. /* Make sure image isn't bigger than I can handle */
  170183. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170184. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170185. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170186. /* For now, precision must match compiled-in value... */
  170187. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170188. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170189. /* Check that number of components won't exceed internal array sizes */
  170190. if (cinfo->num_components > MAX_COMPONENTS)
  170191. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170192. MAX_COMPONENTS);
  170193. /* Compute maximum sampling factors; check factor validity */
  170194. cinfo->max_h_samp_factor = 1;
  170195. cinfo->max_v_samp_factor = 1;
  170196. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170197. ci++, compptr++) {
  170198. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170199. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170200. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170201. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170202. compptr->h_samp_factor);
  170203. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170204. compptr->v_samp_factor);
  170205. }
  170206. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170207. * In the full decompressor, this will be overridden by jdmaster.c;
  170208. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170209. */
  170210. cinfo->min_DCT_scaled_size = DCTSIZE;
  170211. /* Compute dimensions of components */
  170212. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170213. ci++, compptr++) {
  170214. compptr->DCT_scaled_size = DCTSIZE;
  170215. /* Size in DCT blocks */
  170216. compptr->width_in_blocks = (JDIMENSION)
  170217. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170218. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170219. compptr->height_in_blocks = (JDIMENSION)
  170220. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170221. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170222. /* downsampled_width and downsampled_height will also be overridden by
  170223. * jdmaster.c if we are doing full decompression. The transcoder library
  170224. * doesn't use these values, but the calling application might.
  170225. */
  170226. /* Size in samples */
  170227. compptr->downsampled_width = (JDIMENSION)
  170228. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170229. (long) cinfo->max_h_samp_factor);
  170230. compptr->downsampled_height = (JDIMENSION)
  170231. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170232. (long) cinfo->max_v_samp_factor);
  170233. /* Mark component needed, until color conversion says otherwise */
  170234. compptr->component_needed = TRUE;
  170235. /* Mark no quantization table yet saved for component */
  170236. compptr->quant_table = NULL;
  170237. }
  170238. /* Compute number of fully interleaved MCU rows. */
  170239. cinfo->total_iMCU_rows = (JDIMENSION)
  170240. jdiv_round_up((long) cinfo->image_height,
  170241. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170242. /* Decide whether file contains multiple scans */
  170243. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170244. cinfo->inputctl->has_multiple_scans = TRUE;
  170245. else
  170246. cinfo->inputctl->has_multiple_scans = FALSE;
  170247. }
  170248. LOCAL(void)
  170249. per_scan_setup2 (j_decompress_ptr cinfo)
  170250. /* Do computations that are needed before processing a JPEG scan */
  170251. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170252. {
  170253. int ci, mcublks, tmp;
  170254. jpeg_component_info *compptr;
  170255. if (cinfo->comps_in_scan == 1) {
  170256. /* Noninterleaved (single-component) scan */
  170257. compptr = cinfo->cur_comp_info[0];
  170258. /* Overall image size in MCUs */
  170259. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170260. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170261. /* For noninterleaved scan, always one block per MCU */
  170262. compptr->MCU_width = 1;
  170263. compptr->MCU_height = 1;
  170264. compptr->MCU_blocks = 1;
  170265. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170266. compptr->last_col_width = 1;
  170267. /* For noninterleaved scans, it is convenient to define last_row_height
  170268. * as the number of block rows present in the last iMCU row.
  170269. */
  170270. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170271. if (tmp == 0) tmp = compptr->v_samp_factor;
  170272. compptr->last_row_height = tmp;
  170273. /* Prepare array describing MCU composition */
  170274. cinfo->blocks_in_MCU = 1;
  170275. cinfo->MCU_membership[0] = 0;
  170276. } else {
  170277. /* Interleaved (multi-component) scan */
  170278. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170279. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170280. MAX_COMPS_IN_SCAN);
  170281. /* Overall image size in MCUs */
  170282. cinfo->MCUs_per_row = (JDIMENSION)
  170283. jdiv_round_up((long) cinfo->image_width,
  170284. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170285. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170286. jdiv_round_up((long) cinfo->image_height,
  170287. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170288. cinfo->blocks_in_MCU = 0;
  170289. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170290. compptr = cinfo->cur_comp_info[ci];
  170291. /* Sampling factors give # of blocks of component in each MCU */
  170292. compptr->MCU_width = compptr->h_samp_factor;
  170293. compptr->MCU_height = compptr->v_samp_factor;
  170294. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170295. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170296. /* Figure number of non-dummy blocks in last MCU column & row */
  170297. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170298. if (tmp == 0) tmp = compptr->MCU_width;
  170299. compptr->last_col_width = tmp;
  170300. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170301. if (tmp == 0) tmp = compptr->MCU_height;
  170302. compptr->last_row_height = tmp;
  170303. /* Prepare array describing MCU composition */
  170304. mcublks = compptr->MCU_blocks;
  170305. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170306. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170307. while (mcublks-- > 0) {
  170308. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170309. }
  170310. }
  170311. }
  170312. }
  170313. /*
  170314. * Save away a copy of the Q-table referenced by each component present
  170315. * in the current scan, unless already saved during a prior scan.
  170316. *
  170317. * In a multiple-scan JPEG file, the encoder could assign different components
  170318. * the same Q-table slot number, but change table definitions between scans
  170319. * so that each component uses a different Q-table. (The IJG encoder is not
  170320. * currently capable of doing this, but other encoders might.) Since we want
  170321. * to be able to dequantize all the components at the end of the file, this
  170322. * means that we have to save away the table actually used for each component.
  170323. * We do this by copying the table at the start of the first scan containing
  170324. * the component.
  170325. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170326. * slot between scans of a component using that slot. If the encoder does so
  170327. * anyway, this decoder will simply use the Q-table values that were current
  170328. * at the start of the first scan for the component.
  170329. *
  170330. * The decompressor output side looks only at the saved quant tables,
  170331. * not at the current Q-table slots.
  170332. */
  170333. LOCAL(void)
  170334. latch_quant_tables (j_decompress_ptr cinfo)
  170335. {
  170336. int ci, qtblno;
  170337. jpeg_component_info *compptr;
  170338. JQUANT_TBL * qtbl;
  170339. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170340. compptr = cinfo->cur_comp_info[ci];
  170341. /* No work if we already saved Q-table for this component */
  170342. if (compptr->quant_table != NULL)
  170343. continue;
  170344. /* Make sure specified quantization table is present */
  170345. qtblno = compptr->quant_tbl_no;
  170346. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170347. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170348. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170349. /* OK, save away the quantization table */
  170350. qtbl = (JQUANT_TBL *)
  170351. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170352. SIZEOF(JQUANT_TBL));
  170353. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170354. compptr->quant_table = qtbl;
  170355. }
  170356. }
  170357. /*
  170358. * Initialize the input modules to read a scan of compressed data.
  170359. * The first call to this is done by jdmaster.c after initializing
  170360. * the entire decompressor (during jpeg_start_decompress).
  170361. * Subsequent calls come from consume_markers, below.
  170362. */
  170363. METHODDEF(void)
  170364. start_input_pass2 (j_decompress_ptr cinfo)
  170365. {
  170366. per_scan_setup2(cinfo);
  170367. latch_quant_tables(cinfo);
  170368. (*cinfo->entropy->start_pass) (cinfo);
  170369. (*cinfo->coef->start_input_pass) (cinfo);
  170370. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170371. }
  170372. /*
  170373. * Finish up after inputting a compressed-data scan.
  170374. * This is called by the coefficient controller after it's read all
  170375. * the expected data of the scan.
  170376. */
  170377. METHODDEF(void)
  170378. finish_input_pass (j_decompress_ptr cinfo)
  170379. {
  170380. cinfo->inputctl->consume_input = consume_markers;
  170381. }
  170382. /*
  170383. * Read JPEG markers before, between, or after compressed-data scans.
  170384. * Change state as necessary when a new scan is reached.
  170385. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170386. *
  170387. * The consume_input method pointer points either here or to the
  170388. * coefficient controller's consume_data routine, depending on whether
  170389. * we are reading a compressed data segment or inter-segment markers.
  170390. */
  170391. METHODDEF(int)
  170392. consume_markers (j_decompress_ptr cinfo)
  170393. {
  170394. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170395. int val;
  170396. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170397. return JPEG_REACHED_EOI;
  170398. val = (*cinfo->marker->read_markers) (cinfo);
  170399. switch (val) {
  170400. case JPEG_REACHED_SOS: /* Found SOS */
  170401. if (inputctl->inheaders) { /* 1st SOS */
  170402. initial_setup2(cinfo);
  170403. inputctl->inheaders = FALSE;
  170404. /* Note: start_input_pass must be called by jdmaster.c
  170405. * before any more input can be consumed. jdapimin.c is
  170406. * responsible for enforcing this sequencing.
  170407. */
  170408. } else { /* 2nd or later SOS marker */
  170409. if (! inputctl->pub.has_multiple_scans)
  170410. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170411. start_input_pass2(cinfo);
  170412. }
  170413. break;
  170414. case JPEG_REACHED_EOI: /* Found EOI */
  170415. inputctl->pub.eoi_reached = TRUE;
  170416. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170417. if (cinfo->marker->saw_SOF)
  170418. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170419. } else {
  170420. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170421. * if user set output_scan_number larger than number of scans.
  170422. */
  170423. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170424. cinfo->output_scan_number = cinfo->input_scan_number;
  170425. }
  170426. break;
  170427. case JPEG_SUSPENDED:
  170428. break;
  170429. }
  170430. return val;
  170431. }
  170432. /*
  170433. * Reset state to begin a fresh datastream.
  170434. */
  170435. METHODDEF(void)
  170436. reset_input_controller (j_decompress_ptr cinfo)
  170437. {
  170438. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170439. inputctl->pub.consume_input = consume_markers;
  170440. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170441. inputctl->pub.eoi_reached = FALSE;
  170442. inputctl->inheaders = TRUE;
  170443. /* Reset other modules */
  170444. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170445. (*cinfo->marker->reset_marker_reader) (cinfo);
  170446. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170447. cinfo->coef_bits = NULL;
  170448. }
  170449. /*
  170450. * Initialize the input controller module.
  170451. * This is called only once, when the decompression object is created.
  170452. */
  170453. GLOBAL(void)
  170454. jinit_input_controller (j_decompress_ptr cinfo)
  170455. {
  170456. my_inputctl_ptr inputctl;
  170457. /* Create subobject in permanent pool */
  170458. inputctl = (my_inputctl_ptr)
  170459. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170460. SIZEOF(my_input_controller));
  170461. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170462. /* Initialize method pointers */
  170463. inputctl->pub.consume_input = consume_markers;
  170464. inputctl->pub.reset_input_controller = reset_input_controller;
  170465. inputctl->pub.start_input_pass = start_input_pass2;
  170466. inputctl->pub.finish_input_pass = finish_input_pass;
  170467. /* Initialize state: can't use reset_input_controller since we don't
  170468. * want to try to reset other modules yet.
  170469. */
  170470. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170471. inputctl->pub.eoi_reached = FALSE;
  170472. inputctl->inheaders = TRUE;
  170473. }
  170474. /*** End of inlined file: jdinput.c ***/
  170475. /*** Start of inlined file: jdmainct.c ***/
  170476. #define JPEG_INTERNALS
  170477. /*
  170478. * In the current system design, the main buffer need never be a full-image
  170479. * buffer; any full-height buffers will be found inside the coefficient or
  170480. * postprocessing controllers. Nonetheless, the main controller is not
  170481. * trivial. Its responsibility is to provide context rows for upsampling/
  170482. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170483. *
  170484. * Postprocessor input data is counted in "row groups". A row group
  170485. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170486. * sample rows of each component. (We require DCT_scaled_size values to be
  170487. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170488. * values will likely be powers of two, so we actually have the stronger
  170489. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170490. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170491. * row group (times any additional scale factor that the upsampler is
  170492. * applying).
  170493. *
  170494. * The coefficient controller will deliver data to us one iMCU row at a time;
  170495. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170496. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170497. * to one row of MCUs when the image is fully interleaved.) Note that the
  170498. * number of sample rows varies across components, but the number of row
  170499. * groups does not. Some garbage sample rows may be included in the last iMCU
  170500. * row at the bottom of the image.
  170501. *
  170502. * Depending on the vertical scaling algorithm used, the upsampler may need
  170503. * access to the sample row(s) above and below its current input row group.
  170504. * The upsampler is required to set need_context_rows TRUE at global selection
  170505. * time if so. When need_context_rows is FALSE, this controller can simply
  170506. * obtain one iMCU row at a time from the coefficient controller and dole it
  170507. * out as row groups to the postprocessor.
  170508. *
  170509. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170510. * passed to postprocessing contains at least one row group's worth of samples
  170511. * above and below the row group(s) being processed. Note that the context
  170512. * rows "above" the first passed row group appear at negative row offsets in
  170513. * the passed buffer. At the top and bottom of the image, the required
  170514. * context rows are manufactured by duplicating the first or last real sample
  170515. * row; this avoids having special cases in the upsampling inner loops.
  170516. *
  170517. * The amount of context is fixed at one row group just because that's a
  170518. * convenient number for this controller to work with. The existing
  170519. * upsamplers really only need one sample row of context. An upsampler
  170520. * supporting arbitrary output rescaling might wish for more than one row
  170521. * group of context when shrinking the image; tough, we don't handle that.
  170522. * (This is justified by the assumption that downsizing will be handled mostly
  170523. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170524. * the upsample step needn't be much less than one.)
  170525. *
  170526. * To provide the desired context, we have to retain the last two row groups
  170527. * of one iMCU row while reading in the next iMCU row. (The last row group
  170528. * can't be processed until we have another row group for its below-context,
  170529. * and so we have to save the next-to-last group too for its above-context.)
  170530. * We could do this most simply by copying data around in our buffer, but
  170531. * that'd be very slow. We can avoid copying any data by creating a rather
  170532. * strange pointer structure. Here's how it works. We allocate a workspace
  170533. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170534. * of row groups per iMCU row). We create two sets of redundant pointers to
  170535. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170536. * pointer lists look like this:
  170537. * M+1 M-1
  170538. * master pointer --> 0 master pointer --> 0
  170539. * 1 1
  170540. * ... ...
  170541. * M-3 M-3
  170542. * M-2 M
  170543. * M-1 M+1
  170544. * M M-2
  170545. * M+1 M-1
  170546. * 0 0
  170547. * We read alternate iMCU rows using each master pointer; thus the last two
  170548. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170549. * The pointer lists are set up so that the required context rows appear to
  170550. * be adjacent to the proper places when we pass the pointer lists to the
  170551. * upsampler.
  170552. *
  170553. * The above pictures describe the normal state of the pointer lists.
  170554. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170555. * the first or last sample row as necessary (this is cheaper than copying
  170556. * sample rows around).
  170557. *
  170558. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170559. * situation each iMCU row provides only one row group so the buffering logic
  170560. * must be different (eg, we must read two iMCU rows before we can emit the
  170561. * first row group). For now, we simply do not support providing context
  170562. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170563. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170564. * want it quick and dirty, so a context-free upsampler is sufficient.
  170565. */
  170566. /* Private buffer controller object */
  170567. typedef struct {
  170568. struct jpeg_d_main_controller pub; /* public fields */
  170569. /* Pointer to allocated workspace (M or M+2 row groups). */
  170570. JSAMPARRAY buffer[MAX_COMPONENTS];
  170571. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170572. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170573. /* Remaining fields are only used in the context case. */
  170574. /* These are the master pointers to the funny-order pointer lists. */
  170575. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170576. int whichptr; /* indicates which pointer set is now in use */
  170577. int context_state; /* process_data state machine status */
  170578. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170579. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170580. } my_main_controller4;
  170581. typedef my_main_controller4 * my_main_ptr4;
  170582. /* context_state values: */
  170583. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170584. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170585. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170586. /* Forward declarations */
  170587. METHODDEF(void) process_data_simple_main2
  170588. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170589. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170590. METHODDEF(void) process_data_context_main
  170591. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170592. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170593. #ifdef QUANT_2PASS_SUPPORTED
  170594. METHODDEF(void) process_data_crank_post
  170595. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170596. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170597. #endif
  170598. LOCAL(void)
  170599. alloc_funny_pointers (j_decompress_ptr cinfo)
  170600. /* Allocate space for the funny pointer lists.
  170601. * This is done only once, not once per pass.
  170602. */
  170603. {
  170604. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170605. int ci, rgroup;
  170606. int M = cinfo->min_DCT_scaled_size;
  170607. jpeg_component_info *compptr;
  170608. JSAMPARRAY xbuf;
  170609. /* Get top-level space for component array pointers.
  170610. * We alloc both arrays with one call to save a few cycles.
  170611. */
  170612. main_->xbuffer[0] = (JSAMPIMAGE)
  170613. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170614. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170615. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170616. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170617. ci++, compptr++) {
  170618. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170619. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170620. /* Get space for pointer lists --- M+4 row groups in each list.
  170621. * We alloc both pointer lists with one call to save a few cycles.
  170622. */
  170623. xbuf = (JSAMPARRAY)
  170624. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170625. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170626. xbuf += rgroup; /* want one row group at negative offsets */
  170627. main_->xbuffer[0][ci] = xbuf;
  170628. xbuf += rgroup * (M + 4);
  170629. main_->xbuffer[1][ci] = xbuf;
  170630. }
  170631. }
  170632. LOCAL(void)
  170633. make_funny_pointers (j_decompress_ptr cinfo)
  170634. /* Create the funny pointer lists discussed in the comments above.
  170635. * The actual workspace is already allocated (in main->buffer),
  170636. * and the space for the pointer lists is allocated too.
  170637. * This routine just fills in the curiously ordered lists.
  170638. * This will be repeated at the beginning of each pass.
  170639. */
  170640. {
  170641. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170642. int ci, i, rgroup;
  170643. int M = cinfo->min_DCT_scaled_size;
  170644. jpeg_component_info *compptr;
  170645. JSAMPARRAY buf, xbuf0, xbuf1;
  170646. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170647. ci++, compptr++) {
  170648. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170649. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170650. xbuf0 = main_->xbuffer[0][ci];
  170651. xbuf1 = main_->xbuffer[1][ci];
  170652. /* First copy the workspace pointers as-is */
  170653. buf = main_->buffer[ci];
  170654. for (i = 0; i < rgroup * (M + 2); i++) {
  170655. xbuf0[i] = xbuf1[i] = buf[i];
  170656. }
  170657. /* In the second list, put the last four row groups in swapped order */
  170658. for (i = 0; i < rgroup * 2; i++) {
  170659. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170660. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170661. }
  170662. /* The wraparound pointers at top and bottom will be filled later
  170663. * (see set_wraparound_pointers, below). Initially we want the "above"
  170664. * pointers to duplicate the first actual data line. This only needs
  170665. * to happen in xbuffer[0].
  170666. */
  170667. for (i = 0; i < rgroup; i++) {
  170668. xbuf0[i - rgroup] = xbuf0[0];
  170669. }
  170670. }
  170671. }
  170672. LOCAL(void)
  170673. set_wraparound_pointers (j_decompress_ptr cinfo)
  170674. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170675. * This changes the pointer list state from top-of-image to the normal state.
  170676. */
  170677. {
  170678. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170679. int ci, i, rgroup;
  170680. int M = cinfo->min_DCT_scaled_size;
  170681. jpeg_component_info *compptr;
  170682. JSAMPARRAY xbuf0, xbuf1;
  170683. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170684. ci++, compptr++) {
  170685. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170686. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170687. xbuf0 = main_->xbuffer[0][ci];
  170688. xbuf1 = main_->xbuffer[1][ci];
  170689. for (i = 0; i < rgroup; i++) {
  170690. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170691. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170692. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170693. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170694. }
  170695. }
  170696. }
  170697. LOCAL(void)
  170698. set_bottom_pointers (j_decompress_ptr cinfo)
  170699. /* Change the pointer lists to duplicate the last sample row at the bottom
  170700. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170701. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170702. */
  170703. {
  170704. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170705. int ci, i, rgroup, iMCUheight, rows_left;
  170706. jpeg_component_info *compptr;
  170707. JSAMPARRAY xbuf;
  170708. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170709. ci++, compptr++) {
  170710. /* Count sample rows in one iMCU row and in one row group */
  170711. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170712. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170713. /* Count nondummy sample rows remaining for this component */
  170714. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170715. if (rows_left == 0) rows_left = iMCUheight;
  170716. /* Count nondummy row groups. Should get same answer for each component,
  170717. * so we need only do it once.
  170718. */
  170719. if (ci == 0) {
  170720. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170721. }
  170722. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170723. * last partial rowgroup and ensures at least one full rowgroup of context.
  170724. */
  170725. xbuf = main_->xbuffer[main_->whichptr][ci];
  170726. for (i = 0; i < rgroup * 2; i++) {
  170727. xbuf[rows_left + i] = xbuf[rows_left-1];
  170728. }
  170729. }
  170730. }
  170731. /*
  170732. * Initialize for a processing pass.
  170733. */
  170734. METHODDEF(void)
  170735. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170736. {
  170737. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170738. switch (pass_mode) {
  170739. case JBUF_PASS_THRU:
  170740. if (cinfo->upsample->need_context_rows) {
  170741. main_->pub.process_data = process_data_context_main;
  170742. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170743. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170744. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170745. main_->iMCU_row_ctr = 0;
  170746. } else {
  170747. /* Simple case with no context needed */
  170748. main_->pub.process_data = process_data_simple_main2;
  170749. }
  170750. main_->buffer_full = FALSE; /* Mark buffer empty */
  170751. main_->rowgroup_ctr = 0;
  170752. break;
  170753. #ifdef QUANT_2PASS_SUPPORTED
  170754. case JBUF_CRANK_DEST:
  170755. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170756. main_->pub.process_data = process_data_crank_post;
  170757. break;
  170758. #endif
  170759. default:
  170760. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170761. break;
  170762. }
  170763. }
  170764. /*
  170765. * Process some data.
  170766. * This handles the simple case where no context is required.
  170767. */
  170768. METHODDEF(void)
  170769. process_data_simple_main2 (j_decompress_ptr cinfo,
  170770. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170771. JDIMENSION out_rows_avail)
  170772. {
  170773. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170774. JDIMENSION rowgroups_avail;
  170775. /* Read input data if we haven't filled the main buffer yet */
  170776. if (! main_->buffer_full) {
  170777. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170778. return; /* suspension forced, can do nothing more */
  170779. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170780. }
  170781. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170782. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170783. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170784. * to the postprocessor. The postprocessor has to check for bottom
  170785. * of image anyway (at row resolution), so no point in us doing it too.
  170786. */
  170787. /* Feed the postprocessor */
  170788. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170789. &main_->rowgroup_ctr, rowgroups_avail,
  170790. output_buf, out_row_ctr, out_rows_avail);
  170791. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170792. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170793. main_->buffer_full = FALSE;
  170794. main_->rowgroup_ctr = 0;
  170795. }
  170796. }
  170797. /*
  170798. * Process some data.
  170799. * This handles the case where context rows must be provided.
  170800. */
  170801. METHODDEF(void)
  170802. process_data_context_main (j_decompress_ptr cinfo,
  170803. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170804. JDIMENSION out_rows_avail)
  170805. {
  170806. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170807. /* Read input data if we haven't filled the main buffer yet */
  170808. if (! main_->buffer_full) {
  170809. if (! (*cinfo->coef->decompress_data) (cinfo,
  170810. main_->xbuffer[main_->whichptr]))
  170811. return; /* suspension forced, can do nothing more */
  170812. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170813. main_->iMCU_row_ctr++; /* count rows received */
  170814. }
  170815. /* Postprocessor typically will not swallow all the input data it is handed
  170816. * in one call (due to filling the output buffer first). Must be prepared
  170817. * to exit and restart. This switch lets us keep track of how far we got.
  170818. * Note that each case falls through to the next on successful completion.
  170819. */
  170820. switch (main_->context_state) {
  170821. case CTX_POSTPONED_ROW:
  170822. /* Call postprocessor using previously set pointers for postponed row */
  170823. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170824. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170825. output_buf, out_row_ctr, out_rows_avail);
  170826. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170827. return; /* Need to suspend */
  170828. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170829. if (*out_row_ctr >= out_rows_avail)
  170830. return; /* Postprocessor exactly filled output buf */
  170831. /*FALLTHROUGH*/
  170832. case CTX_PREPARE_FOR_IMCU:
  170833. /* Prepare to process first M-1 row groups of this iMCU row */
  170834. main_->rowgroup_ctr = 0;
  170835. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170836. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170837. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170838. */
  170839. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170840. set_bottom_pointers(cinfo);
  170841. main_->context_state = CTX_PROCESS_IMCU;
  170842. /*FALLTHROUGH*/
  170843. case CTX_PROCESS_IMCU:
  170844. /* Call postprocessor using previously set pointers */
  170845. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170846. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170847. output_buf, out_row_ctr, out_rows_avail);
  170848. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170849. return; /* Need to suspend */
  170850. /* After the first iMCU, change wraparound pointers to normal state */
  170851. if (main_->iMCU_row_ctr == 1)
  170852. set_wraparound_pointers(cinfo);
  170853. /* Prepare to load new iMCU row using other xbuffer list */
  170854. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170855. main_->buffer_full = FALSE;
  170856. /* Still need to process last row group of this iMCU row, */
  170857. /* which is saved at index M+1 of the other xbuffer */
  170858. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170859. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170860. main_->context_state = CTX_POSTPONED_ROW;
  170861. }
  170862. }
  170863. /*
  170864. * Process some data.
  170865. * Final pass of two-pass quantization: just call the postprocessor.
  170866. * Source data will be the postprocessor controller's internal buffer.
  170867. */
  170868. #ifdef QUANT_2PASS_SUPPORTED
  170869. METHODDEF(void)
  170870. process_data_crank_post (j_decompress_ptr cinfo,
  170871. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170872. JDIMENSION out_rows_avail)
  170873. {
  170874. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170875. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170876. output_buf, out_row_ctr, out_rows_avail);
  170877. }
  170878. #endif /* QUANT_2PASS_SUPPORTED */
  170879. /*
  170880. * Initialize main buffer controller.
  170881. */
  170882. GLOBAL(void)
  170883. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170884. {
  170885. my_main_ptr4 main_;
  170886. int ci, rgroup, ngroups;
  170887. jpeg_component_info *compptr;
  170888. main_ = (my_main_ptr4)
  170889. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170890. SIZEOF(my_main_controller4));
  170891. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170892. main_->pub.start_pass = start_pass_main2;
  170893. if (need_full_buffer) /* shouldn't happen */
  170894. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170895. /* Allocate the workspace.
  170896. * ngroups is the number of row groups we need.
  170897. */
  170898. if (cinfo->upsample->need_context_rows) {
  170899. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170900. ERREXIT(cinfo, JERR_NOTIMPL);
  170901. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170902. ngroups = cinfo->min_DCT_scaled_size + 2;
  170903. } else {
  170904. ngroups = cinfo->min_DCT_scaled_size;
  170905. }
  170906. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170907. ci++, compptr++) {
  170908. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170909. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170910. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170911. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170912. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170913. (JDIMENSION) (rgroup * ngroups));
  170914. }
  170915. }
  170916. /*** End of inlined file: jdmainct.c ***/
  170917. /*** Start of inlined file: jdmarker.c ***/
  170918. #define JPEG_INTERNALS
  170919. /* Private state */
  170920. typedef struct {
  170921. struct jpeg_marker_reader pub; /* public fields */
  170922. /* Application-overridable marker processing methods */
  170923. jpeg_marker_parser_method process_COM;
  170924. jpeg_marker_parser_method process_APPn[16];
  170925. /* Limit on marker data length to save for each marker type */
  170926. unsigned int length_limit_COM;
  170927. unsigned int length_limit_APPn[16];
  170928. /* Status of COM/APPn marker saving */
  170929. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170930. unsigned int bytes_read; /* data bytes read so far in marker */
  170931. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170932. } my_marker_reader;
  170933. typedef my_marker_reader * my_marker_ptr2;
  170934. /*
  170935. * Macros for fetching data from the data source module.
  170936. *
  170937. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170938. * the current restart point; we update them only when we have reached a
  170939. * suitable place to restart if a suspension occurs.
  170940. */
  170941. /* Declare and initialize local copies of input pointer/count */
  170942. #define INPUT_VARS(cinfo) \
  170943. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170944. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170945. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170946. /* Unload the local copies --- do this only at a restart boundary */
  170947. #define INPUT_SYNC(cinfo) \
  170948. ( datasrc->next_input_byte = next_input_byte, \
  170949. datasrc->bytes_in_buffer = bytes_in_buffer )
  170950. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170951. #define INPUT_RELOAD(cinfo) \
  170952. ( next_input_byte = datasrc->next_input_byte, \
  170953. bytes_in_buffer = datasrc->bytes_in_buffer )
  170954. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170955. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170956. * but we must reload the local copies after a successful fill.
  170957. */
  170958. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170959. if (bytes_in_buffer == 0) { \
  170960. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170961. { action; } \
  170962. INPUT_RELOAD(cinfo); \
  170963. }
  170964. /* Read a byte into variable V.
  170965. * If must suspend, take the specified action (typically "return FALSE").
  170966. */
  170967. #define INPUT_BYTE(cinfo,V,action) \
  170968. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170969. bytes_in_buffer--; \
  170970. V = GETJOCTET(*next_input_byte++); )
  170971. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170972. * V should be declared unsigned int or perhaps INT32.
  170973. */
  170974. #define INPUT_2BYTES(cinfo,V,action) \
  170975. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170976. bytes_in_buffer--; \
  170977. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170978. MAKE_BYTE_AVAIL(cinfo,action); \
  170979. bytes_in_buffer--; \
  170980. V += GETJOCTET(*next_input_byte++); )
  170981. /*
  170982. * Routines to process JPEG markers.
  170983. *
  170984. * Entry condition: JPEG marker itself has been read and its code saved
  170985. * in cinfo->unread_marker; input restart point is just after the marker.
  170986. *
  170987. * Exit: if return TRUE, have read and processed any parameters, and have
  170988. * updated the restart point to point after the parameters.
  170989. * If return FALSE, was forced to suspend before reaching end of
  170990. * marker parameters; restart point has not been moved. Same routine
  170991. * will be called again after application supplies more input data.
  170992. *
  170993. * This approach to suspension assumes that all of a marker's parameters
  170994. * can fit into a single input bufferload. This should hold for "normal"
  170995. * markers. Some COM/APPn markers might have large parameter segments
  170996. * that might not fit. If we are simply dropping such a marker, we use
  170997. * skip_input_data to get past it, and thereby put the problem on the
  170998. * source manager's shoulders. If we are saving the marker's contents
  170999. * into memory, we use a slightly different convention: when forced to
  171000. * suspend, the marker processor updates the restart point to the end of
  171001. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171002. * On resumption, cinfo->unread_marker still contains the marker code,
  171003. * but the data source will point to the next chunk of marker data.
  171004. * The marker processor must retain internal state to deal with this.
  171005. *
  171006. * Note that we don't bother to avoid duplicate trace messages if a
  171007. * suspension occurs within marker parameters. Other side effects
  171008. * require more care.
  171009. */
  171010. LOCAL(boolean)
  171011. get_soi (j_decompress_ptr cinfo)
  171012. /* Process an SOI marker */
  171013. {
  171014. int i;
  171015. TRACEMS(cinfo, 1, JTRC_SOI);
  171016. if (cinfo->marker->saw_SOI)
  171017. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171018. /* Reset all parameters that are defined to be reset by SOI */
  171019. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171020. cinfo->arith_dc_L[i] = 0;
  171021. cinfo->arith_dc_U[i] = 1;
  171022. cinfo->arith_ac_K[i] = 5;
  171023. }
  171024. cinfo->restart_interval = 0;
  171025. /* Set initial assumptions for colorspace etc */
  171026. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171027. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171028. cinfo->saw_JFIF_marker = FALSE;
  171029. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171030. cinfo->JFIF_minor_version = 1;
  171031. cinfo->density_unit = 0;
  171032. cinfo->X_density = 1;
  171033. cinfo->Y_density = 1;
  171034. cinfo->saw_Adobe_marker = FALSE;
  171035. cinfo->Adobe_transform = 0;
  171036. cinfo->marker->saw_SOI = TRUE;
  171037. return TRUE;
  171038. }
  171039. LOCAL(boolean)
  171040. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171041. /* Process a SOFn marker */
  171042. {
  171043. INT32 length;
  171044. int c, ci;
  171045. jpeg_component_info * compptr;
  171046. INPUT_VARS(cinfo);
  171047. cinfo->progressive_mode = is_prog;
  171048. cinfo->arith_code = is_arith;
  171049. INPUT_2BYTES(cinfo, length, return FALSE);
  171050. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171051. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171052. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171053. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171054. length -= 8;
  171055. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171056. (int) cinfo->image_width, (int) cinfo->image_height,
  171057. cinfo->num_components);
  171058. if (cinfo->marker->saw_SOF)
  171059. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171060. /* We don't support files in which the image height is initially specified */
  171061. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171062. /* might as well have a general sanity check. */
  171063. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171064. || cinfo->num_components <= 0)
  171065. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171066. if (length != (cinfo->num_components * 3))
  171067. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171068. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171069. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171070. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171071. cinfo->num_components * SIZEOF(jpeg_component_info));
  171072. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171073. ci++, compptr++) {
  171074. compptr->component_index = ci;
  171075. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171076. INPUT_BYTE(cinfo, c, return FALSE);
  171077. compptr->h_samp_factor = (c >> 4) & 15;
  171078. compptr->v_samp_factor = (c ) & 15;
  171079. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171080. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171081. compptr->component_id, compptr->h_samp_factor,
  171082. compptr->v_samp_factor, compptr->quant_tbl_no);
  171083. }
  171084. cinfo->marker->saw_SOF = TRUE;
  171085. INPUT_SYNC(cinfo);
  171086. return TRUE;
  171087. }
  171088. LOCAL(boolean)
  171089. get_sos (j_decompress_ptr cinfo)
  171090. /* Process a SOS marker */
  171091. {
  171092. INT32 length;
  171093. int i, ci, n, c, cc;
  171094. jpeg_component_info * compptr;
  171095. INPUT_VARS(cinfo);
  171096. if (! cinfo->marker->saw_SOF)
  171097. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171098. INPUT_2BYTES(cinfo, length, return FALSE);
  171099. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171100. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171101. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171102. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171103. cinfo->comps_in_scan = n;
  171104. /* Collect the component-spec parameters */
  171105. for (i = 0; i < n; i++) {
  171106. INPUT_BYTE(cinfo, cc, return FALSE);
  171107. INPUT_BYTE(cinfo, c, return FALSE);
  171108. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171109. ci++, compptr++) {
  171110. if (cc == compptr->component_id)
  171111. goto id_found;
  171112. }
  171113. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171114. id_found:
  171115. cinfo->cur_comp_info[i] = compptr;
  171116. compptr->dc_tbl_no = (c >> 4) & 15;
  171117. compptr->ac_tbl_no = (c ) & 15;
  171118. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171119. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171120. }
  171121. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171122. INPUT_BYTE(cinfo, c, return FALSE);
  171123. cinfo->Ss = c;
  171124. INPUT_BYTE(cinfo, c, return FALSE);
  171125. cinfo->Se = c;
  171126. INPUT_BYTE(cinfo, c, return FALSE);
  171127. cinfo->Ah = (c >> 4) & 15;
  171128. cinfo->Al = (c ) & 15;
  171129. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171130. cinfo->Ah, cinfo->Al);
  171131. /* Prepare to scan data & restart markers */
  171132. cinfo->marker->next_restart_num = 0;
  171133. /* Count another SOS marker */
  171134. cinfo->input_scan_number++;
  171135. INPUT_SYNC(cinfo);
  171136. return TRUE;
  171137. }
  171138. #ifdef D_ARITH_CODING_SUPPORTED
  171139. LOCAL(boolean)
  171140. get_dac (j_decompress_ptr cinfo)
  171141. /* Process a DAC marker */
  171142. {
  171143. INT32 length;
  171144. int index, val;
  171145. INPUT_VARS(cinfo);
  171146. INPUT_2BYTES(cinfo, length, return FALSE);
  171147. length -= 2;
  171148. while (length > 0) {
  171149. INPUT_BYTE(cinfo, index, return FALSE);
  171150. INPUT_BYTE(cinfo, val, return FALSE);
  171151. length -= 2;
  171152. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171153. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171154. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171155. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171156. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171157. } else { /* define DC table */
  171158. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171159. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171160. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171161. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171162. }
  171163. }
  171164. if (length != 0)
  171165. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171166. INPUT_SYNC(cinfo);
  171167. return TRUE;
  171168. }
  171169. #else /* ! D_ARITH_CODING_SUPPORTED */
  171170. #define get_dac(cinfo) skip_variable(cinfo)
  171171. #endif /* D_ARITH_CODING_SUPPORTED */
  171172. LOCAL(boolean)
  171173. get_dht (j_decompress_ptr cinfo)
  171174. /* Process a DHT marker */
  171175. {
  171176. INT32 length;
  171177. UINT8 bits[17];
  171178. UINT8 huffval[256];
  171179. int i, index, count;
  171180. JHUFF_TBL **htblptr;
  171181. INPUT_VARS(cinfo);
  171182. INPUT_2BYTES(cinfo, length, return FALSE);
  171183. length -= 2;
  171184. while (length > 16) {
  171185. INPUT_BYTE(cinfo, index, return FALSE);
  171186. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171187. bits[0] = 0;
  171188. count = 0;
  171189. for (i = 1; i <= 16; i++) {
  171190. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171191. count += bits[i];
  171192. }
  171193. length -= 1 + 16;
  171194. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171195. bits[1], bits[2], bits[3], bits[4],
  171196. bits[5], bits[6], bits[7], bits[8]);
  171197. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171198. bits[9], bits[10], bits[11], bits[12],
  171199. bits[13], bits[14], bits[15], bits[16]);
  171200. /* Here we just do minimal validation of the counts to avoid walking
  171201. * off the end of our table space. jdhuff.c will check more carefully.
  171202. */
  171203. if (count > 256 || ((INT32) count) > length)
  171204. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171205. for (i = 0; i < count; i++)
  171206. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171207. length -= count;
  171208. if (index & 0x10) { /* AC table definition */
  171209. index -= 0x10;
  171210. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171211. } else { /* DC table definition */
  171212. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171213. }
  171214. if (index < 0 || index >= NUM_HUFF_TBLS)
  171215. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171216. if (*htblptr == NULL)
  171217. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171218. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171219. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171220. }
  171221. if (length != 0)
  171222. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171223. INPUT_SYNC(cinfo);
  171224. return TRUE;
  171225. }
  171226. LOCAL(boolean)
  171227. get_dqt (j_decompress_ptr cinfo)
  171228. /* Process a DQT marker */
  171229. {
  171230. INT32 length;
  171231. int n, i, prec;
  171232. unsigned int tmp;
  171233. JQUANT_TBL *quant_ptr;
  171234. INPUT_VARS(cinfo);
  171235. INPUT_2BYTES(cinfo, length, return FALSE);
  171236. length -= 2;
  171237. while (length > 0) {
  171238. INPUT_BYTE(cinfo, n, return FALSE);
  171239. prec = n >> 4;
  171240. n &= 0x0F;
  171241. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171242. if (n >= NUM_QUANT_TBLS)
  171243. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171244. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171245. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171246. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171247. for (i = 0; i < DCTSIZE2; i++) {
  171248. if (prec)
  171249. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171250. else
  171251. INPUT_BYTE(cinfo, tmp, return FALSE);
  171252. /* We convert the zigzag-order table to natural array order. */
  171253. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171254. }
  171255. if (cinfo->err->trace_level >= 2) {
  171256. for (i = 0; i < DCTSIZE2; i += 8) {
  171257. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171258. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171259. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171260. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171261. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171262. }
  171263. }
  171264. length -= DCTSIZE2+1;
  171265. if (prec) length -= DCTSIZE2;
  171266. }
  171267. if (length != 0)
  171268. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171269. INPUT_SYNC(cinfo);
  171270. return TRUE;
  171271. }
  171272. LOCAL(boolean)
  171273. get_dri (j_decompress_ptr cinfo)
  171274. /* Process a DRI marker */
  171275. {
  171276. INT32 length;
  171277. unsigned int tmp;
  171278. INPUT_VARS(cinfo);
  171279. INPUT_2BYTES(cinfo, length, return FALSE);
  171280. if (length != 4)
  171281. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171282. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171283. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171284. cinfo->restart_interval = tmp;
  171285. INPUT_SYNC(cinfo);
  171286. return TRUE;
  171287. }
  171288. /*
  171289. * Routines for processing APPn and COM markers.
  171290. * These are either saved in memory or discarded, per application request.
  171291. * APP0 and APP14 are specially checked to see if they are
  171292. * JFIF and Adobe markers, respectively.
  171293. */
  171294. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171295. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171296. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171297. LOCAL(void)
  171298. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171299. unsigned int datalen, INT32 remaining)
  171300. /* Examine first few bytes from an APP0.
  171301. * Take appropriate action if it is a JFIF marker.
  171302. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171303. */
  171304. {
  171305. INT32 totallen = (INT32) datalen + remaining;
  171306. if (datalen >= APP0_DATA_LEN &&
  171307. GETJOCTET(data[0]) == 0x4A &&
  171308. GETJOCTET(data[1]) == 0x46 &&
  171309. GETJOCTET(data[2]) == 0x49 &&
  171310. GETJOCTET(data[3]) == 0x46 &&
  171311. GETJOCTET(data[4]) == 0) {
  171312. /* Found JFIF APP0 marker: save info */
  171313. cinfo->saw_JFIF_marker = TRUE;
  171314. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171315. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171316. cinfo->density_unit = GETJOCTET(data[7]);
  171317. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171318. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171319. /* Check version.
  171320. * Major version must be 1, anything else signals an incompatible change.
  171321. * (We used to treat this as an error, but now it's a nonfatal warning,
  171322. * because some bozo at Hijaak couldn't read the spec.)
  171323. * Minor version should be 0..2, but process anyway if newer.
  171324. */
  171325. if (cinfo->JFIF_major_version != 1)
  171326. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171327. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171328. /* Generate trace messages */
  171329. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171330. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171331. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171332. /* Validate thumbnail dimensions and issue appropriate messages */
  171333. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171334. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171335. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171336. totallen -= APP0_DATA_LEN;
  171337. if (totallen !=
  171338. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171339. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171340. } else if (datalen >= 6 &&
  171341. GETJOCTET(data[0]) == 0x4A &&
  171342. GETJOCTET(data[1]) == 0x46 &&
  171343. GETJOCTET(data[2]) == 0x58 &&
  171344. GETJOCTET(data[3]) == 0x58 &&
  171345. GETJOCTET(data[4]) == 0) {
  171346. /* Found JFIF "JFXX" extension APP0 marker */
  171347. /* The library doesn't actually do anything with these,
  171348. * but we try to produce a helpful trace message.
  171349. */
  171350. switch (GETJOCTET(data[5])) {
  171351. case 0x10:
  171352. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171353. break;
  171354. case 0x11:
  171355. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171356. break;
  171357. case 0x13:
  171358. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171359. break;
  171360. default:
  171361. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171362. GETJOCTET(data[5]), (int) totallen);
  171363. break;
  171364. }
  171365. } else {
  171366. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171367. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171368. }
  171369. }
  171370. LOCAL(void)
  171371. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171372. unsigned int datalen, INT32 remaining)
  171373. /* Examine first few bytes from an APP14.
  171374. * Take appropriate action if it is an Adobe marker.
  171375. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171376. */
  171377. {
  171378. unsigned int version, flags0, flags1, transform;
  171379. if (datalen >= APP14_DATA_LEN &&
  171380. GETJOCTET(data[0]) == 0x41 &&
  171381. GETJOCTET(data[1]) == 0x64 &&
  171382. GETJOCTET(data[2]) == 0x6F &&
  171383. GETJOCTET(data[3]) == 0x62 &&
  171384. GETJOCTET(data[4]) == 0x65) {
  171385. /* Found Adobe APP14 marker */
  171386. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171387. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171388. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171389. transform = GETJOCTET(data[11]);
  171390. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171391. cinfo->saw_Adobe_marker = TRUE;
  171392. cinfo->Adobe_transform = (UINT8) transform;
  171393. } else {
  171394. /* Start of APP14 does not match "Adobe", or too short */
  171395. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171396. }
  171397. }
  171398. METHODDEF(boolean)
  171399. get_interesting_appn (j_decompress_ptr cinfo)
  171400. /* Process an APP0 or APP14 marker without saving it */
  171401. {
  171402. INT32 length;
  171403. JOCTET b[APPN_DATA_LEN];
  171404. unsigned int i, numtoread;
  171405. INPUT_VARS(cinfo);
  171406. INPUT_2BYTES(cinfo, length, return FALSE);
  171407. length -= 2;
  171408. /* get the interesting part of the marker data */
  171409. if (length >= APPN_DATA_LEN)
  171410. numtoread = APPN_DATA_LEN;
  171411. else if (length > 0)
  171412. numtoread = (unsigned int) length;
  171413. else
  171414. numtoread = 0;
  171415. for (i = 0; i < numtoread; i++)
  171416. INPUT_BYTE(cinfo, b[i], return FALSE);
  171417. length -= numtoread;
  171418. /* process it */
  171419. switch (cinfo->unread_marker) {
  171420. case M_APP0:
  171421. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171422. break;
  171423. case M_APP14:
  171424. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171425. break;
  171426. default:
  171427. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171428. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171429. break;
  171430. }
  171431. /* skip any remaining data -- could be lots */
  171432. INPUT_SYNC(cinfo);
  171433. if (length > 0)
  171434. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171435. return TRUE;
  171436. }
  171437. #ifdef SAVE_MARKERS_SUPPORTED
  171438. METHODDEF(boolean)
  171439. save_marker (j_decompress_ptr cinfo)
  171440. /* Save an APPn or COM marker into the marker list */
  171441. {
  171442. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171443. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171444. unsigned int bytes_read, data_length;
  171445. JOCTET FAR * data;
  171446. INT32 length = 0;
  171447. INPUT_VARS(cinfo);
  171448. if (cur_marker == NULL) {
  171449. /* begin reading a marker */
  171450. INPUT_2BYTES(cinfo, length, return FALSE);
  171451. length -= 2;
  171452. if (length >= 0) { /* watch out for bogus length word */
  171453. /* figure out how much we want to save */
  171454. unsigned int limit;
  171455. if (cinfo->unread_marker == (int) M_COM)
  171456. limit = marker->length_limit_COM;
  171457. else
  171458. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171459. if ((unsigned int) length < limit)
  171460. limit = (unsigned int) length;
  171461. /* allocate and initialize the marker item */
  171462. cur_marker = (jpeg_saved_marker_ptr)
  171463. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171464. SIZEOF(struct jpeg_marker_struct) + limit);
  171465. cur_marker->next = NULL;
  171466. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171467. cur_marker->original_length = (unsigned int) length;
  171468. cur_marker->data_length = limit;
  171469. /* data area is just beyond the jpeg_marker_struct */
  171470. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171471. marker->cur_marker = cur_marker;
  171472. marker->bytes_read = 0;
  171473. bytes_read = 0;
  171474. data_length = limit;
  171475. } else {
  171476. /* deal with bogus length word */
  171477. bytes_read = data_length = 0;
  171478. data = NULL;
  171479. }
  171480. } else {
  171481. /* resume reading a marker */
  171482. bytes_read = marker->bytes_read;
  171483. data_length = cur_marker->data_length;
  171484. data = cur_marker->data + bytes_read;
  171485. }
  171486. while (bytes_read < data_length) {
  171487. INPUT_SYNC(cinfo); /* move the restart point to here */
  171488. marker->bytes_read = bytes_read;
  171489. /* If there's not at least one byte in buffer, suspend */
  171490. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171491. /* Copy bytes with reasonable rapidity */
  171492. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171493. *data++ = *next_input_byte++;
  171494. bytes_in_buffer--;
  171495. bytes_read++;
  171496. }
  171497. }
  171498. /* Done reading what we want to read */
  171499. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171500. /* Add new marker to end of list */
  171501. if (cinfo->marker_list == NULL) {
  171502. cinfo->marker_list = cur_marker;
  171503. } else {
  171504. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171505. while (prev->next != NULL)
  171506. prev = prev->next;
  171507. prev->next = cur_marker;
  171508. }
  171509. /* Reset pointer & calc remaining data length */
  171510. data = cur_marker->data;
  171511. length = cur_marker->original_length - data_length;
  171512. }
  171513. /* Reset to initial state for next marker */
  171514. marker->cur_marker = NULL;
  171515. /* Process the marker if interesting; else just make a generic trace msg */
  171516. switch (cinfo->unread_marker) {
  171517. case M_APP0:
  171518. examine_app0(cinfo, data, data_length, length);
  171519. break;
  171520. case M_APP14:
  171521. examine_app14(cinfo, data, data_length, length);
  171522. break;
  171523. default:
  171524. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171525. (int) (data_length + length));
  171526. break;
  171527. }
  171528. /* skip any remaining data -- could be lots */
  171529. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171530. if (length > 0)
  171531. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171532. return TRUE;
  171533. }
  171534. #endif /* SAVE_MARKERS_SUPPORTED */
  171535. METHODDEF(boolean)
  171536. skip_variable (j_decompress_ptr cinfo)
  171537. /* Skip over an unknown or uninteresting variable-length marker */
  171538. {
  171539. INT32 length;
  171540. INPUT_VARS(cinfo);
  171541. INPUT_2BYTES(cinfo, length, return FALSE);
  171542. length -= 2;
  171543. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171544. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171545. if (length > 0)
  171546. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171547. return TRUE;
  171548. }
  171549. /*
  171550. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171551. * Returns FALSE if had to suspend before reaching a marker;
  171552. * in that case cinfo->unread_marker is unchanged.
  171553. *
  171554. * Note that the result might not be a valid marker code,
  171555. * but it will never be 0 or FF.
  171556. */
  171557. LOCAL(boolean)
  171558. next_marker (j_decompress_ptr cinfo)
  171559. {
  171560. int c;
  171561. INPUT_VARS(cinfo);
  171562. for (;;) {
  171563. INPUT_BYTE(cinfo, c, return FALSE);
  171564. /* Skip any non-FF bytes.
  171565. * This may look a bit inefficient, but it will not occur in a valid file.
  171566. * We sync after each discarded byte so that a suspending data source
  171567. * can discard the byte from its buffer.
  171568. */
  171569. while (c != 0xFF) {
  171570. cinfo->marker->discarded_bytes++;
  171571. INPUT_SYNC(cinfo);
  171572. INPUT_BYTE(cinfo, c, return FALSE);
  171573. }
  171574. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171575. * pad bytes, so don't count them in discarded_bytes. We assume there
  171576. * will not be so many consecutive FF bytes as to overflow a suspending
  171577. * data source's input buffer.
  171578. */
  171579. do {
  171580. INPUT_BYTE(cinfo, c, return FALSE);
  171581. } while (c == 0xFF);
  171582. if (c != 0)
  171583. break; /* found a valid marker, exit loop */
  171584. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171585. * Discard it and loop back to try again.
  171586. */
  171587. cinfo->marker->discarded_bytes += 2;
  171588. INPUT_SYNC(cinfo);
  171589. }
  171590. if (cinfo->marker->discarded_bytes != 0) {
  171591. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171592. cinfo->marker->discarded_bytes = 0;
  171593. }
  171594. cinfo->unread_marker = c;
  171595. INPUT_SYNC(cinfo);
  171596. return TRUE;
  171597. }
  171598. LOCAL(boolean)
  171599. first_marker (j_decompress_ptr cinfo)
  171600. /* Like next_marker, but used to obtain the initial SOI marker. */
  171601. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171602. * we might well scan an entire input file before realizing it ain't JPEG.
  171603. * If an application wants to process non-JFIF files, it must seek to the
  171604. * SOI before calling the JPEG library.
  171605. */
  171606. {
  171607. int c, c2;
  171608. INPUT_VARS(cinfo);
  171609. INPUT_BYTE(cinfo, c, return FALSE);
  171610. INPUT_BYTE(cinfo, c2, return FALSE);
  171611. if (c != 0xFF || c2 != (int) M_SOI)
  171612. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171613. cinfo->unread_marker = c2;
  171614. INPUT_SYNC(cinfo);
  171615. return TRUE;
  171616. }
  171617. /*
  171618. * Read markers until SOS or EOI.
  171619. *
  171620. * Returns same codes as are defined for jpeg_consume_input:
  171621. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171622. */
  171623. METHODDEF(int)
  171624. read_markers (j_decompress_ptr cinfo)
  171625. {
  171626. /* Outer loop repeats once for each marker. */
  171627. for (;;) {
  171628. /* Collect the marker proper, unless we already did. */
  171629. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171630. if (cinfo->unread_marker == 0) {
  171631. if (! cinfo->marker->saw_SOI) {
  171632. if (! first_marker(cinfo))
  171633. return JPEG_SUSPENDED;
  171634. } else {
  171635. if (! next_marker(cinfo))
  171636. return JPEG_SUSPENDED;
  171637. }
  171638. }
  171639. /* At this point cinfo->unread_marker contains the marker code and the
  171640. * input point is just past the marker proper, but before any parameters.
  171641. * A suspension will cause us to return with this state still true.
  171642. */
  171643. switch (cinfo->unread_marker) {
  171644. case M_SOI:
  171645. if (! get_soi(cinfo))
  171646. return JPEG_SUSPENDED;
  171647. break;
  171648. case M_SOF0: /* Baseline */
  171649. case M_SOF1: /* Extended sequential, Huffman */
  171650. if (! get_sof(cinfo, FALSE, FALSE))
  171651. return JPEG_SUSPENDED;
  171652. break;
  171653. case M_SOF2: /* Progressive, Huffman */
  171654. if (! get_sof(cinfo, TRUE, FALSE))
  171655. return JPEG_SUSPENDED;
  171656. break;
  171657. case M_SOF9: /* Extended sequential, arithmetic */
  171658. if (! get_sof(cinfo, FALSE, TRUE))
  171659. return JPEG_SUSPENDED;
  171660. break;
  171661. case M_SOF10: /* Progressive, arithmetic */
  171662. if (! get_sof(cinfo, TRUE, TRUE))
  171663. return JPEG_SUSPENDED;
  171664. break;
  171665. /* Currently unsupported SOFn types */
  171666. case M_SOF3: /* Lossless, Huffman */
  171667. case M_SOF5: /* Differential sequential, Huffman */
  171668. case M_SOF6: /* Differential progressive, Huffman */
  171669. case M_SOF7: /* Differential lossless, Huffman */
  171670. case M_JPG: /* Reserved for JPEG extensions */
  171671. case M_SOF11: /* Lossless, arithmetic */
  171672. case M_SOF13: /* Differential sequential, arithmetic */
  171673. case M_SOF14: /* Differential progressive, arithmetic */
  171674. case M_SOF15: /* Differential lossless, arithmetic */
  171675. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171676. break;
  171677. case M_SOS:
  171678. if (! get_sos(cinfo))
  171679. return JPEG_SUSPENDED;
  171680. cinfo->unread_marker = 0; /* processed the marker */
  171681. return JPEG_REACHED_SOS;
  171682. case M_EOI:
  171683. TRACEMS(cinfo, 1, JTRC_EOI);
  171684. cinfo->unread_marker = 0; /* processed the marker */
  171685. return JPEG_REACHED_EOI;
  171686. case M_DAC:
  171687. if (! get_dac(cinfo))
  171688. return JPEG_SUSPENDED;
  171689. break;
  171690. case M_DHT:
  171691. if (! get_dht(cinfo))
  171692. return JPEG_SUSPENDED;
  171693. break;
  171694. case M_DQT:
  171695. if (! get_dqt(cinfo))
  171696. return JPEG_SUSPENDED;
  171697. break;
  171698. case M_DRI:
  171699. if (! get_dri(cinfo))
  171700. return JPEG_SUSPENDED;
  171701. break;
  171702. case M_APP0:
  171703. case M_APP1:
  171704. case M_APP2:
  171705. case M_APP3:
  171706. case M_APP4:
  171707. case M_APP5:
  171708. case M_APP6:
  171709. case M_APP7:
  171710. case M_APP8:
  171711. case M_APP9:
  171712. case M_APP10:
  171713. case M_APP11:
  171714. case M_APP12:
  171715. case M_APP13:
  171716. case M_APP14:
  171717. case M_APP15:
  171718. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171719. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171720. return JPEG_SUSPENDED;
  171721. break;
  171722. case M_COM:
  171723. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171724. return JPEG_SUSPENDED;
  171725. break;
  171726. case M_RST0: /* these are all parameterless */
  171727. case M_RST1:
  171728. case M_RST2:
  171729. case M_RST3:
  171730. case M_RST4:
  171731. case M_RST5:
  171732. case M_RST6:
  171733. case M_RST7:
  171734. case M_TEM:
  171735. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171736. break;
  171737. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171738. if (! skip_variable(cinfo))
  171739. return JPEG_SUSPENDED;
  171740. break;
  171741. default: /* must be DHP, EXP, JPGn, or RESn */
  171742. /* For now, we treat the reserved markers as fatal errors since they are
  171743. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171744. * Once the JPEG 3 version-number marker is well defined, this code
  171745. * ought to change!
  171746. */
  171747. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171748. break;
  171749. }
  171750. /* Successfully processed marker, so reset state variable */
  171751. cinfo->unread_marker = 0;
  171752. } /* end loop */
  171753. }
  171754. /*
  171755. * Read a restart marker, which is expected to appear next in the datastream;
  171756. * if the marker is not there, take appropriate recovery action.
  171757. * Returns FALSE if suspension is required.
  171758. *
  171759. * This is called by the entropy decoder after it has read an appropriate
  171760. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171761. * has already read a marker from the data source. Under normal conditions
  171762. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171763. * it holds a marker which the decoder will be unable to read past.
  171764. */
  171765. METHODDEF(boolean)
  171766. read_restart_marker (j_decompress_ptr cinfo)
  171767. {
  171768. /* Obtain a marker unless we already did. */
  171769. /* Note that next_marker will complain if it skips any data. */
  171770. if (cinfo->unread_marker == 0) {
  171771. if (! next_marker(cinfo))
  171772. return FALSE;
  171773. }
  171774. if (cinfo->unread_marker ==
  171775. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171776. /* Normal case --- swallow the marker and let entropy decoder continue */
  171777. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171778. cinfo->unread_marker = 0;
  171779. } else {
  171780. /* Uh-oh, the restart markers have been messed up. */
  171781. /* Let the data source manager determine how to resync. */
  171782. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171783. cinfo->marker->next_restart_num))
  171784. return FALSE;
  171785. }
  171786. /* Update next-restart state */
  171787. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171788. return TRUE;
  171789. }
  171790. /*
  171791. * This is the default resync_to_restart method for data source managers
  171792. * to use if they don't have any better approach. Some data source managers
  171793. * may be able to back up, or may have additional knowledge about the data
  171794. * which permits a more intelligent recovery strategy; such managers would
  171795. * presumably supply their own resync method.
  171796. *
  171797. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171798. * the restart marker it was expecting. (This code is *not* used unless
  171799. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171800. * the marker code actually found (might be anything, except 0 or FF).
  171801. * The desired restart marker number (0..7) is passed as a parameter.
  171802. * This routine is supposed to apply whatever error recovery strategy seems
  171803. * appropriate in order to position the input stream to the next data segment.
  171804. * Note that cinfo->unread_marker is treated as a marker appearing before
  171805. * the current data-source input point; usually it should be reset to zero
  171806. * before returning.
  171807. * Returns FALSE if suspension is required.
  171808. *
  171809. * This implementation is substantially constrained by wanting to treat the
  171810. * input as a data stream; this means we can't back up. Therefore, we have
  171811. * only the following actions to work with:
  171812. * 1. Simply discard the marker and let the entropy decoder resume at next
  171813. * byte of file.
  171814. * 2. Read forward until we find another marker, discarding intervening
  171815. * data. (In theory we could look ahead within the current bufferload,
  171816. * without having to discard data if we don't find the desired marker.
  171817. * This idea is not implemented here, in part because it makes behavior
  171818. * dependent on buffer size and chance buffer-boundary positions.)
  171819. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171820. * This will cause the entropy decoder to process an empty data segment,
  171821. * inserting dummy zeroes, and then we will reprocess the marker.
  171822. *
  171823. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171824. * appropriate if the found marker is a future restart marker (indicating
  171825. * that we have missed the desired restart marker, probably because it got
  171826. * corrupted).
  171827. * We apply #2 or #3 if the found marker is a restart marker no more than
  171828. * two counts behind or ahead of the expected one. We also apply #2 if the
  171829. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171830. * If the found marker is a restart marker more than 2 counts away, we do #1
  171831. * (too much risk that the marker is erroneous; with luck we will be able to
  171832. * resync at some future point).
  171833. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171834. * overrunning the end of a scan. An implementation limited to single-scan
  171835. * files might find it better to apply #2 for markers other than EOI, since
  171836. * any other marker would have to be bogus data in that case.
  171837. */
  171838. GLOBAL(boolean)
  171839. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171840. {
  171841. int marker = cinfo->unread_marker;
  171842. int action = 1;
  171843. /* Always put up a warning. */
  171844. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171845. /* Outer loop handles repeated decision after scanning forward. */
  171846. for (;;) {
  171847. if (marker < (int) M_SOF0)
  171848. action = 2; /* invalid marker */
  171849. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171850. action = 3; /* valid non-restart marker */
  171851. else {
  171852. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171853. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171854. action = 3; /* one of the next two expected restarts */
  171855. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171856. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171857. action = 2; /* a prior restart, so advance */
  171858. else
  171859. action = 1; /* desired restart or too far away */
  171860. }
  171861. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171862. switch (action) {
  171863. case 1:
  171864. /* Discard marker and let entropy decoder resume processing. */
  171865. cinfo->unread_marker = 0;
  171866. return TRUE;
  171867. case 2:
  171868. /* Scan to the next marker, and repeat the decision loop. */
  171869. if (! next_marker(cinfo))
  171870. return FALSE;
  171871. marker = cinfo->unread_marker;
  171872. break;
  171873. case 3:
  171874. /* Return without advancing past this marker. */
  171875. /* Entropy decoder will be forced to process an empty segment. */
  171876. return TRUE;
  171877. }
  171878. } /* end loop */
  171879. }
  171880. /*
  171881. * Reset marker processing state to begin a fresh datastream.
  171882. */
  171883. METHODDEF(void)
  171884. reset_marker_reader (j_decompress_ptr cinfo)
  171885. {
  171886. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171887. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171888. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171889. cinfo->unread_marker = 0; /* no pending marker */
  171890. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171891. marker->pub.saw_SOF = FALSE;
  171892. marker->pub.discarded_bytes = 0;
  171893. marker->cur_marker = NULL;
  171894. }
  171895. /*
  171896. * Initialize the marker reader module.
  171897. * This is called only once, when the decompression object is created.
  171898. */
  171899. GLOBAL(void)
  171900. jinit_marker_reader (j_decompress_ptr cinfo)
  171901. {
  171902. my_marker_ptr2 marker;
  171903. int i;
  171904. /* Create subobject in permanent pool */
  171905. marker = (my_marker_ptr2)
  171906. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171907. SIZEOF(my_marker_reader));
  171908. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171909. /* Initialize public method pointers */
  171910. marker->pub.reset_marker_reader = reset_marker_reader;
  171911. marker->pub.read_markers = read_markers;
  171912. marker->pub.read_restart_marker = read_restart_marker;
  171913. /* Initialize COM/APPn processing.
  171914. * By default, we examine and then discard APP0 and APP14,
  171915. * but simply discard COM and all other APPn.
  171916. */
  171917. marker->process_COM = skip_variable;
  171918. marker->length_limit_COM = 0;
  171919. for (i = 0; i < 16; i++) {
  171920. marker->process_APPn[i] = skip_variable;
  171921. marker->length_limit_APPn[i] = 0;
  171922. }
  171923. marker->process_APPn[0] = get_interesting_appn;
  171924. marker->process_APPn[14] = get_interesting_appn;
  171925. /* Reset marker processing state */
  171926. reset_marker_reader(cinfo);
  171927. }
  171928. /*
  171929. * Control saving of COM and APPn markers into marker_list.
  171930. */
  171931. #ifdef SAVE_MARKERS_SUPPORTED
  171932. GLOBAL(void)
  171933. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171934. unsigned int length_limit)
  171935. {
  171936. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171937. long maxlength;
  171938. jpeg_marker_parser_method processor;
  171939. /* Length limit mustn't be larger than what we can allocate
  171940. * (should only be a concern in a 16-bit environment).
  171941. */
  171942. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171943. if (((long) length_limit) > maxlength)
  171944. length_limit = (unsigned int) maxlength;
  171945. /* Choose processor routine to use.
  171946. * APP0/APP14 have special requirements.
  171947. */
  171948. if (length_limit) {
  171949. processor = save_marker;
  171950. /* If saving APP0/APP14, save at least enough for our internal use. */
  171951. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171952. length_limit = APP0_DATA_LEN;
  171953. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171954. length_limit = APP14_DATA_LEN;
  171955. } else {
  171956. processor = skip_variable;
  171957. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171958. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171959. processor = get_interesting_appn;
  171960. }
  171961. if (marker_code == (int) M_COM) {
  171962. marker->process_COM = processor;
  171963. marker->length_limit_COM = length_limit;
  171964. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171965. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171966. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171967. } else
  171968. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171969. }
  171970. #endif /* SAVE_MARKERS_SUPPORTED */
  171971. /*
  171972. * Install a special processing method for COM or APPn markers.
  171973. */
  171974. GLOBAL(void)
  171975. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171976. jpeg_marker_parser_method routine)
  171977. {
  171978. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171979. if (marker_code == (int) M_COM)
  171980. marker->process_COM = routine;
  171981. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171982. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171983. else
  171984. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171985. }
  171986. /*** End of inlined file: jdmarker.c ***/
  171987. /*** Start of inlined file: jdmaster.c ***/
  171988. #define JPEG_INTERNALS
  171989. /* Private state */
  171990. typedef struct {
  171991. struct jpeg_decomp_master pub; /* public fields */
  171992. int pass_number; /* # of passes completed */
  171993. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171994. /* Saved references to initialized quantizer modules,
  171995. * in case we need to switch modes.
  171996. */
  171997. struct jpeg_color_quantizer * quantizer_1pass;
  171998. struct jpeg_color_quantizer * quantizer_2pass;
  171999. } my_decomp_master;
  172000. typedef my_decomp_master * my_master_ptr6;
  172001. /*
  172002. * Determine whether merged upsample/color conversion should be used.
  172003. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172004. */
  172005. LOCAL(boolean)
  172006. use_merged_upsample (j_decompress_ptr cinfo)
  172007. {
  172008. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172009. /* Merging is the equivalent of plain box-filter upsampling */
  172010. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172011. return FALSE;
  172012. /* jdmerge.c only supports YCC=>RGB color conversion */
  172013. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172014. cinfo->out_color_space != JCS_RGB ||
  172015. cinfo->out_color_components != RGB_PIXELSIZE)
  172016. return FALSE;
  172017. /* and it only handles 2h1v or 2h2v sampling ratios */
  172018. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172019. cinfo->comp_info[1].h_samp_factor != 1 ||
  172020. cinfo->comp_info[2].h_samp_factor != 1 ||
  172021. cinfo->comp_info[0].v_samp_factor > 2 ||
  172022. cinfo->comp_info[1].v_samp_factor != 1 ||
  172023. cinfo->comp_info[2].v_samp_factor != 1)
  172024. return FALSE;
  172025. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172026. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172027. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172028. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172029. return FALSE;
  172030. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172031. return TRUE; /* by golly, it'll work... */
  172032. #else
  172033. return FALSE;
  172034. #endif
  172035. }
  172036. /*
  172037. * Compute output image dimensions and related values.
  172038. * NOTE: this is exported for possible use by application.
  172039. * Hence it mustn't do anything that can't be done twice.
  172040. * Also note that it may be called before the master module is initialized!
  172041. */
  172042. GLOBAL(void)
  172043. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172044. /* Do computations that are needed before master selection phase */
  172045. {
  172046. #ifdef IDCT_SCALING_SUPPORTED
  172047. int ci;
  172048. jpeg_component_info *compptr;
  172049. #endif
  172050. /* Prevent application from calling me at wrong times */
  172051. if (cinfo->global_state != DSTATE_READY)
  172052. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172053. #ifdef IDCT_SCALING_SUPPORTED
  172054. /* Compute actual output image dimensions and DCT scaling choices. */
  172055. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172056. /* Provide 1/8 scaling */
  172057. cinfo->output_width = (JDIMENSION)
  172058. jdiv_round_up((long) cinfo->image_width, 8L);
  172059. cinfo->output_height = (JDIMENSION)
  172060. jdiv_round_up((long) cinfo->image_height, 8L);
  172061. cinfo->min_DCT_scaled_size = 1;
  172062. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172063. /* Provide 1/4 scaling */
  172064. cinfo->output_width = (JDIMENSION)
  172065. jdiv_round_up((long) cinfo->image_width, 4L);
  172066. cinfo->output_height = (JDIMENSION)
  172067. jdiv_round_up((long) cinfo->image_height, 4L);
  172068. cinfo->min_DCT_scaled_size = 2;
  172069. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172070. /* Provide 1/2 scaling */
  172071. cinfo->output_width = (JDIMENSION)
  172072. jdiv_round_up((long) cinfo->image_width, 2L);
  172073. cinfo->output_height = (JDIMENSION)
  172074. jdiv_round_up((long) cinfo->image_height, 2L);
  172075. cinfo->min_DCT_scaled_size = 4;
  172076. } else {
  172077. /* Provide 1/1 scaling */
  172078. cinfo->output_width = cinfo->image_width;
  172079. cinfo->output_height = cinfo->image_height;
  172080. cinfo->min_DCT_scaled_size = DCTSIZE;
  172081. }
  172082. /* In selecting the actual DCT scaling for each component, we try to
  172083. * scale up the chroma components via IDCT scaling rather than upsampling.
  172084. * This saves time if the upsampler gets to use 1:1 scaling.
  172085. * Note this code assumes that the supported DCT scalings are powers of 2.
  172086. */
  172087. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172088. ci++, compptr++) {
  172089. int ssize = cinfo->min_DCT_scaled_size;
  172090. while (ssize < DCTSIZE &&
  172091. (compptr->h_samp_factor * ssize * 2 <=
  172092. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172093. (compptr->v_samp_factor * ssize * 2 <=
  172094. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172095. ssize = ssize * 2;
  172096. }
  172097. compptr->DCT_scaled_size = ssize;
  172098. }
  172099. /* Recompute downsampled dimensions of components;
  172100. * application needs to know these if using raw downsampled data.
  172101. */
  172102. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172103. ci++, compptr++) {
  172104. /* Size in samples, after IDCT scaling */
  172105. compptr->downsampled_width = (JDIMENSION)
  172106. jdiv_round_up((long) cinfo->image_width *
  172107. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172108. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172109. compptr->downsampled_height = (JDIMENSION)
  172110. jdiv_round_up((long) cinfo->image_height *
  172111. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172112. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172113. }
  172114. #else /* !IDCT_SCALING_SUPPORTED */
  172115. /* Hardwire it to "no scaling" */
  172116. cinfo->output_width = cinfo->image_width;
  172117. cinfo->output_height = cinfo->image_height;
  172118. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172119. * and has computed unscaled downsampled_width and downsampled_height.
  172120. */
  172121. #endif /* IDCT_SCALING_SUPPORTED */
  172122. /* Report number of components in selected colorspace. */
  172123. /* Probably this should be in the color conversion module... */
  172124. switch (cinfo->out_color_space) {
  172125. case JCS_GRAYSCALE:
  172126. cinfo->out_color_components = 1;
  172127. break;
  172128. case JCS_RGB:
  172129. #if RGB_PIXELSIZE != 3
  172130. cinfo->out_color_components = RGB_PIXELSIZE;
  172131. break;
  172132. #endif /* else share code with YCbCr */
  172133. case JCS_YCbCr:
  172134. cinfo->out_color_components = 3;
  172135. break;
  172136. case JCS_CMYK:
  172137. case JCS_YCCK:
  172138. cinfo->out_color_components = 4;
  172139. break;
  172140. default: /* else must be same colorspace as in file */
  172141. cinfo->out_color_components = cinfo->num_components;
  172142. break;
  172143. }
  172144. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172145. cinfo->out_color_components);
  172146. /* See if upsampler will want to emit more than one row at a time */
  172147. if (use_merged_upsample(cinfo))
  172148. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172149. else
  172150. cinfo->rec_outbuf_height = 1;
  172151. }
  172152. /*
  172153. * Several decompression processes need to range-limit values to the range
  172154. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172155. * due to noise introduced by quantization, roundoff error, etc. These
  172156. * processes are inner loops and need to be as fast as possible. On most
  172157. * machines, particularly CPUs with pipelines or instruction prefetch,
  172158. * a (subscript-check-less) C table lookup
  172159. * x = sample_range_limit[x];
  172160. * is faster than explicit tests
  172161. * if (x < 0) x = 0;
  172162. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172163. * These processes all use a common table prepared by the routine below.
  172164. *
  172165. * For most steps we can mathematically guarantee that the initial value
  172166. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172167. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172168. * limiting step (just after the IDCT), a wildly out-of-range value is
  172169. * possible if the input data is corrupt. To avoid any chance of indexing
  172170. * off the end of memory and getting a bad-pointer trap, we perform the
  172171. * post-IDCT limiting thus:
  172172. * x = range_limit[x & MASK];
  172173. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172174. * samples. Under normal circumstances this is more than enough range and
  172175. * a correct output will be generated; with bogus input data the mask will
  172176. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172177. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172178. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172179. * So the post-IDCT limiting table ends up looking like this:
  172180. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172181. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172182. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172183. * 0,1,...,CENTERJSAMPLE-1
  172184. * Negative inputs select values from the upper half of the table after
  172185. * masking.
  172186. *
  172187. * We can save some space by overlapping the start of the post-IDCT table
  172188. * with the simpler range limiting table. The post-IDCT table begins at
  172189. * sample_range_limit + CENTERJSAMPLE.
  172190. *
  172191. * Note that the table is allocated in near data space on PCs; it's small
  172192. * enough and used often enough to justify this.
  172193. */
  172194. LOCAL(void)
  172195. prepare_range_limit_table (j_decompress_ptr cinfo)
  172196. /* Allocate and fill in the sample_range_limit table */
  172197. {
  172198. JSAMPLE * table;
  172199. int i;
  172200. table = (JSAMPLE *)
  172201. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172202. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172203. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172204. cinfo->sample_range_limit = table;
  172205. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172206. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172207. /* Main part of "simple" table: limit[x] = x */
  172208. for (i = 0; i <= MAXJSAMPLE; i++)
  172209. table[i] = (JSAMPLE) i;
  172210. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172211. /* End of simple table, rest of first half of post-IDCT table */
  172212. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172213. table[i] = MAXJSAMPLE;
  172214. /* Second half of post-IDCT table */
  172215. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172216. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172217. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172218. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172219. }
  172220. /*
  172221. * Master selection of decompression modules.
  172222. * This is done once at jpeg_start_decompress time. We determine
  172223. * which modules will be used and give them appropriate initialization calls.
  172224. * We also initialize the decompressor input side to begin consuming data.
  172225. *
  172226. * Since jpeg_read_header has finished, we know what is in the SOF
  172227. * and (first) SOS markers. We also have all the application parameter
  172228. * settings.
  172229. */
  172230. LOCAL(void)
  172231. master_selection (j_decompress_ptr cinfo)
  172232. {
  172233. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172234. boolean use_c_buffer;
  172235. long samplesperrow;
  172236. JDIMENSION jd_samplesperrow;
  172237. /* Initialize dimensions and other stuff */
  172238. jpeg_calc_output_dimensions(cinfo);
  172239. prepare_range_limit_table(cinfo);
  172240. /* Width of an output scanline must be representable as JDIMENSION. */
  172241. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172242. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172243. if ((long) jd_samplesperrow != samplesperrow)
  172244. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172245. /* Initialize my private state */
  172246. master->pass_number = 0;
  172247. master->using_merged_upsample = use_merged_upsample(cinfo);
  172248. /* Color quantizer selection */
  172249. master->quantizer_1pass = NULL;
  172250. master->quantizer_2pass = NULL;
  172251. /* No mode changes if not using buffered-image mode. */
  172252. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172253. cinfo->enable_1pass_quant = FALSE;
  172254. cinfo->enable_external_quant = FALSE;
  172255. cinfo->enable_2pass_quant = FALSE;
  172256. }
  172257. if (cinfo->quantize_colors) {
  172258. if (cinfo->raw_data_out)
  172259. ERREXIT(cinfo, JERR_NOTIMPL);
  172260. /* 2-pass quantizer only works in 3-component color space. */
  172261. if (cinfo->out_color_components != 3) {
  172262. cinfo->enable_1pass_quant = TRUE;
  172263. cinfo->enable_external_quant = FALSE;
  172264. cinfo->enable_2pass_quant = FALSE;
  172265. cinfo->colormap = NULL;
  172266. } else if (cinfo->colormap != NULL) {
  172267. cinfo->enable_external_quant = TRUE;
  172268. } else if (cinfo->two_pass_quantize) {
  172269. cinfo->enable_2pass_quant = TRUE;
  172270. } else {
  172271. cinfo->enable_1pass_quant = TRUE;
  172272. }
  172273. if (cinfo->enable_1pass_quant) {
  172274. #ifdef QUANT_1PASS_SUPPORTED
  172275. jinit_1pass_quantizer(cinfo);
  172276. master->quantizer_1pass = cinfo->cquantize;
  172277. #else
  172278. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172279. #endif
  172280. }
  172281. /* We use the 2-pass code to map to external colormaps. */
  172282. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172283. #ifdef QUANT_2PASS_SUPPORTED
  172284. jinit_2pass_quantizer(cinfo);
  172285. master->quantizer_2pass = cinfo->cquantize;
  172286. #else
  172287. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172288. #endif
  172289. }
  172290. /* If both quantizers are initialized, the 2-pass one is left active;
  172291. * this is necessary for starting with quantization to an external map.
  172292. */
  172293. }
  172294. /* Post-processing: in particular, color conversion first */
  172295. if (! cinfo->raw_data_out) {
  172296. if (master->using_merged_upsample) {
  172297. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172298. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172299. #else
  172300. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172301. #endif
  172302. } else {
  172303. jinit_color_deconverter(cinfo);
  172304. jinit_upsampler(cinfo);
  172305. }
  172306. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172307. }
  172308. /* Inverse DCT */
  172309. jinit_inverse_dct(cinfo);
  172310. /* Entropy decoding: either Huffman or arithmetic coding. */
  172311. if (cinfo->arith_code) {
  172312. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172313. } else {
  172314. if (cinfo->progressive_mode) {
  172315. #ifdef D_PROGRESSIVE_SUPPORTED
  172316. jinit_phuff_decoder(cinfo);
  172317. #else
  172318. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172319. #endif
  172320. } else
  172321. jinit_huff_decoder(cinfo);
  172322. }
  172323. /* Initialize principal buffer controllers. */
  172324. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172325. jinit_d_coef_controller(cinfo, use_c_buffer);
  172326. if (! cinfo->raw_data_out)
  172327. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172328. /* We can now tell the memory manager to allocate virtual arrays. */
  172329. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172330. /* Initialize input side of decompressor to consume first scan. */
  172331. (*cinfo->inputctl->start_input_pass) (cinfo);
  172332. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172333. /* If jpeg_start_decompress will read the whole file, initialize
  172334. * progress monitoring appropriately. The input step is counted
  172335. * as one pass.
  172336. */
  172337. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172338. cinfo->inputctl->has_multiple_scans) {
  172339. int nscans;
  172340. /* Estimate number of scans to set pass_limit. */
  172341. if (cinfo->progressive_mode) {
  172342. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172343. nscans = 2 + 3 * cinfo->num_components;
  172344. } else {
  172345. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172346. nscans = cinfo->num_components;
  172347. }
  172348. cinfo->progress->pass_counter = 0L;
  172349. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172350. cinfo->progress->completed_passes = 0;
  172351. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172352. /* Count the input pass as done */
  172353. master->pass_number++;
  172354. }
  172355. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172356. }
  172357. /*
  172358. * Per-pass setup.
  172359. * This is called at the beginning of each output pass. We determine which
  172360. * modules will be active during this pass and give them appropriate
  172361. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172362. * is a "real" output pass or a dummy pass for color quantization.
  172363. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172364. */
  172365. METHODDEF(void)
  172366. prepare_for_output_pass (j_decompress_ptr cinfo)
  172367. {
  172368. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172369. if (master->pub.is_dummy_pass) {
  172370. #ifdef QUANT_2PASS_SUPPORTED
  172371. /* Final pass of 2-pass quantization */
  172372. master->pub.is_dummy_pass = FALSE;
  172373. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172374. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172375. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172376. #else
  172377. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172378. #endif /* QUANT_2PASS_SUPPORTED */
  172379. } else {
  172380. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172381. /* Select new quantization method */
  172382. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172383. cinfo->cquantize = master->quantizer_2pass;
  172384. master->pub.is_dummy_pass = TRUE;
  172385. } else if (cinfo->enable_1pass_quant) {
  172386. cinfo->cquantize = master->quantizer_1pass;
  172387. } else {
  172388. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172389. }
  172390. }
  172391. (*cinfo->idct->start_pass) (cinfo);
  172392. (*cinfo->coef->start_output_pass) (cinfo);
  172393. if (! cinfo->raw_data_out) {
  172394. if (! master->using_merged_upsample)
  172395. (*cinfo->cconvert->start_pass) (cinfo);
  172396. (*cinfo->upsample->start_pass) (cinfo);
  172397. if (cinfo->quantize_colors)
  172398. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172399. (*cinfo->post->start_pass) (cinfo,
  172400. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172401. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172402. }
  172403. }
  172404. /* Set up progress monitor's pass info if present */
  172405. if (cinfo->progress != NULL) {
  172406. cinfo->progress->completed_passes = master->pass_number;
  172407. cinfo->progress->total_passes = master->pass_number +
  172408. (master->pub.is_dummy_pass ? 2 : 1);
  172409. /* In buffered-image mode, we assume one more output pass if EOI not
  172410. * yet reached, but no more passes if EOI has been reached.
  172411. */
  172412. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172413. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172414. }
  172415. }
  172416. }
  172417. /*
  172418. * Finish up at end of an output pass.
  172419. */
  172420. METHODDEF(void)
  172421. finish_output_pass (j_decompress_ptr cinfo)
  172422. {
  172423. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172424. if (cinfo->quantize_colors)
  172425. (*cinfo->cquantize->finish_pass) (cinfo);
  172426. master->pass_number++;
  172427. }
  172428. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172429. /*
  172430. * Switch to a new external colormap between output passes.
  172431. */
  172432. GLOBAL(void)
  172433. jpeg_new_colormap (j_decompress_ptr cinfo)
  172434. {
  172435. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172436. /* Prevent application from calling me at wrong times */
  172437. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172438. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172439. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172440. cinfo->colormap != NULL) {
  172441. /* Select 2-pass quantizer for external colormap use */
  172442. cinfo->cquantize = master->quantizer_2pass;
  172443. /* Notify quantizer of colormap change */
  172444. (*cinfo->cquantize->new_color_map) (cinfo);
  172445. master->pub.is_dummy_pass = FALSE; /* just in case */
  172446. } else
  172447. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172448. }
  172449. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172450. /*
  172451. * Initialize master decompression control and select active modules.
  172452. * This is performed at the start of jpeg_start_decompress.
  172453. */
  172454. GLOBAL(void)
  172455. jinit_master_decompress (j_decompress_ptr cinfo)
  172456. {
  172457. my_master_ptr6 master;
  172458. master = (my_master_ptr6)
  172459. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172460. SIZEOF(my_decomp_master));
  172461. cinfo->master = (struct jpeg_decomp_master *) master;
  172462. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172463. master->pub.finish_output_pass = finish_output_pass;
  172464. master->pub.is_dummy_pass = FALSE;
  172465. master_selection(cinfo);
  172466. }
  172467. /*** End of inlined file: jdmaster.c ***/
  172468. #undef FIX
  172469. /*** Start of inlined file: jdmerge.c ***/
  172470. #define JPEG_INTERNALS
  172471. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172472. /* Private subobject */
  172473. typedef struct {
  172474. struct jpeg_upsampler pub; /* public fields */
  172475. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172476. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172477. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172478. JSAMPARRAY output_buf));
  172479. /* Private state for YCC->RGB conversion */
  172480. int * Cr_r_tab; /* => table for Cr to R conversion */
  172481. int * Cb_b_tab; /* => table for Cb to B conversion */
  172482. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172483. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172484. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172485. * We need a "spare" row buffer to hold the second output row if the
  172486. * application provides just a one-row buffer; we also use the spare
  172487. * to discard the dummy last row if the image height is odd.
  172488. */
  172489. JSAMPROW spare_row;
  172490. boolean spare_full; /* T if spare buffer is occupied */
  172491. JDIMENSION out_row_width; /* samples per output row */
  172492. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172493. } my_upsampler;
  172494. typedef my_upsampler * my_upsample_ptr;
  172495. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172496. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172497. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172498. /*
  172499. * Initialize tables for YCC->RGB colorspace conversion.
  172500. * This is taken directly from jdcolor.c; see that file for more info.
  172501. */
  172502. LOCAL(void)
  172503. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172504. {
  172505. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172506. int i;
  172507. INT32 x;
  172508. SHIFT_TEMPS
  172509. upsample->Cr_r_tab = (int *)
  172510. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172511. (MAXJSAMPLE+1) * SIZEOF(int));
  172512. upsample->Cb_b_tab = (int *)
  172513. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172514. (MAXJSAMPLE+1) * SIZEOF(int));
  172515. upsample->Cr_g_tab = (INT32 *)
  172516. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172517. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172518. upsample->Cb_g_tab = (INT32 *)
  172519. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172520. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172521. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172522. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172523. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172524. /* Cr=>R value is nearest int to 1.40200 * x */
  172525. upsample->Cr_r_tab[i] = (int)
  172526. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172527. /* Cb=>B value is nearest int to 1.77200 * x */
  172528. upsample->Cb_b_tab[i] = (int)
  172529. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172530. /* Cr=>G value is scaled-up -0.71414 * x */
  172531. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172532. /* Cb=>G value is scaled-up -0.34414 * x */
  172533. /* We also add in ONE_HALF so that need not do it in inner loop */
  172534. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172535. }
  172536. }
  172537. /*
  172538. * Initialize for an upsampling pass.
  172539. */
  172540. METHODDEF(void)
  172541. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172542. {
  172543. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172544. /* Mark the spare buffer empty */
  172545. upsample->spare_full = FALSE;
  172546. /* Initialize total-height counter for detecting bottom of image */
  172547. upsample->rows_to_go = cinfo->output_height;
  172548. }
  172549. /*
  172550. * Control routine to do upsampling (and color conversion).
  172551. *
  172552. * The control routine just handles the row buffering considerations.
  172553. */
  172554. METHODDEF(void)
  172555. merged_2v_upsample (j_decompress_ptr cinfo,
  172556. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172557. JDIMENSION,
  172558. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172559. JDIMENSION out_rows_avail)
  172560. /* 2:1 vertical sampling case: may need a spare row. */
  172561. {
  172562. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172563. JSAMPROW work_ptrs[2];
  172564. JDIMENSION num_rows; /* number of rows returned to caller */
  172565. if (upsample->spare_full) {
  172566. /* If we have a spare row saved from a previous cycle, just return it. */
  172567. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172568. 1, upsample->out_row_width);
  172569. num_rows = 1;
  172570. upsample->spare_full = FALSE;
  172571. } else {
  172572. /* Figure number of rows to return to caller. */
  172573. num_rows = 2;
  172574. /* Not more than the distance to the end of the image. */
  172575. if (num_rows > upsample->rows_to_go)
  172576. num_rows = upsample->rows_to_go;
  172577. /* And not more than what the client can accept: */
  172578. out_rows_avail -= *out_row_ctr;
  172579. if (num_rows > out_rows_avail)
  172580. num_rows = out_rows_avail;
  172581. /* Create output pointer array for upsampler. */
  172582. work_ptrs[0] = output_buf[*out_row_ctr];
  172583. if (num_rows > 1) {
  172584. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172585. } else {
  172586. work_ptrs[1] = upsample->spare_row;
  172587. upsample->spare_full = TRUE;
  172588. }
  172589. /* Now do the upsampling. */
  172590. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172591. }
  172592. /* Adjust counts */
  172593. *out_row_ctr += num_rows;
  172594. upsample->rows_to_go -= num_rows;
  172595. /* When the buffer is emptied, declare this input row group consumed */
  172596. if (! upsample->spare_full)
  172597. (*in_row_group_ctr)++;
  172598. }
  172599. METHODDEF(void)
  172600. merged_1v_upsample (j_decompress_ptr cinfo,
  172601. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172602. JDIMENSION,
  172603. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172604. JDIMENSION)
  172605. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172606. {
  172607. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172608. /* Just do the upsampling. */
  172609. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172610. output_buf + *out_row_ctr);
  172611. /* Adjust counts */
  172612. (*out_row_ctr)++;
  172613. (*in_row_group_ctr)++;
  172614. }
  172615. /*
  172616. * These are the routines invoked by the control routines to do
  172617. * the actual upsampling/conversion. One row group is processed per call.
  172618. *
  172619. * Note: since we may be writing directly into application-supplied buffers,
  172620. * we have to be honest about the output width; we can't assume the buffer
  172621. * has been rounded up to an even width.
  172622. */
  172623. /*
  172624. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172625. */
  172626. METHODDEF(void)
  172627. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172628. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172629. JSAMPARRAY output_buf)
  172630. {
  172631. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172632. register int y, cred, cgreen, cblue;
  172633. int cb, cr;
  172634. register JSAMPROW outptr;
  172635. JSAMPROW inptr0, inptr1, inptr2;
  172636. JDIMENSION col;
  172637. /* copy these pointers into registers if possible */
  172638. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172639. int * Crrtab = upsample->Cr_r_tab;
  172640. int * Cbbtab = upsample->Cb_b_tab;
  172641. INT32 * Crgtab = upsample->Cr_g_tab;
  172642. INT32 * Cbgtab = upsample->Cb_g_tab;
  172643. SHIFT_TEMPS
  172644. inptr0 = input_buf[0][in_row_group_ctr];
  172645. inptr1 = input_buf[1][in_row_group_ctr];
  172646. inptr2 = input_buf[2][in_row_group_ctr];
  172647. outptr = output_buf[0];
  172648. /* Loop for each pair of output pixels */
  172649. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172650. /* Do the chroma part of the calculation */
  172651. cb = GETJSAMPLE(*inptr1++);
  172652. cr = GETJSAMPLE(*inptr2++);
  172653. cred = Crrtab[cr];
  172654. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172655. cblue = Cbbtab[cb];
  172656. /* Fetch 2 Y values and emit 2 pixels */
  172657. y = GETJSAMPLE(*inptr0++);
  172658. outptr[RGB_RED] = range_limit[y + cred];
  172659. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172660. outptr[RGB_BLUE] = range_limit[y + cblue];
  172661. outptr += RGB_PIXELSIZE;
  172662. y = GETJSAMPLE(*inptr0++);
  172663. outptr[RGB_RED] = range_limit[y + cred];
  172664. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172665. outptr[RGB_BLUE] = range_limit[y + cblue];
  172666. outptr += RGB_PIXELSIZE;
  172667. }
  172668. /* If image width is odd, do the last output column separately */
  172669. if (cinfo->output_width & 1) {
  172670. cb = GETJSAMPLE(*inptr1);
  172671. cr = GETJSAMPLE(*inptr2);
  172672. cred = Crrtab[cr];
  172673. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172674. cblue = Cbbtab[cb];
  172675. y = GETJSAMPLE(*inptr0);
  172676. outptr[RGB_RED] = range_limit[y + cred];
  172677. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172678. outptr[RGB_BLUE] = range_limit[y + cblue];
  172679. }
  172680. }
  172681. /*
  172682. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172683. */
  172684. METHODDEF(void)
  172685. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172686. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172687. JSAMPARRAY output_buf)
  172688. {
  172689. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172690. register int y, cred, cgreen, cblue;
  172691. int cb, cr;
  172692. register JSAMPROW outptr0, outptr1;
  172693. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172694. JDIMENSION col;
  172695. /* copy these pointers into registers if possible */
  172696. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172697. int * Crrtab = upsample->Cr_r_tab;
  172698. int * Cbbtab = upsample->Cb_b_tab;
  172699. INT32 * Crgtab = upsample->Cr_g_tab;
  172700. INT32 * Cbgtab = upsample->Cb_g_tab;
  172701. SHIFT_TEMPS
  172702. inptr00 = input_buf[0][in_row_group_ctr*2];
  172703. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172704. inptr1 = input_buf[1][in_row_group_ctr];
  172705. inptr2 = input_buf[2][in_row_group_ctr];
  172706. outptr0 = output_buf[0];
  172707. outptr1 = output_buf[1];
  172708. /* Loop for each group of output pixels */
  172709. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172710. /* Do the chroma part of the calculation */
  172711. cb = GETJSAMPLE(*inptr1++);
  172712. cr = GETJSAMPLE(*inptr2++);
  172713. cred = Crrtab[cr];
  172714. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172715. cblue = Cbbtab[cb];
  172716. /* Fetch 4 Y values and emit 4 pixels */
  172717. y = GETJSAMPLE(*inptr00++);
  172718. outptr0[RGB_RED] = range_limit[y + cred];
  172719. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172720. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172721. outptr0 += RGB_PIXELSIZE;
  172722. y = GETJSAMPLE(*inptr00++);
  172723. outptr0[RGB_RED] = range_limit[y + cred];
  172724. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172725. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172726. outptr0 += RGB_PIXELSIZE;
  172727. y = GETJSAMPLE(*inptr01++);
  172728. outptr1[RGB_RED] = range_limit[y + cred];
  172729. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172730. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172731. outptr1 += RGB_PIXELSIZE;
  172732. y = GETJSAMPLE(*inptr01++);
  172733. outptr1[RGB_RED] = range_limit[y + cred];
  172734. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172735. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172736. outptr1 += RGB_PIXELSIZE;
  172737. }
  172738. /* If image width is odd, do the last output column separately */
  172739. if (cinfo->output_width & 1) {
  172740. cb = GETJSAMPLE(*inptr1);
  172741. cr = GETJSAMPLE(*inptr2);
  172742. cred = Crrtab[cr];
  172743. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172744. cblue = Cbbtab[cb];
  172745. y = GETJSAMPLE(*inptr00);
  172746. outptr0[RGB_RED] = range_limit[y + cred];
  172747. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172748. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172749. y = GETJSAMPLE(*inptr01);
  172750. outptr1[RGB_RED] = range_limit[y + cred];
  172751. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172752. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172753. }
  172754. }
  172755. /*
  172756. * Module initialization routine for merged upsampling/color conversion.
  172757. *
  172758. * NB: this is called under the conditions determined by use_merged_upsample()
  172759. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172760. * of this module; no safety checks are made here.
  172761. */
  172762. GLOBAL(void)
  172763. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172764. {
  172765. my_upsample_ptr upsample;
  172766. upsample = (my_upsample_ptr)
  172767. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172768. SIZEOF(my_upsampler));
  172769. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172770. upsample->pub.start_pass = start_pass_merged_upsample;
  172771. upsample->pub.need_context_rows = FALSE;
  172772. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172773. if (cinfo->max_v_samp_factor == 2) {
  172774. upsample->pub.upsample = merged_2v_upsample;
  172775. upsample->upmethod = h2v2_merged_upsample;
  172776. /* Allocate a spare row buffer */
  172777. upsample->spare_row = (JSAMPROW)
  172778. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172779. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172780. } else {
  172781. upsample->pub.upsample = merged_1v_upsample;
  172782. upsample->upmethod = h2v1_merged_upsample;
  172783. /* No spare row needed */
  172784. upsample->spare_row = NULL;
  172785. }
  172786. build_ycc_rgb_table2(cinfo);
  172787. }
  172788. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172789. /*** End of inlined file: jdmerge.c ***/
  172790. #undef ASSIGN_STATE
  172791. /*** Start of inlined file: jdphuff.c ***/
  172792. #define JPEG_INTERNALS
  172793. #ifdef D_PROGRESSIVE_SUPPORTED
  172794. /*
  172795. * Expanded entropy decoder object for progressive Huffman decoding.
  172796. *
  172797. * The savable_state subrecord contains fields that change within an MCU,
  172798. * but must not be updated permanently until we complete the MCU.
  172799. */
  172800. typedef struct {
  172801. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172802. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172803. } savable_state3;
  172804. /* This macro is to work around compilers with missing or broken
  172805. * structure assignment. You'll need to fix this code if you have
  172806. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172807. */
  172808. #ifndef NO_STRUCT_ASSIGN
  172809. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172810. #else
  172811. #if MAX_COMPS_IN_SCAN == 4
  172812. #define ASSIGN_STATE(dest,src) \
  172813. ((dest).EOBRUN = (src).EOBRUN, \
  172814. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172815. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172816. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172817. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172818. #endif
  172819. #endif
  172820. typedef struct {
  172821. struct jpeg_entropy_decoder pub; /* public fields */
  172822. /* These fields are loaded into local variables at start of each MCU.
  172823. * In case of suspension, we exit WITHOUT updating them.
  172824. */
  172825. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172826. savable_state3 saved; /* Other state at start of MCU */
  172827. /* These fields are NOT loaded into local working state. */
  172828. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172829. /* Pointers to derived tables (these workspaces have image lifespan) */
  172830. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172831. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172832. } phuff_entropy_decoder;
  172833. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172834. /* Forward declarations */
  172835. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172836. JBLOCKROW *MCU_data));
  172837. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172838. JBLOCKROW *MCU_data));
  172839. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172840. JBLOCKROW *MCU_data));
  172841. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172842. JBLOCKROW *MCU_data));
  172843. /*
  172844. * Initialize for a Huffman-compressed scan.
  172845. */
  172846. METHODDEF(void)
  172847. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172848. {
  172849. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172850. boolean is_DC_band, bad;
  172851. int ci, coefi, tbl;
  172852. int *coef_bit_ptr;
  172853. jpeg_component_info * compptr;
  172854. is_DC_band = (cinfo->Ss == 0);
  172855. /* Validate scan parameters */
  172856. bad = FALSE;
  172857. if (is_DC_band) {
  172858. if (cinfo->Se != 0)
  172859. bad = TRUE;
  172860. } else {
  172861. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172862. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172863. bad = TRUE;
  172864. /* AC scans may have only one component */
  172865. if (cinfo->comps_in_scan != 1)
  172866. bad = TRUE;
  172867. }
  172868. if (cinfo->Ah != 0) {
  172869. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172870. if (cinfo->Al != cinfo->Ah-1)
  172871. bad = TRUE;
  172872. }
  172873. if (cinfo->Al > 13) /* need not check for < 0 */
  172874. bad = TRUE;
  172875. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172876. * but the spec doesn't say so, and we try to be liberal about what we
  172877. * accept. Note: large Al values could result in out-of-range DC
  172878. * coefficients during early scans, leading to bizarre displays due to
  172879. * overflows in the IDCT math. But we won't crash.
  172880. */
  172881. if (bad)
  172882. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172883. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172884. /* Update progression status, and verify that scan order is legal.
  172885. * Note that inter-scan inconsistencies are treated as warnings
  172886. * not fatal errors ... not clear if this is right way to behave.
  172887. */
  172888. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172889. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172890. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172891. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172892. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172893. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172894. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172895. if (cinfo->Ah != expected)
  172896. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172897. coef_bit_ptr[coefi] = cinfo->Al;
  172898. }
  172899. }
  172900. /* Select MCU decoding routine */
  172901. if (cinfo->Ah == 0) {
  172902. if (is_DC_band)
  172903. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172904. else
  172905. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172906. } else {
  172907. if (is_DC_band)
  172908. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172909. else
  172910. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172911. }
  172912. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172913. compptr = cinfo->cur_comp_info[ci];
  172914. /* Make sure requested tables are present, and compute derived tables.
  172915. * We may build same derived table more than once, but it's not expensive.
  172916. */
  172917. if (is_DC_band) {
  172918. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172919. tbl = compptr->dc_tbl_no;
  172920. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172921. & entropy->derived_tbls[tbl]);
  172922. }
  172923. } else {
  172924. tbl = compptr->ac_tbl_no;
  172925. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172926. & entropy->derived_tbls[tbl]);
  172927. /* remember the single active table */
  172928. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172929. }
  172930. /* Initialize DC predictions to 0 */
  172931. entropy->saved.last_dc_val[ci] = 0;
  172932. }
  172933. /* Initialize bitread state variables */
  172934. entropy->bitstate.bits_left = 0;
  172935. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172936. entropy->pub.insufficient_data = FALSE;
  172937. /* Initialize private state variables */
  172938. entropy->saved.EOBRUN = 0;
  172939. /* Initialize restart counter */
  172940. entropy->restarts_to_go = cinfo->restart_interval;
  172941. }
  172942. /*
  172943. * Check for a restart marker & resynchronize decoder.
  172944. * Returns FALSE if must suspend.
  172945. */
  172946. LOCAL(boolean)
  172947. process_restartp (j_decompress_ptr cinfo)
  172948. {
  172949. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172950. int ci;
  172951. /* Throw away any unused bits remaining in bit buffer; */
  172952. /* include any full bytes in next_marker's count of discarded bytes */
  172953. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172954. entropy->bitstate.bits_left = 0;
  172955. /* Advance past the RSTn marker */
  172956. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172957. return FALSE;
  172958. /* Re-initialize DC predictions to 0 */
  172959. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172960. entropy->saved.last_dc_val[ci] = 0;
  172961. /* Re-init EOB run count, too */
  172962. entropy->saved.EOBRUN = 0;
  172963. /* Reset restart counter */
  172964. entropy->restarts_to_go = cinfo->restart_interval;
  172965. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172966. * against a marker. In that case we will end up treating the next data
  172967. * segment as empty, and we can avoid producing bogus output pixels by
  172968. * leaving the flag set.
  172969. */
  172970. if (cinfo->unread_marker == 0)
  172971. entropy->pub.insufficient_data = FALSE;
  172972. return TRUE;
  172973. }
  172974. /*
  172975. * Huffman MCU decoding.
  172976. * Each of these routines decodes and returns one MCU's worth of
  172977. * Huffman-compressed coefficients.
  172978. * The coefficients are reordered from zigzag order into natural array order,
  172979. * but are not dequantized.
  172980. *
  172981. * The i'th block of the MCU is stored into the block pointed to by
  172982. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172983. *
  172984. * We return FALSE if data source requested suspension. In that case no
  172985. * changes have been made to permanent state. (Exception: some output
  172986. * coefficients may already have been assigned. This is harmless for
  172987. * spectral selection, since we'll just re-assign them on the next call.
  172988. * Successive approximation AC refinement has to be more careful, however.)
  172989. */
  172990. /*
  172991. * MCU decoding for DC initial scan (either spectral selection,
  172992. * or first pass of successive approximation).
  172993. */
  172994. METHODDEF(boolean)
  172995. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172996. {
  172997. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172998. int Al = cinfo->Al;
  172999. register int s, r;
  173000. int blkn, ci;
  173001. JBLOCKROW block;
  173002. BITREAD_STATE_VARS;
  173003. savable_state3 state;
  173004. d_derived_tbl * tbl;
  173005. jpeg_component_info * compptr;
  173006. /* Process restart marker if needed; may have to suspend */
  173007. if (cinfo->restart_interval) {
  173008. if (entropy->restarts_to_go == 0)
  173009. if (! process_restartp(cinfo))
  173010. return FALSE;
  173011. }
  173012. /* If we've run out of data, just leave the MCU set to zeroes.
  173013. * This way, we return uniform gray for the remainder of the segment.
  173014. */
  173015. if (! entropy->pub.insufficient_data) {
  173016. /* Load up working state */
  173017. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173018. ASSIGN_STATE(state, entropy->saved);
  173019. /* Outer loop handles each block in the MCU */
  173020. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173021. block = MCU_data[blkn];
  173022. ci = cinfo->MCU_membership[blkn];
  173023. compptr = cinfo->cur_comp_info[ci];
  173024. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173025. /* Decode a single block's worth of coefficients */
  173026. /* Section F.2.2.1: decode the DC coefficient difference */
  173027. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173028. if (s) {
  173029. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173030. r = GET_BITS(s);
  173031. s = HUFF_EXTEND(r, s);
  173032. }
  173033. /* Convert DC difference to actual value, update last_dc_val */
  173034. s += state.last_dc_val[ci];
  173035. state.last_dc_val[ci] = s;
  173036. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173037. (*block)[0] = (JCOEF) (s << Al);
  173038. }
  173039. /* Completed MCU, so update state */
  173040. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173041. ASSIGN_STATE(entropy->saved, state);
  173042. }
  173043. /* Account for restart interval (no-op if not using restarts) */
  173044. entropy->restarts_to_go--;
  173045. return TRUE;
  173046. }
  173047. /*
  173048. * MCU decoding for AC initial scan (either spectral selection,
  173049. * or first pass of successive approximation).
  173050. */
  173051. METHODDEF(boolean)
  173052. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173053. {
  173054. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173055. int Se = cinfo->Se;
  173056. int Al = cinfo->Al;
  173057. register int s, k, r;
  173058. unsigned int EOBRUN;
  173059. JBLOCKROW block;
  173060. BITREAD_STATE_VARS;
  173061. d_derived_tbl * tbl;
  173062. /* Process restart marker if needed; may have to suspend */
  173063. if (cinfo->restart_interval) {
  173064. if (entropy->restarts_to_go == 0)
  173065. if (! process_restartp(cinfo))
  173066. return FALSE;
  173067. }
  173068. /* If we've run out of data, just leave the MCU set to zeroes.
  173069. * This way, we return uniform gray for the remainder of the segment.
  173070. */
  173071. if (! entropy->pub.insufficient_data) {
  173072. /* Load up working state.
  173073. * We can avoid loading/saving bitread state if in an EOB run.
  173074. */
  173075. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173076. /* There is always only one block per MCU */
  173077. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173078. EOBRUN--; /* ...process it now (we do nothing) */
  173079. else {
  173080. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173081. block = MCU_data[0];
  173082. tbl = entropy->ac_derived_tbl;
  173083. for (k = cinfo->Ss; k <= Se; k++) {
  173084. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173085. r = s >> 4;
  173086. s &= 15;
  173087. if (s) {
  173088. k += r;
  173089. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173090. r = GET_BITS(s);
  173091. s = HUFF_EXTEND(r, s);
  173092. /* Scale and output coefficient in natural (dezigzagged) order */
  173093. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173094. } else {
  173095. if (r == 15) { /* ZRL */
  173096. k += 15; /* skip 15 zeroes in band */
  173097. } else { /* EOBr, run length is 2^r + appended bits */
  173098. EOBRUN = 1 << r;
  173099. if (r) { /* EOBr, r > 0 */
  173100. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173101. r = GET_BITS(r);
  173102. EOBRUN += r;
  173103. }
  173104. EOBRUN--; /* this band is processed at this moment */
  173105. break; /* force end-of-band */
  173106. }
  173107. }
  173108. }
  173109. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173110. }
  173111. /* Completed MCU, so update state */
  173112. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173113. }
  173114. /* Account for restart interval (no-op if not using restarts) */
  173115. entropy->restarts_to_go--;
  173116. return TRUE;
  173117. }
  173118. /*
  173119. * MCU decoding for DC successive approximation refinement scan.
  173120. * Note: we assume such scans can be multi-component, although the spec
  173121. * is not very clear on the point.
  173122. */
  173123. METHODDEF(boolean)
  173124. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173125. {
  173126. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173127. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173128. int blkn;
  173129. JBLOCKROW block;
  173130. BITREAD_STATE_VARS;
  173131. /* Process restart marker if needed; may have to suspend */
  173132. if (cinfo->restart_interval) {
  173133. if (entropy->restarts_to_go == 0)
  173134. if (! process_restartp(cinfo))
  173135. return FALSE;
  173136. }
  173137. /* Not worth the cycles to check insufficient_data here,
  173138. * since we will not change the data anyway if we read zeroes.
  173139. */
  173140. /* Load up working state */
  173141. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173142. /* Outer loop handles each block in the MCU */
  173143. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173144. block = MCU_data[blkn];
  173145. /* Encoded data is simply the next bit of the two's-complement DC value */
  173146. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173147. if (GET_BITS(1))
  173148. (*block)[0] |= p1;
  173149. /* Note: since we use |=, repeating the assignment later is safe */
  173150. }
  173151. /* Completed MCU, so update state */
  173152. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173153. /* Account for restart interval (no-op if not using restarts) */
  173154. entropy->restarts_to_go--;
  173155. return TRUE;
  173156. }
  173157. /*
  173158. * MCU decoding for AC successive approximation refinement scan.
  173159. */
  173160. METHODDEF(boolean)
  173161. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173162. {
  173163. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173164. int Se = cinfo->Se;
  173165. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173166. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173167. register int s, k, r;
  173168. unsigned int EOBRUN;
  173169. JBLOCKROW block;
  173170. JCOEFPTR thiscoef;
  173171. BITREAD_STATE_VARS;
  173172. d_derived_tbl * tbl;
  173173. int num_newnz;
  173174. int newnz_pos[DCTSIZE2];
  173175. /* Process restart marker if needed; may have to suspend */
  173176. if (cinfo->restart_interval) {
  173177. if (entropy->restarts_to_go == 0)
  173178. if (! process_restartp(cinfo))
  173179. return FALSE;
  173180. }
  173181. /* If we've run out of data, don't modify the MCU.
  173182. */
  173183. if (! entropy->pub.insufficient_data) {
  173184. /* Load up working state */
  173185. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173186. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173187. /* There is always only one block per MCU */
  173188. block = MCU_data[0];
  173189. tbl = entropy->ac_derived_tbl;
  173190. /* If we are forced to suspend, we must undo the assignments to any newly
  173191. * nonzero coefficients in the block, because otherwise we'd get confused
  173192. * next time about which coefficients were already nonzero.
  173193. * But we need not undo addition of bits to already-nonzero coefficients;
  173194. * instead, we can test the current bit to see if we already did it.
  173195. */
  173196. num_newnz = 0;
  173197. /* initialize coefficient loop counter to start of band */
  173198. k = cinfo->Ss;
  173199. if (EOBRUN == 0) {
  173200. for (; k <= Se; k++) {
  173201. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173202. r = s >> 4;
  173203. s &= 15;
  173204. if (s) {
  173205. if (s != 1) /* size of new coef should always be 1 */
  173206. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173207. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173208. if (GET_BITS(1))
  173209. s = p1; /* newly nonzero coef is positive */
  173210. else
  173211. s = m1; /* newly nonzero coef is negative */
  173212. } else {
  173213. if (r != 15) {
  173214. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173215. if (r) {
  173216. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173217. r = GET_BITS(r);
  173218. EOBRUN += r;
  173219. }
  173220. break; /* rest of block is handled by EOB logic */
  173221. }
  173222. /* note s = 0 for processing ZRL */
  173223. }
  173224. /* Advance over already-nonzero coefs and r still-zero coefs,
  173225. * appending correction bits to the nonzeroes. A correction bit is 1
  173226. * if the absolute value of the coefficient must be increased.
  173227. */
  173228. do {
  173229. thiscoef = *block + jpeg_natural_order[k];
  173230. if (*thiscoef != 0) {
  173231. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173232. if (GET_BITS(1)) {
  173233. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173234. if (*thiscoef >= 0)
  173235. *thiscoef += p1;
  173236. else
  173237. *thiscoef += m1;
  173238. }
  173239. }
  173240. } else {
  173241. if (--r < 0)
  173242. break; /* reached target zero coefficient */
  173243. }
  173244. k++;
  173245. } while (k <= Se);
  173246. if (s) {
  173247. int pos = jpeg_natural_order[k];
  173248. /* Output newly nonzero coefficient */
  173249. (*block)[pos] = (JCOEF) s;
  173250. /* Remember its position in case we have to suspend */
  173251. newnz_pos[num_newnz++] = pos;
  173252. }
  173253. }
  173254. }
  173255. if (EOBRUN > 0) {
  173256. /* Scan any remaining coefficient positions after the end-of-band
  173257. * (the last newly nonzero coefficient, if any). Append a correction
  173258. * bit to each already-nonzero coefficient. A correction bit is 1
  173259. * if the absolute value of the coefficient must be increased.
  173260. */
  173261. for (; k <= Se; k++) {
  173262. thiscoef = *block + jpeg_natural_order[k];
  173263. if (*thiscoef != 0) {
  173264. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173265. if (GET_BITS(1)) {
  173266. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173267. if (*thiscoef >= 0)
  173268. *thiscoef += p1;
  173269. else
  173270. *thiscoef += m1;
  173271. }
  173272. }
  173273. }
  173274. }
  173275. /* Count one block completed in EOB run */
  173276. EOBRUN--;
  173277. }
  173278. /* Completed MCU, so update state */
  173279. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173280. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173281. }
  173282. /* Account for restart interval (no-op if not using restarts) */
  173283. entropy->restarts_to_go--;
  173284. return TRUE;
  173285. undoit:
  173286. /* Re-zero any output coefficients that we made newly nonzero */
  173287. while (num_newnz > 0)
  173288. (*block)[newnz_pos[--num_newnz]] = 0;
  173289. return FALSE;
  173290. }
  173291. /*
  173292. * Module initialization routine for progressive Huffman entropy decoding.
  173293. */
  173294. GLOBAL(void)
  173295. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173296. {
  173297. phuff_entropy_ptr2 entropy;
  173298. int *coef_bit_ptr;
  173299. int ci, i;
  173300. entropy = (phuff_entropy_ptr2)
  173301. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173302. SIZEOF(phuff_entropy_decoder));
  173303. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173304. entropy->pub.start_pass = start_pass_phuff_decoder;
  173305. /* Mark derived tables unallocated */
  173306. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173307. entropy->derived_tbls[i] = NULL;
  173308. }
  173309. /* Create progression status table */
  173310. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173311. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173312. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173313. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173314. for (ci = 0; ci < cinfo->num_components; ci++)
  173315. for (i = 0; i < DCTSIZE2; i++)
  173316. *coef_bit_ptr++ = -1;
  173317. }
  173318. #endif /* D_PROGRESSIVE_SUPPORTED */
  173319. /*** End of inlined file: jdphuff.c ***/
  173320. /*** Start of inlined file: jdpostct.c ***/
  173321. #define JPEG_INTERNALS
  173322. /* Private buffer controller object */
  173323. typedef struct {
  173324. struct jpeg_d_post_controller pub; /* public fields */
  173325. /* Color quantization source buffer: this holds output data from
  173326. * the upsample/color conversion step to be passed to the quantizer.
  173327. * For two-pass color quantization, we need a full-image buffer;
  173328. * for one-pass operation, a strip buffer is sufficient.
  173329. */
  173330. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173331. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173332. JDIMENSION strip_height; /* buffer size in rows */
  173333. /* for two-pass mode only: */
  173334. JDIMENSION starting_row; /* row # of first row in current strip */
  173335. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173336. } my_post_controller;
  173337. typedef my_post_controller * my_post_ptr;
  173338. /* Forward declarations */
  173339. METHODDEF(void) post_process_1pass
  173340. JPP((j_decompress_ptr cinfo,
  173341. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173342. JDIMENSION in_row_groups_avail,
  173343. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173344. JDIMENSION out_rows_avail));
  173345. #ifdef QUANT_2PASS_SUPPORTED
  173346. METHODDEF(void) post_process_prepass
  173347. JPP((j_decompress_ptr cinfo,
  173348. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173349. JDIMENSION in_row_groups_avail,
  173350. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173351. JDIMENSION out_rows_avail));
  173352. METHODDEF(void) post_process_2pass
  173353. JPP((j_decompress_ptr cinfo,
  173354. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173355. JDIMENSION in_row_groups_avail,
  173356. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173357. JDIMENSION out_rows_avail));
  173358. #endif
  173359. /*
  173360. * Initialize for a processing pass.
  173361. */
  173362. METHODDEF(void)
  173363. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173364. {
  173365. my_post_ptr post = (my_post_ptr) cinfo->post;
  173366. switch (pass_mode) {
  173367. case JBUF_PASS_THRU:
  173368. if (cinfo->quantize_colors) {
  173369. /* Single-pass processing with color quantization. */
  173370. post->pub.post_process_data = post_process_1pass;
  173371. /* We could be doing buffered-image output before starting a 2-pass
  173372. * color quantization; in that case, jinit_d_post_controller did not
  173373. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173374. */
  173375. if (post->buffer == NULL) {
  173376. post->buffer = (*cinfo->mem->access_virt_sarray)
  173377. ((j_common_ptr) cinfo, post->whole_image,
  173378. (JDIMENSION) 0, post->strip_height, TRUE);
  173379. }
  173380. } else {
  173381. /* For single-pass processing without color quantization,
  173382. * I have no work to do; just call the upsampler directly.
  173383. */
  173384. post->pub.post_process_data = cinfo->upsample->upsample;
  173385. }
  173386. break;
  173387. #ifdef QUANT_2PASS_SUPPORTED
  173388. case JBUF_SAVE_AND_PASS:
  173389. /* First pass of 2-pass quantization */
  173390. if (post->whole_image == NULL)
  173391. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173392. post->pub.post_process_data = post_process_prepass;
  173393. break;
  173394. case JBUF_CRANK_DEST:
  173395. /* Second pass of 2-pass quantization */
  173396. if (post->whole_image == NULL)
  173397. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173398. post->pub.post_process_data = post_process_2pass;
  173399. break;
  173400. #endif /* QUANT_2PASS_SUPPORTED */
  173401. default:
  173402. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173403. break;
  173404. }
  173405. post->starting_row = post->next_row = 0;
  173406. }
  173407. /*
  173408. * Process some data in the one-pass (strip buffer) case.
  173409. * This is used for color precision reduction as well as one-pass quantization.
  173410. */
  173411. METHODDEF(void)
  173412. post_process_1pass (j_decompress_ptr cinfo,
  173413. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173414. JDIMENSION in_row_groups_avail,
  173415. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173416. JDIMENSION out_rows_avail)
  173417. {
  173418. my_post_ptr post = (my_post_ptr) cinfo->post;
  173419. JDIMENSION num_rows, max_rows;
  173420. /* Fill the buffer, but not more than what we can dump out in one go. */
  173421. /* Note we rely on the upsampler to detect bottom of image. */
  173422. max_rows = out_rows_avail - *out_row_ctr;
  173423. if (max_rows > post->strip_height)
  173424. max_rows = post->strip_height;
  173425. num_rows = 0;
  173426. (*cinfo->upsample->upsample) (cinfo,
  173427. input_buf, in_row_group_ctr, in_row_groups_avail,
  173428. post->buffer, &num_rows, max_rows);
  173429. /* Quantize and emit data. */
  173430. (*cinfo->cquantize->color_quantize) (cinfo,
  173431. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173432. *out_row_ctr += num_rows;
  173433. }
  173434. #ifdef QUANT_2PASS_SUPPORTED
  173435. /*
  173436. * Process some data in the first pass of 2-pass quantization.
  173437. */
  173438. METHODDEF(void)
  173439. post_process_prepass (j_decompress_ptr cinfo,
  173440. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173441. JDIMENSION in_row_groups_avail,
  173442. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173443. JDIMENSION)
  173444. {
  173445. my_post_ptr post = (my_post_ptr) cinfo->post;
  173446. JDIMENSION old_next_row, num_rows;
  173447. /* Reposition virtual buffer if at start of strip. */
  173448. if (post->next_row == 0) {
  173449. post->buffer = (*cinfo->mem->access_virt_sarray)
  173450. ((j_common_ptr) cinfo, post->whole_image,
  173451. post->starting_row, post->strip_height, TRUE);
  173452. }
  173453. /* Upsample some data (up to a strip height's worth). */
  173454. old_next_row = post->next_row;
  173455. (*cinfo->upsample->upsample) (cinfo,
  173456. input_buf, in_row_group_ctr, in_row_groups_avail,
  173457. post->buffer, &post->next_row, post->strip_height);
  173458. /* Allow quantizer to scan new data. No data is emitted, */
  173459. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173460. if (post->next_row > old_next_row) {
  173461. num_rows = post->next_row - old_next_row;
  173462. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173463. (JSAMPARRAY) NULL, (int) num_rows);
  173464. *out_row_ctr += num_rows;
  173465. }
  173466. /* Advance if we filled the strip. */
  173467. if (post->next_row >= post->strip_height) {
  173468. post->starting_row += post->strip_height;
  173469. post->next_row = 0;
  173470. }
  173471. }
  173472. /*
  173473. * Process some data in the second pass of 2-pass quantization.
  173474. */
  173475. METHODDEF(void)
  173476. post_process_2pass (j_decompress_ptr cinfo,
  173477. JSAMPIMAGE, JDIMENSION *,
  173478. JDIMENSION,
  173479. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173480. JDIMENSION out_rows_avail)
  173481. {
  173482. my_post_ptr post = (my_post_ptr) cinfo->post;
  173483. JDIMENSION num_rows, max_rows;
  173484. /* Reposition virtual buffer if at start of strip. */
  173485. if (post->next_row == 0) {
  173486. post->buffer = (*cinfo->mem->access_virt_sarray)
  173487. ((j_common_ptr) cinfo, post->whole_image,
  173488. post->starting_row, post->strip_height, FALSE);
  173489. }
  173490. /* Determine number of rows to emit. */
  173491. num_rows = post->strip_height - post->next_row; /* available in strip */
  173492. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173493. if (num_rows > max_rows)
  173494. num_rows = max_rows;
  173495. /* We have to check bottom of image here, can't depend on upsampler. */
  173496. max_rows = cinfo->output_height - post->starting_row;
  173497. if (num_rows > max_rows)
  173498. num_rows = max_rows;
  173499. /* Quantize and emit data. */
  173500. (*cinfo->cquantize->color_quantize) (cinfo,
  173501. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173502. (int) num_rows);
  173503. *out_row_ctr += num_rows;
  173504. /* Advance if we filled the strip. */
  173505. post->next_row += num_rows;
  173506. if (post->next_row >= post->strip_height) {
  173507. post->starting_row += post->strip_height;
  173508. post->next_row = 0;
  173509. }
  173510. }
  173511. #endif /* QUANT_2PASS_SUPPORTED */
  173512. /*
  173513. * Initialize postprocessing controller.
  173514. */
  173515. GLOBAL(void)
  173516. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173517. {
  173518. my_post_ptr post;
  173519. post = (my_post_ptr)
  173520. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173521. SIZEOF(my_post_controller));
  173522. cinfo->post = (struct jpeg_d_post_controller *) post;
  173523. post->pub.start_pass = start_pass_dpost;
  173524. post->whole_image = NULL; /* flag for no virtual arrays */
  173525. post->buffer = NULL; /* flag for no strip buffer */
  173526. /* Create the quantization buffer, if needed */
  173527. if (cinfo->quantize_colors) {
  173528. /* The buffer strip height is max_v_samp_factor, which is typically
  173529. * an efficient number of rows for upsampling to return.
  173530. * (In the presence of output rescaling, we might want to be smarter?)
  173531. */
  173532. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173533. if (need_full_buffer) {
  173534. /* Two-pass color quantization: need full-image storage. */
  173535. /* We round up the number of rows to a multiple of the strip height. */
  173536. #ifdef QUANT_2PASS_SUPPORTED
  173537. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173538. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173539. cinfo->output_width * cinfo->out_color_components,
  173540. (JDIMENSION) jround_up((long) cinfo->output_height,
  173541. (long) post->strip_height),
  173542. post->strip_height);
  173543. #else
  173544. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173545. #endif /* QUANT_2PASS_SUPPORTED */
  173546. } else {
  173547. /* One-pass color quantization: just make a strip buffer. */
  173548. post->buffer = (*cinfo->mem->alloc_sarray)
  173549. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173550. cinfo->output_width * cinfo->out_color_components,
  173551. post->strip_height);
  173552. }
  173553. }
  173554. }
  173555. /*** End of inlined file: jdpostct.c ***/
  173556. #undef FIX
  173557. /*** Start of inlined file: jdsample.c ***/
  173558. #define JPEG_INTERNALS
  173559. /* Pointer to routine to upsample a single component */
  173560. typedef JMETHOD(void, upsample1_ptr,
  173561. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173562. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173563. /* Private subobject */
  173564. typedef struct {
  173565. struct jpeg_upsampler pub; /* public fields */
  173566. /* Color conversion buffer. When using separate upsampling and color
  173567. * conversion steps, this buffer holds one upsampled row group until it
  173568. * has been color converted and output.
  173569. * Note: we do not allocate any storage for component(s) which are full-size,
  173570. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173571. * simply set to point to the input data array, thereby avoiding copying.
  173572. */
  173573. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173574. /* Per-component upsampling method pointers */
  173575. upsample1_ptr methods[MAX_COMPONENTS];
  173576. int next_row_out; /* counts rows emitted from color_buf */
  173577. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173578. /* Height of an input row group for each component. */
  173579. int rowgroup_height[MAX_COMPONENTS];
  173580. /* These arrays save pixel expansion factors so that int_expand need not
  173581. * recompute them each time. They are unused for other upsampling methods.
  173582. */
  173583. UINT8 h_expand[MAX_COMPONENTS];
  173584. UINT8 v_expand[MAX_COMPONENTS];
  173585. } my_upsampler2;
  173586. typedef my_upsampler2 * my_upsample_ptr2;
  173587. /*
  173588. * Initialize for an upsampling pass.
  173589. */
  173590. METHODDEF(void)
  173591. start_pass_upsample (j_decompress_ptr cinfo)
  173592. {
  173593. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173594. /* Mark the conversion buffer empty */
  173595. upsample->next_row_out = cinfo->max_v_samp_factor;
  173596. /* Initialize total-height counter for detecting bottom of image */
  173597. upsample->rows_to_go = cinfo->output_height;
  173598. }
  173599. /*
  173600. * Control routine to do upsampling (and color conversion).
  173601. *
  173602. * In this version we upsample each component independently.
  173603. * We upsample one row group into the conversion buffer, then apply
  173604. * color conversion a row at a time.
  173605. */
  173606. METHODDEF(void)
  173607. sep_upsample (j_decompress_ptr cinfo,
  173608. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173609. JDIMENSION,
  173610. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173611. JDIMENSION out_rows_avail)
  173612. {
  173613. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173614. int ci;
  173615. jpeg_component_info * compptr;
  173616. JDIMENSION num_rows;
  173617. /* Fill the conversion buffer, if it's empty */
  173618. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173619. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173620. ci++, compptr++) {
  173621. /* Invoke per-component upsample method. Notice we pass a POINTER
  173622. * to color_buf[ci], so that fullsize_upsample can change it.
  173623. */
  173624. (*upsample->methods[ci]) (cinfo, compptr,
  173625. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173626. upsample->color_buf + ci);
  173627. }
  173628. upsample->next_row_out = 0;
  173629. }
  173630. /* Color-convert and emit rows */
  173631. /* How many we have in the buffer: */
  173632. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173633. /* Not more than the distance to the end of the image. Need this test
  173634. * in case the image height is not a multiple of max_v_samp_factor:
  173635. */
  173636. if (num_rows > upsample->rows_to_go)
  173637. num_rows = upsample->rows_to_go;
  173638. /* And not more than what the client can accept: */
  173639. out_rows_avail -= *out_row_ctr;
  173640. if (num_rows > out_rows_avail)
  173641. num_rows = out_rows_avail;
  173642. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173643. (JDIMENSION) upsample->next_row_out,
  173644. output_buf + *out_row_ctr,
  173645. (int) num_rows);
  173646. /* Adjust counts */
  173647. *out_row_ctr += num_rows;
  173648. upsample->rows_to_go -= num_rows;
  173649. upsample->next_row_out += num_rows;
  173650. /* When the buffer is emptied, declare this input row group consumed */
  173651. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173652. (*in_row_group_ctr)++;
  173653. }
  173654. /*
  173655. * These are the routines invoked by sep_upsample to upsample pixel values
  173656. * of a single component. One row group is processed per call.
  173657. */
  173658. /*
  173659. * For full-size components, we just make color_buf[ci] point at the
  173660. * input buffer, and thus avoid copying any data. Note that this is
  173661. * safe only because sep_upsample doesn't declare the input row group
  173662. * "consumed" until we are done color converting and emitting it.
  173663. */
  173664. METHODDEF(void)
  173665. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173666. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173667. {
  173668. *output_data_ptr = input_data;
  173669. }
  173670. /*
  173671. * This is a no-op version used for "uninteresting" components.
  173672. * These components will not be referenced by color conversion.
  173673. */
  173674. METHODDEF(void)
  173675. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173676. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173677. {
  173678. *output_data_ptr = NULL; /* safety check */
  173679. }
  173680. /*
  173681. * This version handles any integral sampling ratios.
  173682. * This is not used for typical JPEG files, so it need not be fast.
  173683. * Nor, for that matter, is it particularly accurate: the algorithm is
  173684. * simple replication of the input pixel onto the corresponding output
  173685. * pixels. The hi-falutin sampling literature refers to this as a
  173686. * "box filter". A box filter tends to introduce visible artifacts,
  173687. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173688. * you would be well advised to improve this code.
  173689. */
  173690. METHODDEF(void)
  173691. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173692. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173693. {
  173694. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173695. JSAMPARRAY output_data = *output_data_ptr;
  173696. register JSAMPROW inptr, outptr;
  173697. register JSAMPLE invalue;
  173698. register int h;
  173699. JSAMPROW outend;
  173700. int h_expand, v_expand;
  173701. int inrow, outrow;
  173702. h_expand = upsample->h_expand[compptr->component_index];
  173703. v_expand = upsample->v_expand[compptr->component_index];
  173704. inrow = outrow = 0;
  173705. while (outrow < cinfo->max_v_samp_factor) {
  173706. /* Generate one output row with proper horizontal expansion */
  173707. inptr = input_data[inrow];
  173708. outptr = output_data[outrow];
  173709. outend = outptr + cinfo->output_width;
  173710. while (outptr < outend) {
  173711. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173712. for (h = h_expand; h > 0; h--) {
  173713. *outptr++ = invalue;
  173714. }
  173715. }
  173716. /* Generate any additional output rows by duplicating the first one */
  173717. if (v_expand > 1) {
  173718. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173719. v_expand-1, cinfo->output_width);
  173720. }
  173721. inrow++;
  173722. outrow += v_expand;
  173723. }
  173724. }
  173725. /*
  173726. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173727. * It's still a box filter.
  173728. */
  173729. METHODDEF(void)
  173730. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173731. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173732. {
  173733. JSAMPARRAY output_data = *output_data_ptr;
  173734. register JSAMPROW inptr, outptr;
  173735. register JSAMPLE invalue;
  173736. JSAMPROW outend;
  173737. int inrow;
  173738. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173739. inptr = input_data[inrow];
  173740. outptr = output_data[inrow];
  173741. outend = outptr + cinfo->output_width;
  173742. while (outptr < outend) {
  173743. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173744. *outptr++ = invalue;
  173745. *outptr++ = invalue;
  173746. }
  173747. }
  173748. }
  173749. /*
  173750. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173751. * It's still a box filter.
  173752. */
  173753. METHODDEF(void)
  173754. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173755. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173756. {
  173757. JSAMPARRAY output_data = *output_data_ptr;
  173758. register JSAMPROW inptr, outptr;
  173759. register JSAMPLE invalue;
  173760. JSAMPROW outend;
  173761. int inrow, outrow;
  173762. inrow = outrow = 0;
  173763. while (outrow < cinfo->max_v_samp_factor) {
  173764. inptr = input_data[inrow];
  173765. outptr = output_data[outrow];
  173766. outend = outptr + cinfo->output_width;
  173767. while (outptr < outend) {
  173768. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173769. *outptr++ = invalue;
  173770. *outptr++ = invalue;
  173771. }
  173772. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173773. 1, cinfo->output_width);
  173774. inrow++;
  173775. outrow += 2;
  173776. }
  173777. }
  173778. /*
  173779. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173780. *
  173781. * The upsampling algorithm is linear interpolation between pixel centers,
  173782. * also known as a "triangle filter". This is a good compromise between
  173783. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173784. * of the way between input pixel centers.
  173785. *
  173786. * A note about the "bias" calculations: when rounding fractional values to
  173787. * integer, we do not want to always round 0.5 up to the next integer.
  173788. * If we did that, we'd introduce a noticeable bias towards larger values.
  173789. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173790. * alternate pixel locations (a simple ordered dither pattern).
  173791. */
  173792. METHODDEF(void)
  173793. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173794. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173795. {
  173796. JSAMPARRAY output_data = *output_data_ptr;
  173797. register JSAMPROW inptr, outptr;
  173798. register int invalue;
  173799. register JDIMENSION colctr;
  173800. int inrow;
  173801. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173802. inptr = input_data[inrow];
  173803. outptr = output_data[inrow];
  173804. /* Special case for first column */
  173805. invalue = GETJSAMPLE(*inptr++);
  173806. *outptr++ = (JSAMPLE) invalue;
  173807. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173808. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173809. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173810. invalue = GETJSAMPLE(*inptr++) * 3;
  173811. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173812. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173813. }
  173814. /* Special case for last column */
  173815. invalue = GETJSAMPLE(*inptr);
  173816. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173817. *outptr++ = (JSAMPLE) invalue;
  173818. }
  173819. }
  173820. /*
  173821. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173822. * Again a triangle filter; see comments for h2v1 case, above.
  173823. *
  173824. * It is OK for us to reference the adjacent input rows because we demanded
  173825. * context from the main buffer controller (see initialization code).
  173826. */
  173827. METHODDEF(void)
  173828. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173829. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173830. {
  173831. JSAMPARRAY output_data = *output_data_ptr;
  173832. register JSAMPROW inptr0, inptr1, outptr;
  173833. #if BITS_IN_JSAMPLE == 8
  173834. register int thiscolsum, lastcolsum, nextcolsum;
  173835. #else
  173836. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173837. #endif
  173838. register JDIMENSION colctr;
  173839. int inrow, outrow, v;
  173840. inrow = outrow = 0;
  173841. while (outrow < cinfo->max_v_samp_factor) {
  173842. for (v = 0; v < 2; v++) {
  173843. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173844. inptr0 = input_data[inrow];
  173845. if (v == 0) /* next nearest is row above */
  173846. inptr1 = input_data[inrow-1];
  173847. else /* next nearest is row below */
  173848. inptr1 = input_data[inrow+1];
  173849. outptr = output_data[outrow++];
  173850. /* Special case for first column */
  173851. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173852. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173853. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173854. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173855. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173856. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173857. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173858. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173859. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173860. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173861. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173862. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173863. }
  173864. /* Special case for last column */
  173865. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173866. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173867. }
  173868. inrow++;
  173869. }
  173870. }
  173871. /*
  173872. * Module initialization routine for upsampling.
  173873. */
  173874. GLOBAL(void)
  173875. jinit_upsampler (j_decompress_ptr cinfo)
  173876. {
  173877. my_upsample_ptr2 upsample;
  173878. int ci;
  173879. jpeg_component_info * compptr;
  173880. boolean need_buffer, do_fancy;
  173881. int h_in_group, v_in_group, h_out_group, v_out_group;
  173882. upsample = (my_upsample_ptr2)
  173883. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173884. SIZEOF(my_upsampler2));
  173885. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173886. upsample->pub.start_pass = start_pass_upsample;
  173887. upsample->pub.upsample = sep_upsample;
  173888. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173889. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173890. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173891. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173892. * so don't ask for it.
  173893. */
  173894. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173895. /* Verify we can handle the sampling factors, select per-component methods,
  173896. * and create storage as needed.
  173897. */
  173898. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173899. ci++, compptr++) {
  173900. /* Compute size of an "input group" after IDCT scaling. This many samples
  173901. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173902. */
  173903. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173904. cinfo->min_DCT_scaled_size;
  173905. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173906. cinfo->min_DCT_scaled_size;
  173907. h_out_group = cinfo->max_h_samp_factor;
  173908. v_out_group = cinfo->max_v_samp_factor;
  173909. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173910. need_buffer = TRUE;
  173911. if (! compptr->component_needed) {
  173912. /* Don't bother to upsample an uninteresting component. */
  173913. upsample->methods[ci] = noop_upsample;
  173914. need_buffer = FALSE;
  173915. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173916. /* Fullsize components can be processed without any work. */
  173917. upsample->methods[ci] = fullsize_upsample;
  173918. need_buffer = FALSE;
  173919. } else if (h_in_group * 2 == h_out_group &&
  173920. v_in_group == v_out_group) {
  173921. /* Special cases for 2h1v upsampling */
  173922. if (do_fancy && compptr->downsampled_width > 2)
  173923. upsample->methods[ci] = h2v1_fancy_upsample;
  173924. else
  173925. upsample->methods[ci] = h2v1_upsample;
  173926. } else if (h_in_group * 2 == h_out_group &&
  173927. v_in_group * 2 == v_out_group) {
  173928. /* Special cases for 2h2v upsampling */
  173929. if (do_fancy && compptr->downsampled_width > 2) {
  173930. upsample->methods[ci] = h2v2_fancy_upsample;
  173931. upsample->pub.need_context_rows = TRUE;
  173932. } else
  173933. upsample->methods[ci] = h2v2_upsample;
  173934. } else if ((h_out_group % h_in_group) == 0 &&
  173935. (v_out_group % v_in_group) == 0) {
  173936. /* Generic integral-factors upsampling method */
  173937. upsample->methods[ci] = int_upsample;
  173938. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173939. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173940. } else
  173941. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173942. if (need_buffer) {
  173943. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173944. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173945. (JDIMENSION) jround_up((long) cinfo->output_width,
  173946. (long) cinfo->max_h_samp_factor),
  173947. (JDIMENSION) cinfo->max_v_samp_factor);
  173948. }
  173949. }
  173950. }
  173951. /*** End of inlined file: jdsample.c ***/
  173952. /*** Start of inlined file: jdtrans.c ***/
  173953. #define JPEG_INTERNALS
  173954. /* Forward declarations */
  173955. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173956. /*
  173957. * Read the coefficient arrays from a JPEG file.
  173958. * jpeg_read_header must be completed before calling this.
  173959. *
  173960. * The entire image is read into a set of virtual coefficient-block arrays,
  173961. * one per component. The return value is a pointer to the array of
  173962. * virtual-array descriptors. These can be manipulated directly via the
  173963. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173964. * To release the memory occupied by the virtual arrays, call
  173965. * jpeg_finish_decompress() when done with the data.
  173966. *
  173967. * An alternative usage is to simply obtain access to the coefficient arrays
  173968. * during a buffered-image-mode decompression operation. This is allowed
  173969. * after any jpeg_finish_output() call. The arrays can be accessed until
  173970. * jpeg_finish_decompress() is called. (Note that any call to the library
  173971. * may reposition the arrays, so don't rely on access_virt_barray() results
  173972. * to stay valid across library calls.)
  173973. *
  173974. * Returns NULL if suspended. This case need be checked only if
  173975. * a suspending data source is used.
  173976. */
  173977. GLOBAL(jvirt_barray_ptr *)
  173978. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173979. {
  173980. if (cinfo->global_state == DSTATE_READY) {
  173981. /* First call: initialize active modules */
  173982. transdecode_master_selection(cinfo);
  173983. cinfo->global_state = DSTATE_RDCOEFS;
  173984. }
  173985. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173986. /* Absorb whole file into the coef buffer */
  173987. for (;;) {
  173988. int retcode;
  173989. /* Call progress monitor hook if present */
  173990. if (cinfo->progress != NULL)
  173991. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173992. /* Absorb some more input */
  173993. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173994. if (retcode == JPEG_SUSPENDED)
  173995. return NULL;
  173996. if (retcode == JPEG_REACHED_EOI)
  173997. break;
  173998. /* Advance progress counter if appropriate */
  173999. if (cinfo->progress != NULL &&
  174000. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174001. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174002. /* startup underestimated number of scans; ratchet up one scan */
  174003. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174004. }
  174005. }
  174006. }
  174007. /* Set state so that jpeg_finish_decompress does the right thing */
  174008. cinfo->global_state = DSTATE_STOPPING;
  174009. }
  174010. /* At this point we should be in state DSTATE_STOPPING if being used
  174011. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174012. * to the coefficients during a full buffered-image-mode decompression.
  174013. */
  174014. if ((cinfo->global_state == DSTATE_STOPPING ||
  174015. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174016. return cinfo->coef->coef_arrays;
  174017. }
  174018. /* Oops, improper usage */
  174019. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174020. return NULL; /* keep compiler happy */
  174021. }
  174022. /*
  174023. * Master selection of decompression modules for transcoding.
  174024. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174025. */
  174026. LOCAL(void)
  174027. transdecode_master_selection (j_decompress_ptr cinfo)
  174028. {
  174029. /* This is effectively a buffered-image operation. */
  174030. cinfo->buffered_image = TRUE;
  174031. /* Entropy decoding: either Huffman or arithmetic coding. */
  174032. if (cinfo->arith_code) {
  174033. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174034. } else {
  174035. if (cinfo->progressive_mode) {
  174036. #ifdef D_PROGRESSIVE_SUPPORTED
  174037. jinit_phuff_decoder(cinfo);
  174038. #else
  174039. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174040. #endif
  174041. } else
  174042. jinit_huff_decoder(cinfo);
  174043. }
  174044. /* Always get a full-image coefficient buffer. */
  174045. jinit_d_coef_controller(cinfo, TRUE);
  174046. /* We can now tell the memory manager to allocate virtual arrays. */
  174047. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174048. /* Initialize input side of decompressor to consume first scan. */
  174049. (*cinfo->inputctl->start_input_pass) (cinfo);
  174050. /* Initialize progress monitoring. */
  174051. if (cinfo->progress != NULL) {
  174052. int nscans;
  174053. /* Estimate number of scans to set pass_limit. */
  174054. if (cinfo->progressive_mode) {
  174055. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174056. nscans = 2 + 3 * cinfo->num_components;
  174057. } else if (cinfo->inputctl->has_multiple_scans) {
  174058. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174059. nscans = cinfo->num_components;
  174060. } else {
  174061. nscans = 1;
  174062. }
  174063. cinfo->progress->pass_counter = 0L;
  174064. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174065. cinfo->progress->completed_passes = 0;
  174066. cinfo->progress->total_passes = 1;
  174067. }
  174068. }
  174069. /*** End of inlined file: jdtrans.c ***/
  174070. /*** Start of inlined file: jfdctflt.c ***/
  174071. #define JPEG_INTERNALS
  174072. #ifdef DCT_FLOAT_SUPPORTED
  174073. /*
  174074. * This module is specialized to the case DCTSIZE = 8.
  174075. */
  174076. #if DCTSIZE != 8
  174077. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174078. #endif
  174079. /*
  174080. * Perform the forward DCT on one block of samples.
  174081. */
  174082. GLOBAL(void)
  174083. jpeg_fdct_float (FAST_FLOAT * data)
  174084. {
  174085. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174086. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174087. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174088. FAST_FLOAT *dataptr;
  174089. int ctr;
  174090. /* Pass 1: process rows. */
  174091. dataptr = data;
  174092. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174093. tmp0 = dataptr[0] + dataptr[7];
  174094. tmp7 = dataptr[0] - dataptr[7];
  174095. tmp1 = dataptr[1] + dataptr[6];
  174096. tmp6 = dataptr[1] - dataptr[6];
  174097. tmp2 = dataptr[2] + dataptr[5];
  174098. tmp5 = dataptr[2] - dataptr[5];
  174099. tmp3 = dataptr[3] + dataptr[4];
  174100. tmp4 = dataptr[3] - dataptr[4];
  174101. /* Even part */
  174102. tmp10 = tmp0 + tmp3; /* phase 2 */
  174103. tmp13 = tmp0 - tmp3;
  174104. tmp11 = tmp1 + tmp2;
  174105. tmp12 = tmp1 - tmp2;
  174106. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174107. dataptr[4] = tmp10 - tmp11;
  174108. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174109. dataptr[2] = tmp13 + z1; /* phase 5 */
  174110. dataptr[6] = tmp13 - z1;
  174111. /* Odd part */
  174112. tmp10 = tmp4 + tmp5; /* phase 2 */
  174113. tmp11 = tmp5 + tmp6;
  174114. tmp12 = tmp6 + tmp7;
  174115. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174116. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174117. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174118. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174119. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174120. z11 = tmp7 + z3; /* phase 5 */
  174121. z13 = tmp7 - z3;
  174122. dataptr[5] = z13 + z2; /* phase 6 */
  174123. dataptr[3] = z13 - z2;
  174124. dataptr[1] = z11 + z4;
  174125. dataptr[7] = z11 - z4;
  174126. dataptr += DCTSIZE; /* advance pointer to next row */
  174127. }
  174128. /* Pass 2: process columns. */
  174129. dataptr = data;
  174130. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174131. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174132. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174133. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174134. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174135. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174136. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174137. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174138. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174139. /* Even part */
  174140. tmp10 = tmp0 + tmp3; /* phase 2 */
  174141. tmp13 = tmp0 - tmp3;
  174142. tmp11 = tmp1 + tmp2;
  174143. tmp12 = tmp1 - tmp2;
  174144. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174145. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174146. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174147. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174148. dataptr[DCTSIZE*6] = tmp13 - z1;
  174149. /* Odd part */
  174150. tmp10 = tmp4 + tmp5; /* phase 2 */
  174151. tmp11 = tmp5 + tmp6;
  174152. tmp12 = tmp6 + tmp7;
  174153. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174154. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174155. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174156. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174157. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174158. z11 = tmp7 + z3; /* phase 5 */
  174159. z13 = tmp7 - z3;
  174160. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174161. dataptr[DCTSIZE*3] = z13 - z2;
  174162. dataptr[DCTSIZE*1] = z11 + z4;
  174163. dataptr[DCTSIZE*7] = z11 - z4;
  174164. dataptr++; /* advance pointer to next column */
  174165. }
  174166. }
  174167. #endif /* DCT_FLOAT_SUPPORTED */
  174168. /*** End of inlined file: jfdctflt.c ***/
  174169. /*** Start of inlined file: jfdctint.c ***/
  174170. #define JPEG_INTERNALS
  174171. #ifdef DCT_ISLOW_SUPPORTED
  174172. /*
  174173. * This module is specialized to the case DCTSIZE = 8.
  174174. */
  174175. #if DCTSIZE != 8
  174176. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174177. #endif
  174178. /*
  174179. * The poop on this scaling stuff is as follows:
  174180. *
  174181. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174182. * larger than the true DCT outputs. The final outputs are therefore
  174183. * a factor of N larger than desired; since N=8 this can be cured by
  174184. * a simple right shift at the end of the algorithm. The advantage of
  174185. * this arrangement is that we save two multiplications per 1-D DCT,
  174186. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174187. * In the IJG code, this factor of 8 is removed by the quantization step
  174188. * (in jcdctmgr.c), NOT in this module.
  174189. *
  174190. * We have to do addition and subtraction of the integer inputs, which
  174191. * is no problem, and multiplication by fractional constants, which is
  174192. * a problem to do in integer arithmetic. We multiply all the constants
  174193. * by CONST_SCALE and convert them to integer constants (thus retaining
  174194. * CONST_BITS bits of precision in the constants). After doing a
  174195. * multiplication we have to divide the product by CONST_SCALE, with proper
  174196. * rounding, to produce the correct output. This division can be done
  174197. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174198. * as long as possible so that partial sums can be added together with
  174199. * full fractional precision.
  174200. *
  174201. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174202. * they are represented to better-than-integral precision. These outputs
  174203. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174204. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174205. * array is INT32 anyway.)
  174206. *
  174207. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174208. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174209. * shows that the values given below are the most effective.
  174210. */
  174211. #if BITS_IN_JSAMPLE == 8
  174212. #define CONST_BITS 13
  174213. #define PASS1_BITS 2
  174214. #else
  174215. #define CONST_BITS 13
  174216. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174217. #endif
  174218. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174219. * causing a lot of useless floating-point operations at run time.
  174220. * To get around this we use the following pre-calculated constants.
  174221. * If you change CONST_BITS you may want to add appropriate values.
  174222. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174223. */
  174224. #if CONST_BITS == 13
  174225. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174226. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174227. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174228. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174229. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174230. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174231. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174232. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174233. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174234. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174235. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174236. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174237. #else
  174238. #define FIX_0_298631336 FIX(0.298631336)
  174239. #define FIX_0_390180644 FIX(0.390180644)
  174240. #define FIX_0_541196100 FIX(0.541196100)
  174241. #define FIX_0_765366865 FIX(0.765366865)
  174242. #define FIX_0_899976223 FIX(0.899976223)
  174243. #define FIX_1_175875602 FIX(1.175875602)
  174244. #define FIX_1_501321110 FIX(1.501321110)
  174245. #define FIX_1_847759065 FIX(1.847759065)
  174246. #define FIX_1_961570560 FIX(1.961570560)
  174247. #define FIX_2_053119869 FIX(2.053119869)
  174248. #define FIX_2_562915447 FIX(2.562915447)
  174249. #define FIX_3_072711026 FIX(3.072711026)
  174250. #endif
  174251. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174252. * For 8-bit samples with the recommended scaling, all the variable
  174253. * and constant values involved are no more than 16 bits wide, so a
  174254. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174255. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174256. */
  174257. #if BITS_IN_JSAMPLE == 8
  174258. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174259. #else
  174260. #define MULTIPLY(var,const) ((var) * (const))
  174261. #endif
  174262. /*
  174263. * Perform the forward DCT on one block of samples.
  174264. */
  174265. GLOBAL(void)
  174266. jpeg_fdct_islow (DCTELEM * data)
  174267. {
  174268. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174269. INT32 tmp10, tmp11, tmp12, tmp13;
  174270. INT32 z1, z2, z3, z4, z5;
  174271. DCTELEM *dataptr;
  174272. int ctr;
  174273. SHIFT_TEMPS
  174274. /* Pass 1: process rows. */
  174275. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174276. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174277. dataptr = data;
  174278. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174279. tmp0 = dataptr[0] + dataptr[7];
  174280. tmp7 = dataptr[0] - dataptr[7];
  174281. tmp1 = dataptr[1] + dataptr[6];
  174282. tmp6 = dataptr[1] - dataptr[6];
  174283. tmp2 = dataptr[2] + dataptr[5];
  174284. tmp5 = dataptr[2] - dataptr[5];
  174285. tmp3 = dataptr[3] + dataptr[4];
  174286. tmp4 = dataptr[3] - dataptr[4];
  174287. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174288. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174289. */
  174290. tmp10 = tmp0 + tmp3;
  174291. tmp13 = tmp0 - tmp3;
  174292. tmp11 = tmp1 + tmp2;
  174293. tmp12 = tmp1 - tmp2;
  174294. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174295. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174296. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174297. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174298. CONST_BITS-PASS1_BITS);
  174299. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174300. CONST_BITS-PASS1_BITS);
  174301. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174302. * cK represents cos(K*pi/16).
  174303. * i0..i3 in the paper are tmp4..tmp7 here.
  174304. */
  174305. z1 = tmp4 + tmp7;
  174306. z2 = tmp5 + tmp6;
  174307. z3 = tmp4 + tmp6;
  174308. z4 = tmp5 + tmp7;
  174309. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174310. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174311. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174312. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174313. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174314. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174315. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174316. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174317. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174318. z3 += z5;
  174319. z4 += z5;
  174320. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174321. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174322. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174323. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174324. dataptr += DCTSIZE; /* advance pointer to next row */
  174325. }
  174326. /* Pass 2: process columns.
  174327. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174328. * by an overall factor of 8.
  174329. */
  174330. dataptr = data;
  174331. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174332. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174333. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174334. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174335. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174336. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174337. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174338. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174339. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174340. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174341. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174342. */
  174343. tmp10 = tmp0 + tmp3;
  174344. tmp13 = tmp0 - tmp3;
  174345. tmp11 = tmp1 + tmp2;
  174346. tmp12 = tmp1 - tmp2;
  174347. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174348. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174349. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174350. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174351. CONST_BITS+PASS1_BITS);
  174352. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174353. CONST_BITS+PASS1_BITS);
  174354. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174355. * cK represents cos(K*pi/16).
  174356. * i0..i3 in the paper are tmp4..tmp7 here.
  174357. */
  174358. z1 = tmp4 + tmp7;
  174359. z2 = tmp5 + tmp6;
  174360. z3 = tmp4 + tmp6;
  174361. z4 = tmp5 + tmp7;
  174362. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174363. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174364. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174365. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174366. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174367. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174368. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174369. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174370. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174371. z3 += z5;
  174372. z4 += z5;
  174373. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174374. CONST_BITS+PASS1_BITS);
  174375. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174376. CONST_BITS+PASS1_BITS);
  174377. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174378. CONST_BITS+PASS1_BITS);
  174379. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174380. CONST_BITS+PASS1_BITS);
  174381. dataptr++; /* advance pointer to next column */
  174382. }
  174383. }
  174384. #endif /* DCT_ISLOW_SUPPORTED */
  174385. /*** End of inlined file: jfdctint.c ***/
  174386. #undef CONST_BITS
  174387. #undef MULTIPLY
  174388. #undef FIX_0_541196100
  174389. /*** Start of inlined file: jfdctfst.c ***/
  174390. #define JPEG_INTERNALS
  174391. #ifdef DCT_IFAST_SUPPORTED
  174392. /*
  174393. * This module is specialized to the case DCTSIZE = 8.
  174394. */
  174395. #if DCTSIZE != 8
  174396. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174397. #endif
  174398. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174399. * see jfdctint.c for more details. However, we choose to descale
  174400. * (right shift) multiplication products as soon as they are formed,
  174401. * rather than carrying additional fractional bits into subsequent additions.
  174402. * This compromises accuracy slightly, but it lets us save a few shifts.
  174403. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174404. * everywhere except in the multiplications proper; this saves a good deal
  174405. * of work on 16-bit-int machines.
  174406. *
  174407. * Again to save a few shifts, the intermediate results between pass 1 and
  174408. * pass 2 are not upscaled, but are represented only to integral precision.
  174409. *
  174410. * A final compromise is to represent the multiplicative constants to only
  174411. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174412. * machines, and may also reduce the cost of multiplication (since there
  174413. * are fewer one-bits in the constants).
  174414. */
  174415. #define CONST_BITS 8
  174416. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174417. * causing a lot of useless floating-point operations at run time.
  174418. * To get around this we use the following pre-calculated constants.
  174419. * If you change CONST_BITS you may want to add appropriate values.
  174420. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174421. */
  174422. #if CONST_BITS == 8
  174423. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174424. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174425. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174426. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174427. #else
  174428. #define FIX_0_382683433 FIX(0.382683433)
  174429. #define FIX_0_541196100 FIX(0.541196100)
  174430. #define FIX_0_707106781 FIX(0.707106781)
  174431. #define FIX_1_306562965 FIX(1.306562965)
  174432. #endif
  174433. /* We can gain a little more speed, with a further compromise in accuracy,
  174434. * by omitting the addition in a descaling shift. This yields an incorrectly
  174435. * rounded result half the time...
  174436. */
  174437. #ifndef USE_ACCURATE_ROUNDING
  174438. #undef DESCALE
  174439. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174440. #endif
  174441. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174442. * descale to yield a DCTELEM result.
  174443. */
  174444. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174445. /*
  174446. * Perform the forward DCT on one block of samples.
  174447. */
  174448. GLOBAL(void)
  174449. jpeg_fdct_ifast (DCTELEM * data)
  174450. {
  174451. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174452. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174453. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174454. DCTELEM *dataptr;
  174455. int ctr;
  174456. SHIFT_TEMPS
  174457. /* Pass 1: process rows. */
  174458. dataptr = data;
  174459. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174460. tmp0 = dataptr[0] + dataptr[7];
  174461. tmp7 = dataptr[0] - dataptr[7];
  174462. tmp1 = dataptr[1] + dataptr[6];
  174463. tmp6 = dataptr[1] - dataptr[6];
  174464. tmp2 = dataptr[2] + dataptr[5];
  174465. tmp5 = dataptr[2] - dataptr[5];
  174466. tmp3 = dataptr[3] + dataptr[4];
  174467. tmp4 = dataptr[3] - dataptr[4];
  174468. /* Even part */
  174469. tmp10 = tmp0 + tmp3; /* phase 2 */
  174470. tmp13 = tmp0 - tmp3;
  174471. tmp11 = tmp1 + tmp2;
  174472. tmp12 = tmp1 - tmp2;
  174473. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174474. dataptr[4] = tmp10 - tmp11;
  174475. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174476. dataptr[2] = tmp13 + z1; /* phase 5 */
  174477. dataptr[6] = tmp13 - z1;
  174478. /* Odd part */
  174479. tmp10 = tmp4 + tmp5; /* phase 2 */
  174480. tmp11 = tmp5 + tmp6;
  174481. tmp12 = tmp6 + tmp7;
  174482. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174483. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174484. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174485. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174486. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174487. z11 = tmp7 + z3; /* phase 5 */
  174488. z13 = tmp7 - z3;
  174489. dataptr[5] = z13 + z2; /* phase 6 */
  174490. dataptr[3] = z13 - z2;
  174491. dataptr[1] = z11 + z4;
  174492. dataptr[7] = z11 - z4;
  174493. dataptr += DCTSIZE; /* advance pointer to next row */
  174494. }
  174495. /* Pass 2: process columns. */
  174496. dataptr = data;
  174497. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174498. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174499. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174500. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174501. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174502. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174503. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174504. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174505. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174506. /* Even part */
  174507. tmp10 = tmp0 + tmp3; /* phase 2 */
  174508. tmp13 = tmp0 - tmp3;
  174509. tmp11 = tmp1 + tmp2;
  174510. tmp12 = tmp1 - tmp2;
  174511. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174512. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174513. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174514. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174515. dataptr[DCTSIZE*6] = tmp13 - z1;
  174516. /* Odd part */
  174517. tmp10 = tmp4 + tmp5; /* phase 2 */
  174518. tmp11 = tmp5 + tmp6;
  174519. tmp12 = tmp6 + tmp7;
  174520. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174521. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174522. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174523. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174524. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174525. z11 = tmp7 + z3; /* phase 5 */
  174526. z13 = tmp7 - z3;
  174527. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174528. dataptr[DCTSIZE*3] = z13 - z2;
  174529. dataptr[DCTSIZE*1] = z11 + z4;
  174530. dataptr[DCTSIZE*7] = z11 - z4;
  174531. dataptr++; /* advance pointer to next column */
  174532. }
  174533. }
  174534. #endif /* DCT_IFAST_SUPPORTED */
  174535. /*** End of inlined file: jfdctfst.c ***/
  174536. #undef FIX_0_541196100
  174537. /*** Start of inlined file: jidctflt.c ***/
  174538. #define JPEG_INTERNALS
  174539. #ifdef DCT_FLOAT_SUPPORTED
  174540. /*
  174541. * This module is specialized to the case DCTSIZE = 8.
  174542. */
  174543. #if DCTSIZE != 8
  174544. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174545. #endif
  174546. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174547. * entry; produce a float result.
  174548. */
  174549. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174550. /*
  174551. * Perform dequantization and inverse DCT on one block of coefficients.
  174552. */
  174553. GLOBAL(void)
  174554. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174555. JCOEFPTR coef_block,
  174556. JSAMPARRAY output_buf, JDIMENSION output_col)
  174557. {
  174558. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174559. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174560. FAST_FLOAT z5, z10, z11, z12, z13;
  174561. JCOEFPTR inptr;
  174562. FLOAT_MULT_TYPE * quantptr;
  174563. FAST_FLOAT * wsptr;
  174564. JSAMPROW outptr;
  174565. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174566. int ctr;
  174567. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174568. SHIFT_TEMPS
  174569. /* Pass 1: process columns from input, store into work array. */
  174570. inptr = coef_block;
  174571. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174572. wsptr = workspace;
  174573. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174574. /* Due to quantization, we will usually find that many of the input
  174575. * coefficients are zero, especially the AC terms. We can exploit this
  174576. * by short-circuiting the IDCT calculation for any column in which all
  174577. * the AC terms are zero. In that case each output is equal to the
  174578. * DC coefficient (with scale factor as needed).
  174579. * With typical images and quantization tables, half or more of the
  174580. * column DCT calculations can be simplified this way.
  174581. */
  174582. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174583. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174584. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174585. inptr[DCTSIZE*7] == 0) {
  174586. /* AC terms all zero */
  174587. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174588. wsptr[DCTSIZE*0] = dcval;
  174589. wsptr[DCTSIZE*1] = dcval;
  174590. wsptr[DCTSIZE*2] = dcval;
  174591. wsptr[DCTSIZE*3] = dcval;
  174592. wsptr[DCTSIZE*4] = dcval;
  174593. wsptr[DCTSIZE*5] = dcval;
  174594. wsptr[DCTSIZE*6] = dcval;
  174595. wsptr[DCTSIZE*7] = dcval;
  174596. inptr++; /* advance pointers to next column */
  174597. quantptr++;
  174598. wsptr++;
  174599. continue;
  174600. }
  174601. /* Even part */
  174602. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174603. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174604. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174605. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174606. tmp10 = tmp0 + tmp2; /* phase 3 */
  174607. tmp11 = tmp0 - tmp2;
  174608. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174609. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174610. tmp0 = tmp10 + tmp13; /* phase 2 */
  174611. tmp3 = tmp10 - tmp13;
  174612. tmp1 = tmp11 + tmp12;
  174613. tmp2 = tmp11 - tmp12;
  174614. /* Odd part */
  174615. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174616. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174617. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174618. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174619. z13 = tmp6 + tmp5; /* phase 6 */
  174620. z10 = tmp6 - tmp5;
  174621. z11 = tmp4 + tmp7;
  174622. z12 = tmp4 - tmp7;
  174623. tmp7 = z11 + z13; /* phase 5 */
  174624. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174625. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174626. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174627. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174628. tmp6 = tmp12 - tmp7; /* phase 2 */
  174629. tmp5 = tmp11 - tmp6;
  174630. tmp4 = tmp10 + tmp5;
  174631. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174632. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174633. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174634. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174635. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174636. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174637. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174638. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174639. inptr++; /* advance pointers to next column */
  174640. quantptr++;
  174641. wsptr++;
  174642. }
  174643. /* Pass 2: process rows from work array, store into output array. */
  174644. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174645. wsptr = workspace;
  174646. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174647. outptr = output_buf[ctr] + output_col;
  174648. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174649. * However, the column calculation has created many nonzero AC terms, so
  174650. * the simplification applies less often (typically 5% to 10% of the time).
  174651. * And testing floats for zero is relatively expensive, so we don't bother.
  174652. */
  174653. /* Even part */
  174654. tmp10 = wsptr[0] + wsptr[4];
  174655. tmp11 = wsptr[0] - wsptr[4];
  174656. tmp13 = wsptr[2] + wsptr[6];
  174657. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174658. tmp0 = tmp10 + tmp13;
  174659. tmp3 = tmp10 - tmp13;
  174660. tmp1 = tmp11 + tmp12;
  174661. tmp2 = tmp11 - tmp12;
  174662. /* Odd part */
  174663. z13 = wsptr[5] + wsptr[3];
  174664. z10 = wsptr[5] - wsptr[3];
  174665. z11 = wsptr[1] + wsptr[7];
  174666. z12 = wsptr[1] - wsptr[7];
  174667. tmp7 = z11 + z13;
  174668. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174669. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174670. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174671. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174672. tmp6 = tmp12 - tmp7;
  174673. tmp5 = tmp11 - tmp6;
  174674. tmp4 = tmp10 + tmp5;
  174675. /* Final output stage: scale down by a factor of 8 and range-limit */
  174676. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174677. & RANGE_MASK];
  174678. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174679. & RANGE_MASK];
  174680. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174681. & RANGE_MASK];
  174682. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174683. & RANGE_MASK];
  174684. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174685. & RANGE_MASK];
  174686. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174687. & RANGE_MASK];
  174688. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174689. & RANGE_MASK];
  174690. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174691. & RANGE_MASK];
  174692. wsptr += DCTSIZE; /* advance pointer to next row */
  174693. }
  174694. }
  174695. #endif /* DCT_FLOAT_SUPPORTED */
  174696. /*** End of inlined file: jidctflt.c ***/
  174697. #undef CONST_BITS
  174698. #undef FIX_1_847759065
  174699. #undef MULTIPLY
  174700. #undef DEQUANTIZE
  174701. #undef DESCALE
  174702. /*** Start of inlined file: jidctfst.c ***/
  174703. #define JPEG_INTERNALS
  174704. #ifdef DCT_IFAST_SUPPORTED
  174705. /*
  174706. * This module is specialized to the case DCTSIZE = 8.
  174707. */
  174708. #if DCTSIZE != 8
  174709. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174710. #endif
  174711. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174712. * see jidctint.c for more details. However, we choose to descale
  174713. * (right shift) multiplication products as soon as they are formed,
  174714. * rather than carrying additional fractional bits into subsequent additions.
  174715. * This compromises accuracy slightly, but it lets us save a few shifts.
  174716. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174717. * everywhere except in the multiplications proper; this saves a good deal
  174718. * of work on 16-bit-int machines.
  174719. *
  174720. * The dequantized coefficients are not integers because the AA&N scaling
  174721. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174722. * so that the first and second IDCT rounds have the same input scaling.
  174723. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174724. * avoid a descaling shift; this compromises accuracy rather drastically
  174725. * for small quantization table entries, but it saves a lot of shifts.
  174726. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174727. * so we use a much larger scaling factor to preserve accuracy.
  174728. *
  174729. * A final compromise is to represent the multiplicative constants to only
  174730. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174731. * machines, and may also reduce the cost of multiplication (since there
  174732. * are fewer one-bits in the constants).
  174733. */
  174734. #if BITS_IN_JSAMPLE == 8
  174735. #define CONST_BITS 8
  174736. #define PASS1_BITS 2
  174737. #else
  174738. #define CONST_BITS 8
  174739. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174740. #endif
  174741. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174742. * causing a lot of useless floating-point operations at run time.
  174743. * To get around this we use the following pre-calculated constants.
  174744. * If you change CONST_BITS you may want to add appropriate values.
  174745. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174746. */
  174747. #if CONST_BITS == 8
  174748. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174749. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174750. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174751. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174752. #else
  174753. #define FIX_1_082392200 FIX(1.082392200)
  174754. #define FIX_1_414213562 FIX(1.414213562)
  174755. #define FIX_1_847759065 FIX(1.847759065)
  174756. #define FIX_2_613125930 FIX(2.613125930)
  174757. #endif
  174758. /* We can gain a little more speed, with a further compromise in accuracy,
  174759. * by omitting the addition in a descaling shift. This yields an incorrectly
  174760. * rounded result half the time...
  174761. */
  174762. #ifndef USE_ACCURATE_ROUNDING
  174763. #undef DESCALE
  174764. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174765. #endif
  174766. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174767. * descale to yield a DCTELEM result.
  174768. */
  174769. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174770. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174771. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174772. * multiplication will do. For 12-bit data, the multiplier table is
  174773. * declared INT32, so a 32-bit multiply will be used.
  174774. */
  174775. #if BITS_IN_JSAMPLE == 8
  174776. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174777. #else
  174778. #define DEQUANTIZE(coef,quantval) \
  174779. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174780. #endif
  174781. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174782. * We assume that int right shift is unsigned if INT32 right shift is.
  174783. */
  174784. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174785. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174786. #if BITS_IN_JSAMPLE == 8
  174787. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174788. #else
  174789. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174790. #endif
  174791. #define IRIGHT_SHIFT(x,shft) \
  174792. ((ishift_temp = (x)) < 0 ? \
  174793. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174794. (ishift_temp >> (shft)))
  174795. #else
  174796. #define ISHIFT_TEMPS
  174797. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174798. #endif
  174799. #ifdef USE_ACCURATE_ROUNDING
  174800. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174801. #else
  174802. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174803. #endif
  174804. /*
  174805. * Perform dequantization and inverse DCT on one block of coefficients.
  174806. */
  174807. GLOBAL(void)
  174808. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174809. JCOEFPTR coef_block,
  174810. JSAMPARRAY output_buf, JDIMENSION output_col)
  174811. {
  174812. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174813. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174814. DCTELEM z5, z10, z11, z12, z13;
  174815. JCOEFPTR inptr;
  174816. IFAST_MULT_TYPE * quantptr;
  174817. int * wsptr;
  174818. JSAMPROW outptr;
  174819. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174820. int ctr;
  174821. int workspace[DCTSIZE2]; /* buffers data between passes */
  174822. SHIFT_TEMPS /* for DESCALE */
  174823. ISHIFT_TEMPS /* for IDESCALE */
  174824. /* Pass 1: process columns from input, store into work array. */
  174825. inptr = coef_block;
  174826. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174827. wsptr = workspace;
  174828. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174829. /* Due to quantization, we will usually find that many of the input
  174830. * coefficients are zero, especially the AC terms. We can exploit this
  174831. * by short-circuiting the IDCT calculation for any column in which all
  174832. * the AC terms are zero. In that case each output is equal to the
  174833. * DC coefficient (with scale factor as needed).
  174834. * With typical images and quantization tables, half or more of the
  174835. * column DCT calculations can be simplified this way.
  174836. */
  174837. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174838. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174839. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174840. inptr[DCTSIZE*7] == 0) {
  174841. /* AC terms all zero */
  174842. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174843. wsptr[DCTSIZE*0] = dcval;
  174844. wsptr[DCTSIZE*1] = dcval;
  174845. wsptr[DCTSIZE*2] = dcval;
  174846. wsptr[DCTSIZE*3] = dcval;
  174847. wsptr[DCTSIZE*4] = dcval;
  174848. wsptr[DCTSIZE*5] = dcval;
  174849. wsptr[DCTSIZE*6] = dcval;
  174850. wsptr[DCTSIZE*7] = dcval;
  174851. inptr++; /* advance pointers to next column */
  174852. quantptr++;
  174853. wsptr++;
  174854. continue;
  174855. }
  174856. /* Even part */
  174857. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174858. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174859. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174860. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174861. tmp10 = tmp0 + tmp2; /* phase 3 */
  174862. tmp11 = tmp0 - tmp2;
  174863. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174864. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174865. tmp0 = tmp10 + tmp13; /* phase 2 */
  174866. tmp3 = tmp10 - tmp13;
  174867. tmp1 = tmp11 + tmp12;
  174868. tmp2 = tmp11 - tmp12;
  174869. /* Odd part */
  174870. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174871. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174872. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174873. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174874. z13 = tmp6 + tmp5; /* phase 6 */
  174875. z10 = tmp6 - tmp5;
  174876. z11 = tmp4 + tmp7;
  174877. z12 = tmp4 - tmp7;
  174878. tmp7 = z11 + z13; /* phase 5 */
  174879. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174880. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174881. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174882. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174883. tmp6 = tmp12 - tmp7; /* phase 2 */
  174884. tmp5 = tmp11 - tmp6;
  174885. tmp4 = tmp10 + tmp5;
  174886. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174887. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174888. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174889. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174890. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174891. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174892. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174893. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174894. inptr++; /* advance pointers to next column */
  174895. quantptr++;
  174896. wsptr++;
  174897. }
  174898. /* Pass 2: process rows from work array, store into output array. */
  174899. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174900. /* and also undo the PASS1_BITS scaling. */
  174901. wsptr = workspace;
  174902. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174903. outptr = output_buf[ctr] + output_col;
  174904. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174905. * However, the column calculation has created many nonzero AC terms, so
  174906. * the simplification applies less often (typically 5% to 10% of the time).
  174907. * On machines with very fast multiplication, it's possible that the
  174908. * test takes more time than it's worth. In that case this section
  174909. * may be commented out.
  174910. */
  174911. #ifndef NO_ZERO_ROW_TEST
  174912. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174913. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174914. /* AC terms all zero */
  174915. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174916. & RANGE_MASK];
  174917. outptr[0] = dcval;
  174918. outptr[1] = dcval;
  174919. outptr[2] = dcval;
  174920. outptr[3] = dcval;
  174921. outptr[4] = dcval;
  174922. outptr[5] = dcval;
  174923. outptr[6] = dcval;
  174924. outptr[7] = dcval;
  174925. wsptr += DCTSIZE; /* advance pointer to next row */
  174926. continue;
  174927. }
  174928. #endif
  174929. /* Even part */
  174930. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174931. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174932. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174933. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174934. - tmp13;
  174935. tmp0 = tmp10 + tmp13;
  174936. tmp3 = tmp10 - tmp13;
  174937. tmp1 = tmp11 + tmp12;
  174938. tmp2 = tmp11 - tmp12;
  174939. /* Odd part */
  174940. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174941. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174942. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174943. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174944. tmp7 = z11 + z13; /* phase 5 */
  174945. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174946. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174947. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174948. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174949. tmp6 = tmp12 - tmp7; /* phase 2 */
  174950. tmp5 = tmp11 - tmp6;
  174951. tmp4 = tmp10 + tmp5;
  174952. /* Final output stage: scale down by a factor of 8 and range-limit */
  174953. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174954. & RANGE_MASK];
  174955. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174956. & RANGE_MASK];
  174957. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174958. & RANGE_MASK];
  174959. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174960. & RANGE_MASK];
  174961. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174962. & RANGE_MASK];
  174963. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174964. & RANGE_MASK];
  174965. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174966. & RANGE_MASK];
  174967. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174968. & RANGE_MASK];
  174969. wsptr += DCTSIZE; /* advance pointer to next row */
  174970. }
  174971. }
  174972. #endif /* DCT_IFAST_SUPPORTED */
  174973. /*** End of inlined file: jidctfst.c ***/
  174974. #undef CONST_BITS
  174975. #undef FIX_1_847759065
  174976. #undef MULTIPLY
  174977. #undef DEQUANTIZE
  174978. /*** Start of inlined file: jidctint.c ***/
  174979. #define JPEG_INTERNALS
  174980. #ifdef DCT_ISLOW_SUPPORTED
  174981. /*
  174982. * This module is specialized to the case DCTSIZE = 8.
  174983. */
  174984. #if DCTSIZE != 8
  174985. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174986. #endif
  174987. /*
  174988. * The poop on this scaling stuff is as follows:
  174989. *
  174990. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174991. * larger than the true IDCT outputs. The final outputs are therefore
  174992. * a factor of N larger than desired; since N=8 this can be cured by
  174993. * a simple right shift at the end of the algorithm. The advantage of
  174994. * this arrangement is that we save two multiplications per 1-D IDCT,
  174995. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174996. *
  174997. * We have to do addition and subtraction of the integer inputs, which
  174998. * is no problem, and multiplication by fractional constants, which is
  174999. * a problem to do in integer arithmetic. We multiply all the constants
  175000. * by CONST_SCALE and convert them to integer constants (thus retaining
  175001. * CONST_BITS bits of precision in the constants). After doing a
  175002. * multiplication we have to divide the product by CONST_SCALE, with proper
  175003. * rounding, to produce the correct output. This division can be done
  175004. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175005. * as long as possible so that partial sums can be added together with
  175006. * full fractional precision.
  175007. *
  175008. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175009. * they are represented to better-than-integral precision. These outputs
  175010. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175011. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175012. * intermediate INT32 array would be needed.)
  175013. *
  175014. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175015. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175016. * shows that the values given below are the most effective.
  175017. */
  175018. #if BITS_IN_JSAMPLE == 8
  175019. #define CONST_BITS 13
  175020. #define PASS1_BITS 2
  175021. #else
  175022. #define CONST_BITS 13
  175023. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175024. #endif
  175025. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175026. * causing a lot of useless floating-point operations at run time.
  175027. * To get around this we use the following pre-calculated constants.
  175028. * If you change CONST_BITS you may want to add appropriate values.
  175029. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175030. */
  175031. #if CONST_BITS == 13
  175032. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175033. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175034. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175035. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175036. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175037. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175038. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175039. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175040. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175041. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175042. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175043. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175044. #else
  175045. #define FIX_0_298631336 FIX(0.298631336)
  175046. #define FIX_0_390180644 FIX(0.390180644)
  175047. #define FIX_0_541196100 FIX(0.541196100)
  175048. #define FIX_0_765366865 FIX(0.765366865)
  175049. #define FIX_0_899976223 FIX(0.899976223)
  175050. #define FIX_1_175875602 FIX(1.175875602)
  175051. #define FIX_1_501321110 FIX(1.501321110)
  175052. #define FIX_1_847759065 FIX(1.847759065)
  175053. #define FIX_1_961570560 FIX(1.961570560)
  175054. #define FIX_2_053119869 FIX(2.053119869)
  175055. #define FIX_2_562915447 FIX(2.562915447)
  175056. #define FIX_3_072711026 FIX(3.072711026)
  175057. #endif
  175058. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175059. * For 8-bit samples with the recommended scaling, all the variable
  175060. * and constant values involved are no more than 16 bits wide, so a
  175061. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175062. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175063. */
  175064. #if BITS_IN_JSAMPLE == 8
  175065. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175066. #else
  175067. #define MULTIPLY(var,const) ((var) * (const))
  175068. #endif
  175069. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175070. * entry; produce an int result. In this module, both inputs and result
  175071. * are 16 bits or less, so either int or short multiply will work.
  175072. */
  175073. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175074. /*
  175075. * Perform dequantization and inverse DCT on one block of coefficients.
  175076. */
  175077. GLOBAL(void)
  175078. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175079. JCOEFPTR coef_block,
  175080. JSAMPARRAY output_buf, JDIMENSION output_col)
  175081. {
  175082. INT32 tmp0, tmp1, tmp2, tmp3;
  175083. INT32 tmp10, tmp11, tmp12, tmp13;
  175084. INT32 z1, z2, z3, z4, z5;
  175085. JCOEFPTR inptr;
  175086. ISLOW_MULT_TYPE * quantptr;
  175087. int * wsptr;
  175088. JSAMPROW outptr;
  175089. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175090. int ctr;
  175091. int workspace[DCTSIZE2]; /* buffers data between passes */
  175092. SHIFT_TEMPS
  175093. /* Pass 1: process columns from input, store into work array. */
  175094. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175095. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175096. inptr = coef_block;
  175097. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175098. wsptr = workspace;
  175099. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175100. /* Due to quantization, we will usually find that many of the input
  175101. * coefficients are zero, especially the AC terms. We can exploit this
  175102. * by short-circuiting the IDCT calculation for any column in which all
  175103. * the AC terms are zero. In that case each output is equal to the
  175104. * DC coefficient (with scale factor as needed).
  175105. * With typical images and quantization tables, half or more of the
  175106. * column DCT calculations can be simplified this way.
  175107. */
  175108. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175109. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175110. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175111. inptr[DCTSIZE*7] == 0) {
  175112. /* AC terms all zero */
  175113. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175114. wsptr[DCTSIZE*0] = dcval;
  175115. wsptr[DCTSIZE*1] = dcval;
  175116. wsptr[DCTSIZE*2] = dcval;
  175117. wsptr[DCTSIZE*3] = dcval;
  175118. wsptr[DCTSIZE*4] = dcval;
  175119. wsptr[DCTSIZE*5] = dcval;
  175120. wsptr[DCTSIZE*6] = dcval;
  175121. wsptr[DCTSIZE*7] = dcval;
  175122. inptr++; /* advance pointers to next column */
  175123. quantptr++;
  175124. wsptr++;
  175125. continue;
  175126. }
  175127. /* Even part: reverse the even part of the forward DCT. */
  175128. /* The rotator is sqrt(2)*c(-6). */
  175129. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175130. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175131. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175132. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175133. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175134. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175135. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175136. tmp0 = (z2 + z3) << CONST_BITS;
  175137. tmp1 = (z2 - z3) << CONST_BITS;
  175138. tmp10 = tmp0 + tmp3;
  175139. tmp13 = tmp0 - tmp3;
  175140. tmp11 = tmp1 + tmp2;
  175141. tmp12 = tmp1 - tmp2;
  175142. /* Odd part per figure 8; the matrix is unitary and hence its
  175143. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175144. */
  175145. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175146. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175147. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175148. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175149. z1 = tmp0 + tmp3;
  175150. z2 = tmp1 + tmp2;
  175151. z3 = tmp0 + tmp2;
  175152. z4 = tmp1 + tmp3;
  175153. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175154. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175155. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175156. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175157. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175158. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175159. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175160. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175161. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175162. z3 += z5;
  175163. z4 += z5;
  175164. tmp0 += z1 + z3;
  175165. tmp1 += z2 + z4;
  175166. tmp2 += z2 + z3;
  175167. tmp3 += z1 + z4;
  175168. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175169. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175170. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175171. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175172. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175173. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175174. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175175. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175176. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175177. inptr++; /* advance pointers to next column */
  175178. quantptr++;
  175179. wsptr++;
  175180. }
  175181. /* Pass 2: process rows from work array, store into output array. */
  175182. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175183. /* and also undo the PASS1_BITS scaling. */
  175184. wsptr = workspace;
  175185. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175186. outptr = output_buf[ctr] + output_col;
  175187. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175188. * However, the column calculation has created many nonzero AC terms, so
  175189. * the simplification applies less often (typically 5% to 10% of the time).
  175190. * On machines with very fast multiplication, it's possible that the
  175191. * test takes more time than it's worth. In that case this section
  175192. * may be commented out.
  175193. */
  175194. #ifndef NO_ZERO_ROW_TEST
  175195. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175196. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175197. /* AC terms all zero */
  175198. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175199. & RANGE_MASK];
  175200. outptr[0] = dcval;
  175201. outptr[1] = dcval;
  175202. outptr[2] = dcval;
  175203. outptr[3] = dcval;
  175204. outptr[4] = dcval;
  175205. outptr[5] = dcval;
  175206. outptr[6] = dcval;
  175207. outptr[7] = dcval;
  175208. wsptr += DCTSIZE; /* advance pointer to next row */
  175209. continue;
  175210. }
  175211. #endif
  175212. /* Even part: reverse the even part of the forward DCT. */
  175213. /* The rotator is sqrt(2)*c(-6). */
  175214. z2 = (INT32) wsptr[2];
  175215. z3 = (INT32) wsptr[6];
  175216. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175217. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175218. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175219. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175220. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175221. tmp10 = tmp0 + tmp3;
  175222. tmp13 = tmp0 - tmp3;
  175223. tmp11 = tmp1 + tmp2;
  175224. tmp12 = tmp1 - tmp2;
  175225. /* Odd part per figure 8; the matrix is unitary and hence its
  175226. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175227. */
  175228. tmp0 = (INT32) wsptr[7];
  175229. tmp1 = (INT32) wsptr[5];
  175230. tmp2 = (INT32) wsptr[3];
  175231. tmp3 = (INT32) wsptr[1];
  175232. z1 = tmp0 + tmp3;
  175233. z2 = tmp1 + tmp2;
  175234. z3 = tmp0 + tmp2;
  175235. z4 = tmp1 + tmp3;
  175236. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175237. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175238. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175239. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175240. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175241. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175242. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175243. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175244. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175245. z3 += z5;
  175246. z4 += z5;
  175247. tmp0 += z1 + z3;
  175248. tmp1 += z2 + z4;
  175249. tmp2 += z2 + z3;
  175250. tmp3 += z1 + z4;
  175251. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175252. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175253. CONST_BITS+PASS1_BITS+3)
  175254. & RANGE_MASK];
  175255. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175256. CONST_BITS+PASS1_BITS+3)
  175257. & RANGE_MASK];
  175258. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175259. CONST_BITS+PASS1_BITS+3)
  175260. & RANGE_MASK];
  175261. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175262. CONST_BITS+PASS1_BITS+3)
  175263. & RANGE_MASK];
  175264. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175265. CONST_BITS+PASS1_BITS+3)
  175266. & RANGE_MASK];
  175267. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175268. CONST_BITS+PASS1_BITS+3)
  175269. & RANGE_MASK];
  175270. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175271. CONST_BITS+PASS1_BITS+3)
  175272. & RANGE_MASK];
  175273. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175274. CONST_BITS+PASS1_BITS+3)
  175275. & RANGE_MASK];
  175276. wsptr += DCTSIZE; /* advance pointer to next row */
  175277. }
  175278. }
  175279. #endif /* DCT_ISLOW_SUPPORTED */
  175280. /*** End of inlined file: jidctint.c ***/
  175281. /*** Start of inlined file: jidctred.c ***/
  175282. #define JPEG_INTERNALS
  175283. #ifdef IDCT_SCALING_SUPPORTED
  175284. /*
  175285. * This module is specialized to the case DCTSIZE = 8.
  175286. */
  175287. #if DCTSIZE != 8
  175288. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175289. #endif
  175290. /* Scaling is the same as in jidctint.c. */
  175291. #if BITS_IN_JSAMPLE == 8
  175292. #define CONST_BITS 13
  175293. #define PASS1_BITS 2
  175294. #else
  175295. #define CONST_BITS 13
  175296. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175297. #endif
  175298. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175299. * causing a lot of useless floating-point operations at run time.
  175300. * To get around this we use the following pre-calculated constants.
  175301. * If you change CONST_BITS you may want to add appropriate values.
  175302. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175303. */
  175304. #if CONST_BITS == 13
  175305. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175306. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175307. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175308. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175309. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175310. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175311. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175312. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175313. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175314. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175315. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175316. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175317. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175318. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175319. #else
  175320. #define FIX_0_211164243 FIX(0.211164243)
  175321. #define FIX_0_509795579 FIX(0.509795579)
  175322. #define FIX_0_601344887 FIX(0.601344887)
  175323. #define FIX_0_720959822 FIX(0.720959822)
  175324. #define FIX_0_765366865 FIX(0.765366865)
  175325. #define FIX_0_850430095 FIX(0.850430095)
  175326. #define FIX_0_899976223 FIX(0.899976223)
  175327. #define FIX_1_061594337 FIX(1.061594337)
  175328. #define FIX_1_272758580 FIX(1.272758580)
  175329. #define FIX_1_451774981 FIX(1.451774981)
  175330. #define FIX_1_847759065 FIX(1.847759065)
  175331. #define FIX_2_172734803 FIX(2.172734803)
  175332. #define FIX_2_562915447 FIX(2.562915447)
  175333. #define FIX_3_624509785 FIX(3.624509785)
  175334. #endif
  175335. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175336. * For 8-bit samples with the recommended scaling, all the variable
  175337. * and constant values involved are no more than 16 bits wide, so a
  175338. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175339. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175340. */
  175341. #if BITS_IN_JSAMPLE == 8
  175342. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175343. #else
  175344. #define MULTIPLY(var,const) ((var) * (const))
  175345. #endif
  175346. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175347. * entry; produce an int result. In this module, both inputs and result
  175348. * are 16 bits or less, so either int or short multiply will work.
  175349. */
  175350. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175351. /*
  175352. * Perform dequantization and inverse DCT on one block of coefficients,
  175353. * producing a reduced-size 4x4 output block.
  175354. */
  175355. GLOBAL(void)
  175356. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175357. JCOEFPTR coef_block,
  175358. JSAMPARRAY output_buf, JDIMENSION output_col)
  175359. {
  175360. INT32 tmp0, tmp2, tmp10, tmp12;
  175361. INT32 z1, z2, z3, z4;
  175362. JCOEFPTR inptr;
  175363. ISLOW_MULT_TYPE * quantptr;
  175364. int * wsptr;
  175365. JSAMPROW outptr;
  175366. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175367. int ctr;
  175368. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175369. SHIFT_TEMPS
  175370. /* Pass 1: process columns from input, store into work array. */
  175371. inptr = coef_block;
  175372. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175373. wsptr = workspace;
  175374. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175375. /* Don't bother to process column 4, because second pass won't use it */
  175376. if (ctr == DCTSIZE-4)
  175377. continue;
  175378. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175379. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175380. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175381. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175382. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175383. wsptr[DCTSIZE*0] = dcval;
  175384. wsptr[DCTSIZE*1] = dcval;
  175385. wsptr[DCTSIZE*2] = dcval;
  175386. wsptr[DCTSIZE*3] = dcval;
  175387. continue;
  175388. }
  175389. /* Even part */
  175390. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175391. tmp0 <<= (CONST_BITS+1);
  175392. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175393. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175394. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175395. tmp10 = tmp0 + tmp2;
  175396. tmp12 = tmp0 - tmp2;
  175397. /* Odd part */
  175398. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175399. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175400. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175401. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175402. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175403. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175404. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175405. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175406. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175407. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175408. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175409. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175410. /* Final output stage */
  175411. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175412. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175413. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175414. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175415. }
  175416. /* Pass 2: process 4 rows from work array, store into output array. */
  175417. wsptr = workspace;
  175418. for (ctr = 0; ctr < 4; ctr++) {
  175419. outptr = output_buf[ctr] + output_col;
  175420. /* It's not clear whether a zero row test is worthwhile here ... */
  175421. #ifndef NO_ZERO_ROW_TEST
  175422. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175423. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175424. /* AC terms all zero */
  175425. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175426. & RANGE_MASK];
  175427. outptr[0] = dcval;
  175428. outptr[1] = dcval;
  175429. outptr[2] = dcval;
  175430. outptr[3] = dcval;
  175431. wsptr += DCTSIZE; /* advance pointer to next row */
  175432. continue;
  175433. }
  175434. #endif
  175435. /* Even part */
  175436. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175437. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175438. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175439. tmp10 = tmp0 + tmp2;
  175440. tmp12 = tmp0 - tmp2;
  175441. /* Odd part */
  175442. z1 = (INT32) wsptr[7];
  175443. z2 = (INT32) wsptr[5];
  175444. z3 = (INT32) wsptr[3];
  175445. z4 = (INT32) wsptr[1];
  175446. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175447. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175448. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175449. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175450. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175451. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175452. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175453. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175454. /* Final output stage */
  175455. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175456. CONST_BITS+PASS1_BITS+3+1)
  175457. & RANGE_MASK];
  175458. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175459. CONST_BITS+PASS1_BITS+3+1)
  175460. & RANGE_MASK];
  175461. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175462. CONST_BITS+PASS1_BITS+3+1)
  175463. & RANGE_MASK];
  175464. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175465. CONST_BITS+PASS1_BITS+3+1)
  175466. & RANGE_MASK];
  175467. wsptr += DCTSIZE; /* advance pointer to next row */
  175468. }
  175469. }
  175470. /*
  175471. * Perform dequantization and inverse DCT on one block of coefficients,
  175472. * producing a reduced-size 2x2 output block.
  175473. */
  175474. GLOBAL(void)
  175475. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175476. JCOEFPTR coef_block,
  175477. JSAMPARRAY output_buf, JDIMENSION output_col)
  175478. {
  175479. INT32 tmp0, tmp10, z1;
  175480. JCOEFPTR inptr;
  175481. ISLOW_MULT_TYPE * quantptr;
  175482. int * wsptr;
  175483. JSAMPROW outptr;
  175484. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175485. int ctr;
  175486. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175487. SHIFT_TEMPS
  175488. /* Pass 1: process columns from input, store into work array. */
  175489. inptr = coef_block;
  175490. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175491. wsptr = workspace;
  175492. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175493. /* Don't bother to process columns 2,4,6 */
  175494. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175495. continue;
  175496. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175497. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175498. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175499. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175500. wsptr[DCTSIZE*0] = dcval;
  175501. wsptr[DCTSIZE*1] = dcval;
  175502. continue;
  175503. }
  175504. /* Even part */
  175505. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175506. tmp10 = z1 << (CONST_BITS+2);
  175507. /* Odd part */
  175508. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175509. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175510. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175511. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175512. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175513. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175514. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175515. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175516. /* Final output stage */
  175517. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175518. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175519. }
  175520. /* Pass 2: process 2 rows from work array, store into output array. */
  175521. wsptr = workspace;
  175522. for (ctr = 0; ctr < 2; ctr++) {
  175523. outptr = output_buf[ctr] + output_col;
  175524. /* It's not clear whether a zero row test is worthwhile here ... */
  175525. #ifndef NO_ZERO_ROW_TEST
  175526. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175527. /* AC terms all zero */
  175528. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175529. & RANGE_MASK];
  175530. outptr[0] = dcval;
  175531. outptr[1] = dcval;
  175532. wsptr += DCTSIZE; /* advance pointer to next row */
  175533. continue;
  175534. }
  175535. #endif
  175536. /* Even part */
  175537. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175538. /* Odd part */
  175539. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175540. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175541. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175542. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175543. /* Final output stage */
  175544. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175545. CONST_BITS+PASS1_BITS+3+2)
  175546. & RANGE_MASK];
  175547. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175548. CONST_BITS+PASS1_BITS+3+2)
  175549. & RANGE_MASK];
  175550. wsptr += DCTSIZE; /* advance pointer to next row */
  175551. }
  175552. }
  175553. /*
  175554. * Perform dequantization and inverse DCT on one block of coefficients,
  175555. * producing a reduced-size 1x1 output block.
  175556. */
  175557. GLOBAL(void)
  175558. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175559. JCOEFPTR coef_block,
  175560. JSAMPARRAY output_buf, JDIMENSION output_col)
  175561. {
  175562. int dcval;
  175563. ISLOW_MULT_TYPE * quantptr;
  175564. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175565. SHIFT_TEMPS
  175566. /* We hardly need an inverse DCT routine for this: just take the
  175567. * average pixel value, which is one-eighth of the DC coefficient.
  175568. */
  175569. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175570. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175571. dcval = (int) DESCALE((INT32) dcval, 3);
  175572. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175573. }
  175574. #endif /* IDCT_SCALING_SUPPORTED */
  175575. /*** End of inlined file: jidctred.c ***/
  175576. /*** Start of inlined file: jmemmgr.c ***/
  175577. #define JPEG_INTERNALS
  175578. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175579. /*** Start of inlined file: jmemsys.h ***/
  175580. #ifndef __jmemsys_h__
  175581. #define __jmemsys_h__
  175582. /* Short forms of external names for systems with brain-damaged linkers. */
  175583. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175584. #define jpeg_get_small jGetSmall
  175585. #define jpeg_free_small jFreeSmall
  175586. #define jpeg_get_large jGetLarge
  175587. #define jpeg_free_large jFreeLarge
  175588. #define jpeg_mem_available jMemAvail
  175589. #define jpeg_open_backing_store jOpenBackStore
  175590. #define jpeg_mem_init jMemInit
  175591. #define jpeg_mem_term jMemTerm
  175592. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175593. /*
  175594. * These two functions are used to allocate and release small chunks of
  175595. * memory. (Typically the total amount requested through jpeg_get_small is
  175596. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175597. * Behavior should be the same as for the standard library functions malloc
  175598. * and free; in particular, jpeg_get_small must return NULL on failure.
  175599. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175600. * size of the object being freed, just in case it's needed.
  175601. * On an 80x86 machine using small-data memory model, these manage near heap.
  175602. */
  175603. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175604. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175605. size_t sizeofobject));
  175606. /*
  175607. * These two functions are used to allocate and release large chunks of
  175608. * memory (up to the total free space designated by jpeg_mem_available).
  175609. * The interface is the same as above, except that on an 80x86 machine,
  175610. * far pointers are used. On most other machines these are identical to
  175611. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175612. * in case a different allocation strategy is desirable for large chunks.
  175613. */
  175614. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175615. size_t sizeofobject));
  175616. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175617. size_t sizeofobject));
  175618. /*
  175619. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175620. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175621. * matter, but that case should never come into play). This macro is needed
  175622. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175623. * On those machines, we expect that jconfig.h will provide a proper value.
  175624. * On machines with 32-bit flat address spaces, any large constant may be used.
  175625. *
  175626. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175627. * size_t and will be a multiple of sizeof(align_type).
  175628. */
  175629. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175630. #define MAX_ALLOC_CHUNK 1000000000L
  175631. #endif
  175632. /*
  175633. * This routine computes the total space still available for allocation by
  175634. * jpeg_get_large. If more space than this is needed, backing store will be
  175635. * used. NOTE: any memory already allocated must not be counted.
  175636. *
  175637. * There is a minimum space requirement, corresponding to the minimum
  175638. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175639. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175640. * all working storage in memory, is also passed in case it is useful.
  175641. * Finally, the total space already allocated is passed. If no better
  175642. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175643. * is often a suitable calculation.
  175644. *
  175645. * It is OK for jpeg_mem_available to underestimate the space available
  175646. * (that'll just lead to more backing-store access than is really necessary).
  175647. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175648. * a slop factor from the true available space. 5% should be enough.
  175649. *
  175650. * On machines with lots of virtual memory, any large constant may be returned.
  175651. * Conversely, zero may be returned to always use the minimum amount of memory.
  175652. */
  175653. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175654. long min_bytes_needed,
  175655. long max_bytes_needed,
  175656. long already_allocated));
  175657. /*
  175658. * This structure holds whatever state is needed to access a single
  175659. * backing-store object. The read/write/close method pointers are called
  175660. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175661. * are private to the system-dependent backing store routines.
  175662. */
  175663. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175664. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175665. typedef unsigned short XMSH; /* type of extended-memory handles */
  175666. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175667. typedef union {
  175668. short file_handle; /* DOS file handle if it's a temp file */
  175669. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175670. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175671. } handle_union;
  175672. #endif /* USE_MSDOS_MEMMGR */
  175673. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175674. #include <Files.h>
  175675. #endif /* USE_MAC_MEMMGR */
  175676. //typedef struct backing_store_struct * backing_store_ptr;
  175677. typedef struct backing_store_struct {
  175678. /* Methods for reading/writing/closing this backing-store object */
  175679. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175680. struct backing_store_struct *info,
  175681. void FAR * buffer_address,
  175682. long file_offset, long byte_count));
  175683. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175684. struct backing_store_struct *info,
  175685. void FAR * buffer_address,
  175686. long file_offset, long byte_count));
  175687. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175688. struct backing_store_struct *info));
  175689. /* Private fields for system-dependent backing-store management */
  175690. #ifdef USE_MSDOS_MEMMGR
  175691. /* For the MS-DOS manager (jmemdos.c), we need: */
  175692. handle_union handle; /* reference to backing-store storage object */
  175693. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175694. #else
  175695. #ifdef USE_MAC_MEMMGR
  175696. /* For the Mac manager (jmemmac.c), we need: */
  175697. short temp_file; /* file reference number to temp file */
  175698. FSSpec tempSpec; /* the FSSpec for the temp file */
  175699. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175700. #else
  175701. /* For a typical implementation with temp files, we need: */
  175702. FILE * temp_file; /* stdio reference to temp file */
  175703. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175704. #endif
  175705. #endif
  175706. } backing_store_info;
  175707. /*
  175708. * Initial opening of a backing-store object. This must fill in the
  175709. * read/write/close pointers in the object. The read/write routines
  175710. * may take an error exit if the specified maximum file size is exceeded.
  175711. * (If jpeg_mem_available always returns a large value, this routine can
  175712. * just take an error exit.)
  175713. */
  175714. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175715. struct backing_store_struct *info,
  175716. long total_bytes_needed));
  175717. /*
  175718. * These routines take care of any system-dependent initialization and
  175719. * cleanup required. jpeg_mem_init will be called before anything is
  175720. * allocated (and, therefore, nothing in cinfo is of use except the error
  175721. * manager pointer). It should return a suitable default value for
  175722. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175723. * application. (Note that max_memory_to_use is only important if
  175724. * jpeg_mem_available chooses to consult it ... no one else will.)
  175725. * jpeg_mem_term may assume that all requested memory has been freed and that
  175726. * all opened backing-store objects have been closed.
  175727. */
  175728. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175729. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175730. #endif
  175731. /*** End of inlined file: jmemsys.h ***/
  175732. /* import the system-dependent declarations */
  175733. #ifndef NO_GETENV
  175734. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175735. extern char * getenv JPP((const char * name));
  175736. #endif
  175737. #endif
  175738. /*
  175739. * Some important notes:
  175740. * The allocation routines provided here must never return NULL.
  175741. * They should exit to error_exit if unsuccessful.
  175742. *
  175743. * It's not a good idea to try to merge the sarray and barray routines,
  175744. * even though they are textually almost the same, because samples are
  175745. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175746. * in machines where byte pointers have a different representation from
  175747. * word pointers, the resulting machine code could not be the same.
  175748. */
  175749. /*
  175750. * Many machines require storage alignment: longs must start on 4-byte
  175751. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175752. * always returns pointers that are multiples of the worst-case alignment
  175753. * requirement, and we had better do so too.
  175754. * There isn't any really portable way to determine the worst-case alignment
  175755. * requirement. This module assumes that the alignment requirement is
  175756. * multiples of sizeof(ALIGN_TYPE).
  175757. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175758. * workstations (where doubles really do need 8-byte alignment) and will work
  175759. * fine on nearly everything. If your machine has lesser alignment needs,
  175760. * you can save a few bytes by making ALIGN_TYPE smaller.
  175761. * The only place I know of where this will NOT work is certain Macintosh
  175762. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175763. * Doing 10-byte alignment is counterproductive because longwords won't be
  175764. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175765. * such a compiler.
  175766. */
  175767. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175768. #define ALIGN_TYPE double
  175769. #endif
  175770. /*
  175771. * We allocate objects from "pools", where each pool is gotten with a single
  175772. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175773. * overhead within a pool, except for alignment padding. Each pool has a
  175774. * header with a link to the next pool of the same class.
  175775. * Small and large pool headers are identical except that the latter's
  175776. * link pointer must be FAR on 80x86 machines.
  175777. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175778. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175779. * of the alignment requirement of ALIGN_TYPE.
  175780. */
  175781. typedef union small_pool_struct * small_pool_ptr;
  175782. typedef union small_pool_struct {
  175783. struct {
  175784. small_pool_ptr next; /* next in list of pools */
  175785. size_t bytes_used; /* how many bytes already used within pool */
  175786. size_t bytes_left; /* bytes still available in this pool */
  175787. } hdr;
  175788. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175789. } small_pool_hdr;
  175790. typedef union large_pool_struct FAR * large_pool_ptr;
  175791. typedef union large_pool_struct {
  175792. struct {
  175793. large_pool_ptr next; /* next in list of pools */
  175794. size_t bytes_used; /* how many bytes already used within pool */
  175795. size_t bytes_left; /* bytes still available in this pool */
  175796. } hdr;
  175797. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175798. } large_pool_hdr;
  175799. /*
  175800. * Here is the full definition of a memory manager object.
  175801. */
  175802. typedef struct {
  175803. struct jpeg_memory_mgr pub; /* public fields */
  175804. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175805. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175806. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175807. /* Since we only have one lifetime class of virtual arrays, only one
  175808. * linked list is necessary (for each datatype). Note that the virtual
  175809. * array control blocks being linked together are actually stored somewhere
  175810. * in the small-pool list.
  175811. */
  175812. jvirt_sarray_ptr virt_sarray_list;
  175813. jvirt_barray_ptr virt_barray_list;
  175814. /* This counts total space obtained from jpeg_get_small/large */
  175815. long total_space_allocated;
  175816. /* alloc_sarray and alloc_barray set this value for use by virtual
  175817. * array routines.
  175818. */
  175819. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175820. } my_memory_mgr;
  175821. typedef my_memory_mgr * my_mem_ptr;
  175822. /*
  175823. * The control blocks for virtual arrays.
  175824. * Note that these blocks are allocated in the "small" pool area.
  175825. * System-dependent info for the associated backing store (if any) is hidden
  175826. * inside the backing_store_info struct.
  175827. */
  175828. struct jvirt_sarray_control {
  175829. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175830. JDIMENSION rows_in_array; /* total virtual array height */
  175831. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175832. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175833. JDIMENSION rows_in_mem; /* height of memory buffer */
  175834. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175835. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175836. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175837. boolean pre_zero; /* pre-zero mode requested? */
  175838. boolean dirty; /* do current buffer contents need written? */
  175839. boolean b_s_open; /* is backing-store data valid? */
  175840. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175841. backing_store_info b_s_info; /* System-dependent control info */
  175842. };
  175843. struct jvirt_barray_control {
  175844. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175845. JDIMENSION rows_in_array; /* total virtual array height */
  175846. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175847. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175848. JDIMENSION rows_in_mem; /* height of memory buffer */
  175849. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175850. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175851. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175852. boolean pre_zero; /* pre-zero mode requested? */
  175853. boolean dirty; /* do current buffer contents need written? */
  175854. boolean b_s_open; /* is backing-store data valid? */
  175855. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175856. backing_store_info b_s_info; /* System-dependent control info */
  175857. };
  175858. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175859. LOCAL(void)
  175860. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175861. {
  175862. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175863. small_pool_ptr shdr_ptr;
  175864. large_pool_ptr lhdr_ptr;
  175865. /* Since this is only a debugging stub, we can cheat a little by using
  175866. * fprintf directly rather than going through the trace message code.
  175867. * This is helpful because message parm array can't handle longs.
  175868. */
  175869. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175870. pool_id, mem->total_space_allocated);
  175871. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175872. lhdr_ptr = lhdr_ptr->hdr.next) {
  175873. fprintf(stderr, " Large chunk used %ld\n",
  175874. (long) lhdr_ptr->hdr.bytes_used);
  175875. }
  175876. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175877. shdr_ptr = shdr_ptr->hdr.next) {
  175878. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175879. (long) shdr_ptr->hdr.bytes_used,
  175880. (long) shdr_ptr->hdr.bytes_left);
  175881. }
  175882. }
  175883. #endif /* MEM_STATS */
  175884. LOCAL(void)
  175885. out_of_memory (j_common_ptr cinfo, int which)
  175886. /* Report an out-of-memory error and stop execution */
  175887. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175888. {
  175889. #ifdef MEM_STATS
  175890. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175891. #endif
  175892. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175893. }
  175894. /*
  175895. * Allocation of "small" objects.
  175896. *
  175897. * For these, we use pooled storage. When a new pool must be created,
  175898. * we try to get enough space for the current request plus a "slop" factor,
  175899. * where the slop will be the amount of leftover space in the new pool.
  175900. * The speed vs. space tradeoff is largely determined by the slop values.
  175901. * A different slop value is provided for each pool class (lifetime),
  175902. * and we also distinguish the first pool of a class from later ones.
  175903. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175904. * machines, but may be too small if longs are 64 bits or more.
  175905. */
  175906. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175907. {
  175908. 1600, /* first PERMANENT pool */
  175909. 16000 /* first IMAGE pool */
  175910. };
  175911. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175912. {
  175913. 0, /* additional PERMANENT pools */
  175914. 5000 /* additional IMAGE pools */
  175915. };
  175916. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175917. METHODDEF(void *)
  175918. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175919. /* Allocate a "small" object */
  175920. {
  175921. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175922. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175923. char * data_ptr;
  175924. size_t odd_bytes, min_request, slop;
  175925. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175926. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175927. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175928. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175929. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175930. if (odd_bytes > 0)
  175931. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175932. /* See if space is available in any existing pool */
  175933. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175934. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175935. prev_hdr_ptr = NULL;
  175936. hdr_ptr = mem->small_list[pool_id];
  175937. while (hdr_ptr != NULL) {
  175938. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175939. break; /* found pool with enough space */
  175940. prev_hdr_ptr = hdr_ptr;
  175941. hdr_ptr = hdr_ptr->hdr.next;
  175942. }
  175943. /* Time to make a new pool? */
  175944. if (hdr_ptr == NULL) {
  175945. /* min_request is what we need now, slop is what will be leftover */
  175946. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175947. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175948. slop = first_pool_slop[pool_id];
  175949. else
  175950. slop = extra_pool_slop[pool_id];
  175951. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175952. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175953. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175954. /* Try to get space, if fail reduce slop and try again */
  175955. for (;;) {
  175956. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175957. if (hdr_ptr != NULL)
  175958. break;
  175959. slop /= 2;
  175960. if (slop < MIN_SLOP) /* give up when it gets real small */
  175961. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175962. }
  175963. mem->total_space_allocated += min_request + slop;
  175964. /* Success, initialize the new pool header and add to end of list */
  175965. hdr_ptr->hdr.next = NULL;
  175966. hdr_ptr->hdr.bytes_used = 0;
  175967. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175968. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175969. mem->small_list[pool_id] = hdr_ptr;
  175970. else
  175971. prev_hdr_ptr->hdr.next = hdr_ptr;
  175972. }
  175973. /* OK, allocate the object from the current pool */
  175974. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175975. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175976. hdr_ptr->hdr.bytes_used += sizeofobject;
  175977. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175978. return (void *) data_ptr;
  175979. }
  175980. /*
  175981. * Allocation of "large" objects.
  175982. *
  175983. * The external semantics of these are the same as "small" objects,
  175984. * except that FAR pointers are used on 80x86. However the pool
  175985. * management heuristics are quite different. We assume that each
  175986. * request is large enough that it may as well be passed directly to
  175987. * jpeg_get_large; the pool management just links everything together
  175988. * so that we can free it all on demand.
  175989. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175990. * structures. The routines that create these structures (see below)
  175991. * deliberately bunch rows together to ensure a large request size.
  175992. */
  175993. METHODDEF(void FAR *)
  175994. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175995. /* Allocate a "large" object */
  175996. {
  175997. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175998. large_pool_ptr hdr_ptr;
  175999. size_t odd_bytes;
  176000. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176001. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176002. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176003. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176004. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176005. if (odd_bytes > 0)
  176006. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176007. /* Always make a new pool */
  176008. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176009. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176010. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176011. SIZEOF(large_pool_hdr));
  176012. if (hdr_ptr == NULL)
  176013. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176014. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176015. /* Success, initialize the new pool header and add to list */
  176016. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176017. /* We maintain space counts in each pool header for statistical purposes,
  176018. * even though they are not needed for allocation.
  176019. */
  176020. hdr_ptr->hdr.bytes_used = sizeofobject;
  176021. hdr_ptr->hdr.bytes_left = 0;
  176022. mem->large_list[pool_id] = hdr_ptr;
  176023. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176024. }
  176025. /*
  176026. * Creation of 2-D sample arrays.
  176027. * The pointers are in near heap, the samples themselves in FAR heap.
  176028. *
  176029. * To minimize allocation overhead and to allow I/O of large contiguous
  176030. * blocks, we allocate the sample rows in groups of as many rows as possible
  176031. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176032. * NB: the virtual array control routines, later in this file, know about
  176033. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176034. * object so that it can be saved away if this sarray is the workspace for
  176035. * a virtual array.
  176036. */
  176037. METHODDEF(JSAMPARRAY)
  176038. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176039. JDIMENSION samplesperrow, JDIMENSION numrows)
  176040. /* Allocate a 2-D sample array */
  176041. {
  176042. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176043. JSAMPARRAY result;
  176044. JSAMPROW workspace;
  176045. JDIMENSION rowsperchunk, currow, i;
  176046. long ltemp;
  176047. /* Calculate max # of rows allowed in one allocation chunk */
  176048. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176049. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176050. if (ltemp <= 0)
  176051. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176052. if (ltemp < (long) numrows)
  176053. rowsperchunk = (JDIMENSION) ltemp;
  176054. else
  176055. rowsperchunk = numrows;
  176056. mem->last_rowsperchunk = rowsperchunk;
  176057. /* Get space for row pointers (small object) */
  176058. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176059. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176060. /* Get the rows themselves (large objects) */
  176061. currow = 0;
  176062. while (currow < numrows) {
  176063. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176064. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176065. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176066. * SIZEOF(JSAMPLE)));
  176067. for (i = rowsperchunk; i > 0; i--) {
  176068. result[currow++] = workspace;
  176069. workspace += samplesperrow;
  176070. }
  176071. }
  176072. return result;
  176073. }
  176074. /*
  176075. * Creation of 2-D coefficient-block arrays.
  176076. * This is essentially the same as the code for sample arrays, above.
  176077. */
  176078. METHODDEF(JBLOCKARRAY)
  176079. alloc_barray (j_common_ptr cinfo, int pool_id,
  176080. JDIMENSION blocksperrow, JDIMENSION numrows)
  176081. /* Allocate a 2-D coefficient-block array */
  176082. {
  176083. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176084. JBLOCKARRAY result;
  176085. JBLOCKROW workspace;
  176086. JDIMENSION rowsperchunk, currow, i;
  176087. long ltemp;
  176088. /* Calculate max # of rows allowed in one allocation chunk */
  176089. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176090. ((long) blocksperrow * SIZEOF(JBLOCK));
  176091. if (ltemp <= 0)
  176092. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176093. if (ltemp < (long) numrows)
  176094. rowsperchunk = (JDIMENSION) ltemp;
  176095. else
  176096. rowsperchunk = numrows;
  176097. mem->last_rowsperchunk = rowsperchunk;
  176098. /* Get space for row pointers (small object) */
  176099. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176100. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176101. /* Get the rows themselves (large objects) */
  176102. currow = 0;
  176103. while (currow < numrows) {
  176104. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176105. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176106. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176107. * SIZEOF(JBLOCK)));
  176108. for (i = rowsperchunk; i > 0; i--) {
  176109. result[currow++] = workspace;
  176110. workspace += blocksperrow;
  176111. }
  176112. }
  176113. return result;
  176114. }
  176115. /*
  176116. * About virtual array management:
  176117. *
  176118. * The above "normal" array routines are only used to allocate strip buffers
  176119. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176120. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176121. * time, but the memory manager must save the whole array for repeated
  176122. * accesses. The intended implementation is that there is a strip buffer in
  176123. * memory (as high as is possible given the desired memory limit), plus a
  176124. * backing file that holds the rest of the array.
  176125. *
  176126. * The request_virt_array routines are told the total size of the image and
  176127. * the maximum number of rows that will be accessed at once. The in-memory
  176128. * buffer must be at least as large as the maxaccess value.
  176129. *
  176130. * The request routines create control blocks but not the in-memory buffers.
  176131. * That is postponed until realize_virt_arrays is called. At that time the
  176132. * total amount of space needed is known (approximately, anyway), so free
  176133. * memory can be divided up fairly.
  176134. *
  176135. * The access_virt_array routines are responsible for making a specific strip
  176136. * area accessible (after reading or writing the backing file, if necessary).
  176137. * Note that the access routines are told whether the caller intends to modify
  176138. * the accessed strip; during a read-only pass this saves having to rewrite
  176139. * data to disk. The access routines are also responsible for pre-zeroing
  176140. * any newly accessed rows, if pre-zeroing was requested.
  176141. *
  176142. * In current usage, the access requests are usually for nonoverlapping
  176143. * strips; that is, successive access start_row numbers differ by exactly
  176144. * num_rows = maxaccess. This means we can get good performance with simple
  176145. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176146. * of the access height; then there will never be accesses across bufferload
  176147. * boundaries. The code will still work with overlapping access requests,
  176148. * but it doesn't handle bufferload overlaps very efficiently.
  176149. */
  176150. METHODDEF(jvirt_sarray_ptr)
  176151. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176152. JDIMENSION samplesperrow, JDIMENSION numrows,
  176153. JDIMENSION maxaccess)
  176154. /* Request a virtual 2-D sample array */
  176155. {
  176156. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176157. jvirt_sarray_ptr result;
  176158. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176159. if (pool_id != JPOOL_IMAGE)
  176160. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176161. /* get control block */
  176162. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176163. SIZEOF(struct jvirt_sarray_control));
  176164. result->mem_buffer = NULL; /* marks array not yet realized */
  176165. result->rows_in_array = numrows;
  176166. result->samplesperrow = samplesperrow;
  176167. result->maxaccess = maxaccess;
  176168. result->pre_zero = pre_zero;
  176169. result->b_s_open = FALSE; /* no associated backing-store object */
  176170. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176171. mem->virt_sarray_list = result;
  176172. return result;
  176173. }
  176174. METHODDEF(jvirt_barray_ptr)
  176175. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176176. JDIMENSION blocksperrow, JDIMENSION numrows,
  176177. JDIMENSION maxaccess)
  176178. /* Request a virtual 2-D coefficient-block array */
  176179. {
  176180. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176181. jvirt_barray_ptr result;
  176182. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176183. if (pool_id != JPOOL_IMAGE)
  176184. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176185. /* get control block */
  176186. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176187. SIZEOF(struct jvirt_barray_control));
  176188. result->mem_buffer = NULL; /* marks array not yet realized */
  176189. result->rows_in_array = numrows;
  176190. result->blocksperrow = blocksperrow;
  176191. result->maxaccess = maxaccess;
  176192. result->pre_zero = pre_zero;
  176193. result->b_s_open = FALSE; /* no associated backing-store object */
  176194. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176195. mem->virt_barray_list = result;
  176196. return result;
  176197. }
  176198. METHODDEF(void)
  176199. realize_virt_arrays (j_common_ptr cinfo)
  176200. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176201. {
  176202. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176203. long space_per_minheight, maximum_space, avail_mem;
  176204. long minheights, max_minheights;
  176205. jvirt_sarray_ptr sptr;
  176206. jvirt_barray_ptr bptr;
  176207. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176208. * and the maximum space needed (full image height in each buffer).
  176209. * These may be of use to the system-dependent jpeg_mem_available routine.
  176210. */
  176211. space_per_minheight = 0;
  176212. maximum_space = 0;
  176213. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176214. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176215. space_per_minheight += (long) sptr->maxaccess *
  176216. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176217. maximum_space += (long) sptr->rows_in_array *
  176218. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176219. }
  176220. }
  176221. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176222. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176223. space_per_minheight += (long) bptr->maxaccess *
  176224. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176225. maximum_space += (long) bptr->rows_in_array *
  176226. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176227. }
  176228. }
  176229. if (space_per_minheight <= 0)
  176230. return; /* no unrealized arrays, no work */
  176231. /* Determine amount of memory to actually use; this is system-dependent. */
  176232. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176233. mem->total_space_allocated);
  176234. /* If the maximum space needed is available, make all the buffers full
  176235. * height; otherwise parcel it out with the same number of minheights
  176236. * in each buffer.
  176237. */
  176238. if (avail_mem >= maximum_space)
  176239. max_minheights = 1000000000L;
  176240. else {
  176241. max_minheights = avail_mem / space_per_minheight;
  176242. /* If there doesn't seem to be enough space, try to get the minimum
  176243. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176244. */
  176245. if (max_minheights <= 0)
  176246. max_minheights = 1;
  176247. }
  176248. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176249. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176250. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176251. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176252. if (minheights <= max_minheights) {
  176253. /* This buffer fits in memory */
  176254. sptr->rows_in_mem = sptr->rows_in_array;
  176255. } else {
  176256. /* It doesn't fit in memory, create backing store. */
  176257. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176258. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176259. (long) sptr->rows_in_array *
  176260. (long) sptr->samplesperrow *
  176261. (long) SIZEOF(JSAMPLE));
  176262. sptr->b_s_open = TRUE;
  176263. }
  176264. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176265. sptr->samplesperrow, sptr->rows_in_mem);
  176266. sptr->rowsperchunk = mem->last_rowsperchunk;
  176267. sptr->cur_start_row = 0;
  176268. sptr->first_undef_row = 0;
  176269. sptr->dirty = FALSE;
  176270. }
  176271. }
  176272. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176273. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176274. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176275. if (minheights <= max_minheights) {
  176276. /* This buffer fits in memory */
  176277. bptr->rows_in_mem = bptr->rows_in_array;
  176278. } else {
  176279. /* It doesn't fit in memory, create backing store. */
  176280. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176281. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176282. (long) bptr->rows_in_array *
  176283. (long) bptr->blocksperrow *
  176284. (long) SIZEOF(JBLOCK));
  176285. bptr->b_s_open = TRUE;
  176286. }
  176287. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176288. bptr->blocksperrow, bptr->rows_in_mem);
  176289. bptr->rowsperchunk = mem->last_rowsperchunk;
  176290. bptr->cur_start_row = 0;
  176291. bptr->first_undef_row = 0;
  176292. bptr->dirty = FALSE;
  176293. }
  176294. }
  176295. }
  176296. LOCAL(void)
  176297. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176298. /* Do backing store read or write of a virtual sample array */
  176299. {
  176300. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176301. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176302. file_offset = ptr->cur_start_row * bytesperrow;
  176303. /* Loop to read or write each allocation chunk in mem_buffer */
  176304. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176305. /* One chunk, but check for short chunk at end of buffer */
  176306. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176307. /* Transfer no more than is currently defined */
  176308. thisrow = (long) ptr->cur_start_row + i;
  176309. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176310. /* Transfer no more than fits in file */
  176311. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176312. if (rows <= 0) /* this chunk might be past end of file! */
  176313. break;
  176314. byte_count = rows * bytesperrow;
  176315. if (writing)
  176316. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176317. (void FAR *) ptr->mem_buffer[i],
  176318. file_offset, byte_count);
  176319. else
  176320. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176321. (void FAR *) ptr->mem_buffer[i],
  176322. file_offset, byte_count);
  176323. file_offset += byte_count;
  176324. }
  176325. }
  176326. LOCAL(void)
  176327. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176328. /* Do backing store read or write of a virtual coefficient-block array */
  176329. {
  176330. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176331. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176332. file_offset = ptr->cur_start_row * bytesperrow;
  176333. /* Loop to read or write each allocation chunk in mem_buffer */
  176334. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176335. /* One chunk, but check for short chunk at end of buffer */
  176336. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176337. /* Transfer no more than is currently defined */
  176338. thisrow = (long) ptr->cur_start_row + i;
  176339. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176340. /* Transfer no more than fits in file */
  176341. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176342. if (rows <= 0) /* this chunk might be past end of file! */
  176343. break;
  176344. byte_count = rows * bytesperrow;
  176345. if (writing)
  176346. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176347. (void FAR *) ptr->mem_buffer[i],
  176348. file_offset, byte_count);
  176349. else
  176350. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176351. (void FAR *) ptr->mem_buffer[i],
  176352. file_offset, byte_count);
  176353. file_offset += byte_count;
  176354. }
  176355. }
  176356. METHODDEF(JSAMPARRAY)
  176357. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176358. JDIMENSION start_row, JDIMENSION num_rows,
  176359. boolean writable)
  176360. /* Access the part of a virtual sample array starting at start_row */
  176361. /* and extending for num_rows rows. writable is true if */
  176362. /* caller intends to modify the accessed area. */
  176363. {
  176364. JDIMENSION end_row = start_row + num_rows;
  176365. JDIMENSION undef_row;
  176366. /* debugging check */
  176367. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176368. ptr->mem_buffer == NULL)
  176369. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176370. /* Make the desired part of the virtual array accessible */
  176371. if (start_row < ptr->cur_start_row ||
  176372. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176373. if (! ptr->b_s_open)
  176374. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176375. /* Flush old buffer contents if necessary */
  176376. if (ptr->dirty) {
  176377. do_sarray_io(cinfo, ptr, TRUE);
  176378. ptr->dirty = FALSE;
  176379. }
  176380. /* Decide what part of virtual array to access.
  176381. * Algorithm: if target address > current window, assume forward scan,
  176382. * load starting at target address. If target address < current window,
  176383. * assume backward scan, load so that target area is top of window.
  176384. * Note that when switching from forward write to forward read, will have
  176385. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176386. */
  176387. if (start_row > ptr->cur_start_row) {
  176388. ptr->cur_start_row = start_row;
  176389. } else {
  176390. /* use long arithmetic here to avoid overflow & unsigned problems */
  176391. long ltemp;
  176392. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176393. if (ltemp < 0)
  176394. ltemp = 0; /* don't fall off front end of file */
  176395. ptr->cur_start_row = (JDIMENSION) ltemp;
  176396. }
  176397. /* Read in the selected part of the array.
  176398. * During the initial write pass, we will do no actual read
  176399. * because the selected part is all undefined.
  176400. */
  176401. do_sarray_io(cinfo, ptr, FALSE);
  176402. }
  176403. /* Ensure the accessed part of the array is defined; prezero if needed.
  176404. * To improve locality of access, we only prezero the part of the array
  176405. * that the caller is about to access, not the entire in-memory array.
  176406. */
  176407. if (ptr->first_undef_row < end_row) {
  176408. if (ptr->first_undef_row < start_row) {
  176409. if (writable) /* writer skipped over a section of array */
  176410. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176411. undef_row = start_row; /* but reader is allowed to read ahead */
  176412. } else {
  176413. undef_row = ptr->first_undef_row;
  176414. }
  176415. if (writable)
  176416. ptr->first_undef_row = end_row;
  176417. if (ptr->pre_zero) {
  176418. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176419. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176420. end_row -= ptr->cur_start_row;
  176421. while (undef_row < end_row) {
  176422. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176423. undef_row++;
  176424. }
  176425. } else {
  176426. if (! writable) /* reader looking at undefined data */
  176427. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176428. }
  176429. }
  176430. /* Flag the buffer dirty if caller will write in it */
  176431. if (writable)
  176432. ptr->dirty = TRUE;
  176433. /* Return address of proper part of the buffer */
  176434. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176435. }
  176436. METHODDEF(JBLOCKARRAY)
  176437. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176438. JDIMENSION start_row, JDIMENSION num_rows,
  176439. boolean writable)
  176440. /* Access the part of a virtual block array starting at start_row */
  176441. /* and extending for num_rows rows. writable is true if */
  176442. /* caller intends to modify the accessed area. */
  176443. {
  176444. JDIMENSION end_row = start_row + num_rows;
  176445. JDIMENSION undef_row;
  176446. /* debugging check */
  176447. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176448. ptr->mem_buffer == NULL)
  176449. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176450. /* Make the desired part of the virtual array accessible */
  176451. if (start_row < ptr->cur_start_row ||
  176452. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176453. if (! ptr->b_s_open)
  176454. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176455. /* Flush old buffer contents if necessary */
  176456. if (ptr->dirty) {
  176457. do_barray_io(cinfo, ptr, TRUE);
  176458. ptr->dirty = FALSE;
  176459. }
  176460. /* Decide what part of virtual array to access.
  176461. * Algorithm: if target address > current window, assume forward scan,
  176462. * load starting at target address. If target address < current window,
  176463. * assume backward scan, load so that target area is top of window.
  176464. * Note that when switching from forward write to forward read, will have
  176465. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176466. */
  176467. if (start_row > ptr->cur_start_row) {
  176468. ptr->cur_start_row = start_row;
  176469. } else {
  176470. /* use long arithmetic here to avoid overflow & unsigned problems */
  176471. long ltemp;
  176472. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176473. if (ltemp < 0)
  176474. ltemp = 0; /* don't fall off front end of file */
  176475. ptr->cur_start_row = (JDIMENSION) ltemp;
  176476. }
  176477. /* Read in the selected part of the array.
  176478. * During the initial write pass, we will do no actual read
  176479. * because the selected part is all undefined.
  176480. */
  176481. do_barray_io(cinfo, ptr, FALSE);
  176482. }
  176483. /* Ensure the accessed part of the array is defined; prezero if needed.
  176484. * To improve locality of access, we only prezero the part of the array
  176485. * that the caller is about to access, not the entire in-memory array.
  176486. */
  176487. if (ptr->first_undef_row < end_row) {
  176488. if (ptr->first_undef_row < start_row) {
  176489. if (writable) /* writer skipped over a section of array */
  176490. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176491. undef_row = start_row; /* but reader is allowed to read ahead */
  176492. } else {
  176493. undef_row = ptr->first_undef_row;
  176494. }
  176495. if (writable)
  176496. ptr->first_undef_row = end_row;
  176497. if (ptr->pre_zero) {
  176498. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176499. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176500. end_row -= ptr->cur_start_row;
  176501. while (undef_row < end_row) {
  176502. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176503. undef_row++;
  176504. }
  176505. } else {
  176506. if (! writable) /* reader looking at undefined data */
  176507. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176508. }
  176509. }
  176510. /* Flag the buffer dirty if caller will write in it */
  176511. if (writable)
  176512. ptr->dirty = TRUE;
  176513. /* Return address of proper part of the buffer */
  176514. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176515. }
  176516. /*
  176517. * Release all objects belonging to a specified pool.
  176518. */
  176519. METHODDEF(void)
  176520. free_pool (j_common_ptr cinfo, int pool_id)
  176521. {
  176522. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176523. small_pool_ptr shdr_ptr;
  176524. large_pool_ptr lhdr_ptr;
  176525. size_t space_freed;
  176526. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176527. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176528. #ifdef MEM_STATS
  176529. if (cinfo->err->trace_level > 1)
  176530. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176531. #endif
  176532. /* If freeing IMAGE pool, close any virtual arrays first */
  176533. if (pool_id == JPOOL_IMAGE) {
  176534. jvirt_sarray_ptr sptr;
  176535. jvirt_barray_ptr bptr;
  176536. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176537. if (sptr->b_s_open) { /* there may be no backing store */
  176538. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176539. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176540. }
  176541. }
  176542. mem->virt_sarray_list = NULL;
  176543. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176544. if (bptr->b_s_open) { /* there may be no backing store */
  176545. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176546. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176547. }
  176548. }
  176549. mem->virt_barray_list = NULL;
  176550. }
  176551. /* Release large objects */
  176552. lhdr_ptr = mem->large_list[pool_id];
  176553. mem->large_list[pool_id] = NULL;
  176554. while (lhdr_ptr != NULL) {
  176555. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176556. space_freed = lhdr_ptr->hdr.bytes_used +
  176557. lhdr_ptr->hdr.bytes_left +
  176558. SIZEOF(large_pool_hdr);
  176559. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176560. mem->total_space_allocated -= space_freed;
  176561. lhdr_ptr = next_lhdr_ptr;
  176562. }
  176563. /* Release small objects */
  176564. shdr_ptr = mem->small_list[pool_id];
  176565. mem->small_list[pool_id] = NULL;
  176566. while (shdr_ptr != NULL) {
  176567. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176568. space_freed = shdr_ptr->hdr.bytes_used +
  176569. shdr_ptr->hdr.bytes_left +
  176570. SIZEOF(small_pool_hdr);
  176571. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176572. mem->total_space_allocated -= space_freed;
  176573. shdr_ptr = next_shdr_ptr;
  176574. }
  176575. }
  176576. /*
  176577. * Close up shop entirely.
  176578. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176579. */
  176580. METHODDEF(void)
  176581. self_destruct (j_common_ptr cinfo)
  176582. {
  176583. int pool;
  176584. /* Close all backing store, release all memory.
  176585. * Releasing pools in reverse order might help avoid fragmentation
  176586. * with some (brain-damaged) malloc libraries.
  176587. */
  176588. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176589. free_pool(cinfo, pool);
  176590. }
  176591. /* Release the memory manager control block too. */
  176592. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176593. cinfo->mem = NULL; /* ensures I will be called only once */
  176594. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176595. }
  176596. /*
  176597. * Memory manager initialization.
  176598. * When this is called, only the error manager pointer is valid in cinfo!
  176599. */
  176600. GLOBAL(void)
  176601. jinit_memory_mgr (j_common_ptr cinfo)
  176602. {
  176603. my_mem_ptr mem;
  176604. long max_to_use;
  176605. int pool;
  176606. size_t test_mac;
  176607. cinfo->mem = NULL; /* for safety if init fails */
  176608. /* Check for configuration errors.
  176609. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176610. * doesn't reflect any real hardware alignment requirement.
  176611. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176612. * in common if and only if X is a power of 2, ie has only one one-bit.
  176613. * Some compilers may give an "unreachable code" warning here; ignore it.
  176614. */
  176615. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176616. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176617. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176618. * a multiple of SIZEOF(ALIGN_TYPE).
  176619. * Again, an "unreachable code" warning may be ignored here.
  176620. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176621. */
  176622. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176623. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176624. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176625. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176626. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176627. /* Attempt to allocate memory manager's control block */
  176628. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176629. if (mem == NULL) {
  176630. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176631. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176632. }
  176633. /* OK, fill in the method pointers */
  176634. mem->pub.alloc_small = alloc_small;
  176635. mem->pub.alloc_large = alloc_large;
  176636. mem->pub.alloc_sarray = alloc_sarray;
  176637. mem->pub.alloc_barray = alloc_barray;
  176638. mem->pub.request_virt_sarray = request_virt_sarray;
  176639. mem->pub.request_virt_barray = request_virt_barray;
  176640. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176641. mem->pub.access_virt_sarray = access_virt_sarray;
  176642. mem->pub.access_virt_barray = access_virt_barray;
  176643. mem->pub.free_pool = free_pool;
  176644. mem->pub.self_destruct = self_destruct;
  176645. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176646. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176647. /* Initialize working state */
  176648. mem->pub.max_memory_to_use = max_to_use;
  176649. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176650. mem->small_list[pool] = NULL;
  176651. mem->large_list[pool] = NULL;
  176652. }
  176653. mem->virt_sarray_list = NULL;
  176654. mem->virt_barray_list = NULL;
  176655. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176656. /* Declare ourselves open for business */
  176657. cinfo->mem = & mem->pub;
  176658. /* Check for an environment variable JPEGMEM; if found, override the
  176659. * default max_memory setting from jpeg_mem_init. Note that the
  176660. * surrounding application may again override this value.
  176661. * If your system doesn't support getenv(), define NO_GETENV to disable
  176662. * this feature.
  176663. */
  176664. #ifndef NO_GETENV
  176665. { char * memenv;
  176666. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176667. char ch = 'x';
  176668. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176669. if (ch == 'm' || ch == 'M')
  176670. max_to_use *= 1000L;
  176671. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176672. }
  176673. }
  176674. }
  176675. #endif
  176676. }
  176677. /*** End of inlined file: jmemmgr.c ***/
  176678. /*** Start of inlined file: jmemnobs.c ***/
  176679. #define JPEG_INTERNALS
  176680. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176681. extern void * malloc JPP((size_t size));
  176682. extern void free JPP((void *ptr));
  176683. #endif
  176684. /*
  176685. * Memory allocation and freeing are controlled by the regular library
  176686. * routines malloc() and free().
  176687. */
  176688. GLOBAL(void *)
  176689. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176690. {
  176691. return (void *) malloc(sizeofobject);
  176692. }
  176693. GLOBAL(void)
  176694. jpeg_free_small (j_common_ptr , void * object, size_t)
  176695. {
  176696. free(object);
  176697. }
  176698. /*
  176699. * "Large" objects are treated the same as "small" ones.
  176700. * NB: although we include FAR keywords in the routine declarations,
  176701. * this file won't actually work in 80x86 small/medium model; at least,
  176702. * you probably won't be able to process useful-size images in only 64KB.
  176703. */
  176704. GLOBAL(void FAR *)
  176705. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176706. {
  176707. return (void FAR *) malloc(sizeofobject);
  176708. }
  176709. GLOBAL(void)
  176710. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176711. {
  176712. free(object);
  176713. }
  176714. /*
  176715. * This routine computes the total memory space available for allocation.
  176716. * Here we always say, "we got all you want bud!"
  176717. */
  176718. GLOBAL(long)
  176719. jpeg_mem_available (j_common_ptr, long,
  176720. long max_bytes_needed, long)
  176721. {
  176722. return max_bytes_needed;
  176723. }
  176724. /*
  176725. * Backing store (temporary file) management.
  176726. * Since jpeg_mem_available always promised the moon,
  176727. * this should never be called and we can just error out.
  176728. */
  176729. GLOBAL(void)
  176730. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176731. long )
  176732. {
  176733. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176734. }
  176735. /*
  176736. * These routines take care of any system-dependent initialization and
  176737. * cleanup required. Here, there isn't any.
  176738. */
  176739. GLOBAL(long)
  176740. jpeg_mem_init (j_common_ptr)
  176741. {
  176742. return 0; /* just set max_memory_to_use to 0 */
  176743. }
  176744. GLOBAL(void)
  176745. jpeg_mem_term (j_common_ptr)
  176746. {
  176747. /* no work */
  176748. }
  176749. /*** End of inlined file: jmemnobs.c ***/
  176750. /*** Start of inlined file: jquant1.c ***/
  176751. #define JPEG_INTERNALS
  176752. #ifdef QUANT_1PASS_SUPPORTED
  176753. /*
  176754. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176755. * high quality, colormapped output capability. A 2-pass quantizer usually
  176756. * gives better visual quality; however, for quantized grayscale output this
  176757. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176758. * quantizer, though you can turn it off if you really want to.
  176759. *
  176760. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176761. * image. We use a map consisting of all combinations of Ncolors[i] color
  176762. * values for the i'th component. The Ncolors[] values are chosen so that
  176763. * their product, the total number of colors, is no more than that requested.
  176764. * (In most cases, the product will be somewhat less.)
  176765. *
  176766. * Since the colormap is orthogonal, the representative value for each color
  176767. * component can be determined without considering the other components;
  176768. * then these indexes can be combined into a colormap index by a standard
  176769. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176770. * can be precalculated and stored in the lookup table colorindex[].
  176771. * colorindex[i][j] maps pixel value j in component i to the nearest
  176772. * representative value (grid plane) for that component; this index is
  176773. * multiplied by the array stride for component i, so that the
  176774. * index of the colormap entry closest to a given pixel value is just
  176775. * sum( colorindex[component-number][pixel-component-value] )
  176776. * Aside from being fast, this scheme allows for variable spacing between
  176777. * representative values with no additional lookup cost.
  176778. *
  176779. * If gamma correction has been applied in color conversion, it might be wise
  176780. * to adjust the color grid spacing so that the representative colors are
  176781. * equidistant in linear space. At this writing, gamma correction is not
  176782. * implemented by jdcolor, so nothing is done here.
  176783. */
  176784. /* Declarations for ordered dithering.
  176785. *
  176786. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176787. * dithering is described in many references, for instance Dale Schumacher's
  176788. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176789. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176790. * "dither" value to the input pixel and then round the result to the nearest
  176791. * output value. The dither value is equivalent to (0.5 - threshold) times
  176792. * the distance between output values. For ordered dithering, we assume that
  176793. * the output colors are equally spaced; if not, results will probably be
  176794. * worse, since the dither may be too much or too little at a given point.
  176795. *
  176796. * The normal calculation would be to form pixel value + dither, range-limit
  176797. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176798. * We can skip the separate range-limiting step by extending the colorindex
  176799. * table in both directions.
  176800. */
  176801. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176802. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176803. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176804. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176805. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176806. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176807. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176808. /* Bayer's order-4 dither array. Generated by the code given in
  176809. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176810. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176811. */
  176812. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176813. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176814. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176815. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176816. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176817. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176818. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176819. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176820. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176821. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176822. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176823. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176824. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176825. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176826. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176827. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176828. };
  176829. /* Declarations for Floyd-Steinberg dithering.
  176830. *
  176831. * Errors are accumulated into the array fserrors[], at a resolution of
  176832. * 1/16th of a pixel count. The error at a given pixel is propagated
  176833. * to its not-yet-processed neighbors using the standard F-S fractions,
  176834. * ... (here) 7/16
  176835. * 3/16 5/16 1/16
  176836. * We work left-to-right on even rows, right-to-left on odd rows.
  176837. *
  176838. * We can get away with a single array (holding one row's worth of errors)
  176839. * by using it to store the current row's errors at pixel columns not yet
  176840. * processed, but the next row's errors at columns already processed. We
  176841. * need only a few extra variables to hold the errors immediately around the
  176842. * current column. (If we are lucky, those variables are in registers, but
  176843. * even if not, they're probably cheaper to access than array elements are.)
  176844. *
  176845. * The fserrors[] array is indexed [component#][position].
  176846. * We provide (#columns + 2) entries per component; the extra entry at each
  176847. * end saves us from special-casing the first and last pixels.
  176848. *
  176849. * Note: on a wide image, we might not have enough room in a PC's near data
  176850. * segment to hold the error array; so it is allocated with alloc_large.
  176851. */
  176852. #if BITS_IN_JSAMPLE == 8
  176853. typedef INT16 FSERROR; /* 16 bits should be enough */
  176854. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176855. #else
  176856. typedef INT32 FSERROR; /* may need more than 16 bits */
  176857. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176858. #endif
  176859. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176860. /* Private subobject */
  176861. #define MAX_Q_COMPS 4 /* max components I can handle */
  176862. typedef struct {
  176863. struct jpeg_color_quantizer pub; /* public fields */
  176864. /* Initially allocated colormap is saved here */
  176865. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176866. int sv_actual; /* number of entries in use */
  176867. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176868. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176869. * premultiplied as described above. Since colormap indexes must fit into
  176870. * JSAMPLEs, the entries of this array will too.
  176871. */
  176872. boolean is_padded; /* is the colorindex padded for odither? */
  176873. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176874. /* Variables for ordered dithering */
  176875. int row_index; /* cur row's vertical index in dither matrix */
  176876. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176877. /* Variables for Floyd-Steinberg dithering */
  176878. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176879. boolean on_odd_row; /* flag to remember which row we are on */
  176880. } my_cquantizer;
  176881. typedef my_cquantizer * my_cquantize_ptr;
  176882. /*
  176883. * Policy-making subroutines for create_colormap and create_colorindex.
  176884. * These routines determine the colormap to be used. The rest of the module
  176885. * only assumes that the colormap is orthogonal.
  176886. *
  176887. * * select_ncolors decides how to divvy up the available colors
  176888. * among the components.
  176889. * * output_value defines the set of representative values for a component.
  176890. * * largest_input_value defines the mapping from input values to
  176891. * representative values for a component.
  176892. * Note that the latter two routines may impose different policies for
  176893. * different components, though this is not currently done.
  176894. */
  176895. LOCAL(int)
  176896. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176897. /* Determine allocation of desired colors to components, */
  176898. /* and fill in Ncolors[] array to indicate choice. */
  176899. /* Return value is total number of colors (product of Ncolors[] values). */
  176900. {
  176901. int nc = cinfo->out_color_components; /* number of color components */
  176902. int max_colors = cinfo->desired_number_of_colors;
  176903. int total_colors, iroot, i, j;
  176904. boolean changed;
  176905. long temp;
  176906. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176907. /* We can allocate at least the nc'th root of max_colors per component. */
  176908. /* Compute floor(nc'th root of max_colors). */
  176909. iroot = 1;
  176910. do {
  176911. iroot++;
  176912. temp = iroot; /* set temp = iroot ** nc */
  176913. for (i = 1; i < nc; i++)
  176914. temp *= iroot;
  176915. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176916. iroot--; /* now iroot = floor(root) */
  176917. /* Must have at least 2 color values per component */
  176918. if (iroot < 2)
  176919. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176920. /* Initialize to iroot color values for each component */
  176921. total_colors = 1;
  176922. for (i = 0; i < nc; i++) {
  176923. Ncolors[i] = iroot;
  176924. total_colors *= iroot;
  176925. }
  176926. /* We may be able to increment the count for one or more components without
  176927. * exceeding max_colors, though we know not all can be incremented.
  176928. * Sometimes, the first component can be incremented more than once!
  176929. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176930. * In RGB colorspace, try to increment G first, then R, then B.
  176931. */
  176932. do {
  176933. changed = FALSE;
  176934. for (i = 0; i < nc; i++) {
  176935. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176936. /* calculate new total_colors if Ncolors[j] is incremented */
  176937. temp = total_colors / Ncolors[j];
  176938. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176939. if (temp > (long) max_colors)
  176940. break; /* won't fit, done with this pass */
  176941. Ncolors[j]++; /* OK, apply the increment */
  176942. total_colors = (int) temp;
  176943. changed = TRUE;
  176944. }
  176945. } while (changed);
  176946. return total_colors;
  176947. }
  176948. LOCAL(int)
  176949. output_value (j_decompress_ptr, int, int j, int maxj)
  176950. /* Return j'th output value, where j will range from 0 to maxj */
  176951. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176952. {
  176953. /* We always provide values 0 and MAXJSAMPLE for each component;
  176954. * any additional values are equally spaced between these limits.
  176955. * (Forcing the upper and lower values to the limits ensures that
  176956. * dithering can't produce a color outside the selected gamut.)
  176957. */
  176958. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176959. }
  176960. LOCAL(int)
  176961. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176962. /* Return largest input value that should map to j'th output value */
  176963. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176964. {
  176965. /* Breakpoints are halfway between values returned by output_value */
  176966. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176967. }
  176968. /*
  176969. * Create the colormap.
  176970. */
  176971. LOCAL(void)
  176972. create_colormap (j_decompress_ptr cinfo)
  176973. {
  176974. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176975. JSAMPARRAY colormap; /* Created colormap */
  176976. int total_colors; /* Number of distinct output colors */
  176977. int i,j,k, nci, blksize, blkdist, ptr, val;
  176978. /* Select number of colors for each component */
  176979. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176980. /* Report selected color counts */
  176981. if (cinfo->out_color_components == 3)
  176982. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176983. total_colors, cquantize->Ncolors[0],
  176984. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176985. else
  176986. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176987. /* Allocate and fill in the colormap. */
  176988. /* The colors are ordered in the map in standard row-major order, */
  176989. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176990. colormap = (*cinfo->mem->alloc_sarray)
  176991. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176992. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176993. /* blksize is number of adjacent repeated entries for a component */
  176994. /* blkdist is distance between groups of identical entries for a component */
  176995. blkdist = total_colors;
  176996. for (i = 0; i < cinfo->out_color_components; i++) {
  176997. /* fill in colormap entries for i'th color component */
  176998. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176999. blksize = blkdist / nci;
  177000. for (j = 0; j < nci; j++) {
  177001. /* Compute j'th output value (out of nci) for component */
  177002. val = output_value(cinfo, i, j, nci-1);
  177003. /* Fill in all colormap entries that have this value of this component */
  177004. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177005. /* fill in blksize entries beginning at ptr */
  177006. for (k = 0; k < blksize; k++)
  177007. colormap[i][ptr+k] = (JSAMPLE) val;
  177008. }
  177009. }
  177010. blkdist = blksize; /* blksize of this color is blkdist of next */
  177011. }
  177012. /* Save the colormap in private storage,
  177013. * where it will survive color quantization mode changes.
  177014. */
  177015. cquantize->sv_colormap = colormap;
  177016. cquantize->sv_actual = total_colors;
  177017. }
  177018. /*
  177019. * Create the color index table.
  177020. */
  177021. LOCAL(void)
  177022. create_colorindex (j_decompress_ptr cinfo)
  177023. {
  177024. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177025. JSAMPROW indexptr;
  177026. int i,j,k, nci, blksize, val, pad;
  177027. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177028. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177029. * This is not necessary in the other dithering modes. However, we
  177030. * flag whether it was done in case user changes dithering mode.
  177031. */
  177032. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177033. pad = MAXJSAMPLE*2;
  177034. cquantize->is_padded = TRUE;
  177035. } else {
  177036. pad = 0;
  177037. cquantize->is_padded = FALSE;
  177038. }
  177039. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177040. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177041. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177042. (JDIMENSION) cinfo->out_color_components);
  177043. /* blksize is number of adjacent repeated entries for a component */
  177044. blksize = cquantize->sv_actual;
  177045. for (i = 0; i < cinfo->out_color_components; i++) {
  177046. /* fill in colorindex entries for i'th color component */
  177047. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177048. blksize = blksize / nci;
  177049. /* adjust colorindex pointers to provide padding at negative indexes. */
  177050. if (pad)
  177051. cquantize->colorindex[i] += MAXJSAMPLE;
  177052. /* in loop, val = index of current output value, */
  177053. /* and k = largest j that maps to current val */
  177054. indexptr = cquantize->colorindex[i];
  177055. val = 0;
  177056. k = largest_input_value(cinfo, i, 0, nci-1);
  177057. for (j = 0; j <= MAXJSAMPLE; j++) {
  177058. while (j > k) /* advance val if past boundary */
  177059. k = largest_input_value(cinfo, i, ++val, nci-1);
  177060. /* premultiply so that no multiplication needed in main processing */
  177061. indexptr[j] = (JSAMPLE) (val * blksize);
  177062. }
  177063. /* Pad at both ends if necessary */
  177064. if (pad)
  177065. for (j = 1; j <= MAXJSAMPLE; j++) {
  177066. indexptr[-j] = indexptr[0];
  177067. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177068. }
  177069. }
  177070. }
  177071. /*
  177072. * Create an ordered-dither array for a component having ncolors
  177073. * distinct output values.
  177074. */
  177075. LOCAL(ODITHER_MATRIX_PTR)
  177076. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177077. {
  177078. ODITHER_MATRIX_PTR odither;
  177079. int j,k;
  177080. INT32 num,den;
  177081. odither = (ODITHER_MATRIX_PTR)
  177082. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177083. SIZEOF(ODITHER_MATRIX));
  177084. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177085. * Hence the dither value for the matrix cell with fill order f
  177086. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177087. * On 16-bit-int machine, be careful to avoid overflow.
  177088. */
  177089. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177090. for (j = 0; j < ODITHER_SIZE; j++) {
  177091. for (k = 0; k < ODITHER_SIZE; k++) {
  177092. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177093. * MAXJSAMPLE;
  177094. /* Ensure round towards zero despite C's lack of consistency
  177095. * about rounding negative values in integer division...
  177096. */
  177097. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177098. }
  177099. }
  177100. return odither;
  177101. }
  177102. /*
  177103. * Create the ordered-dither tables.
  177104. * Components having the same number of representative colors may
  177105. * share a dither table.
  177106. */
  177107. LOCAL(void)
  177108. create_odither_tables (j_decompress_ptr cinfo)
  177109. {
  177110. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177111. ODITHER_MATRIX_PTR odither;
  177112. int i, j, nci;
  177113. for (i = 0; i < cinfo->out_color_components; i++) {
  177114. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177115. odither = NULL; /* search for matching prior component */
  177116. for (j = 0; j < i; j++) {
  177117. if (nci == cquantize->Ncolors[j]) {
  177118. odither = cquantize->odither[j];
  177119. break;
  177120. }
  177121. }
  177122. if (odither == NULL) /* need a new table? */
  177123. odither = make_odither_array(cinfo, nci);
  177124. cquantize->odither[i] = odither;
  177125. }
  177126. }
  177127. /*
  177128. * Map some rows of pixels to the output colormapped representation.
  177129. */
  177130. METHODDEF(void)
  177131. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177132. JSAMPARRAY output_buf, int num_rows)
  177133. /* General case, no dithering */
  177134. {
  177135. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177136. JSAMPARRAY colorindex = cquantize->colorindex;
  177137. register int pixcode, ci;
  177138. register JSAMPROW ptrin, ptrout;
  177139. int row;
  177140. JDIMENSION col;
  177141. JDIMENSION width = cinfo->output_width;
  177142. register int nc = cinfo->out_color_components;
  177143. for (row = 0; row < num_rows; row++) {
  177144. ptrin = input_buf[row];
  177145. ptrout = output_buf[row];
  177146. for (col = width; col > 0; col--) {
  177147. pixcode = 0;
  177148. for (ci = 0; ci < nc; ci++) {
  177149. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177150. }
  177151. *ptrout++ = (JSAMPLE) pixcode;
  177152. }
  177153. }
  177154. }
  177155. METHODDEF(void)
  177156. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177157. JSAMPARRAY output_buf, int num_rows)
  177158. /* Fast path for out_color_components==3, no dithering */
  177159. {
  177160. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177161. register int pixcode;
  177162. register JSAMPROW ptrin, ptrout;
  177163. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177164. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177165. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177166. int row;
  177167. JDIMENSION col;
  177168. JDIMENSION width = cinfo->output_width;
  177169. for (row = 0; row < num_rows; row++) {
  177170. ptrin = input_buf[row];
  177171. ptrout = output_buf[row];
  177172. for (col = width; col > 0; col--) {
  177173. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177174. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177175. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177176. *ptrout++ = (JSAMPLE) pixcode;
  177177. }
  177178. }
  177179. }
  177180. METHODDEF(void)
  177181. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177182. JSAMPARRAY output_buf, int num_rows)
  177183. /* General case, with ordered dithering */
  177184. {
  177185. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177186. register JSAMPROW input_ptr;
  177187. register JSAMPROW output_ptr;
  177188. JSAMPROW colorindex_ci;
  177189. int * dither; /* points to active row of dither matrix */
  177190. int row_index, col_index; /* current indexes into dither matrix */
  177191. int nc = cinfo->out_color_components;
  177192. int ci;
  177193. int row;
  177194. JDIMENSION col;
  177195. JDIMENSION width = cinfo->output_width;
  177196. for (row = 0; row < num_rows; row++) {
  177197. /* Initialize output values to 0 so can process components separately */
  177198. jzero_far((void FAR *) output_buf[row],
  177199. (size_t) (width * SIZEOF(JSAMPLE)));
  177200. row_index = cquantize->row_index;
  177201. for (ci = 0; ci < nc; ci++) {
  177202. input_ptr = input_buf[row] + ci;
  177203. output_ptr = output_buf[row];
  177204. colorindex_ci = cquantize->colorindex[ci];
  177205. dither = cquantize->odither[ci][row_index];
  177206. col_index = 0;
  177207. for (col = width; col > 0; col--) {
  177208. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177209. * select output value, accumulate into output code for this pixel.
  177210. * Range-limiting need not be done explicitly, as we have extended
  177211. * the colorindex table to produce the right answers for out-of-range
  177212. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177213. * required amount of padding.
  177214. */
  177215. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177216. input_ptr += nc;
  177217. output_ptr++;
  177218. col_index = (col_index + 1) & ODITHER_MASK;
  177219. }
  177220. }
  177221. /* Advance row index for next row */
  177222. row_index = (row_index + 1) & ODITHER_MASK;
  177223. cquantize->row_index = row_index;
  177224. }
  177225. }
  177226. METHODDEF(void)
  177227. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177228. JSAMPARRAY output_buf, int num_rows)
  177229. /* Fast path for out_color_components==3, with ordered dithering */
  177230. {
  177231. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177232. register int pixcode;
  177233. register JSAMPROW input_ptr;
  177234. register JSAMPROW output_ptr;
  177235. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177236. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177237. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177238. int * dither0; /* points to active row of dither matrix */
  177239. int * dither1;
  177240. int * dither2;
  177241. int row_index, col_index; /* current indexes into dither matrix */
  177242. int row;
  177243. JDIMENSION col;
  177244. JDIMENSION width = cinfo->output_width;
  177245. for (row = 0; row < num_rows; row++) {
  177246. row_index = cquantize->row_index;
  177247. input_ptr = input_buf[row];
  177248. output_ptr = output_buf[row];
  177249. dither0 = cquantize->odither[0][row_index];
  177250. dither1 = cquantize->odither[1][row_index];
  177251. dither2 = cquantize->odither[2][row_index];
  177252. col_index = 0;
  177253. for (col = width; col > 0; col--) {
  177254. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177255. dither0[col_index]]);
  177256. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177257. dither1[col_index]]);
  177258. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177259. dither2[col_index]]);
  177260. *output_ptr++ = (JSAMPLE) pixcode;
  177261. col_index = (col_index + 1) & ODITHER_MASK;
  177262. }
  177263. row_index = (row_index + 1) & ODITHER_MASK;
  177264. cquantize->row_index = row_index;
  177265. }
  177266. }
  177267. METHODDEF(void)
  177268. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177269. JSAMPARRAY output_buf, int num_rows)
  177270. /* General case, with Floyd-Steinberg dithering */
  177271. {
  177272. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177273. register LOCFSERROR cur; /* current error or pixel value */
  177274. LOCFSERROR belowerr; /* error for pixel below cur */
  177275. LOCFSERROR bpreverr; /* error for below/prev col */
  177276. LOCFSERROR bnexterr; /* error for below/next col */
  177277. LOCFSERROR delta;
  177278. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177279. register JSAMPROW input_ptr;
  177280. register JSAMPROW output_ptr;
  177281. JSAMPROW colorindex_ci;
  177282. JSAMPROW colormap_ci;
  177283. int pixcode;
  177284. int nc = cinfo->out_color_components;
  177285. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177286. int dirnc; /* dir * nc */
  177287. int ci;
  177288. int row;
  177289. JDIMENSION col;
  177290. JDIMENSION width = cinfo->output_width;
  177291. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177292. SHIFT_TEMPS
  177293. for (row = 0; row < num_rows; row++) {
  177294. /* Initialize output values to 0 so can process components separately */
  177295. jzero_far((void FAR *) output_buf[row],
  177296. (size_t) (width * SIZEOF(JSAMPLE)));
  177297. for (ci = 0; ci < nc; ci++) {
  177298. input_ptr = input_buf[row] + ci;
  177299. output_ptr = output_buf[row];
  177300. if (cquantize->on_odd_row) {
  177301. /* work right to left in this row */
  177302. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177303. output_ptr += width-1;
  177304. dir = -1;
  177305. dirnc = -nc;
  177306. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177307. } else {
  177308. /* work left to right in this row */
  177309. dir = 1;
  177310. dirnc = nc;
  177311. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177312. }
  177313. colorindex_ci = cquantize->colorindex[ci];
  177314. colormap_ci = cquantize->sv_colormap[ci];
  177315. /* Preset error values: no error propagated to first pixel from left */
  177316. cur = 0;
  177317. /* and no error propagated to row below yet */
  177318. belowerr = bpreverr = 0;
  177319. for (col = width; col > 0; col--) {
  177320. /* cur holds the error propagated from the previous pixel on the
  177321. * current line. Add the error propagated from the previous line
  177322. * to form the complete error correction term for this pixel, and
  177323. * round the error term (which is expressed * 16) to an integer.
  177324. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177325. * for either sign of the error value.
  177326. * Note: errorptr points to *previous* column's array entry.
  177327. */
  177328. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177329. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177330. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177331. * of the range_limit array.
  177332. */
  177333. cur += GETJSAMPLE(*input_ptr);
  177334. cur = GETJSAMPLE(range_limit[cur]);
  177335. /* Select output value, accumulate into output code for this pixel */
  177336. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177337. *output_ptr += (JSAMPLE) pixcode;
  177338. /* Compute actual representation error at this pixel */
  177339. /* Note: we can do this even though we don't have the final */
  177340. /* pixel code, because the colormap is orthogonal. */
  177341. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177342. /* Compute error fractions to be propagated to adjacent pixels.
  177343. * Add these into the running sums, and simultaneously shift the
  177344. * next-line error sums left by 1 column.
  177345. */
  177346. bnexterr = cur;
  177347. delta = cur * 2;
  177348. cur += delta; /* form error * 3 */
  177349. errorptr[0] = (FSERROR) (bpreverr + cur);
  177350. cur += delta; /* form error * 5 */
  177351. bpreverr = belowerr + cur;
  177352. belowerr = bnexterr;
  177353. cur += delta; /* form error * 7 */
  177354. /* At this point cur contains the 7/16 error value to be propagated
  177355. * to the next pixel on the current line, and all the errors for the
  177356. * next line have been shifted over. We are therefore ready to move on.
  177357. */
  177358. input_ptr += dirnc; /* advance input ptr to next column */
  177359. output_ptr += dir; /* advance output ptr to next column */
  177360. errorptr += dir; /* advance errorptr to current column */
  177361. }
  177362. /* Post-loop cleanup: we must unload the final error value into the
  177363. * final fserrors[] entry. Note we need not unload belowerr because
  177364. * it is for the dummy column before or after the actual array.
  177365. */
  177366. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177367. }
  177368. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177369. }
  177370. }
  177371. /*
  177372. * Allocate workspace for Floyd-Steinberg errors.
  177373. */
  177374. LOCAL(void)
  177375. alloc_fs_workspace (j_decompress_ptr cinfo)
  177376. {
  177377. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177378. size_t arraysize;
  177379. int i;
  177380. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177381. for (i = 0; i < cinfo->out_color_components; i++) {
  177382. cquantize->fserrors[i] = (FSERRPTR)
  177383. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177384. }
  177385. }
  177386. /*
  177387. * Initialize for one-pass color quantization.
  177388. */
  177389. METHODDEF(void)
  177390. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177391. {
  177392. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177393. size_t arraysize;
  177394. int i;
  177395. /* Install my colormap. */
  177396. cinfo->colormap = cquantize->sv_colormap;
  177397. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177398. /* Initialize for desired dithering mode. */
  177399. switch (cinfo->dither_mode) {
  177400. case JDITHER_NONE:
  177401. if (cinfo->out_color_components == 3)
  177402. cquantize->pub.color_quantize = color_quantize3;
  177403. else
  177404. cquantize->pub.color_quantize = color_quantize;
  177405. break;
  177406. case JDITHER_ORDERED:
  177407. if (cinfo->out_color_components == 3)
  177408. cquantize->pub.color_quantize = quantize3_ord_dither;
  177409. else
  177410. cquantize->pub.color_quantize = quantize_ord_dither;
  177411. cquantize->row_index = 0; /* initialize state for ordered dither */
  177412. /* If user changed to ordered dither from another mode,
  177413. * we must recreate the color index table with padding.
  177414. * This will cost extra space, but probably isn't very likely.
  177415. */
  177416. if (! cquantize->is_padded)
  177417. create_colorindex(cinfo);
  177418. /* Create ordered-dither tables if we didn't already. */
  177419. if (cquantize->odither[0] == NULL)
  177420. create_odither_tables(cinfo);
  177421. break;
  177422. case JDITHER_FS:
  177423. cquantize->pub.color_quantize = quantize_fs_dither;
  177424. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177425. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177426. if (cquantize->fserrors[0] == NULL)
  177427. alloc_fs_workspace(cinfo);
  177428. /* Initialize the propagated errors to zero. */
  177429. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177430. for (i = 0; i < cinfo->out_color_components; i++)
  177431. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177432. break;
  177433. default:
  177434. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177435. break;
  177436. }
  177437. }
  177438. /*
  177439. * Finish up at the end of the pass.
  177440. */
  177441. METHODDEF(void)
  177442. finish_pass_1_quant (j_decompress_ptr)
  177443. {
  177444. /* no work in 1-pass case */
  177445. }
  177446. /*
  177447. * Switch to a new external colormap between output passes.
  177448. * Shouldn't get to this module!
  177449. */
  177450. METHODDEF(void)
  177451. new_color_map_1_quant (j_decompress_ptr cinfo)
  177452. {
  177453. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177454. }
  177455. /*
  177456. * Module initialization routine for 1-pass color quantization.
  177457. */
  177458. GLOBAL(void)
  177459. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177460. {
  177461. my_cquantize_ptr cquantize;
  177462. cquantize = (my_cquantize_ptr)
  177463. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177464. SIZEOF(my_cquantizer));
  177465. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177466. cquantize->pub.start_pass = start_pass_1_quant;
  177467. cquantize->pub.finish_pass = finish_pass_1_quant;
  177468. cquantize->pub.new_color_map = new_color_map_1_quant;
  177469. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177470. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177471. /* Make sure my internal arrays won't overflow */
  177472. if (cinfo->out_color_components > MAX_Q_COMPS)
  177473. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177474. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177475. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177476. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177477. /* Create the colormap and color index table. */
  177478. create_colormap(cinfo);
  177479. create_colorindex(cinfo);
  177480. /* Allocate Floyd-Steinberg workspace now if requested.
  177481. * We do this now since it is FAR storage and may affect the memory
  177482. * manager's space calculations. If the user changes to FS dither
  177483. * mode in a later pass, we will allocate the space then, and will
  177484. * possibly overrun the max_memory_to_use setting.
  177485. */
  177486. if (cinfo->dither_mode == JDITHER_FS)
  177487. alloc_fs_workspace(cinfo);
  177488. }
  177489. #endif /* QUANT_1PASS_SUPPORTED */
  177490. /*** End of inlined file: jquant1.c ***/
  177491. /*** Start of inlined file: jquant2.c ***/
  177492. #define JPEG_INTERNALS
  177493. #ifdef QUANT_2PASS_SUPPORTED
  177494. /*
  177495. * This module implements the well-known Heckbert paradigm for color
  177496. * quantization. Most of the ideas used here can be traced back to
  177497. * Heckbert's seminal paper
  177498. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177499. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177500. *
  177501. * In the first pass over the image, we accumulate a histogram showing the
  177502. * usage count of each possible color. To keep the histogram to a reasonable
  177503. * size, we reduce the precision of the input; typical practice is to retain
  177504. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177505. * in the same histogram cell.
  177506. *
  177507. * Next, the color-selection step begins with a box representing the whole
  177508. * color space, and repeatedly splits the "largest" remaining box until we
  177509. * have as many boxes as desired colors. Then the mean color in each
  177510. * remaining box becomes one of the possible output colors.
  177511. *
  177512. * The second pass over the image maps each input pixel to the closest output
  177513. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177514. * This mapping is logically trivial, but making it go fast enough requires
  177515. * considerable care.
  177516. *
  177517. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177518. * the "largest" box and deciding where to cut it. The particular policies
  177519. * used here have proved out well in experimental comparisons, but better ones
  177520. * may yet be found.
  177521. *
  177522. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177523. * space, processing the raw upsampled data without a color conversion step.
  177524. * This allowed the color conversion math to be done only once per colormap
  177525. * entry, not once per pixel. However, that optimization precluded other
  177526. * useful optimizations (such as merging color conversion with upsampling)
  177527. * and it also interfered with desired capabilities such as quantizing to an
  177528. * externally-supplied colormap. We have therefore abandoned that approach.
  177529. * The present code works in the post-conversion color space, typically RGB.
  177530. *
  177531. * To improve the visual quality of the results, we actually work in scaled
  177532. * RGB space, giving G distances more weight than R, and R in turn more than
  177533. * B. To do everything in integer math, we must use integer scale factors.
  177534. * The 2/3/1 scale factors used here correspond loosely to the relative
  177535. * weights of the colors in the NTSC grayscale equation.
  177536. * If you want to use this code to quantize a non-RGB color space, you'll
  177537. * probably need to change these scale factors.
  177538. */
  177539. #define R_SCALE 2 /* scale R distances by this much */
  177540. #define G_SCALE 3 /* scale G distances by this much */
  177541. #define B_SCALE 1 /* and B by this much */
  177542. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177543. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177544. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177545. * you'll get compile errors until you extend this logic. In that case
  177546. * you'll probably want to tweak the histogram sizes too.
  177547. */
  177548. #if RGB_RED == 0
  177549. #define C0_SCALE R_SCALE
  177550. #endif
  177551. #if RGB_BLUE == 0
  177552. #define C0_SCALE B_SCALE
  177553. #endif
  177554. #if RGB_GREEN == 1
  177555. #define C1_SCALE G_SCALE
  177556. #endif
  177557. #if RGB_RED == 2
  177558. #define C2_SCALE R_SCALE
  177559. #endif
  177560. #if RGB_BLUE == 2
  177561. #define C2_SCALE B_SCALE
  177562. #endif
  177563. /*
  177564. * First we have the histogram data structure and routines for creating it.
  177565. *
  177566. * The number of bits of precision can be adjusted by changing these symbols.
  177567. * We recommend keeping 6 bits for G and 5 each for R and B.
  177568. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177569. * better results; if you are short of memory, 5 bits all around will save
  177570. * some space but degrade the results.
  177571. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177572. * (preferably unsigned long) for each cell. In practice this is overkill;
  177573. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177574. * and clamping those that do overflow to the maximum value will give close-
  177575. * enough results. This reduces the recommended histogram size from 256Kb
  177576. * to 128Kb, which is a useful savings on PC-class machines.
  177577. * (In the second pass the histogram space is re-used for pixel mapping data;
  177578. * in that capacity, each cell must be able to store zero to the number of
  177579. * desired colors. 16 bits/cell is plenty for that too.)
  177580. * Since the JPEG code is intended to run in small memory model on 80x86
  177581. * machines, we can't just allocate the histogram in one chunk. Instead
  177582. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177583. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177584. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177585. * on 80x86 machines, the pointer row is in near memory but the actual
  177586. * arrays are in far memory (same arrangement as we use for image arrays).
  177587. */
  177588. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177589. /* These will do the right thing for either R,G,B or B,G,R color order,
  177590. * but you may not like the results for other color orders.
  177591. */
  177592. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177593. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177594. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177595. /* Number of elements along histogram axes. */
  177596. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177597. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177598. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177599. /* These are the amounts to shift an input value to get a histogram index. */
  177600. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177601. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177602. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177603. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177604. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177605. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177606. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177607. typedef hist2d * hist3d; /* type for top-level pointer */
  177608. /* Declarations for Floyd-Steinberg dithering.
  177609. *
  177610. * Errors are accumulated into the array fserrors[], at a resolution of
  177611. * 1/16th of a pixel count. The error at a given pixel is propagated
  177612. * to its not-yet-processed neighbors using the standard F-S fractions,
  177613. * ... (here) 7/16
  177614. * 3/16 5/16 1/16
  177615. * We work left-to-right on even rows, right-to-left on odd rows.
  177616. *
  177617. * We can get away with a single array (holding one row's worth of errors)
  177618. * by using it to store the current row's errors at pixel columns not yet
  177619. * processed, but the next row's errors at columns already processed. We
  177620. * need only a few extra variables to hold the errors immediately around the
  177621. * current column. (If we are lucky, those variables are in registers, but
  177622. * even if not, they're probably cheaper to access than array elements are.)
  177623. *
  177624. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177625. * each end saves us from special-casing the first and last pixels.
  177626. * Each entry is three values long, one value for each color component.
  177627. *
  177628. * Note: on a wide image, we might not have enough room in a PC's near data
  177629. * segment to hold the error array; so it is allocated with alloc_large.
  177630. */
  177631. #if BITS_IN_JSAMPLE == 8
  177632. typedef INT16 FSERROR; /* 16 bits should be enough */
  177633. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177634. #else
  177635. typedef INT32 FSERROR; /* may need more than 16 bits */
  177636. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177637. #endif
  177638. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177639. /* Private subobject */
  177640. typedef struct {
  177641. struct jpeg_color_quantizer pub; /* public fields */
  177642. /* Space for the eventually created colormap is stashed here */
  177643. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177644. int desired; /* desired # of colors = size of colormap */
  177645. /* Variables for accumulating image statistics */
  177646. hist3d histogram; /* pointer to the histogram */
  177647. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177648. /* Variables for Floyd-Steinberg dithering */
  177649. FSERRPTR fserrors; /* accumulated errors */
  177650. boolean on_odd_row; /* flag to remember which row we are on */
  177651. int * error_limiter; /* table for clamping the applied error */
  177652. } my_cquantizer2;
  177653. typedef my_cquantizer2 * my_cquantize_ptr2;
  177654. /*
  177655. * Prescan some rows of pixels.
  177656. * In this module the prescan simply updates the histogram, which has been
  177657. * initialized to zeroes by start_pass.
  177658. * An output_buf parameter is required by the method signature, but no data
  177659. * is actually output (in fact the buffer controller is probably passing a
  177660. * NULL pointer).
  177661. */
  177662. METHODDEF(void)
  177663. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177664. JSAMPARRAY, int num_rows)
  177665. {
  177666. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177667. register JSAMPROW ptr;
  177668. register histptr histp;
  177669. register hist3d histogram = cquantize->histogram;
  177670. int row;
  177671. JDIMENSION col;
  177672. JDIMENSION width = cinfo->output_width;
  177673. for (row = 0; row < num_rows; row++) {
  177674. ptr = input_buf[row];
  177675. for (col = width; col > 0; col--) {
  177676. /* get pixel value and index into the histogram */
  177677. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177678. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177679. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177680. /* increment, check for overflow and undo increment if so. */
  177681. if (++(*histp) <= 0)
  177682. (*histp)--;
  177683. ptr += 3;
  177684. }
  177685. }
  177686. }
  177687. /*
  177688. * Next we have the really interesting routines: selection of a colormap
  177689. * given the completed histogram.
  177690. * These routines work with a list of "boxes", each representing a rectangular
  177691. * subset of the input color space (to histogram precision).
  177692. */
  177693. typedef struct {
  177694. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177695. int c0min, c0max;
  177696. int c1min, c1max;
  177697. int c2min, c2max;
  177698. /* The volume (actually 2-norm) of the box */
  177699. INT32 volume;
  177700. /* The number of nonzero histogram cells within this box */
  177701. long colorcount;
  177702. } box;
  177703. typedef box * boxptr;
  177704. LOCAL(boxptr)
  177705. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177706. /* Find the splittable box with the largest color population */
  177707. /* Returns NULL if no splittable boxes remain */
  177708. {
  177709. register boxptr boxp;
  177710. register int i;
  177711. register long maxc = 0;
  177712. boxptr which = NULL;
  177713. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177714. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177715. which = boxp;
  177716. maxc = boxp->colorcount;
  177717. }
  177718. }
  177719. return which;
  177720. }
  177721. LOCAL(boxptr)
  177722. find_biggest_volume (boxptr boxlist, int numboxes)
  177723. /* Find the splittable box with the largest (scaled) volume */
  177724. /* Returns NULL if no splittable boxes remain */
  177725. {
  177726. register boxptr boxp;
  177727. register int i;
  177728. register INT32 maxv = 0;
  177729. boxptr which = NULL;
  177730. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177731. if (boxp->volume > maxv) {
  177732. which = boxp;
  177733. maxv = boxp->volume;
  177734. }
  177735. }
  177736. return which;
  177737. }
  177738. LOCAL(void)
  177739. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177740. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177741. /* and recompute its volume and population */
  177742. {
  177743. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177744. hist3d histogram = cquantize->histogram;
  177745. histptr histp;
  177746. int c0,c1,c2;
  177747. int c0min,c0max,c1min,c1max,c2min,c2max;
  177748. INT32 dist0,dist1,dist2;
  177749. long ccount;
  177750. c0min = boxp->c0min; c0max = boxp->c0max;
  177751. c1min = boxp->c1min; c1max = boxp->c1max;
  177752. c2min = boxp->c2min; c2max = boxp->c2max;
  177753. if (c0max > c0min)
  177754. for (c0 = c0min; c0 <= c0max; c0++)
  177755. for (c1 = c1min; c1 <= c1max; c1++) {
  177756. histp = & histogram[c0][c1][c2min];
  177757. for (c2 = c2min; c2 <= c2max; c2++)
  177758. if (*histp++ != 0) {
  177759. boxp->c0min = c0min = c0;
  177760. goto have_c0min;
  177761. }
  177762. }
  177763. have_c0min:
  177764. if (c0max > c0min)
  177765. for (c0 = c0max; c0 >= c0min; c0--)
  177766. for (c1 = c1min; c1 <= c1max; c1++) {
  177767. histp = & histogram[c0][c1][c2min];
  177768. for (c2 = c2min; c2 <= c2max; c2++)
  177769. if (*histp++ != 0) {
  177770. boxp->c0max = c0max = c0;
  177771. goto have_c0max;
  177772. }
  177773. }
  177774. have_c0max:
  177775. if (c1max > c1min)
  177776. for (c1 = c1min; c1 <= c1max; c1++)
  177777. for (c0 = c0min; c0 <= c0max; c0++) {
  177778. histp = & histogram[c0][c1][c2min];
  177779. for (c2 = c2min; c2 <= c2max; c2++)
  177780. if (*histp++ != 0) {
  177781. boxp->c1min = c1min = c1;
  177782. goto have_c1min;
  177783. }
  177784. }
  177785. have_c1min:
  177786. if (c1max > c1min)
  177787. for (c1 = c1max; c1 >= c1min; c1--)
  177788. for (c0 = c0min; c0 <= c0max; c0++) {
  177789. histp = & histogram[c0][c1][c2min];
  177790. for (c2 = c2min; c2 <= c2max; c2++)
  177791. if (*histp++ != 0) {
  177792. boxp->c1max = c1max = c1;
  177793. goto have_c1max;
  177794. }
  177795. }
  177796. have_c1max:
  177797. if (c2max > c2min)
  177798. for (c2 = c2min; c2 <= c2max; c2++)
  177799. for (c0 = c0min; c0 <= c0max; c0++) {
  177800. histp = & histogram[c0][c1min][c2];
  177801. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177802. if (*histp != 0) {
  177803. boxp->c2min = c2min = c2;
  177804. goto have_c2min;
  177805. }
  177806. }
  177807. have_c2min:
  177808. if (c2max > c2min)
  177809. for (c2 = c2max; c2 >= c2min; c2--)
  177810. for (c0 = c0min; c0 <= c0max; c0++) {
  177811. histp = & histogram[c0][c1min][c2];
  177812. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177813. if (*histp != 0) {
  177814. boxp->c2max = c2max = c2;
  177815. goto have_c2max;
  177816. }
  177817. }
  177818. have_c2max:
  177819. /* Update box volume.
  177820. * We use 2-norm rather than real volume here; this biases the method
  177821. * against making long narrow boxes, and it has the side benefit that
  177822. * a box is splittable iff norm > 0.
  177823. * Since the differences are expressed in histogram-cell units,
  177824. * we have to shift back to JSAMPLE units to get consistent distances;
  177825. * after which, we scale according to the selected distance scale factors.
  177826. */
  177827. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177828. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177829. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177830. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177831. /* Now scan remaining volume of box and compute population */
  177832. ccount = 0;
  177833. for (c0 = c0min; c0 <= c0max; c0++)
  177834. for (c1 = c1min; c1 <= c1max; c1++) {
  177835. histp = & histogram[c0][c1][c2min];
  177836. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177837. if (*histp != 0) {
  177838. ccount++;
  177839. }
  177840. }
  177841. boxp->colorcount = ccount;
  177842. }
  177843. LOCAL(int)
  177844. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177845. int desired_colors)
  177846. /* Repeatedly select and split the largest box until we have enough boxes */
  177847. {
  177848. int n,lb;
  177849. int c0,c1,c2,cmax;
  177850. register boxptr b1,b2;
  177851. while (numboxes < desired_colors) {
  177852. /* Select box to split.
  177853. * Current algorithm: by population for first half, then by volume.
  177854. */
  177855. if (numboxes*2 <= desired_colors) {
  177856. b1 = find_biggest_color_pop(boxlist, numboxes);
  177857. } else {
  177858. b1 = find_biggest_volume(boxlist, numboxes);
  177859. }
  177860. if (b1 == NULL) /* no splittable boxes left! */
  177861. break;
  177862. b2 = &boxlist[numboxes]; /* where new box will go */
  177863. /* Copy the color bounds to the new box. */
  177864. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177865. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177866. /* Choose which axis to split the box on.
  177867. * Current algorithm: longest scaled axis.
  177868. * See notes in update_box about scaling distances.
  177869. */
  177870. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177871. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177872. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177873. /* We want to break any ties in favor of green, then red, blue last.
  177874. * This code does the right thing for R,G,B or B,G,R color orders only.
  177875. */
  177876. #if RGB_RED == 0
  177877. cmax = c1; n = 1;
  177878. if (c0 > cmax) { cmax = c0; n = 0; }
  177879. if (c2 > cmax) { n = 2; }
  177880. #else
  177881. cmax = c1; n = 1;
  177882. if (c2 > cmax) { cmax = c2; n = 2; }
  177883. if (c0 > cmax) { n = 0; }
  177884. #endif
  177885. /* Choose split point along selected axis, and update box bounds.
  177886. * Current algorithm: split at halfway point.
  177887. * (Since the box has been shrunk to minimum volume,
  177888. * any split will produce two nonempty subboxes.)
  177889. * Note that lb value is max for lower box, so must be < old max.
  177890. */
  177891. switch (n) {
  177892. case 0:
  177893. lb = (b1->c0max + b1->c0min) / 2;
  177894. b1->c0max = lb;
  177895. b2->c0min = lb+1;
  177896. break;
  177897. case 1:
  177898. lb = (b1->c1max + b1->c1min) / 2;
  177899. b1->c1max = lb;
  177900. b2->c1min = lb+1;
  177901. break;
  177902. case 2:
  177903. lb = (b1->c2max + b1->c2min) / 2;
  177904. b1->c2max = lb;
  177905. b2->c2min = lb+1;
  177906. break;
  177907. }
  177908. /* Update stats for boxes */
  177909. update_box(cinfo, b1);
  177910. update_box(cinfo, b2);
  177911. numboxes++;
  177912. }
  177913. return numboxes;
  177914. }
  177915. LOCAL(void)
  177916. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177917. /* Compute representative color for a box, put it in colormap[icolor] */
  177918. {
  177919. /* Current algorithm: mean weighted by pixels (not colors) */
  177920. /* Note it is important to get the rounding correct! */
  177921. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177922. hist3d histogram = cquantize->histogram;
  177923. histptr histp;
  177924. int c0,c1,c2;
  177925. int c0min,c0max,c1min,c1max,c2min,c2max;
  177926. long count;
  177927. long total = 0;
  177928. long c0total = 0;
  177929. long c1total = 0;
  177930. long c2total = 0;
  177931. c0min = boxp->c0min; c0max = boxp->c0max;
  177932. c1min = boxp->c1min; c1max = boxp->c1max;
  177933. c2min = boxp->c2min; c2max = boxp->c2max;
  177934. for (c0 = c0min; c0 <= c0max; c0++)
  177935. for (c1 = c1min; c1 <= c1max; c1++) {
  177936. histp = & histogram[c0][c1][c2min];
  177937. for (c2 = c2min; c2 <= c2max; c2++) {
  177938. if ((count = *histp++) != 0) {
  177939. total += count;
  177940. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177941. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177942. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177943. }
  177944. }
  177945. }
  177946. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177947. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177948. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177949. }
  177950. LOCAL(void)
  177951. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177952. /* Master routine for color selection */
  177953. {
  177954. boxptr boxlist;
  177955. int numboxes;
  177956. int i;
  177957. /* Allocate workspace for box list */
  177958. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177959. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177960. /* Initialize one box containing whole space */
  177961. numboxes = 1;
  177962. boxlist[0].c0min = 0;
  177963. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177964. boxlist[0].c1min = 0;
  177965. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177966. boxlist[0].c2min = 0;
  177967. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177968. /* Shrink it to actually-used volume and set its statistics */
  177969. update_box(cinfo, & boxlist[0]);
  177970. /* Perform median-cut to produce final box list */
  177971. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177972. /* Compute the representative color for each box, fill colormap */
  177973. for (i = 0; i < numboxes; i++)
  177974. compute_color(cinfo, & boxlist[i], i);
  177975. cinfo->actual_number_of_colors = numboxes;
  177976. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177977. }
  177978. /*
  177979. * These routines are concerned with the time-critical task of mapping input
  177980. * colors to the nearest color in the selected colormap.
  177981. *
  177982. * We re-use the histogram space as an "inverse color map", essentially a
  177983. * cache for the results of nearest-color searches. All colors within a
  177984. * histogram cell will be mapped to the same colormap entry, namely the one
  177985. * closest to the cell's center. This may not be quite the closest entry to
  177986. * the actual input color, but it's almost as good. A zero in the cache
  177987. * indicates we haven't found the nearest color for that cell yet; the array
  177988. * is cleared to zeroes before starting the mapping pass. When we find the
  177989. * nearest color for a cell, its colormap index plus one is recorded in the
  177990. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177991. * when they need to use an unfilled entry in the cache.
  177992. *
  177993. * Our method of efficiently finding nearest colors is based on the "locally
  177994. * sorted search" idea described by Heckbert and on the incremental distance
  177995. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177996. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177997. * the distances from a given colormap entry to each cell of the histogram can
  177998. * be computed quickly using an incremental method: the differences between
  177999. * distances to adjacent cells themselves differ by a constant. This allows a
  178000. * fairly fast implementation of the "brute force" approach of computing the
  178001. * distance from every colormap entry to every histogram cell. Unfortunately,
  178002. * it needs a work array to hold the best-distance-so-far for each histogram
  178003. * cell (because the inner loop has to be over cells, not colormap entries).
  178004. * The work array elements have to be INT32s, so the work array would need
  178005. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178006. *
  178007. * To get around these problems, we apply Thomas' method to compute the
  178008. * nearest colors for only the cells within a small subbox of the histogram.
  178009. * The work array need be only as big as the subbox, so the memory usage
  178010. * problem is solved. Furthermore, we need not fill subboxes that are never
  178011. * referenced in pass2; many images use only part of the color gamut, so a
  178012. * fair amount of work is saved. An additional advantage of this
  178013. * approach is that we can apply Heckbert's locality criterion to quickly
  178014. * eliminate colormap entries that are far away from the subbox; typically
  178015. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178016. * and we need not compute their distances to individual cells in the subbox.
  178017. * The speed of this approach is heavily influenced by the subbox size: too
  178018. * small means too much overhead, too big loses because Heckbert's criterion
  178019. * can't eliminate as many colormap entries. Empirically the best subbox
  178020. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178021. *
  178022. * Thomas' article also describes a refined method which is asymptotically
  178023. * faster than the brute-force method, but it is also far more complex and
  178024. * cannot efficiently be applied to small subboxes. It is therefore not
  178025. * useful for programs intended to be portable to DOS machines. On machines
  178026. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178027. * refined method might be faster than the present code --- but then again,
  178028. * it might not be any faster, and it's certainly more complicated.
  178029. */
  178030. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178031. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178032. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178033. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178034. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178035. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178036. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178037. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178038. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178039. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178040. /*
  178041. * The next three routines implement inverse colormap filling. They could
  178042. * all be folded into one big routine, but splitting them up this way saves
  178043. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178044. * and may allow some compilers to produce better code by registerizing more
  178045. * inner-loop variables.
  178046. */
  178047. LOCAL(int)
  178048. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178049. JSAMPLE colorlist[])
  178050. /* Locate the colormap entries close enough to an update box to be candidates
  178051. * for the nearest entry to some cell(s) in the update box. The update box
  178052. * is specified by the center coordinates of its first cell. The number of
  178053. * candidate colormap entries is returned, and their colormap indexes are
  178054. * placed in colorlist[].
  178055. * This routine uses Heckbert's "locally sorted search" criterion to select
  178056. * the colors that need further consideration.
  178057. */
  178058. {
  178059. int numcolors = cinfo->actual_number_of_colors;
  178060. int maxc0, maxc1, maxc2;
  178061. int centerc0, centerc1, centerc2;
  178062. int i, x, ncolors;
  178063. INT32 minmaxdist, min_dist, max_dist, tdist;
  178064. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178065. /* Compute true coordinates of update box's upper corner and center.
  178066. * Actually we compute the coordinates of the center of the upper-corner
  178067. * histogram cell, which are the upper bounds of the volume we care about.
  178068. * Note that since ">>" rounds down, the "center" values may be closer to
  178069. * min than to max; hence comparisons to them must be "<=", not "<".
  178070. */
  178071. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178072. centerc0 = (minc0 + maxc0) >> 1;
  178073. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178074. centerc1 = (minc1 + maxc1) >> 1;
  178075. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178076. centerc2 = (minc2 + maxc2) >> 1;
  178077. /* For each color in colormap, find:
  178078. * 1. its minimum squared-distance to any point in the update box
  178079. * (zero if color is within update box);
  178080. * 2. its maximum squared-distance to any point in the update box.
  178081. * Both of these can be found by considering only the corners of the box.
  178082. * We save the minimum distance for each color in mindist[];
  178083. * only the smallest maximum distance is of interest.
  178084. */
  178085. minmaxdist = 0x7FFFFFFFL;
  178086. for (i = 0; i < numcolors; i++) {
  178087. /* We compute the squared-c0-distance term, then add in the other two. */
  178088. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178089. if (x < minc0) {
  178090. tdist = (x - minc0) * C0_SCALE;
  178091. min_dist = tdist*tdist;
  178092. tdist = (x - maxc0) * C0_SCALE;
  178093. max_dist = tdist*tdist;
  178094. } else if (x > maxc0) {
  178095. tdist = (x - maxc0) * C0_SCALE;
  178096. min_dist = tdist*tdist;
  178097. tdist = (x - minc0) * C0_SCALE;
  178098. max_dist = tdist*tdist;
  178099. } else {
  178100. /* within cell range so no contribution to min_dist */
  178101. min_dist = 0;
  178102. if (x <= centerc0) {
  178103. tdist = (x - maxc0) * C0_SCALE;
  178104. max_dist = tdist*tdist;
  178105. } else {
  178106. tdist = (x - minc0) * C0_SCALE;
  178107. max_dist = tdist*tdist;
  178108. }
  178109. }
  178110. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178111. if (x < minc1) {
  178112. tdist = (x - minc1) * C1_SCALE;
  178113. min_dist += tdist*tdist;
  178114. tdist = (x - maxc1) * C1_SCALE;
  178115. max_dist += tdist*tdist;
  178116. } else if (x > maxc1) {
  178117. tdist = (x - maxc1) * C1_SCALE;
  178118. min_dist += tdist*tdist;
  178119. tdist = (x - minc1) * C1_SCALE;
  178120. max_dist += tdist*tdist;
  178121. } else {
  178122. /* within cell range so no contribution to min_dist */
  178123. if (x <= centerc1) {
  178124. tdist = (x - maxc1) * C1_SCALE;
  178125. max_dist += tdist*tdist;
  178126. } else {
  178127. tdist = (x - minc1) * C1_SCALE;
  178128. max_dist += tdist*tdist;
  178129. }
  178130. }
  178131. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178132. if (x < minc2) {
  178133. tdist = (x - minc2) * C2_SCALE;
  178134. min_dist += tdist*tdist;
  178135. tdist = (x - maxc2) * C2_SCALE;
  178136. max_dist += tdist*tdist;
  178137. } else if (x > maxc2) {
  178138. tdist = (x - maxc2) * C2_SCALE;
  178139. min_dist += tdist*tdist;
  178140. tdist = (x - minc2) * C2_SCALE;
  178141. max_dist += tdist*tdist;
  178142. } else {
  178143. /* within cell range so no contribution to min_dist */
  178144. if (x <= centerc2) {
  178145. tdist = (x - maxc2) * C2_SCALE;
  178146. max_dist += tdist*tdist;
  178147. } else {
  178148. tdist = (x - minc2) * C2_SCALE;
  178149. max_dist += tdist*tdist;
  178150. }
  178151. }
  178152. mindist[i] = min_dist; /* save away the results */
  178153. if (max_dist < minmaxdist)
  178154. minmaxdist = max_dist;
  178155. }
  178156. /* Now we know that no cell in the update box is more than minmaxdist
  178157. * away from some colormap entry. Therefore, only colors that are
  178158. * within minmaxdist of some part of the box need be considered.
  178159. */
  178160. ncolors = 0;
  178161. for (i = 0; i < numcolors; i++) {
  178162. if (mindist[i] <= minmaxdist)
  178163. colorlist[ncolors++] = (JSAMPLE) i;
  178164. }
  178165. return ncolors;
  178166. }
  178167. LOCAL(void)
  178168. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178169. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178170. /* Find the closest colormap entry for each cell in the update box,
  178171. * given the list of candidate colors prepared by find_nearby_colors.
  178172. * Return the indexes of the closest entries in the bestcolor[] array.
  178173. * This routine uses Thomas' incremental distance calculation method to
  178174. * find the distance from a colormap entry to successive cells in the box.
  178175. */
  178176. {
  178177. int ic0, ic1, ic2;
  178178. int i, icolor;
  178179. register INT32 * bptr; /* pointer into bestdist[] array */
  178180. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178181. INT32 dist0, dist1; /* initial distance values */
  178182. register INT32 dist2; /* current distance in inner loop */
  178183. INT32 xx0, xx1; /* distance increments */
  178184. register INT32 xx2;
  178185. INT32 inc0, inc1, inc2; /* initial values for increments */
  178186. /* This array holds the distance to the nearest-so-far color for each cell */
  178187. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178188. /* Initialize best-distance for each cell of the update box */
  178189. bptr = bestdist;
  178190. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178191. *bptr++ = 0x7FFFFFFFL;
  178192. /* For each color selected by find_nearby_colors,
  178193. * compute its distance to the center of each cell in the box.
  178194. * If that's less than best-so-far, update best distance and color number.
  178195. */
  178196. /* Nominal steps between cell centers ("x" in Thomas article) */
  178197. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178198. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178199. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178200. for (i = 0; i < numcolors; i++) {
  178201. icolor = GETJSAMPLE(colorlist[i]);
  178202. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178203. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178204. dist0 = inc0*inc0;
  178205. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178206. dist0 += inc1*inc1;
  178207. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178208. dist0 += inc2*inc2;
  178209. /* Form the initial difference increments */
  178210. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178211. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178212. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178213. /* Now loop over all cells in box, updating distance per Thomas method */
  178214. bptr = bestdist;
  178215. cptr = bestcolor;
  178216. xx0 = inc0;
  178217. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178218. dist1 = dist0;
  178219. xx1 = inc1;
  178220. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178221. dist2 = dist1;
  178222. xx2 = inc2;
  178223. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178224. if (dist2 < *bptr) {
  178225. *bptr = dist2;
  178226. *cptr = (JSAMPLE) icolor;
  178227. }
  178228. dist2 += xx2;
  178229. xx2 += 2 * STEP_C2 * STEP_C2;
  178230. bptr++;
  178231. cptr++;
  178232. }
  178233. dist1 += xx1;
  178234. xx1 += 2 * STEP_C1 * STEP_C1;
  178235. }
  178236. dist0 += xx0;
  178237. xx0 += 2 * STEP_C0 * STEP_C0;
  178238. }
  178239. }
  178240. }
  178241. LOCAL(void)
  178242. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178243. /* Fill the inverse-colormap entries in the update box that contains */
  178244. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178245. /* we can fill as many others as we wish.) */
  178246. {
  178247. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178248. hist3d histogram = cquantize->histogram;
  178249. int minc0, minc1, minc2; /* lower left corner of update box */
  178250. int ic0, ic1, ic2;
  178251. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178252. register histptr cachep; /* pointer into main cache array */
  178253. /* This array lists the candidate colormap indexes. */
  178254. JSAMPLE colorlist[MAXNUMCOLORS];
  178255. int numcolors; /* number of candidate colors */
  178256. /* This array holds the actually closest colormap index for each cell. */
  178257. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178258. /* Convert cell coordinates to update box ID */
  178259. c0 >>= BOX_C0_LOG;
  178260. c1 >>= BOX_C1_LOG;
  178261. c2 >>= BOX_C2_LOG;
  178262. /* Compute true coordinates of update box's origin corner.
  178263. * Actually we compute the coordinates of the center of the corner
  178264. * histogram cell, which are the lower bounds of the volume we care about.
  178265. */
  178266. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178267. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178268. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178269. /* Determine which colormap entries are close enough to be candidates
  178270. * for the nearest entry to some cell in the update box.
  178271. */
  178272. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178273. /* Determine the actually nearest colors. */
  178274. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178275. bestcolor);
  178276. /* Save the best color numbers (plus 1) in the main cache array */
  178277. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178278. c1 <<= BOX_C1_LOG;
  178279. c2 <<= BOX_C2_LOG;
  178280. cptr = bestcolor;
  178281. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178282. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178283. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178284. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178285. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178286. }
  178287. }
  178288. }
  178289. }
  178290. /*
  178291. * Map some rows of pixels to the output colormapped representation.
  178292. */
  178293. METHODDEF(void)
  178294. pass2_no_dither (j_decompress_ptr cinfo,
  178295. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178296. /* This version performs no dithering */
  178297. {
  178298. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178299. hist3d histogram = cquantize->histogram;
  178300. register JSAMPROW inptr, outptr;
  178301. register histptr cachep;
  178302. register int c0, c1, c2;
  178303. int row;
  178304. JDIMENSION col;
  178305. JDIMENSION width = cinfo->output_width;
  178306. for (row = 0; row < num_rows; row++) {
  178307. inptr = input_buf[row];
  178308. outptr = output_buf[row];
  178309. for (col = width; col > 0; col--) {
  178310. /* get pixel value and index into the cache */
  178311. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178312. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178313. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178314. cachep = & histogram[c0][c1][c2];
  178315. /* If we have not seen this color before, find nearest colormap entry */
  178316. /* and update the cache */
  178317. if (*cachep == 0)
  178318. fill_inverse_cmap(cinfo, c0,c1,c2);
  178319. /* Now emit the colormap index for this cell */
  178320. *outptr++ = (JSAMPLE) (*cachep - 1);
  178321. }
  178322. }
  178323. }
  178324. METHODDEF(void)
  178325. pass2_fs_dither (j_decompress_ptr cinfo,
  178326. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178327. /* This version performs Floyd-Steinberg dithering */
  178328. {
  178329. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178330. hist3d histogram = cquantize->histogram;
  178331. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178332. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178333. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178334. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178335. JSAMPROW inptr; /* => current input pixel */
  178336. JSAMPROW outptr; /* => current output pixel */
  178337. histptr cachep;
  178338. int dir; /* +1 or -1 depending on direction */
  178339. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178340. int row;
  178341. JDIMENSION col;
  178342. JDIMENSION width = cinfo->output_width;
  178343. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178344. int *error_limit = cquantize->error_limiter;
  178345. JSAMPROW colormap0 = cinfo->colormap[0];
  178346. JSAMPROW colormap1 = cinfo->colormap[1];
  178347. JSAMPROW colormap2 = cinfo->colormap[2];
  178348. SHIFT_TEMPS
  178349. for (row = 0; row < num_rows; row++) {
  178350. inptr = input_buf[row];
  178351. outptr = output_buf[row];
  178352. if (cquantize->on_odd_row) {
  178353. /* work right to left in this row */
  178354. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178355. outptr += width-1;
  178356. dir = -1;
  178357. dir3 = -3;
  178358. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178359. cquantize->on_odd_row = FALSE; /* flip for next time */
  178360. } else {
  178361. /* work left to right in this row */
  178362. dir = 1;
  178363. dir3 = 3;
  178364. errorptr = cquantize->fserrors; /* => entry before first real column */
  178365. cquantize->on_odd_row = TRUE; /* flip for next time */
  178366. }
  178367. /* Preset error values: no error propagated to first pixel from left */
  178368. cur0 = cur1 = cur2 = 0;
  178369. /* and no error propagated to row below yet */
  178370. belowerr0 = belowerr1 = belowerr2 = 0;
  178371. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178372. for (col = width; col > 0; col--) {
  178373. /* curN holds the error propagated from the previous pixel on the
  178374. * current line. Add the error propagated from the previous line
  178375. * to form the complete error correction term for this pixel, and
  178376. * round the error term (which is expressed * 16) to an integer.
  178377. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178378. * for either sign of the error value.
  178379. * Note: errorptr points to *previous* column's array entry.
  178380. */
  178381. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178382. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178383. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178384. /* Limit the error using transfer function set by init_error_limit.
  178385. * See comments with init_error_limit for rationale.
  178386. */
  178387. cur0 = error_limit[cur0];
  178388. cur1 = error_limit[cur1];
  178389. cur2 = error_limit[cur2];
  178390. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178391. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178392. * this sets the required size of the range_limit array.
  178393. */
  178394. cur0 += GETJSAMPLE(inptr[0]);
  178395. cur1 += GETJSAMPLE(inptr[1]);
  178396. cur2 += GETJSAMPLE(inptr[2]);
  178397. cur0 = GETJSAMPLE(range_limit[cur0]);
  178398. cur1 = GETJSAMPLE(range_limit[cur1]);
  178399. cur2 = GETJSAMPLE(range_limit[cur2]);
  178400. /* Index into the cache with adjusted pixel value */
  178401. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178402. /* If we have not seen this color before, find nearest colormap */
  178403. /* entry and update the cache */
  178404. if (*cachep == 0)
  178405. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178406. /* Now emit the colormap index for this cell */
  178407. { register int pixcode = *cachep - 1;
  178408. *outptr = (JSAMPLE) pixcode;
  178409. /* Compute representation error for this pixel */
  178410. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178411. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178412. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178413. }
  178414. /* Compute error fractions to be propagated to adjacent pixels.
  178415. * Add these into the running sums, and simultaneously shift the
  178416. * next-line error sums left by 1 column.
  178417. */
  178418. { register LOCFSERROR bnexterr, delta;
  178419. bnexterr = cur0; /* Process component 0 */
  178420. delta = cur0 * 2;
  178421. cur0 += delta; /* form error * 3 */
  178422. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178423. cur0 += delta; /* form error * 5 */
  178424. bpreverr0 = belowerr0 + cur0;
  178425. belowerr0 = bnexterr;
  178426. cur0 += delta; /* form error * 7 */
  178427. bnexterr = cur1; /* Process component 1 */
  178428. delta = cur1 * 2;
  178429. cur1 += delta; /* form error * 3 */
  178430. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178431. cur1 += delta; /* form error * 5 */
  178432. bpreverr1 = belowerr1 + cur1;
  178433. belowerr1 = bnexterr;
  178434. cur1 += delta; /* form error * 7 */
  178435. bnexterr = cur2; /* Process component 2 */
  178436. delta = cur2 * 2;
  178437. cur2 += delta; /* form error * 3 */
  178438. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178439. cur2 += delta; /* form error * 5 */
  178440. bpreverr2 = belowerr2 + cur2;
  178441. belowerr2 = bnexterr;
  178442. cur2 += delta; /* form error * 7 */
  178443. }
  178444. /* At this point curN contains the 7/16 error value to be propagated
  178445. * to the next pixel on the current line, and all the errors for the
  178446. * next line have been shifted over. We are therefore ready to move on.
  178447. */
  178448. inptr += dir3; /* Advance pixel pointers to next column */
  178449. outptr += dir;
  178450. errorptr += dir3; /* advance errorptr to current column */
  178451. }
  178452. /* Post-loop cleanup: we must unload the final error values into the
  178453. * final fserrors[] entry. Note we need not unload belowerrN because
  178454. * it is for the dummy column before or after the actual array.
  178455. */
  178456. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178457. errorptr[1] = (FSERROR) bpreverr1;
  178458. errorptr[2] = (FSERROR) bpreverr2;
  178459. }
  178460. }
  178461. /*
  178462. * Initialize the error-limiting transfer function (lookup table).
  178463. * The raw F-S error computation can potentially compute error values of up to
  178464. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178465. * much less, otherwise obviously wrong pixels will be created. (Typical
  178466. * effects include weird fringes at color-area boundaries, isolated bright
  178467. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178468. * is to ensure that the "corners" of the color cube are allocated as output
  178469. * colors; then repeated errors in the same direction cannot cause cascading
  178470. * error buildup. However, that only prevents the error from getting
  178471. * completely out of hand; Aaron Giles reports that error limiting improves
  178472. * the results even with corner colors allocated.
  178473. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178474. * well, but the smoother transfer function used below is even better. Thanks
  178475. * to Aaron Giles for this idea.
  178476. */
  178477. LOCAL(void)
  178478. init_error_limit (j_decompress_ptr cinfo)
  178479. /* Allocate and fill in the error_limiter table */
  178480. {
  178481. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178482. int * table;
  178483. int in, out;
  178484. table = (int *) (*cinfo->mem->alloc_small)
  178485. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178486. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178487. cquantize->error_limiter = table;
  178488. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178489. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178490. out = 0;
  178491. for (in = 0; in < STEPSIZE; in++, out++) {
  178492. table[in] = out; table[-in] = -out;
  178493. }
  178494. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178495. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178496. table[in] = out; table[-in] = -out;
  178497. }
  178498. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178499. for (; in <= MAXJSAMPLE; in++) {
  178500. table[in] = out; table[-in] = -out;
  178501. }
  178502. #undef STEPSIZE
  178503. }
  178504. /*
  178505. * Finish up at the end of each pass.
  178506. */
  178507. METHODDEF(void)
  178508. finish_pass1 (j_decompress_ptr cinfo)
  178509. {
  178510. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178511. /* Select the representative colors and fill in cinfo->colormap */
  178512. cinfo->colormap = cquantize->sv_colormap;
  178513. select_colors(cinfo, cquantize->desired);
  178514. /* Force next pass to zero the color index table */
  178515. cquantize->needs_zeroed = TRUE;
  178516. }
  178517. METHODDEF(void)
  178518. finish_pass2 (j_decompress_ptr)
  178519. {
  178520. /* no work */
  178521. }
  178522. /*
  178523. * Initialize for each processing pass.
  178524. */
  178525. METHODDEF(void)
  178526. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178527. {
  178528. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178529. hist3d histogram = cquantize->histogram;
  178530. int i;
  178531. /* Only F-S dithering or no dithering is supported. */
  178532. /* If user asks for ordered dither, give him F-S. */
  178533. if (cinfo->dither_mode != JDITHER_NONE)
  178534. cinfo->dither_mode = JDITHER_FS;
  178535. if (is_pre_scan) {
  178536. /* Set up method pointers */
  178537. cquantize->pub.color_quantize = prescan_quantize;
  178538. cquantize->pub.finish_pass = finish_pass1;
  178539. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178540. } else {
  178541. /* Set up method pointers */
  178542. if (cinfo->dither_mode == JDITHER_FS)
  178543. cquantize->pub.color_quantize = pass2_fs_dither;
  178544. else
  178545. cquantize->pub.color_quantize = pass2_no_dither;
  178546. cquantize->pub.finish_pass = finish_pass2;
  178547. /* Make sure color count is acceptable */
  178548. i = cinfo->actual_number_of_colors;
  178549. if (i < 1)
  178550. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178551. if (i > MAXNUMCOLORS)
  178552. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178553. if (cinfo->dither_mode == JDITHER_FS) {
  178554. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178555. (3 * SIZEOF(FSERROR)));
  178556. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178557. if (cquantize->fserrors == NULL)
  178558. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178559. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178560. /* Initialize the propagated errors to zero. */
  178561. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178562. /* Make the error-limit table if we didn't already. */
  178563. if (cquantize->error_limiter == NULL)
  178564. init_error_limit(cinfo);
  178565. cquantize->on_odd_row = FALSE;
  178566. }
  178567. }
  178568. /* Zero the histogram or inverse color map, if necessary */
  178569. if (cquantize->needs_zeroed) {
  178570. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178571. jzero_far((void FAR *) histogram[i],
  178572. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178573. }
  178574. cquantize->needs_zeroed = FALSE;
  178575. }
  178576. }
  178577. /*
  178578. * Switch to a new external colormap between output passes.
  178579. */
  178580. METHODDEF(void)
  178581. new_color_map_2_quant (j_decompress_ptr cinfo)
  178582. {
  178583. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178584. /* Reset the inverse color map */
  178585. cquantize->needs_zeroed = TRUE;
  178586. }
  178587. /*
  178588. * Module initialization routine for 2-pass color quantization.
  178589. */
  178590. GLOBAL(void)
  178591. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178592. {
  178593. my_cquantize_ptr2 cquantize;
  178594. int i;
  178595. cquantize = (my_cquantize_ptr2)
  178596. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178597. SIZEOF(my_cquantizer2));
  178598. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178599. cquantize->pub.start_pass = start_pass_2_quant;
  178600. cquantize->pub.new_color_map = new_color_map_2_quant;
  178601. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178602. cquantize->error_limiter = NULL;
  178603. /* Make sure jdmaster didn't give me a case I can't handle */
  178604. if (cinfo->out_color_components != 3)
  178605. ERREXIT(cinfo, JERR_NOTIMPL);
  178606. /* Allocate the histogram/inverse colormap storage */
  178607. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178608. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178609. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178610. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178611. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178612. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178613. }
  178614. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178615. /* Allocate storage for the completed colormap, if required.
  178616. * We do this now since it is FAR storage and may affect
  178617. * the memory manager's space calculations.
  178618. */
  178619. if (cinfo->enable_2pass_quant) {
  178620. /* Make sure color count is acceptable */
  178621. int desired = cinfo->desired_number_of_colors;
  178622. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178623. if (desired < 8)
  178624. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178625. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178626. if (desired > MAXNUMCOLORS)
  178627. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178628. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178629. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178630. cquantize->desired = desired;
  178631. } else
  178632. cquantize->sv_colormap = NULL;
  178633. /* Only F-S dithering or no dithering is supported. */
  178634. /* If user asks for ordered dither, give him F-S. */
  178635. if (cinfo->dither_mode != JDITHER_NONE)
  178636. cinfo->dither_mode = JDITHER_FS;
  178637. /* Allocate Floyd-Steinberg workspace if necessary.
  178638. * This isn't really needed until pass 2, but again it is FAR storage.
  178639. * Although we will cope with a later change in dither_mode,
  178640. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178641. */
  178642. if (cinfo->dither_mode == JDITHER_FS) {
  178643. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178644. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178645. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178646. /* Might as well create the error-limiting table too. */
  178647. init_error_limit(cinfo);
  178648. }
  178649. }
  178650. #endif /* QUANT_2PASS_SUPPORTED */
  178651. /*** End of inlined file: jquant2.c ***/
  178652. /*** Start of inlined file: jutils.c ***/
  178653. #define JPEG_INTERNALS
  178654. /*
  178655. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178656. * of a DCT block read in natural order (left to right, top to bottom).
  178657. */
  178658. #if 0 /* This table is not actually needed in v6a */
  178659. const int jpeg_zigzag_order[DCTSIZE2] = {
  178660. 0, 1, 5, 6, 14, 15, 27, 28,
  178661. 2, 4, 7, 13, 16, 26, 29, 42,
  178662. 3, 8, 12, 17, 25, 30, 41, 43,
  178663. 9, 11, 18, 24, 31, 40, 44, 53,
  178664. 10, 19, 23, 32, 39, 45, 52, 54,
  178665. 20, 22, 33, 38, 46, 51, 55, 60,
  178666. 21, 34, 37, 47, 50, 56, 59, 61,
  178667. 35, 36, 48, 49, 57, 58, 62, 63
  178668. };
  178669. #endif
  178670. /*
  178671. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178672. * of zigzag order.
  178673. *
  178674. * When reading corrupted data, the Huffman decoders could attempt
  178675. * to reference an entry beyond the end of this array (if the decoded
  178676. * zero run length reaches past the end of the block). To prevent
  178677. * wild stores without adding an inner-loop test, we put some extra
  178678. * "63"s after the real entries. This will cause the extra coefficient
  178679. * to be stored in location 63 of the block, not somewhere random.
  178680. * The worst case would be a run-length of 15, which means we need 16
  178681. * fake entries.
  178682. */
  178683. const int jpeg_natural_order[DCTSIZE2+16] = {
  178684. 0, 1, 8, 16, 9, 2, 3, 10,
  178685. 17, 24, 32, 25, 18, 11, 4, 5,
  178686. 12, 19, 26, 33, 40, 48, 41, 34,
  178687. 27, 20, 13, 6, 7, 14, 21, 28,
  178688. 35, 42, 49, 56, 57, 50, 43, 36,
  178689. 29, 22, 15, 23, 30, 37, 44, 51,
  178690. 58, 59, 52, 45, 38, 31, 39, 46,
  178691. 53, 60, 61, 54, 47, 55, 62, 63,
  178692. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178693. 63, 63, 63, 63, 63, 63, 63, 63
  178694. };
  178695. /*
  178696. * Arithmetic utilities
  178697. */
  178698. GLOBAL(long)
  178699. jdiv_round_up (long a, long b)
  178700. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178701. /* Assumes a >= 0, b > 0 */
  178702. {
  178703. return (a + b - 1L) / b;
  178704. }
  178705. GLOBAL(long)
  178706. jround_up (long a, long b)
  178707. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178708. /* Assumes a >= 0, b > 0 */
  178709. {
  178710. a += b - 1L;
  178711. return a - (a % b);
  178712. }
  178713. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178714. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178715. * are FAR and we're assuming a small-pointer memory model. However, some
  178716. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178717. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178718. * Otherwise, the routines below do it the hard way. (The performance cost
  178719. * is not all that great, because these routines aren't very heavily used.)
  178720. */
  178721. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178722. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178723. #define FMEMZERO(target,size) MEMZERO(target,size)
  178724. #else /* 80x86 case, define if we can */
  178725. #ifdef USE_FMEM
  178726. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178727. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178728. #endif
  178729. #endif
  178730. GLOBAL(void)
  178731. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178732. JSAMPARRAY output_array, int dest_row,
  178733. int num_rows, JDIMENSION num_cols)
  178734. /* Copy some rows of samples from one place to another.
  178735. * num_rows rows are copied from input_array[source_row++]
  178736. * to output_array[dest_row++]; these areas may overlap for duplication.
  178737. * The source and destination arrays must be at least as wide as num_cols.
  178738. */
  178739. {
  178740. register JSAMPROW inptr, outptr;
  178741. #ifdef FMEMCOPY
  178742. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178743. #else
  178744. register JDIMENSION count;
  178745. #endif
  178746. register int row;
  178747. input_array += source_row;
  178748. output_array += dest_row;
  178749. for (row = num_rows; row > 0; row--) {
  178750. inptr = *input_array++;
  178751. outptr = *output_array++;
  178752. #ifdef FMEMCOPY
  178753. FMEMCOPY(outptr, inptr, count);
  178754. #else
  178755. for (count = num_cols; count > 0; count--)
  178756. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178757. #endif
  178758. }
  178759. }
  178760. GLOBAL(void)
  178761. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178762. JDIMENSION num_blocks)
  178763. /* Copy a row of coefficient blocks from one place to another. */
  178764. {
  178765. #ifdef FMEMCOPY
  178766. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178767. #else
  178768. register JCOEFPTR inptr, outptr;
  178769. register long count;
  178770. inptr = (JCOEFPTR) input_row;
  178771. outptr = (JCOEFPTR) output_row;
  178772. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178773. *outptr++ = *inptr++;
  178774. }
  178775. #endif
  178776. }
  178777. GLOBAL(void)
  178778. jzero_far (void FAR * target, size_t bytestozero)
  178779. /* Zero out a chunk of FAR memory. */
  178780. /* This might be sample-array data, block-array data, or alloc_large data. */
  178781. {
  178782. #ifdef FMEMZERO
  178783. FMEMZERO(target, bytestozero);
  178784. #else
  178785. register char FAR * ptr = (char FAR *) target;
  178786. register size_t count;
  178787. for (count = bytestozero; count > 0; count--) {
  178788. *ptr++ = 0;
  178789. }
  178790. #endif
  178791. }
  178792. /*** End of inlined file: jutils.c ***/
  178793. /*** Start of inlined file: transupp.c ***/
  178794. /* Although this file really shouldn't have access to the library internals,
  178795. * it's helpful to let it call jround_up() and jcopy_block_row().
  178796. */
  178797. #define JPEG_INTERNALS
  178798. /*** Start of inlined file: transupp.h ***/
  178799. /* If you happen not to want the image transform support, disable it here */
  178800. #ifndef TRANSFORMS_SUPPORTED
  178801. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178802. #endif
  178803. /* Short forms of external names for systems with brain-damaged linkers. */
  178804. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178805. #define jtransform_request_workspace jTrRequest
  178806. #define jtransform_adjust_parameters jTrAdjust
  178807. #define jtransform_execute_transformation jTrExec
  178808. #define jcopy_markers_setup jCMrkSetup
  178809. #define jcopy_markers_execute jCMrkExec
  178810. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178811. /*
  178812. * Codes for supported types of image transformations.
  178813. */
  178814. typedef enum {
  178815. JXFORM_NONE, /* no transformation */
  178816. JXFORM_FLIP_H, /* horizontal flip */
  178817. JXFORM_FLIP_V, /* vertical flip */
  178818. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178819. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178820. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178821. JXFORM_ROT_180, /* 180-degree rotation */
  178822. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178823. } JXFORM_CODE;
  178824. /*
  178825. * Although rotating and flipping data expressed as DCT coefficients is not
  178826. * hard, there is an asymmetry in the JPEG format specification for images
  178827. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178828. * image edges are padded out to the next iMCU boundary with junk data; but
  178829. * no padding is possible at the top and left edges. If we were to flip
  178830. * the whole image including the pad data, then pad garbage would become
  178831. * visible at the top and/or left, and real pixels would disappear into the
  178832. * pad margins --- perhaps permanently, since encoders & decoders may not
  178833. * bother to preserve DCT blocks that appear to be completely outside the
  178834. * nominal image area. So, we have to exclude any partial iMCUs from the
  178835. * basic transformation.
  178836. *
  178837. * Transpose is the only transformation that can handle partial iMCUs at the
  178838. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178839. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178840. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178841. * The other transforms are defined as combinations of these basic transforms
  178842. * and process edge blocks in a way that preserves the equivalence.
  178843. *
  178844. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178845. * this is not strictly lossless, but it usually gives the best-looking
  178846. * result for odd-size images. Note that when this option is active,
  178847. * the expected mathematical equivalences between the transforms may not hold.
  178848. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178849. * followed by -rot 180 -trim trims both edges.)
  178850. *
  178851. * We also offer a "force to grayscale" option, which simply discards the
  178852. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178853. * the luminance channel is preserved exactly. It's not the same kind of
  178854. * thing as the rotate/flip transformations, but it's convenient to handle it
  178855. * as part of this package, mainly because the transformation routines have to
  178856. * be aware of the option to know how many components to work on.
  178857. */
  178858. typedef struct {
  178859. /* Options: set by caller */
  178860. JXFORM_CODE transform; /* image transform operator */
  178861. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178862. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178863. /* Internal workspace: caller should not touch these */
  178864. int num_components; /* # of components in workspace */
  178865. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178866. } jpeg_transform_info;
  178867. #if TRANSFORMS_SUPPORTED
  178868. /* Request any required workspace */
  178869. EXTERN(void) jtransform_request_workspace
  178870. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178871. /* Adjust output image parameters */
  178872. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178873. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178874. jvirt_barray_ptr *src_coef_arrays,
  178875. jpeg_transform_info *info));
  178876. /* Execute the actual transformation, if any */
  178877. EXTERN(void) jtransform_execute_transformation
  178878. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178879. jvirt_barray_ptr *src_coef_arrays,
  178880. jpeg_transform_info *info));
  178881. #endif /* TRANSFORMS_SUPPORTED */
  178882. /*
  178883. * Support for copying optional markers from source to destination file.
  178884. */
  178885. typedef enum {
  178886. JCOPYOPT_NONE, /* copy no optional markers */
  178887. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178888. JCOPYOPT_ALL /* copy all optional markers */
  178889. } JCOPY_OPTION;
  178890. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178891. /* Setup decompression object to save desired markers in memory */
  178892. EXTERN(void) jcopy_markers_setup
  178893. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178894. /* Copy markers saved in the given source object to the destination object */
  178895. EXTERN(void) jcopy_markers_execute
  178896. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178897. JCOPY_OPTION option));
  178898. /*** End of inlined file: transupp.h ***/
  178899. /* My own external interface */
  178900. #if TRANSFORMS_SUPPORTED
  178901. /*
  178902. * Lossless image transformation routines. These routines work on DCT
  178903. * coefficient arrays and thus do not require any lossy decompression
  178904. * or recompression of the image.
  178905. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178906. *
  178907. * Horizontal flipping is done in-place, using a single top-to-bottom
  178908. * pass through the virtual source array. It will thus be much the
  178909. * fastest option for images larger than main memory.
  178910. *
  178911. * The other routines require a set of destination virtual arrays, so they
  178912. * need twice as much memory as jpegtran normally does. The destination
  178913. * arrays are always written in normal scan order (top to bottom) because
  178914. * the virtual array manager expects this. The source arrays will be scanned
  178915. * in the corresponding order, which means multiple passes through the source
  178916. * arrays for most of the transforms. That could result in much thrashing
  178917. * if the image is larger than main memory.
  178918. *
  178919. * Some notes about the operating environment of the individual transform
  178920. * routines:
  178921. * 1. Both the source and destination virtual arrays are allocated from the
  178922. * source JPEG object, and therefore should be manipulated by calling the
  178923. * source's memory manager.
  178924. * 2. The destination's component count should be used. It may be smaller
  178925. * than the source's when forcing to grayscale.
  178926. * 3. Likewise the destination's sampling factors should be used. When
  178927. * forcing to grayscale the destination's sampling factors will be all 1,
  178928. * and we may as well take that as the effective iMCU size.
  178929. * 4. When "trim" is in effect, the destination's dimensions will be the
  178930. * trimmed values but the source's will be untrimmed.
  178931. * 5. All the routines assume that the source and destination buffers are
  178932. * padded out to a full iMCU boundary. This is true, although for the
  178933. * source buffer it is an undocumented property of jdcoefct.c.
  178934. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178935. * dimensions and ignore the source's.
  178936. */
  178937. LOCAL(void)
  178938. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178939. jvirt_barray_ptr *src_coef_arrays)
  178940. /* Horizontal flip; done in-place, so no separate dest array is required */
  178941. {
  178942. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178943. int ci, k, offset_y;
  178944. JBLOCKARRAY buffer;
  178945. JCOEFPTR ptr1, ptr2;
  178946. JCOEF temp1, temp2;
  178947. jpeg_component_info *compptr;
  178948. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178949. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178950. * mirroring by changing the signs of odd-numbered columns.
  178951. * Partial iMCUs at the right edge are left untouched.
  178952. */
  178953. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178954. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178955. compptr = dstinfo->comp_info + ci;
  178956. comp_width = MCU_cols * compptr->h_samp_factor;
  178957. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178958. blk_y += compptr->v_samp_factor) {
  178959. buffer = (*srcinfo->mem->access_virt_barray)
  178960. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178961. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178962. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178963. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178964. ptr1 = buffer[offset_y][blk_x];
  178965. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178966. /* this unrolled loop doesn't need to know which row it's on... */
  178967. for (k = 0; k < DCTSIZE2; k += 2) {
  178968. temp1 = *ptr1; /* swap even column */
  178969. temp2 = *ptr2;
  178970. *ptr1++ = temp2;
  178971. *ptr2++ = temp1;
  178972. temp1 = *ptr1; /* swap odd column with sign change */
  178973. temp2 = *ptr2;
  178974. *ptr1++ = -temp2;
  178975. *ptr2++ = -temp1;
  178976. }
  178977. }
  178978. }
  178979. }
  178980. }
  178981. }
  178982. LOCAL(void)
  178983. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178984. jvirt_barray_ptr *src_coef_arrays,
  178985. jvirt_barray_ptr *dst_coef_arrays)
  178986. /* Vertical flip */
  178987. {
  178988. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178989. int ci, i, j, offset_y;
  178990. JBLOCKARRAY src_buffer, dst_buffer;
  178991. JBLOCKROW src_row_ptr, dst_row_ptr;
  178992. JCOEFPTR src_ptr, dst_ptr;
  178993. jpeg_component_info *compptr;
  178994. /* We output into a separate array because we can't touch different
  178995. * rows of the source virtual array simultaneously. Otherwise, this
  178996. * is a pretty straightforward analog of horizontal flip.
  178997. * Within a DCT block, vertical mirroring is done by changing the signs
  178998. * of odd-numbered rows.
  178999. * Partial iMCUs at the bottom edge are copied verbatim.
  179000. */
  179001. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179002. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179003. compptr = dstinfo->comp_info + ci;
  179004. comp_height = MCU_rows * compptr->v_samp_factor;
  179005. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179006. dst_blk_y += compptr->v_samp_factor) {
  179007. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179008. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179009. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179010. if (dst_blk_y < comp_height) {
  179011. /* Row is within the mirrorable area. */
  179012. src_buffer = (*srcinfo->mem->access_virt_barray)
  179013. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179014. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179015. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179016. } else {
  179017. /* Bottom-edge blocks will be copied verbatim. */
  179018. src_buffer = (*srcinfo->mem->access_virt_barray)
  179019. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179020. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179021. }
  179022. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179023. if (dst_blk_y < comp_height) {
  179024. /* Row is within the mirrorable area. */
  179025. dst_row_ptr = dst_buffer[offset_y];
  179026. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179027. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179028. dst_blk_x++) {
  179029. dst_ptr = dst_row_ptr[dst_blk_x];
  179030. src_ptr = src_row_ptr[dst_blk_x];
  179031. for (i = 0; i < DCTSIZE; i += 2) {
  179032. /* copy even row */
  179033. for (j = 0; j < DCTSIZE; j++)
  179034. *dst_ptr++ = *src_ptr++;
  179035. /* copy odd row with sign change */
  179036. for (j = 0; j < DCTSIZE; j++)
  179037. *dst_ptr++ = - *src_ptr++;
  179038. }
  179039. }
  179040. } else {
  179041. /* Just copy row verbatim. */
  179042. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179043. compptr->width_in_blocks);
  179044. }
  179045. }
  179046. }
  179047. }
  179048. }
  179049. LOCAL(void)
  179050. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179051. jvirt_barray_ptr *src_coef_arrays,
  179052. jvirt_barray_ptr *dst_coef_arrays)
  179053. /* Transpose source into destination */
  179054. {
  179055. JDIMENSION dst_blk_x, dst_blk_y;
  179056. int ci, i, j, offset_x, offset_y;
  179057. JBLOCKARRAY src_buffer, dst_buffer;
  179058. JCOEFPTR src_ptr, dst_ptr;
  179059. jpeg_component_info *compptr;
  179060. /* Transposing pixels within a block just requires transposing the
  179061. * DCT coefficients.
  179062. * Partial iMCUs at the edges require no special treatment; we simply
  179063. * process all the available DCT blocks for every component.
  179064. */
  179065. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179066. compptr = dstinfo->comp_info + ci;
  179067. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179068. dst_blk_y += compptr->v_samp_factor) {
  179069. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179070. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179071. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179072. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179073. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179074. dst_blk_x += compptr->h_samp_factor) {
  179075. src_buffer = (*srcinfo->mem->access_virt_barray)
  179076. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179077. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179078. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179079. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179080. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179081. for (i = 0; i < DCTSIZE; i++)
  179082. for (j = 0; j < DCTSIZE; j++)
  179083. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179084. }
  179085. }
  179086. }
  179087. }
  179088. }
  179089. }
  179090. LOCAL(void)
  179091. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179092. jvirt_barray_ptr *src_coef_arrays,
  179093. jvirt_barray_ptr *dst_coef_arrays)
  179094. /* 90 degree rotation is equivalent to
  179095. * 1. Transposing the image;
  179096. * 2. Horizontal mirroring.
  179097. * These two steps are merged into a single processing routine.
  179098. */
  179099. {
  179100. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179101. int ci, i, j, offset_x, offset_y;
  179102. JBLOCKARRAY src_buffer, dst_buffer;
  179103. JCOEFPTR src_ptr, dst_ptr;
  179104. jpeg_component_info *compptr;
  179105. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179106. * at the (output) right edge properly. They just get transposed and
  179107. * not mirrored.
  179108. */
  179109. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179110. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179111. compptr = dstinfo->comp_info + ci;
  179112. comp_width = MCU_cols * compptr->h_samp_factor;
  179113. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179114. dst_blk_y += compptr->v_samp_factor) {
  179115. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179116. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179117. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179118. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179119. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179120. dst_blk_x += compptr->h_samp_factor) {
  179121. src_buffer = (*srcinfo->mem->access_virt_barray)
  179122. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179123. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179124. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179125. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179126. if (dst_blk_x < comp_width) {
  179127. /* Block is within the mirrorable area. */
  179128. dst_ptr = dst_buffer[offset_y]
  179129. [comp_width - dst_blk_x - offset_x - 1];
  179130. for (i = 0; i < DCTSIZE; i++) {
  179131. for (j = 0; j < DCTSIZE; j++)
  179132. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179133. i++;
  179134. for (j = 0; j < DCTSIZE; j++)
  179135. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179136. }
  179137. } else {
  179138. /* Edge blocks are transposed but not mirrored. */
  179139. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179140. for (i = 0; i < DCTSIZE; i++)
  179141. for (j = 0; j < DCTSIZE; j++)
  179142. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179143. }
  179144. }
  179145. }
  179146. }
  179147. }
  179148. }
  179149. }
  179150. LOCAL(void)
  179151. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179152. jvirt_barray_ptr *src_coef_arrays,
  179153. jvirt_barray_ptr *dst_coef_arrays)
  179154. /* 270 degree rotation is equivalent to
  179155. * 1. Horizontal mirroring;
  179156. * 2. Transposing the image.
  179157. * These two steps are merged into a single processing routine.
  179158. */
  179159. {
  179160. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179161. int ci, i, j, offset_x, offset_y;
  179162. JBLOCKARRAY src_buffer, dst_buffer;
  179163. JCOEFPTR src_ptr, dst_ptr;
  179164. jpeg_component_info *compptr;
  179165. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179166. * at the (output) bottom edge properly. They just get transposed and
  179167. * not mirrored.
  179168. */
  179169. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179170. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179171. compptr = dstinfo->comp_info + ci;
  179172. comp_height = MCU_rows * compptr->v_samp_factor;
  179173. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179174. dst_blk_y += compptr->v_samp_factor) {
  179175. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179176. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179177. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179178. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179179. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179180. dst_blk_x += compptr->h_samp_factor) {
  179181. src_buffer = (*srcinfo->mem->access_virt_barray)
  179182. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179183. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179184. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179185. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179186. if (dst_blk_y < comp_height) {
  179187. /* Block is within the mirrorable area. */
  179188. src_ptr = src_buffer[offset_x]
  179189. [comp_height - dst_blk_y - offset_y - 1];
  179190. for (i = 0; i < DCTSIZE; i++) {
  179191. for (j = 0; j < DCTSIZE; j++) {
  179192. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179193. j++;
  179194. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179195. }
  179196. }
  179197. } else {
  179198. /* Edge blocks are transposed but not mirrored. */
  179199. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179200. for (i = 0; i < DCTSIZE; i++)
  179201. for (j = 0; j < DCTSIZE; j++)
  179202. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179203. }
  179204. }
  179205. }
  179206. }
  179207. }
  179208. }
  179209. }
  179210. LOCAL(void)
  179211. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179212. jvirt_barray_ptr *src_coef_arrays,
  179213. jvirt_barray_ptr *dst_coef_arrays)
  179214. /* 180 degree rotation is equivalent to
  179215. * 1. Vertical mirroring;
  179216. * 2. Horizontal mirroring.
  179217. * These two steps are merged into a single processing routine.
  179218. */
  179219. {
  179220. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179221. int ci, i, j, offset_y;
  179222. JBLOCKARRAY src_buffer, dst_buffer;
  179223. JBLOCKROW src_row_ptr, dst_row_ptr;
  179224. JCOEFPTR src_ptr, dst_ptr;
  179225. jpeg_component_info *compptr;
  179226. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179227. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179228. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179229. compptr = dstinfo->comp_info + ci;
  179230. comp_width = MCU_cols * compptr->h_samp_factor;
  179231. comp_height = MCU_rows * compptr->v_samp_factor;
  179232. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179233. dst_blk_y += compptr->v_samp_factor) {
  179234. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179235. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179236. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179237. if (dst_blk_y < comp_height) {
  179238. /* Row is within the vertically mirrorable area. */
  179239. src_buffer = (*srcinfo->mem->access_virt_barray)
  179240. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179241. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179242. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179243. } else {
  179244. /* Bottom-edge rows are only mirrored horizontally. */
  179245. src_buffer = (*srcinfo->mem->access_virt_barray)
  179246. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179247. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179248. }
  179249. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179250. if (dst_blk_y < comp_height) {
  179251. /* Row is within the mirrorable area. */
  179252. dst_row_ptr = dst_buffer[offset_y];
  179253. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179254. /* Process the blocks that can be mirrored both ways. */
  179255. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179256. dst_ptr = dst_row_ptr[dst_blk_x];
  179257. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179258. for (i = 0; i < DCTSIZE; i += 2) {
  179259. /* For even row, negate every odd column. */
  179260. for (j = 0; j < DCTSIZE; j += 2) {
  179261. *dst_ptr++ = *src_ptr++;
  179262. *dst_ptr++ = - *src_ptr++;
  179263. }
  179264. /* For odd row, negate every even column. */
  179265. for (j = 0; j < DCTSIZE; j += 2) {
  179266. *dst_ptr++ = - *src_ptr++;
  179267. *dst_ptr++ = *src_ptr++;
  179268. }
  179269. }
  179270. }
  179271. /* Any remaining right-edge blocks are only mirrored vertically. */
  179272. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179273. dst_ptr = dst_row_ptr[dst_blk_x];
  179274. src_ptr = src_row_ptr[dst_blk_x];
  179275. for (i = 0; i < DCTSIZE; i += 2) {
  179276. for (j = 0; j < DCTSIZE; j++)
  179277. *dst_ptr++ = *src_ptr++;
  179278. for (j = 0; j < DCTSIZE; j++)
  179279. *dst_ptr++ = - *src_ptr++;
  179280. }
  179281. }
  179282. } else {
  179283. /* Remaining rows are just mirrored horizontally. */
  179284. dst_row_ptr = dst_buffer[offset_y];
  179285. src_row_ptr = src_buffer[offset_y];
  179286. /* Process the blocks that can be mirrored. */
  179287. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179288. dst_ptr = dst_row_ptr[dst_blk_x];
  179289. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179290. for (i = 0; i < DCTSIZE2; i += 2) {
  179291. *dst_ptr++ = *src_ptr++;
  179292. *dst_ptr++ = - *src_ptr++;
  179293. }
  179294. }
  179295. /* Any remaining right-edge blocks are only copied. */
  179296. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179297. dst_ptr = dst_row_ptr[dst_blk_x];
  179298. src_ptr = src_row_ptr[dst_blk_x];
  179299. for (i = 0; i < DCTSIZE2; i++)
  179300. *dst_ptr++ = *src_ptr++;
  179301. }
  179302. }
  179303. }
  179304. }
  179305. }
  179306. }
  179307. LOCAL(void)
  179308. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179309. jvirt_barray_ptr *src_coef_arrays,
  179310. jvirt_barray_ptr *dst_coef_arrays)
  179311. /* Transverse transpose is equivalent to
  179312. * 1. 180 degree rotation;
  179313. * 2. Transposition;
  179314. * or
  179315. * 1. Horizontal mirroring;
  179316. * 2. Transposition;
  179317. * 3. Horizontal mirroring.
  179318. * These steps are merged into a single processing routine.
  179319. */
  179320. {
  179321. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179322. int ci, i, j, offset_x, offset_y;
  179323. JBLOCKARRAY src_buffer, dst_buffer;
  179324. JCOEFPTR src_ptr, dst_ptr;
  179325. jpeg_component_info *compptr;
  179326. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179327. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179328. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179329. compptr = dstinfo->comp_info + ci;
  179330. comp_width = MCU_cols * compptr->h_samp_factor;
  179331. comp_height = MCU_rows * compptr->v_samp_factor;
  179332. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179333. dst_blk_y += compptr->v_samp_factor) {
  179334. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179335. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179336. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179337. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179338. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179339. dst_blk_x += compptr->h_samp_factor) {
  179340. src_buffer = (*srcinfo->mem->access_virt_barray)
  179341. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179342. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179343. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179344. if (dst_blk_y < comp_height) {
  179345. src_ptr = src_buffer[offset_x]
  179346. [comp_height - dst_blk_y - offset_y - 1];
  179347. if (dst_blk_x < comp_width) {
  179348. /* Block is within the mirrorable area. */
  179349. dst_ptr = dst_buffer[offset_y]
  179350. [comp_width - dst_blk_x - offset_x - 1];
  179351. for (i = 0; i < DCTSIZE; i++) {
  179352. for (j = 0; j < DCTSIZE; j++) {
  179353. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179354. j++;
  179355. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179356. }
  179357. i++;
  179358. for (j = 0; j < DCTSIZE; j++) {
  179359. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179360. j++;
  179361. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179362. }
  179363. }
  179364. } else {
  179365. /* Right-edge blocks are mirrored in y only */
  179366. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179367. for (i = 0; i < DCTSIZE; i++) {
  179368. for (j = 0; j < DCTSIZE; j++) {
  179369. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179370. j++;
  179371. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179372. }
  179373. }
  179374. }
  179375. } else {
  179376. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179377. if (dst_blk_x < comp_width) {
  179378. /* Bottom-edge blocks are mirrored in x only */
  179379. dst_ptr = dst_buffer[offset_y]
  179380. [comp_width - dst_blk_x - offset_x - 1];
  179381. for (i = 0; i < DCTSIZE; i++) {
  179382. for (j = 0; j < DCTSIZE; j++)
  179383. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179384. i++;
  179385. for (j = 0; j < DCTSIZE; j++)
  179386. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179387. }
  179388. } else {
  179389. /* At lower right corner, just transpose, no mirroring */
  179390. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179391. for (i = 0; i < DCTSIZE; i++)
  179392. for (j = 0; j < DCTSIZE; j++)
  179393. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179394. }
  179395. }
  179396. }
  179397. }
  179398. }
  179399. }
  179400. }
  179401. }
  179402. /* Request any required workspace.
  179403. *
  179404. * We allocate the workspace virtual arrays from the source decompression
  179405. * object, so that all the arrays (both the original data and the workspace)
  179406. * will be taken into account while making memory management decisions.
  179407. * Hence, this routine must be called after jpeg_read_header (which reads
  179408. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179409. * the source's virtual arrays).
  179410. */
  179411. GLOBAL(void)
  179412. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179413. jpeg_transform_info *info)
  179414. {
  179415. jvirt_barray_ptr *coef_arrays = NULL;
  179416. jpeg_component_info *compptr;
  179417. int ci;
  179418. if (info->force_grayscale &&
  179419. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179420. srcinfo->num_components == 3) {
  179421. /* We'll only process the first component */
  179422. info->num_components = 1;
  179423. } else {
  179424. /* Process all the components */
  179425. info->num_components = srcinfo->num_components;
  179426. }
  179427. switch (info->transform) {
  179428. case JXFORM_NONE:
  179429. case JXFORM_FLIP_H:
  179430. /* Don't need a workspace array */
  179431. break;
  179432. case JXFORM_FLIP_V:
  179433. case JXFORM_ROT_180:
  179434. /* Need workspace arrays having same dimensions as source image.
  179435. * Note that we allocate arrays padded out to the next iMCU boundary,
  179436. * so that transform routines need not worry about missing edge blocks.
  179437. */
  179438. coef_arrays = (jvirt_barray_ptr *)
  179439. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179440. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179441. for (ci = 0; ci < info->num_components; ci++) {
  179442. compptr = srcinfo->comp_info + ci;
  179443. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179444. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179445. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179446. (long) compptr->h_samp_factor),
  179447. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179448. (long) compptr->v_samp_factor),
  179449. (JDIMENSION) compptr->v_samp_factor);
  179450. }
  179451. break;
  179452. case JXFORM_TRANSPOSE:
  179453. case JXFORM_TRANSVERSE:
  179454. case JXFORM_ROT_90:
  179455. case JXFORM_ROT_270:
  179456. /* Need workspace arrays having transposed dimensions.
  179457. * Note that we allocate arrays padded out to the next iMCU boundary,
  179458. * so that transform routines need not worry about missing edge blocks.
  179459. */
  179460. coef_arrays = (jvirt_barray_ptr *)
  179461. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179462. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179463. for (ci = 0; ci < info->num_components; ci++) {
  179464. compptr = srcinfo->comp_info + ci;
  179465. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179466. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179467. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179468. (long) compptr->v_samp_factor),
  179469. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179470. (long) compptr->h_samp_factor),
  179471. (JDIMENSION) compptr->h_samp_factor);
  179472. }
  179473. break;
  179474. }
  179475. info->workspace_coef_arrays = coef_arrays;
  179476. }
  179477. /* Transpose destination image parameters */
  179478. LOCAL(void)
  179479. transpose_critical_parameters (j_compress_ptr dstinfo)
  179480. {
  179481. int tblno, i, j, ci, itemp;
  179482. jpeg_component_info *compptr;
  179483. JQUANT_TBL *qtblptr;
  179484. JDIMENSION dtemp;
  179485. UINT16 qtemp;
  179486. /* Transpose basic image dimensions */
  179487. dtemp = dstinfo->image_width;
  179488. dstinfo->image_width = dstinfo->image_height;
  179489. dstinfo->image_height = dtemp;
  179490. /* Transpose sampling factors */
  179491. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179492. compptr = dstinfo->comp_info + ci;
  179493. itemp = compptr->h_samp_factor;
  179494. compptr->h_samp_factor = compptr->v_samp_factor;
  179495. compptr->v_samp_factor = itemp;
  179496. }
  179497. /* Transpose quantization tables */
  179498. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179499. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179500. if (qtblptr != NULL) {
  179501. for (i = 0; i < DCTSIZE; i++) {
  179502. for (j = 0; j < i; j++) {
  179503. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179504. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179505. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179506. }
  179507. }
  179508. }
  179509. }
  179510. }
  179511. /* Trim off any partial iMCUs on the indicated destination edge */
  179512. LOCAL(void)
  179513. trim_right_edge (j_compress_ptr dstinfo)
  179514. {
  179515. int ci, max_h_samp_factor;
  179516. JDIMENSION MCU_cols;
  179517. /* We have to compute max_h_samp_factor ourselves,
  179518. * because it hasn't been set yet in the destination
  179519. * (and we don't want to use the source's value).
  179520. */
  179521. max_h_samp_factor = 1;
  179522. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179523. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179524. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179525. }
  179526. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179527. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179528. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179529. }
  179530. LOCAL(void)
  179531. trim_bottom_edge (j_compress_ptr dstinfo)
  179532. {
  179533. int ci, max_v_samp_factor;
  179534. JDIMENSION MCU_rows;
  179535. /* We have to compute max_v_samp_factor ourselves,
  179536. * because it hasn't been set yet in the destination
  179537. * (and we don't want to use the source's value).
  179538. */
  179539. max_v_samp_factor = 1;
  179540. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179541. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179542. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179543. }
  179544. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179545. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179546. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179547. }
  179548. /* Adjust output image parameters as needed.
  179549. *
  179550. * This must be called after jpeg_copy_critical_parameters()
  179551. * and before jpeg_write_coefficients().
  179552. *
  179553. * The return value is the set of virtual coefficient arrays to be written
  179554. * (either the ones allocated by jtransform_request_workspace, or the
  179555. * original source data arrays). The caller will need to pass this value
  179556. * to jpeg_write_coefficients().
  179557. */
  179558. GLOBAL(jvirt_barray_ptr *)
  179559. jtransform_adjust_parameters (j_decompress_ptr,
  179560. j_compress_ptr dstinfo,
  179561. jvirt_barray_ptr *src_coef_arrays,
  179562. jpeg_transform_info *info)
  179563. {
  179564. /* If force-to-grayscale is requested, adjust destination parameters */
  179565. if (info->force_grayscale) {
  179566. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179567. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179568. * will get set to 1, which typically won't match the source.
  179569. * In fact we do this even if the source is already grayscale; that
  179570. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179571. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179572. */
  179573. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179574. dstinfo->num_components == 3) ||
  179575. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179576. dstinfo->num_components == 1)) {
  179577. /* We have to preserve the source's quantization table number. */
  179578. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179579. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179580. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179581. } else {
  179582. /* Sorry, can't do it */
  179583. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179584. }
  179585. }
  179586. /* Correct the destination's image dimensions etc if necessary */
  179587. switch (info->transform) {
  179588. case JXFORM_NONE:
  179589. /* Nothing to do */
  179590. break;
  179591. case JXFORM_FLIP_H:
  179592. if (info->trim)
  179593. trim_right_edge(dstinfo);
  179594. break;
  179595. case JXFORM_FLIP_V:
  179596. if (info->trim)
  179597. trim_bottom_edge(dstinfo);
  179598. break;
  179599. case JXFORM_TRANSPOSE:
  179600. transpose_critical_parameters(dstinfo);
  179601. /* transpose does NOT have to trim anything */
  179602. break;
  179603. case JXFORM_TRANSVERSE:
  179604. transpose_critical_parameters(dstinfo);
  179605. if (info->trim) {
  179606. trim_right_edge(dstinfo);
  179607. trim_bottom_edge(dstinfo);
  179608. }
  179609. break;
  179610. case JXFORM_ROT_90:
  179611. transpose_critical_parameters(dstinfo);
  179612. if (info->trim)
  179613. trim_right_edge(dstinfo);
  179614. break;
  179615. case JXFORM_ROT_180:
  179616. if (info->trim) {
  179617. trim_right_edge(dstinfo);
  179618. trim_bottom_edge(dstinfo);
  179619. }
  179620. break;
  179621. case JXFORM_ROT_270:
  179622. transpose_critical_parameters(dstinfo);
  179623. if (info->trim)
  179624. trim_bottom_edge(dstinfo);
  179625. break;
  179626. }
  179627. /* Return the appropriate output data set */
  179628. if (info->workspace_coef_arrays != NULL)
  179629. return info->workspace_coef_arrays;
  179630. return src_coef_arrays;
  179631. }
  179632. /* Execute the actual transformation, if any.
  179633. *
  179634. * This must be called *after* jpeg_write_coefficients, because it depends
  179635. * on jpeg_write_coefficients to have computed subsidiary values such as
  179636. * the per-component width and height fields in the destination object.
  179637. *
  179638. * Note that some transformations will modify the source data arrays!
  179639. */
  179640. GLOBAL(void)
  179641. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179642. j_compress_ptr dstinfo,
  179643. jvirt_barray_ptr *src_coef_arrays,
  179644. jpeg_transform_info *info)
  179645. {
  179646. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179647. switch (info->transform) {
  179648. case JXFORM_NONE:
  179649. break;
  179650. case JXFORM_FLIP_H:
  179651. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179652. break;
  179653. case JXFORM_FLIP_V:
  179654. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179655. break;
  179656. case JXFORM_TRANSPOSE:
  179657. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179658. break;
  179659. case JXFORM_TRANSVERSE:
  179660. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179661. break;
  179662. case JXFORM_ROT_90:
  179663. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179664. break;
  179665. case JXFORM_ROT_180:
  179666. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179667. break;
  179668. case JXFORM_ROT_270:
  179669. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179670. break;
  179671. }
  179672. }
  179673. #endif /* TRANSFORMS_SUPPORTED */
  179674. /* Setup decompression object to save desired markers in memory.
  179675. * This must be called before jpeg_read_header() to have the desired effect.
  179676. */
  179677. GLOBAL(void)
  179678. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179679. {
  179680. #ifdef SAVE_MARKERS_SUPPORTED
  179681. int m;
  179682. /* Save comments except under NONE option */
  179683. if (option != JCOPYOPT_NONE) {
  179684. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179685. }
  179686. /* Save all types of APPn markers iff ALL option */
  179687. if (option == JCOPYOPT_ALL) {
  179688. for (m = 0; m < 16; m++)
  179689. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179690. }
  179691. #endif /* SAVE_MARKERS_SUPPORTED */
  179692. }
  179693. /* Copy markers saved in the given source object to the destination object.
  179694. * This should be called just after jpeg_start_compress() or
  179695. * jpeg_write_coefficients().
  179696. * Note that those routines will have written the SOI, and also the
  179697. * JFIF APP0 or Adobe APP14 markers if selected.
  179698. */
  179699. GLOBAL(void)
  179700. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179701. JCOPY_OPTION)
  179702. {
  179703. jpeg_saved_marker_ptr marker;
  179704. /* In the current implementation, we don't actually need to examine the
  179705. * option flag here; we just copy everything that got saved.
  179706. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179707. * if the encoder library already wrote one.
  179708. */
  179709. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179710. if (dstinfo->write_JFIF_header &&
  179711. marker->marker == JPEG_APP0 &&
  179712. marker->data_length >= 5 &&
  179713. GETJOCTET(marker->data[0]) == 0x4A &&
  179714. GETJOCTET(marker->data[1]) == 0x46 &&
  179715. GETJOCTET(marker->data[2]) == 0x49 &&
  179716. GETJOCTET(marker->data[3]) == 0x46 &&
  179717. GETJOCTET(marker->data[4]) == 0)
  179718. continue; /* reject duplicate JFIF */
  179719. if (dstinfo->write_Adobe_marker &&
  179720. marker->marker == JPEG_APP0+14 &&
  179721. marker->data_length >= 5 &&
  179722. GETJOCTET(marker->data[0]) == 0x41 &&
  179723. GETJOCTET(marker->data[1]) == 0x64 &&
  179724. GETJOCTET(marker->data[2]) == 0x6F &&
  179725. GETJOCTET(marker->data[3]) == 0x62 &&
  179726. GETJOCTET(marker->data[4]) == 0x65)
  179727. continue; /* reject duplicate Adobe */
  179728. #ifdef NEED_FAR_POINTERS
  179729. /* We could use jpeg_write_marker if the data weren't FAR... */
  179730. {
  179731. unsigned int i;
  179732. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179733. for (i = 0; i < marker->data_length; i++)
  179734. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179735. }
  179736. #else
  179737. jpeg_write_marker(dstinfo, marker->marker,
  179738. marker->data, marker->data_length);
  179739. #endif
  179740. }
  179741. }
  179742. /*** End of inlined file: transupp.c ***/
  179743. #else
  179744. #define JPEG_INTERNALS
  179745. #undef FAR
  179746. #include <jpeglib.h>
  179747. #endif
  179748. }
  179749. #undef max
  179750. #undef min
  179751. #if JUCE_MSVC
  179752. #pragma warning (pop)
  179753. #endif
  179754. BEGIN_JUCE_NAMESPACE
  179755. namespace JPEGHelpers
  179756. {
  179757. using namespace jpeglibNamespace;
  179758. #if ! JUCE_MSVC
  179759. using jpeglibNamespace::boolean;
  179760. #endif
  179761. struct JPEGDecodingFailure {};
  179762. void fatalErrorHandler (j_common_ptr)
  179763. {
  179764. throw JPEGDecodingFailure();
  179765. }
  179766. void silentErrorCallback1 (j_common_ptr) {}
  179767. void silentErrorCallback2 (j_common_ptr, int) {}
  179768. void silentErrorCallback3 (j_common_ptr, char*) {}
  179769. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179770. {
  179771. zerostruct (err);
  179772. err.error_exit = fatalErrorHandler;
  179773. err.emit_message = silentErrorCallback2;
  179774. err.output_message = silentErrorCallback1;
  179775. err.format_message = silentErrorCallback3;
  179776. err.reset_error_mgr = silentErrorCallback1;
  179777. }
  179778. void dummyCallback1 (j_decompress_ptr)
  179779. {
  179780. }
  179781. void jpegSkip (j_decompress_ptr decompStruct, long num)
  179782. {
  179783. decompStruct->src->next_input_byte += num;
  179784. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179785. decompStruct->src->bytes_in_buffer -= num;
  179786. }
  179787. boolean jpegFill (j_decompress_ptr)
  179788. {
  179789. return 0;
  179790. }
  179791. const int jpegBufferSize = 512;
  179792. struct JuceJpegDest : public jpeg_destination_mgr
  179793. {
  179794. OutputStream* output;
  179795. char* buffer;
  179796. };
  179797. void jpegWriteInit (j_compress_ptr)
  179798. {
  179799. }
  179800. void jpegWriteTerminate (j_compress_ptr cinfo)
  179801. {
  179802. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179803. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179804. dest->output->write (dest->buffer, (int) numToWrite);
  179805. }
  179806. boolean jpegWriteFlush (j_compress_ptr cinfo)
  179807. {
  179808. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179809. const int numToWrite = jpegBufferSize;
  179810. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179811. dest->free_in_buffer = jpegBufferSize;
  179812. return dest->output->write (dest->buffer, numToWrite);
  179813. }
  179814. }
  179815. JPEGImageFormat::JPEGImageFormat()
  179816. : quality (-1.0f)
  179817. {
  179818. }
  179819. JPEGImageFormat::~JPEGImageFormat() {}
  179820. void JPEGImageFormat::setQuality (const float newQuality)
  179821. {
  179822. quality = newQuality;
  179823. }
  179824. const String JPEGImageFormat::getFormatName()
  179825. {
  179826. return "JPEG";
  179827. }
  179828. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179829. {
  179830. const int bytesNeeded = 10;
  179831. uint8 header [bytesNeeded];
  179832. if (in.read (header, bytesNeeded) == bytesNeeded)
  179833. {
  179834. return header[0] == 0xff
  179835. && header[1] == 0xd8
  179836. && header[2] == 0xff
  179837. && (header[3] == 0xe0 || header[3] == 0xe1);
  179838. }
  179839. return false;
  179840. }
  179841. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179842. const Image juce_loadWithCoreImage (InputStream& input);
  179843. #endif
  179844. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179845. {
  179846. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179847. return juce_loadWithCoreImage (in);
  179848. #else
  179849. using namespace jpeglibNamespace;
  179850. using namespace JPEGHelpers;
  179851. MemoryOutputStream mb;
  179852. mb.writeFromInputStream (in, -1);
  179853. Image image;
  179854. if (mb.getDataSize() > 16)
  179855. {
  179856. struct jpeg_decompress_struct jpegDecompStruct;
  179857. struct jpeg_error_mgr jerr;
  179858. setupSilentErrorHandler (jerr);
  179859. jpegDecompStruct.err = &jerr;
  179860. jpeg_create_decompress (&jpegDecompStruct);
  179861. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179862. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179863. jpegDecompStruct.src->init_source = dummyCallback1;
  179864. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179865. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179866. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179867. jpegDecompStruct.src->term_source = dummyCallback1;
  179868. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179869. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179870. try
  179871. {
  179872. jpeg_read_header (&jpegDecompStruct, TRUE);
  179873. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179874. const int width = jpegDecompStruct.output_width;
  179875. const int height = jpegDecompStruct.output_height;
  179876. jpegDecompStruct.out_color_space = JCS_RGB;
  179877. JSAMPARRAY buffer
  179878. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179879. JPOOL_IMAGE,
  179880. width * 3, 1);
  179881. if (jpeg_start_decompress (&jpegDecompStruct))
  179882. {
  179883. image = Image (Image::RGB, width, height, false);
  179884. image.getProperties()->set ("originalImageHadAlpha", false);
  179885. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179886. const Image::BitmapData destData (image, true);
  179887. for (int y = 0; y < height; ++y)
  179888. {
  179889. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179890. const uint8* src = *buffer;
  179891. uint8* dest = destData.getLinePointer (y);
  179892. if (hasAlphaChan)
  179893. {
  179894. for (int i = width; --i >= 0;)
  179895. {
  179896. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179897. ((PixelARGB*) dest)->premultiply();
  179898. dest += destData.pixelStride;
  179899. src += 3;
  179900. }
  179901. }
  179902. else
  179903. {
  179904. for (int i = width; --i >= 0;)
  179905. {
  179906. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179907. dest += destData.pixelStride;
  179908. src += 3;
  179909. }
  179910. }
  179911. }
  179912. jpeg_finish_decompress (&jpegDecompStruct);
  179913. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179914. }
  179915. jpeg_destroy_decompress (&jpegDecompStruct);
  179916. }
  179917. catch (...)
  179918. {}
  179919. }
  179920. return image;
  179921. #endif
  179922. }
  179923. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179924. {
  179925. using namespace jpeglibNamespace;
  179926. using namespace JPEGHelpers;
  179927. if (image.hasAlphaChannel())
  179928. {
  179929. // this method could fill the background in white and still save the image..
  179930. jassertfalse;
  179931. return true;
  179932. }
  179933. struct jpeg_compress_struct jpegCompStruct;
  179934. struct jpeg_error_mgr jerr;
  179935. setupSilentErrorHandler (jerr);
  179936. jpegCompStruct.err = &jerr;
  179937. jpeg_create_compress (&jpegCompStruct);
  179938. JuceJpegDest dest;
  179939. jpegCompStruct.dest = &dest;
  179940. dest.output = &out;
  179941. HeapBlock <char> tempBuffer (jpegBufferSize);
  179942. dest.buffer = tempBuffer;
  179943. dest.next_output_byte = (JOCTET*) dest.buffer;
  179944. dest.free_in_buffer = jpegBufferSize;
  179945. dest.init_destination = jpegWriteInit;
  179946. dest.empty_output_buffer = jpegWriteFlush;
  179947. dest.term_destination = jpegWriteTerminate;
  179948. jpegCompStruct.image_width = image.getWidth();
  179949. jpegCompStruct.image_height = image.getHeight();
  179950. jpegCompStruct.input_components = 3;
  179951. jpegCompStruct.in_color_space = JCS_RGB;
  179952. jpegCompStruct.write_JFIF_header = 1;
  179953. jpegCompStruct.X_density = 72;
  179954. jpegCompStruct.Y_density = 72;
  179955. jpeg_set_defaults (&jpegCompStruct);
  179956. jpegCompStruct.dct_method = JDCT_FLOAT;
  179957. jpegCompStruct.optimize_coding = 1;
  179958. //jpegCompStruct.smoothing_factor = 10;
  179959. if (quality < 0.0f)
  179960. quality = 0.85f;
  179961. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179962. jpeg_start_compress (&jpegCompStruct, TRUE);
  179963. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179964. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179965. JPOOL_IMAGE, strideBytes, 1);
  179966. const Image::BitmapData srcData (image, false);
  179967. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179968. {
  179969. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179970. uint8* dst = *buffer;
  179971. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179972. {
  179973. *dst++ = ((const PixelRGB*) src)->getRed();
  179974. *dst++ = ((const PixelRGB*) src)->getGreen();
  179975. *dst++ = ((const PixelRGB*) src)->getBlue();
  179976. src += srcData.pixelStride;
  179977. }
  179978. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179979. }
  179980. jpeg_finish_compress (&jpegCompStruct);
  179981. jpeg_destroy_compress (&jpegCompStruct);
  179982. out.flush();
  179983. return true;
  179984. }
  179985. END_JUCE_NAMESPACE
  179986. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179987. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179988. #if JUCE_MSVC
  179989. #pragma warning (push)
  179990. #pragma warning (disable: 4390 4611)
  179991. #endif
  179992. namespace zlibNamespace
  179993. {
  179994. #if JUCE_INCLUDE_ZLIB_CODE
  179995. #undef OS_CODE
  179996. #undef fdopen
  179997. #undef OS_CODE
  179998. #else
  179999. #include <zlib.h>
  180000. #endif
  180001. }
  180002. namespace pnglibNamespace
  180003. {
  180004. using namespace zlibNamespace;
  180005. #if JUCE_INCLUDE_PNGLIB_CODE
  180006. #if _MSC_VER != 1310
  180007. using ::calloc; // (causes conflict in VS.NET 2003)
  180008. using ::malloc;
  180009. using ::free;
  180010. #endif
  180011. using ::abs;
  180012. #define PNG_INTERNAL
  180013. #define NO_DUMMY_DECL
  180014. #define PNG_SETJMP_NOT_SUPPORTED
  180015. /*** Start of inlined file: png.h ***/
  180016. /* png.h - header file for PNG reference library
  180017. *
  180018. * libpng version 1.2.21 - October 4, 2007
  180019. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180020. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180021. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180022. *
  180023. * Authors and maintainers:
  180024. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180025. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180026. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180027. * See also "Contributing Authors", below.
  180028. *
  180029. * Note about libpng version numbers:
  180030. *
  180031. * Due to various miscommunications, unforeseen code incompatibilities
  180032. * and occasional factors outside the authors' control, version numbering
  180033. * on the library has not always been consistent and straightforward.
  180034. * The following table summarizes matters since version 0.89c, which was
  180035. * the first widely used release:
  180036. *
  180037. * source png.h png.h shared-lib
  180038. * version string int version
  180039. * ------- ------ ----- ----------
  180040. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180041. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180042. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180043. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180044. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180045. * 0.97c 0.97 97 2.0.97
  180046. * 0.98 0.98 98 2.0.98
  180047. * 0.99 0.99 98 2.0.99
  180048. * 0.99a-m 0.99 99 2.0.99
  180049. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180050. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180051. * 1.0.1 png.h string is 10001 2.1.0
  180052. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180053. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180054. * 1.0.2a-b 10003 version, except as noted.
  180055. * 1.0.3 10003
  180056. * 1.0.3a-d 10004
  180057. * 1.0.4 10004
  180058. * 1.0.4a-f 10005
  180059. * 1.0.5 (+ 2 patches) 10005
  180060. * 1.0.5a-d 10006
  180061. * 1.0.5e-r 10100 (not source compatible)
  180062. * 1.0.5s-v 10006 (not binary compatible)
  180063. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180064. * 1.0.6d-f 10007 (still binary incompatible)
  180065. * 1.0.6g 10007
  180066. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180067. * 1.0.6i 10007 10.6i
  180068. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180069. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180070. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180071. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180072. * 1.0.7 1 10007 (still compatible)
  180073. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180074. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180075. * 1.0.8 1 10008 2.1.0.8
  180076. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180077. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180078. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180079. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180080. * 1.0.9 1 10009 2.1.0.9
  180081. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180082. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180083. * 1.0.10 1 10010 2.1.0.10
  180084. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180085. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180086. * 1.0.11 1 10011 2.1.0.11
  180087. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180088. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180089. * 1.0.12 2 10012 2.1.0.12
  180090. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180091. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180092. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180093. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180094. * 1.2.0 3 10200 3.1.2.0
  180095. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180096. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180097. * 1.2.1 3 10201 3.1.2.1
  180098. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180099. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180100. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180101. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180102. * 1.0.13 10 10013 10.so.0.1.0.13
  180103. * 1.2.2 12 10202 12.so.0.1.2.2
  180104. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180105. * 1.2.3 12 10203 12.so.0.1.2.3
  180106. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180107. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180108. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180109. * 1.0.14 10 10014 10.so.0.1.0.14
  180110. * 1.2.4 13 10204 12.so.0.1.2.4
  180111. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180112. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180113. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180114. * 1.0.15 10 10015 10.so.0.1.0.15
  180115. * 1.2.5 13 10205 12.so.0.1.2.5
  180116. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180117. * 1.0.16 10 10016 10.so.0.1.0.16
  180118. * 1.2.6 13 10206 12.so.0.1.2.6
  180119. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180120. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180121. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180122. * 1.0.17 10 10017 10.so.0.1.0.17
  180123. * 1.2.7 13 10207 12.so.0.1.2.7
  180124. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180125. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180126. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180127. * 1.0.18 10 10018 10.so.0.1.0.18
  180128. * 1.2.8 13 10208 12.so.0.1.2.8
  180129. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180130. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180131. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180132. * 1.2.9 13 10209 12.so.0.9[.0]
  180133. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180134. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180135. * 1.2.10 13 10210 12.so.0.10[.0]
  180136. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180137. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180138. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180139. * 1.0.19 10 10019 10.so.0.19[.0]
  180140. * 1.2.11 13 10211 12.so.0.11[.0]
  180141. * 1.0.20 10 10020 10.so.0.20[.0]
  180142. * 1.2.12 13 10212 12.so.0.12[.0]
  180143. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180144. * 1.0.21 10 10021 10.so.0.21[.0]
  180145. * 1.2.13 13 10213 12.so.0.13[.0]
  180146. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180147. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180148. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180149. * 1.0.22 10 10022 10.so.0.22[.0]
  180150. * 1.2.14 13 10214 12.so.0.14[.0]
  180151. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180152. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180153. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180154. * 1.0.23 10 10023 10.so.0.23[.0]
  180155. * 1.2.15 13 10215 12.so.0.15[.0]
  180156. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180157. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180158. * 1.0.24 10 10024 10.so.0.24[.0]
  180159. * 1.2.16 13 10216 12.so.0.16[.0]
  180160. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180161. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180162. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180163. * 1.0.25 10 10025 10.so.0.25[.0]
  180164. * 1.2.17 13 10217 12.so.0.17[.0]
  180165. * 1.0.26 10 10026 10.so.0.26[.0]
  180166. * 1.2.18 13 10218 12.so.0.18[.0]
  180167. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180168. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180169. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180170. * 1.0.27 10 10027 10.so.0.27[.0]
  180171. * 1.2.19 13 10219 12.so.0.19[.0]
  180172. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180173. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180174. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180175. * 1.0.28 10 10028 10.so.0.28[.0]
  180176. * 1.2.20 13 10220 12.so.0.20[.0]
  180177. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180178. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180179. * 1.0.29 10 10029 10.so.0.29[.0]
  180180. * 1.2.21 13 10221 12.so.0.21[.0]
  180181. *
  180182. * Henceforth the source version will match the shared-library major
  180183. * and minor numbers; the shared-library major version number will be
  180184. * used for changes in backward compatibility, as it is intended. The
  180185. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180186. * for applications, is an unsigned integer of the form xyyzz corresponding
  180187. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180188. * were given the previous public release number plus a letter, until
  180189. * version 1.0.6j; from then on they were given the upcoming public
  180190. * release number plus "betaNN" or "rcN".
  180191. *
  180192. * Binary incompatibility exists only when applications make direct access
  180193. * to the info_ptr or png_ptr members through png.h, and the compiled
  180194. * application is loaded with a different version of the library.
  180195. *
  180196. * DLLNUM will change each time there are forward or backward changes
  180197. * in binary compatibility (e.g., when a new feature is added).
  180198. *
  180199. * See libpng.txt or libpng.3 for more information. The PNG specification
  180200. * is available as a W3C Recommendation and as an ISO Specification,
  180201. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180202. */
  180203. /*
  180204. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180205. *
  180206. * If you modify libpng you may insert additional notices immediately following
  180207. * this sentence.
  180208. *
  180209. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180210. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180211. * distributed according to the same disclaimer and license as libpng-1.2.5
  180212. * with the following individual added to the list of Contributing Authors:
  180213. *
  180214. * Cosmin Truta
  180215. *
  180216. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180217. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180218. * distributed according to the same disclaimer and license as libpng-1.0.6
  180219. * with the following individuals added to the list of Contributing Authors:
  180220. *
  180221. * Simon-Pierre Cadieux
  180222. * Eric S. Raymond
  180223. * Gilles Vollant
  180224. *
  180225. * and with the following additions to the disclaimer:
  180226. *
  180227. * There is no warranty against interference with your enjoyment of the
  180228. * library or against infringement. There is no warranty that our
  180229. * efforts or the library will fulfill any of your particular purposes
  180230. * or needs. This library is provided with all faults, and the entire
  180231. * risk of satisfactory quality, performance, accuracy, and effort is with
  180232. * the user.
  180233. *
  180234. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180235. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180236. * distributed according to the same disclaimer and license as libpng-0.96,
  180237. * with the following individuals added to the list of Contributing Authors:
  180238. *
  180239. * Tom Lane
  180240. * Glenn Randers-Pehrson
  180241. * Willem van Schaik
  180242. *
  180243. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180244. * Copyright (c) 1996, 1997 Andreas Dilger
  180245. * Distributed according to the same disclaimer and license as libpng-0.88,
  180246. * with the following individuals added to the list of Contributing Authors:
  180247. *
  180248. * John Bowler
  180249. * Kevin Bracey
  180250. * Sam Bushell
  180251. * Magnus Holmgren
  180252. * Greg Roelofs
  180253. * Tom Tanner
  180254. *
  180255. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180256. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180257. *
  180258. * For the purposes of this copyright and license, "Contributing Authors"
  180259. * is defined as the following set of individuals:
  180260. *
  180261. * Andreas Dilger
  180262. * Dave Martindale
  180263. * Guy Eric Schalnat
  180264. * Paul Schmidt
  180265. * Tim Wegner
  180266. *
  180267. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180268. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180269. * including, without limitation, the warranties of merchantability and of
  180270. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180271. * assume no liability for direct, indirect, incidental, special, exemplary,
  180272. * or consequential damages, which may result from the use of the PNG
  180273. * Reference Library, even if advised of the possibility of such damage.
  180274. *
  180275. * Permission is hereby granted to use, copy, modify, and distribute this
  180276. * source code, or portions hereof, for any purpose, without fee, subject
  180277. * to the following restrictions:
  180278. *
  180279. * 1. The origin of this source code must not be misrepresented.
  180280. *
  180281. * 2. Altered versions must be plainly marked as such and
  180282. * must not be misrepresented as being the original source.
  180283. *
  180284. * 3. This Copyright notice may not be removed or altered from
  180285. * any source or altered source distribution.
  180286. *
  180287. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180288. * fee, and encourage the use of this source code as a component to
  180289. * supporting the PNG file format in commercial products. If you use this
  180290. * source code in a product, acknowledgment is not required but would be
  180291. * appreciated.
  180292. */
  180293. /*
  180294. * A "png_get_copyright" function is available, for convenient use in "about"
  180295. * boxes and the like:
  180296. *
  180297. * printf("%s",png_get_copyright(NULL));
  180298. *
  180299. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180300. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180301. */
  180302. /*
  180303. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180304. * certification mark of the Open Source Initiative.
  180305. */
  180306. /*
  180307. * The contributing authors would like to thank all those who helped
  180308. * with testing, bug fixes, and patience. This wouldn't have been
  180309. * possible without all of you.
  180310. *
  180311. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180312. */
  180313. /*
  180314. * Y2K compliance in libpng:
  180315. * =========================
  180316. *
  180317. * October 4, 2007
  180318. *
  180319. * Since the PNG Development group is an ad-hoc body, we can't make
  180320. * an official declaration.
  180321. *
  180322. * This is your unofficial assurance that libpng from version 0.71 and
  180323. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180324. * versions were also Y2K compliant.
  180325. *
  180326. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180327. * that will hold years up to 65535. The other two hold the date in text
  180328. * format, and will hold years up to 9999.
  180329. *
  180330. * The integer is
  180331. * "png_uint_16 year" in png_time_struct.
  180332. *
  180333. * The strings are
  180334. * "png_charp time_buffer" in png_struct and
  180335. * "near_time_buffer", which is a local character string in png.c.
  180336. *
  180337. * There are seven time-related functions:
  180338. * png.c: png_convert_to_rfc_1123() in png.c
  180339. * (formerly png_convert_to_rfc_1152() in error)
  180340. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180341. * png_convert_from_time_t() in pngwrite.c
  180342. * png_get_tIME() in pngget.c
  180343. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180344. * png_set_tIME() in pngset.c
  180345. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180346. *
  180347. * All handle dates properly in a Y2K environment. The
  180348. * png_convert_from_time_t() function calls gmtime() to convert from system
  180349. * clock time, which returns (year - 1900), which we properly convert to
  180350. * the full 4-digit year. There is a possibility that applications using
  180351. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180352. * function, or that they are incorrectly passing only a 2-digit year
  180353. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180354. * but this is not under our control. The libpng documentation has always
  180355. * stated that it works with 4-digit years, and the APIs have been
  180356. * documented as such.
  180357. *
  180358. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180359. * integer to hold the year, and can hold years as large as 65535.
  180360. *
  180361. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180362. * no date-related code.
  180363. *
  180364. * Glenn Randers-Pehrson
  180365. * libpng maintainer
  180366. * PNG Development Group
  180367. */
  180368. #ifndef PNG_H
  180369. #define PNG_H
  180370. /* This is not the place to learn how to use libpng. The file libpng.txt
  180371. * describes how to use libpng, and the file example.c summarizes it
  180372. * with some code on which to build. This file is useful for looking
  180373. * at the actual function definitions and structure components.
  180374. */
  180375. /* Version information for png.h - this should match the version in png.c */
  180376. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180377. #define PNG_HEADER_VERSION_STRING \
  180378. " libpng version 1.2.21 - October 4, 2007\n"
  180379. #define PNG_LIBPNG_VER_SONUM 0
  180380. #define PNG_LIBPNG_VER_DLLNUM 13
  180381. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180382. #define PNG_LIBPNG_VER_MAJOR 1
  180383. #define PNG_LIBPNG_VER_MINOR 2
  180384. #define PNG_LIBPNG_VER_RELEASE 21
  180385. /* This should match the numeric part of the final component of
  180386. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180387. #define PNG_LIBPNG_VER_BUILD 0
  180388. /* Release Status */
  180389. #define PNG_LIBPNG_BUILD_ALPHA 1
  180390. #define PNG_LIBPNG_BUILD_BETA 2
  180391. #define PNG_LIBPNG_BUILD_RC 3
  180392. #define PNG_LIBPNG_BUILD_STABLE 4
  180393. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180394. /* Release-Specific Flags */
  180395. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180396. PNG_LIBPNG_BUILD_STABLE only */
  180397. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180398. PNG_LIBPNG_BUILD_SPECIAL */
  180399. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180400. PNG_LIBPNG_BUILD_PRIVATE */
  180401. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180402. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180403. * We must not include leading zeros.
  180404. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180405. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180406. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180407. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180408. #ifndef PNG_VERSION_INFO_ONLY
  180409. /* include the compression library's header */
  180410. #endif
  180411. /* include all user configurable info, including optional assembler routines */
  180412. /*** Start of inlined file: pngconf.h ***/
  180413. /* pngconf.h - machine configurable file for libpng
  180414. *
  180415. * libpng version 1.2.21 - October 4, 2007
  180416. * For conditions of distribution and use, see copyright notice in png.h
  180417. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180418. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180419. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180420. */
  180421. /* Any machine specific code is near the front of this file, so if you
  180422. * are configuring libpng for a machine, you may want to read the section
  180423. * starting here down to where it starts to typedef png_color, png_text,
  180424. * and png_info.
  180425. */
  180426. #ifndef PNGCONF_H
  180427. #define PNGCONF_H
  180428. #define PNG_1_2_X
  180429. // These are some Juce config settings that should remove any unnecessary code bloat..
  180430. #define PNG_NO_STDIO 1
  180431. #define PNG_DEBUG 0
  180432. #define PNG_NO_WARNINGS 1
  180433. #define PNG_NO_ERROR_TEXT 1
  180434. #define PNG_NO_ERROR_NUMBERS 1
  180435. #define PNG_NO_USER_MEM 1
  180436. #define PNG_NO_READ_iCCP 1
  180437. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180438. #define PNG_NO_READ_USER_CHUNKS 1
  180439. #define PNG_NO_READ_iTXt 1
  180440. #define PNG_NO_READ_sCAL 1
  180441. #define PNG_NO_READ_sPLT 1
  180442. #define png_error(a, b) png_err(a)
  180443. #define png_warning(a, b)
  180444. #define png_chunk_error(a, b) png_err(a)
  180445. #define png_chunk_warning(a, b)
  180446. /*
  180447. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180448. * includes the resource compiler for Windows DLL configurations.
  180449. */
  180450. #ifdef PNG_USER_CONFIG
  180451. # ifndef PNG_USER_PRIVATEBUILD
  180452. # define PNG_USER_PRIVATEBUILD
  180453. # endif
  180454. #include "pngusr.h"
  180455. #endif
  180456. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180457. #ifdef PNG_CONFIGURE_LIBPNG
  180458. #ifdef HAVE_CONFIG_H
  180459. #include "config.h"
  180460. #endif
  180461. #endif
  180462. /*
  180463. * Added at libpng-1.2.8
  180464. *
  180465. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180466. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180467. * the DLL was built>
  180468. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180469. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180470. * distinguish your DLL from those of the official release. These
  180471. * correspond to the trailing letters that come after the version
  180472. * number and must match your private DLL name>
  180473. * e.g. // private DLL "libpng13gx.dll"
  180474. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180475. *
  180476. * The following macros are also at your disposal if you want to complete the
  180477. * DLL VERSIONINFO structure.
  180478. * - PNG_USER_VERSIONINFO_COMMENTS
  180479. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180480. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180481. */
  180482. #ifdef __STDC__
  180483. #ifdef SPECIALBUILD
  180484. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180485. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180486. #endif
  180487. #ifdef PRIVATEBUILD
  180488. # pragma message("PRIVATEBUILD is deprecated.\
  180489. Use PNG_USER_PRIVATEBUILD instead.")
  180490. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180491. #endif
  180492. #endif /* __STDC__ */
  180493. #ifndef PNG_VERSION_INFO_ONLY
  180494. /* End of material added to libpng-1.2.8 */
  180495. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180496. Restored at libpng-1.2.21 */
  180497. # define PNG_WARN_UNINITIALIZED_ROW 1
  180498. /* End of material added at libpng-1.2.19/1.2.21 */
  180499. /* This is the size of the compression buffer, and thus the size of
  180500. * an IDAT chunk. Make this whatever size you feel is best for your
  180501. * machine. One of these will be allocated per png_struct. When this
  180502. * is full, it writes the data to the disk, and does some other
  180503. * calculations. Making this an extremely small size will slow
  180504. * the library down, but you may want to experiment to determine
  180505. * where it becomes significant, if you are concerned with memory
  180506. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180507. * this describes the size of the buffer available to read the data in.
  180508. * Unless this gets smaller than the size of a row (compressed),
  180509. * it should not make much difference how big this is.
  180510. */
  180511. #ifndef PNG_ZBUF_SIZE
  180512. # define PNG_ZBUF_SIZE 8192
  180513. #endif
  180514. /* Enable if you want a write-only libpng */
  180515. #ifndef PNG_NO_READ_SUPPORTED
  180516. # define PNG_READ_SUPPORTED
  180517. #endif
  180518. /* Enable if you want a read-only libpng */
  180519. #ifndef PNG_NO_WRITE_SUPPORTED
  180520. # define PNG_WRITE_SUPPORTED
  180521. #endif
  180522. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180523. support PNGs that are embedded in MNG datastreams */
  180524. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180525. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180526. # define PNG_MNG_FEATURES_SUPPORTED
  180527. # endif
  180528. #endif
  180529. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180530. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180531. # define PNG_FLOATING_POINT_SUPPORTED
  180532. # endif
  180533. #endif
  180534. /* If you are running on a machine where you cannot allocate more
  180535. * than 64K of memory at once, uncomment this. While libpng will not
  180536. * normally need that much memory in a chunk (unless you load up a very
  180537. * large file), zlib needs to know how big of a chunk it can use, and
  180538. * libpng thus makes sure to check any memory allocation to verify it
  180539. * will fit into memory.
  180540. #define PNG_MAX_MALLOC_64K
  180541. */
  180542. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180543. # define PNG_MAX_MALLOC_64K
  180544. #endif
  180545. /* Special munging to support doing things the 'cygwin' way:
  180546. * 'Normal' png-on-win32 defines/defaults:
  180547. * PNG_BUILD_DLL -- building dll
  180548. * PNG_USE_DLL -- building an application, linking to dll
  180549. * (no define) -- building static library, or building an
  180550. * application and linking to the static lib
  180551. * 'Cygwin' defines/defaults:
  180552. * PNG_BUILD_DLL -- (ignored) building the dll
  180553. * (no define) -- (ignored) building an application, linking to the dll
  180554. * PNG_STATIC -- (ignored) building the static lib, or building an
  180555. * application that links to the static lib.
  180556. * ALL_STATIC -- (ignored) building various static libs, or building an
  180557. * application that links to the static libs.
  180558. * Thus,
  180559. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180560. * this bit of #ifdefs will define the 'correct' config variables based on
  180561. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180562. * unnecessary.
  180563. *
  180564. * Also, the precedence order is:
  180565. * ALL_STATIC (since we can't #undef something outside our namespace)
  180566. * PNG_BUILD_DLL
  180567. * PNG_STATIC
  180568. * (nothing) == PNG_USE_DLL
  180569. *
  180570. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180571. * of auto-import in binutils, we no longer need to worry about
  180572. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180573. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180574. * to __declspec() stuff. However, we DO need to worry about
  180575. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180576. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180577. */
  180578. #if defined(__CYGWIN__)
  180579. # if defined(ALL_STATIC)
  180580. # if defined(PNG_BUILD_DLL)
  180581. # undef PNG_BUILD_DLL
  180582. # endif
  180583. # if defined(PNG_USE_DLL)
  180584. # undef PNG_USE_DLL
  180585. # endif
  180586. # if defined(PNG_DLL)
  180587. # undef PNG_DLL
  180588. # endif
  180589. # if !defined(PNG_STATIC)
  180590. # define PNG_STATIC
  180591. # endif
  180592. # else
  180593. # if defined (PNG_BUILD_DLL)
  180594. # if defined(PNG_STATIC)
  180595. # undef PNG_STATIC
  180596. # endif
  180597. # if defined(PNG_USE_DLL)
  180598. # undef PNG_USE_DLL
  180599. # endif
  180600. # if !defined(PNG_DLL)
  180601. # define PNG_DLL
  180602. # endif
  180603. # else
  180604. # if defined(PNG_STATIC)
  180605. # if defined(PNG_USE_DLL)
  180606. # undef PNG_USE_DLL
  180607. # endif
  180608. # if defined(PNG_DLL)
  180609. # undef PNG_DLL
  180610. # endif
  180611. # else
  180612. # if !defined(PNG_USE_DLL)
  180613. # define PNG_USE_DLL
  180614. # endif
  180615. # if !defined(PNG_DLL)
  180616. # define PNG_DLL
  180617. # endif
  180618. # endif
  180619. # endif
  180620. # endif
  180621. #endif
  180622. /* This protects us against compilers that run on a windowing system
  180623. * and thus don't have or would rather us not use the stdio types:
  180624. * stdin, stdout, and stderr. The only one currently used is stderr
  180625. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180626. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180627. * will also prevent these, plus will prevent the entire set of stdio
  180628. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180629. * unless (PNG_DEBUG > 0) has been #defined.
  180630. *
  180631. * #define PNG_NO_CONSOLE_IO
  180632. * #define PNG_NO_STDIO
  180633. */
  180634. #if defined(_WIN32_WCE)
  180635. # include <windows.h>
  180636. /* Console I/O functions are not supported on WindowsCE */
  180637. # define PNG_NO_CONSOLE_IO
  180638. # ifdef PNG_DEBUG
  180639. # undef PNG_DEBUG
  180640. # endif
  180641. #endif
  180642. #ifdef PNG_BUILD_DLL
  180643. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180644. # ifndef PNG_NO_CONSOLE_IO
  180645. # define PNG_NO_CONSOLE_IO
  180646. # endif
  180647. # endif
  180648. #endif
  180649. # ifdef PNG_NO_STDIO
  180650. # ifndef PNG_NO_CONSOLE_IO
  180651. # define PNG_NO_CONSOLE_IO
  180652. # endif
  180653. # ifdef PNG_DEBUG
  180654. # if (PNG_DEBUG > 0)
  180655. # include <stdio.h>
  180656. # endif
  180657. # endif
  180658. # else
  180659. # if !defined(_WIN32_WCE)
  180660. /* "stdio.h" functions are not supported on WindowsCE */
  180661. # include <stdio.h>
  180662. # endif
  180663. # endif
  180664. /* This macro protects us against machines that don't have function
  180665. * prototypes (ie K&R style headers). If your compiler does not handle
  180666. * function prototypes, define this macro and use the included ansi2knr.
  180667. * I've always been able to use _NO_PROTO as the indicator, but you may
  180668. * need to drag the empty declaration out in front of here, or change the
  180669. * ifdef to suit your own needs.
  180670. */
  180671. #ifndef PNGARG
  180672. #ifdef OF /* zlib prototype munger */
  180673. # define PNGARG(arglist) OF(arglist)
  180674. #else
  180675. #ifdef _NO_PROTO
  180676. # define PNGARG(arglist) ()
  180677. # ifndef PNG_TYPECAST_NULL
  180678. # define PNG_TYPECAST_NULL
  180679. # endif
  180680. #else
  180681. # define PNGARG(arglist) arglist
  180682. #endif /* _NO_PROTO */
  180683. #endif /* OF */
  180684. #endif /* PNGARG */
  180685. /* Try to determine if we are compiling on a Mac. Note that testing for
  180686. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180687. * on non-Mac platforms.
  180688. */
  180689. #ifndef MACOS
  180690. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180691. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180692. # define MACOS
  180693. # endif
  180694. #endif
  180695. /* enough people need this for various reasons to include it here */
  180696. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180697. # include <sys/types.h>
  180698. #endif
  180699. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180700. # define PNG_SETJMP_SUPPORTED
  180701. #endif
  180702. #ifdef PNG_SETJMP_SUPPORTED
  180703. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180704. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180705. */
  180706. # ifdef __linux__
  180707. # ifdef _BSD_SOURCE
  180708. # define PNG_SAVE_BSD_SOURCE
  180709. # undef _BSD_SOURCE
  180710. # endif
  180711. # ifdef _SETJMP_H
  180712. /* If you encounter a compiler error here, see the explanation
  180713. * near the end of INSTALL.
  180714. */
  180715. __png.h__ already includes setjmp.h;
  180716. __dont__ include it again.;
  180717. # endif
  180718. # endif /* __linux__ */
  180719. /* include setjmp.h for error handling */
  180720. # include <setjmp.h>
  180721. # ifdef __linux__
  180722. # ifdef PNG_SAVE_BSD_SOURCE
  180723. # define _BSD_SOURCE
  180724. # undef PNG_SAVE_BSD_SOURCE
  180725. # endif
  180726. # endif /* __linux__ */
  180727. #endif /* PNG_SETJMP_SUPPORTED */
  180728. #ifdef BSD
  180729. #if ! JUCE_MAC
  180730. # include <strings.h>
  180731. #endif
  180732. #else
  180733. # include <string.h>
  180734. #endif
  180735. /* Other defines for things like memory and the like can go here. */
  180736. #ifdef PNG_INTERNAL
  180737. #include <stdlib.h>
  180738. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180739. * aren't usually used outside the library (as far as I know), so it is
  180740. * debatable if they should be exported at all. In the future, when it is
  180741. * possible to have run-time registry of chunk-handling functions, some of
  180742. * these will be made available again.
  180743. #define PNG_EXTERN extern
  180744. */
  180745. #define PNG_EXTERN
  180746. /* Other defines specific to compilers can go here. Try to keep
  180747. * them inside an appropriate ifdef/endif pair for portability.
  180748. */
  180749. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180750. # if defined(MACOS)
  180751. /* We need to check that <math.h> hasn't already been included earlier
  180752. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180753. * <fp.h> if possible.
  180754. */
  180755. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180756. # include <fp.h>
  180757. # endif
  180758. # else
  180759. # include <math.h>
  180760. # endif
  180761. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180762. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180763. * MATH=68881
  180764. */
  180765. # include <m68881.h>
  180766. # endif
  180767. #endif
  180768. /* Codewarrior on NT has linking problems without this. */
  180769. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180770. # define PNG_ALWAYS_EXTERN
  180771. #endif
  180772. /* This provides the non-ANSI (far) memory allocation routines. */
  180773. #if defined(__TURBOC__) && defined(__MSDOS__)
  180774. # include <mem.h>
  180775. # include <alloc.h>
  180776. #endif
  180777. /* I have no idea why is this necessary... */
  180778. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180779. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180780. # include <malloc.h>
  180781. #endif
  180782. /* This controls how fine the dithering gets. As this allocates
  180783. * a largish chunk of memory (32K), those who are not as concerned
  180784. * with dithering quality can decrease some or all of these.
  180785. */
  180786. #ifndef PNG_DITHER_RED_BITS
  180787. # define PNG_DITHER_RED_BITS 5
  180788. #endif
  180789. #ifndef PNG_DITHER_GREEN_BITS
  180790. # define PNG_DITHER_GREEN_BITS 5
  180791. #endif
  180792. #ifndef PNG_DITHER_BLUE_BITS
  180793. # define PNG_DITHER_BLUE_BITS 5
  180794. #endif
  180795. /* This controls how fine the gamma correction becomes when you
  180796. * are only interested in 8 bits anyway. Increasing this value
  180797. * results in more memory being used, and more pow() functions
  180798. * being called to fill in the gamma tables. Don't set this value
  180799. * less then 8, and even that may not work (I haven't tested it).
  180800. */
  180801. #ifndef PNG_MAX_GAMMA_8
  180802. # define PNG_MAX_GAMMA_8 11
  180803. #endif
  180804. /* This controls how much a difference in gamma we can tolerate before
  180805. * we actually start doing gamma conversion.
  180806. */
  180807. #ifndef PNG_GAMMA_THRESHOLD
  180808. # define PNG_GAMMA_THRESHOLD 0.05
  180809. #endif
  180810. #endif /* PNG_INTERNAL */
  180811. /* The following uses const char * instead of char * for error
  180812. * and warning message functions, so some compilers won't complain.
  180813. * If you do not want to use const, define PNG_NO_CONST here.
  180814. */
  180815. #ifndef PNG_NO_CONST
  180816. # define PNG_CONST const
  180817. #else
  180818. # define PNG_CONST
  180819. #endif
  180820. /* The following defines give you the ability to remove code from the
  180821. * library that you will not be using. I wish I could figure out how to
  180822. * automate this, but I can't do that without making it seriously hard
  180823. * on the users. So if you are not using an ability, change the #define
  180824. * to and #undef, and that part of the library will not be compiled. If
  180825. * your linker can't find a function, you may want to make sure the
  180826. * ability is defined here. Some of these depend upon some others being
  180827. * defined. I haven't figured out all the interactions here, so you may
  180828. * have to experiment awhile to get everything to compile. If you are
  180829. * creating or using a shared library, you probably shouldn't touch this,
  180830. * as it will affect the size of the structures, and this will cause bad
  180831. * things to happen if the library and/or application ever change.
  180832. */
  180833. /* Any features you will not be using can be undef'ed here */
  180834. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180835. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180836. * on the compile line, then pick and choose which ones to define without
  180837. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180838. * if you only want to have a png-compliant reader/writer but don't need
  180839. * any of the extra transformations. This saves about 80 kbytes in a
  180840. * typical installation of the library. (PNG_NO_* form added in version
  180841. * 1.0.1c, for consistency)
  180842. */
  180843. /* The size of the png_text structure changed in libpng-1.0.6 when
  180844. * iTXt support was added. iTXt support was turned off by default through
  180845. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180846. * instead of calling png_set_text() and letting libpng malloc it. It
  180847. * was turned on by default in libpng-1.3.0.
  180848. */
  180849. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180850. # ifndef PNG_NO_iTXt_SUPPORTED
  180851. # define PNG_NO_iTXt_SUPPORTED
  180852. # endif
  180853. # ifndef PNG_NO_READ_iTXt
  180854. # define PNG_NO_READ_iTXt
  180855. # endif
  180856. # ifndef PNG_NO_WRITE_iTXt
  180857. # define PNG_NO_WRITE_iTXt
  180858. # endif
  180859. #endif
  180860. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180861. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180862. # define PNG_READ_iTXt
  180863. # endif
  180864. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180865. # define PNG_WRITE_iTXt
  180866. # endif
  180867. #endif
  180868. /* The following support, added after version 1.0.0, can be turned off here en
  180869. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180870. * with old applications that require the length of png_struct and png_info
  180871. * to remain unchanged.
  180872. */
  180873. #ifdef PNG_LEGACY_SUPPORTED
  180874. # define PNG_NO_FREE_ME
  180875. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180876. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180877. # define PNG_NO_READ_USER_CHUNKS
  180878. # define PNG_NO_READ_iCCP
  180879. # define PNG_NO_WRITE_iCCP
  180880. # define PNG_NO_READ_iTXt
  180881. # define PNG_NO_WRITE_iTXt
  180882. # define PNG_NO_READ_sCAL
  180883. # define PNG_NO_WRITE_sCAL
  180884. # define PNG_NO_READ_sPLT
  180885. # define PNG_NO_WRITE_sPLT
  180886. # define PNG_NO_INFO_IMAGE
  180887. # define PNG_NO_READ_RGB_TO_GRAY
  180888. # define PNG_NO_READ_USER_TRANSFORM
  180889. # define PNG_NO_WRITE_USER_TRANSFORM
  180890. # define PNG_NO_USER_MEM
  180891. # define PNG_NO_READ_EMPTY_PLTE
  180892. # define PNG_NO_MNG_FEATURES
  180893. # define PNG_NO_FIXED_POINT_SUPPORTED
  180894. #endif
  180895. /* Ignore attempt to turn off both floating and fixed point support */
  180896. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180897. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180898. # define PNG_FIXED_POINT_SUPPORTED
  180899. #endif
  180900. #ifndef PNG_NO_FREE_ME
  180901. # define PNG_FREE_ME_SUPPORTED
  180902. #endif
  180903. #if defined(PNG_READ_SUPPORTED)
  180904. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180905. !defined(PNG_NO_READ_TRANSFORMS)
  180906. # define PNG_READ_TRANSFORMS_SUPPORTED
  180907. #endif
  180908. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180909. # ifndef PNG_NO_READ_EXPAND
  180910. # define PNG_READ_EXPAND_SUPPORTED
  180911. # endif
  180912. # ifndef PNG_NO_READ_SHIFT
  180913. # define PNG_READ_SHIFT_SUPPORTED
  180914. # endif
  180915. # ifndef PNG_NO_READ_PACK
  180916. # define PNG_READ_PACK_SUPPORTED
  180917. # endif
  180918. # ifndef PNG_NO_READ_BGR
  180919. # define PNG_READ_BGR_SUPPORTED
  180920. # endif
  180921. # ifndef PNG_NO_READ_SWAP
  180922. # define PNG_READ_SWAP_SUPPORTED
  180923. # endif
  180924. # ifndef PNG_NO_READ_PACKSWAP
  180925. # define PNG_READ_PACKSWAP_SUPPORTED
  180926. # endif
  180927. # ifndef PNG_NO_READ_INVERT
  180928. # define PNG_READ_INVERT_SUPPORTED
  180929. # endif
  180930. # ifndef PNG_NO_READ_DITHER
  180931. # define PNG_READ_DITHER_SUPPORTED
  180932. # endif
  180933. # ifndef PNG_NO_READ_BACKGROUND
  180934. # define PNG_READ_BACKGROUND_SUPPORTED
  180935. # endif
  180936. # ifndef PNG_NO_READ_16_TO_8
  180937. # define PNG_READ_16_TO_8_SUPPORTED
  180938. # endif
  180939. # ifndef PNG_NO_READ_FILLER
  180940. # define PNG_READ_FILLER_SUPPORTED
  180941. # endif
  180942. # ifndef PNG_NO_READ_GAMMA
  180943. # define PNG_READ_GAMMA_SUPPORTED
  180944. # endif
  180945. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180946. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180947. # endif
  180948. # ifndef PNG_NO_READ_SWAP_ALPHA
  180949. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180950. # endif
  180951. # ifndef PNG_NO_READ_INVERT_ALPHA
  180952. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180953. # endif
  180954. # ifndef PNG_NO_READ_STRIP_ALPHA
  180955. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180956. # endif
  180957. # ifndef PNG_NO_READ_USER_TRANSFORM
  180958. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180959. # endif
  180960. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180961. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180962. # endif
  180963. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180964. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180965. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180966. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180967. #endif /* about interlacing capability! You'll */
  180968. /* still have interlacing unless you change the following line: */
  180969. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180970. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180971. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180972. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180973. # endif
  180974. #endif
  180975. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180976. /* Deprecated, will be removed from version 2.0.0.
  180977. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180978. #ifndef PNG_NO_READ_EMPTY_PLTE
  180979. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180980. #endif
  180981. #endif
  180982. #endif /* PNG_READ_SUPPORTED */
  180983. #if defined(PNG_WRITE_SUPPORTED)
  180984. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180985. !defined(PNG_NO_WRITE_TRANSFORMS)
  180986. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180987. #endif
  180988. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180989. # ifndef PNG_NO_WRITE_SHIFT
  180990. # define PNG_WRITE_SHIFT_SUPPORTED
  180991. # endif
  180992. # ifndef PNG_NO_WRITE_PACK
  180993. # define PNG_WRITE_PACK_SUPPORTED
  180994. # endif
  180995. # ifndef PNG_NO_WRITE_BGR
  180996. # define PNG_WRITE_BGR_SUPPORTED
  180997. # endif
  180998. # ifndef PNG_NO_WRITE_SWAP
  180999. # define PNG_WRITE_SWAP_SUPPORTED
  181000. # endif
  181001. # ifndef PNG_NO_WRITE_PACKSWAP
  181002. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181003. # endif
  181004. # ifndef PNG_NO_WRITE_INVERT
  181005. # define PNG_WRITE_INVERT_SUPPORTED
  181006. # endif
  181007. # ifndef PNG_NO_WRITE_FILLER
  181008. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181009. # endif
  181010. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181011. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181012. # endif
  181013. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181014. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181015. # endif
  181016. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181017. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181018. # endif
  181019. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181020. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181021. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181022. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181023. encoders, but can cause trouble
  181024. if left undefined */
  181025. #endif
  181026. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181027. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181028. defined(PNG_FLOATING_POINT_SUPPORTED)
  181029. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181030. #endif
  181031. #ifndef PNG_NO_WRITE_FLUSH
  181032. # define PNG_WRITE_FLUSH_SUPPORTED
  181033. #endif
  181034. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181035. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181036. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181037. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181038. #endif
  181039. #endif
  181040. #endif /* PNG_WRITE_SUPPORTED */
  181041. #ifndef PNG_1_0_X
  181042. # ifndef PNG_NO_ERROR_NUMBERS
  181043. # define PNG_ERROR_NUMBERS_SUPPORTED
  181044. # endif
  181045. #endif /* PNG_1_0_X */
  181046. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181047. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181048. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181049. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181050. # endif
  181051. #endif
  181052. #ifndef PNG_NO_STDIO
  181053. # define PNG_TIME_RFC1123_SUPPORTED
  181054. #endif
  181055. /* This adds extra functions in pngget.c for accessing data from the
  181056. * info pointer (added in version 0.99)
  181057. * png_get_image_width()
  181058. * png_get_image_height()
  181059. * png_get_bit_depth()
  181060. * png_get_color_type()
  181061. * png_get_compression_type()
  181062. * png_get_filter_type()
  181063. * png_get_interlace_type()
  181064. * png_get_pixel_aspect_ratio()
  181065. * png_get_pixels_per_meter()
  181066. * png_get_x_offset_pixels()
  181067. * png_get_y_offset_pixels()
  181068. * png_get_x_offset_microns()
  181069. * png_get_y_offset_microns()
  181070. */
  181071. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181072. # define PNG_EASY_ACCESS_SUPPORTED
  181073. #endif
  181074. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181075. * and removed from version 1.2.20. The following will be removed
  181076. * from libpng-1.4.0
  181077. */
  181078. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181079. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181080. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181081. # endif
  181082. #endif
  181083. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181084. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181085. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181086. # endif
  181087. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181088. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181089. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181090. # define PNG_NO_MMX_CODE
  181091. # endif
  181092. # endif
  181093. # if defined(__APPLE__)
  181094. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181095. # define PNG_NO_MMX_CODE
  181096. # endif
  181097. # endif
  181098. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181099. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181100. # define PNG_NO_MMX_CODE
  181101. # endif
  181102. # endif
  181103. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181104. # define PNG_MMX_CODE_SUPPORTED
  181105. # endif
  181106. #endif
  181107. /* end of obsolete code to be removed from libpng-1.4.0 */
  181108. #if !defined(PNG_1_0_X)
  181109. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181110. # define PNG_USER_MEM_SUPPORTED
  181111. #endif
  181112. #endif /* PNG_1_0_X */
  181113. /* Added at libpng-1.2.6 */
  181114. #if !defined(PNG_1_0_X)
  181115. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181116. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181117. # define PNG_SET_USER_LIMITS_SUPPORTED
  181118. #endif
  181119. #endif
  181120. #endif /* PNG_1_0_X */
  181121. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181122. * how large, set these limits to 0x7fffffffL
  181123. */
  181124. #ifndef PNG_USER_WIDTH_MAX
  181125. # define PNG_USER_WIDTH_MAX 1000000L
  181126. #endif
  181127. #ifndef PNG_USER_HEIGHT_MAX
  181128. # define PNG_USER_HEIGHT_MAX 1000000L
  181129. #endif
  181130. /* These are currently experimental features, define them if you want */
  181131. /* very little testing */
  181132. /*
  181133. #ifdef PNG_READ_SUPPORTED
  181134. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181135. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181136. # endif
  181137. #endif
  181138. */
  181139. /* This is only for PowerPC big-endian and 680x0 systems */
  181140. /* some testing */
  181141. /*
  181142. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181143. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181144. #endif
  181145. */
  181146. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181147. /*
  181148. #define PNG_NO_POINTER_INDEXING
  181149. */
  181150. /* These functions are turned off by default, as they will be phased out. */
  181151. /*
  181152. #define PNG_USELESS_TESTS_SUPPORTED
  181153. #define PNG_CORRECT_PALETTE_SUPPORTED
  181154. */
  181155. /* Any chunks you are not interested in, you can undef here. The
  181156. * ones that allocate memory may be expecially important (hIST,
  181157. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181158. * a bit smaller.
  181159. */
  181160. #if defined(PNG_READ_SUPPORTED) && \
  181161. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181162. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181163. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181164. #endif
  181165. #if defined(PNG_WRITE_SUPPORTED) && \
  181166. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181167. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181168. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181169. #endif
  181170. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181171. #ifdef PNG_NO_READ_TEXT
  181172. # define PNG_NO_READ_iTXt
  181173. # define PNG_NO_READ_tEXt
  181174. # define PNG_NO_READ_zTXt
  181175. #endif
  181176. #ifndef PNG_NO_READ_bKGD
  181177. # define PNG_READ_bKGD_SUPPORTED
  181178. # define PNG_bKGD_SUPPORTED
  181179. #endif
  181180. #ifndef PNG_NO_READ_cHRM
  181181. # define PNG_READ_cHRM_SUPPORTED
  181182. # define PNG_cHRM_SUPPORTED
  181183. #endif
  181184. #ifndef PNG_NO_READ_gAMA
  181185. # define PNG_READ_gAMA_SUPPORTED
  181186. # define PNG_gAMA_SUPPORTED
  181187. #endif
  181188. #ifndef PNG_NO_READ_hIST
  181189. # define PNG_READ_hIST_SUPPORTED
  181190. # define PNG_hIST_SUPPORTED
  181191. #endif
  181192. #ifndef PNG_NO_READ_iCCP
  181193. # define PNG_READ_iCCP_SUPPORTED
  181194. # define PNG_iCCP_SUPPORTED
  181195. #endif
  181196. #ifndef PNG_NO_READ_iTXt
  181197. # ifndef PNG_READ_iTXt_SUPPORTED
  181198. # define PNG_READ_iTXt_SUPPORTED
  181199. # endif
  181200. # ifndef PNG_iTXt_SUPPORTED
  181201. # define PNG_iTXt_SUPPORTED
  181202. # endif
  181203. #endif
  181204. #ifndef PNG_NO_READ_oFFs
  181205. # define PNG_READ_oFFs_SUPPORTED
  181206. # define PNG_oFFs_SUPPORTED
  181207. #endif
  181208. #ifndef PNG_NO_READ_pCAL
  181209. # define PNG_READ_pCAL_SUPPORTED
  181210. # define PNG_pCAL_SUPPORTED
  181211. #endif
  181212. #ifndef PNG_NO_READ_sCAL
  181213. # define PNG_READ_sCAL_SUPPORTED
  181214. # define PNG_sCAL_SUPPORTED
  181215. #endif
  181216. #ifndef PNG_NO_READ_pHYs
  181217. # define PNG_READ_pHYs_SUPPORTED
  181218. # define PNG_pHYs_SUPPORTED
  181219. #endif
  181220. #ifndef PNG_NO_READ_sBIT
  181221. # define PNG_READ_sBIT_SUPPORTED
  181222. # define PNG_sBIT_SUPPORTED
  181223. #endif
  181224. #ifndef PNG_NO_READ_sPLT
  181225. # define PNG_READ_sPLT_SUPPORTED
  181226. # define PNG_sPLT_SUPPORTED
  181227. #endif
  181228. #ifndef PNG_NO_READ_sRGB
  181229. # define PNG_READ_sRGB_SUPPORTED
  181230. # define PNG_sRGB_SUPPORTED
  181231. #endif
  181232. #ifndef PNG_NO_READ_tEXt
  181233. # define PNG_READ_tEXt_SUPPORTED
  181234. # define PNG_tEXt_SUPPORTED
  181235. #endif
  181236. #ifndef PNG_NO_READ_tIME
  181237. # define PNG_READ_tIME_SUPPORTED
  181238. # define PNG_tIME_SUPPORTED
  181239. #endif
  181240. #ifndef PNG_NO_READ_tRNS
  181241. # define PNG_READ_tRNS_SUPPORTED
  181242. # define PNG_tRNS_SUPPORTED
  181243. #endif
  181244. #ifndef PNG_NO_READ_zTXt
  181245. # define PNG_READ_zTXt_SUPPORTED
  181246. # define PNG_zTXt_SUPPORTED
  181247. #endif
  181248. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181249. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181250. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181251. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181252. # endif
  181253. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181254. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181255. # endif
  181256. #endif
  181257. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181258. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181259. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181260. # define PNG_USER_CHUNKS_SUPPORTED
  181261. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181262. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181263. # endif
  181264. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181265. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181266. # endif
  181267. #endif
  181268. #ifndef PNG_NO_READ_OPT_PLTE
  181269. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181270. #endif /* optional PLTE chunk in RGB and RGBA images */
  181271. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181272. defined(PNG_READ_zTXt_SUPPORTED)
  181273. # define PNG_READ_TEXT_SUPPORTED
  181274. # define PNG_TEXT_SUPPORTED
  181275. #endif
  181276. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181277. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181278. #ifdef PNG_NO_WRITE_TEXT
  181279. # define PNG_NO_WRITE_iTXt
  181280. # define PNG_NO_WRITE_tEXt
  181281. # define PNG_NO_WRITE_zTXt
  181282. #endif
  181283. #ifndef PNG_NO_WRITE_bKGD
  181284. # define PNG_WRITE_bKGD_SUPPORTED
  181285. # ifndef PNG_bKGD_SUPPORTED
  181286. # define PNG_bKGD_SUPPORTED
  181287. # endif
  181288. #endif
  181289. #ifndef PNG_NO_WRITE_cHRM
  181290. # define PNG_WRITE_cHRM_SUPPORTED
  181291. # ifndef PNG_cHRM_SUPPORTED
  181292. # define PNG_cHRM_SUPPORTED
  181293. # endif
  181294. #endif
  181295. #ifndef PNG_NO_WRITE_gAMA
  181296. # define PNG_WRITE_gAMA_SUPPORTED
  181297. # ifndef PNG_gAMA_SUPPORTED
  181298. # define PNG_gAMA_SUPPORTED
  181299. # endif
  181300. #endif
  181301. #ifndef PNG_NO_WRITE_hIST
  181302. # define PNG_WRITE_hIST_SUPPORTED
  181303. # ifndef PNG_hIST_SUPPORTED
  181304. # define PNG_hIST_SUPPORTED
  181305. # endif
  181306. #endif
  181307. #ifndef PNG_NO_WRITE_iCCP
  181308. # define PNG_WRITE_iCCP_SUPPORTED
  181309. # ifndef PNG_iCCP_SUPPORTED
  181310. # define PNG_iCCP_SUPPORTED
  181311. # endif
  181312. #endif
  181313. #ifndef PNG_NO_WRITE_iTXt
  181314. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181315. # define PNG_WRITE_iTXt_SUPPORTED
  181316. # endif
  181317. # ifndef PNG_iTXt_SUPPORTED
  181318. # define PNG_iTXt_SUPPORTED
  181319. # endif
  181320. #endif
  181321. #ifndef PNG_NO_WRITE_oFFs
  181322. # define PNG_WRITE_oFFs_SUPPORTED
  181323. # ifndef PNG_oFFs_SUPPORTED
  181324. # define PNG_oFFs_SUPPORTED
  181325. # endif
  181326. #endif
  181327. #ifndef PNG_NO_WRITE_pCAL
  181328. # define PNG_WRITE_pCAL_SUPPORTED
  181329. # ifndef PNG_pCAL_SUPPORTED
  181330. # define PNG_pCAL_SUPPORTED
  181331. # endif
  181332. #endif
  181333. #ifndef PNG_NO_WRITE_sCAL
  181334. # define PNG_WRITE_sCAL_SUPPORTED
  181335. # ifndef PNG_sCAL_SUPPORTED
  181336. # define PNG_sCAL_SUPPORTED
  181337. # endif
  181338. #endif
  181339. #ifndef PNG_NO_WRITE_pHYs
  181340. # define PNG_WRITE_pHYs_SUPPORTED
  181341. # ifndef PNG_pHYs_SUPPORTED
  181342. # define PNG_pHYs_SUPPORTED
  181343. # endif
  181344. #endif
  181345. #ifndef PNG_NO_WRITE_sBIT
  181346. # define PNG_WRITE_sBIT_SUPPORTED
  181347. # ifndef PNG_sBIT_SUPPORTED
  181348. # define PNG_sBIT_SUPPORTED
  181349. # endif
  181350. #endif
  181351. #ifndef PNG_NO_WRITE_sPLT
  181352. # define PNG_WRITE_sPLT_SUPPORTED
  181353. # ifndef PNG_sPLT_SUPPORTED
  181354. # define PNG_sPLT_SUPPORTED
  181355. # endif
  181356. #endif
  181357. #ifndef PNG_NO_WRITE_sRGB
  181358. # define PNG_WRITE_sRGB_SUPPORTED
  181359. # ifndef PNG_sRGB_SUPPORTED
  181360. # define PNG_sRGB_SUPPORTED
  181361. # endif
  181362. #endif
  181363. #ifndef PNG_NO_WRITE_tEXt
  181364. # define PNG_WRITE_tEXt_SUPPORTED
  181365. # ifndef PNG_tEXt_SUPPORTED
  181366. # define PNG_tEXt_SUPPORTED
  181367. # endif
  181368. #endif
  181369. #ifndef PNG_NO_WRITE_tIME
  181370. # define PNG_WRITE_tIME_SUPPORTED
  181371. # ifndef PNG_tIME_SUPPORTED
  181372. # define PNG_tIME_SUPPORTED
  181373. # endif
  181374. #endif
  181375. #ifndef PNG_NO_WRITE_tRNS
  181376. # define PNG_WRITE_tRNS_SUPPORTED
  181377. # ifndef PNG_tRNS_SUPPORTED
  181378. # define PNG_tRNS_SUPPORTED
  181379. # endif
  181380. #endif
  181381. #ifndef PNG_NO_WRITE_zTXt
  181382. # define PNG_WRITE_zTXt_SUPPORTED
  181383. # ifndef PNG_zTXt_SUPPORTED
  181384. # define PNG_zTXt_SUPPORTED
  181385. # endif
  181386. #endif
  181387. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181388. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181389. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181390. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181391. # endif
  181392. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181393. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181394. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181395. # endif
  181396. # endif
  181397. #endif
  181398. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181399. defined(PNG_WRITE_zTXt_SUPPORTED)
  181400. # define PNG_WRITE_TEXT_SUPPORTED
  181401. # ifndef PNG_TEXT_SUPPORTED
  181402. # define PNG_TEXT_SUPPORTED
  181403. # endif
  181404. #endif
  181405. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181406. /* Turn this off to disable png_read_png() and
  181407. * png_write_png() and leave the row_pointers member
  181408. * out of the info structure.
  181409. */
  181410. #ifndef PNG_NO_INFO_IMAGE
  181411. # define PNG_INFO_IMAGE_SUPPORTED
  181412. #endif
  181413. /* need the time information for reading tIME chunks */
  181414. #if defined(PNG_tIME_SUPPORTED)
  181415. # if !defined(_WIN32_WCE)
  181416. /* "time.h" functions are not supported on WindowsCE */
  181417. # include <time.h>
  181418. # endif
  181419. #endif
  181420. /* Some typedefs to get us started. These should be safe on most of the
  181421. * common platforms. The typedefs should be at least as large as the
  181422. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181423. * don't have to be exactly that size. Some compilers dislike passing
  181424. * unsigned shorts as function parameters, so you may be better off using
  181425. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181426. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181427. */
  181428. typedef unsigned long png_uint_32;
  181429. typedef long png_int_32;
  181430. typedef unsigned short png_uint_16;
  181431. typedef short png_int_16;
  181432. typedef unsigned char png_byte;
  181433. /* This is usually size_t. It is typedef'ed just in case you need it to
  181434. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181435. #ifdef PNG_SIZE_T
  181436. typedef PNG_SIZE_T png_size_t;
  181437. # define png_sizeof(x) png_convert_size(sizeof (x))
  181438. #else
  181439. typedef size_t png_size_t;
  181440. # define png_sizeof(x) sizeof (x)
  181441. #endif
  181442. /* The following is needed for medium model support. It cannot be in the
  181443. * PNG_INTERNAL section. Needs modification for other compilers besides
  181444. * MSC. Model independent support declares all arrays and pointers to be
  181445. * large using the far keyword. The zlib version used must also support
  181446. * model independent data. As of version zlib 1.0.4, the necessary changes
  181447. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181448. * changes that are needed. (Tim Wegner)
  181449. */
  181450. /* Separate compiler dependencies (problem here is that zlib.h always
  181451. defines FAR. (SJT) */
  181452. #ifdef __BORLANDC__
  181453. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181454. # define LDATA 1
  181455. # else
  181456. # define LDATA 0
  181457. # endif
  181458. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181459. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181460. # define PNG_MAX_MALLOC_64K
  181461. # if (LDATA != 1)
  181462. # ifndef FAR
  181463. # define FAR __far
  181464. # endif
  181465. # define USE_FAR_KEYWORD
  181466. # endif /* LDATA != 1 */
  181467. /* Possibly useful for moving data out of default segment.
  181468. * Uncomment it if you want. Could also define FARDATA as
  181469. * const if your compiler supports it. (SJT)
  181470. # define FARDATA FAR
  181471. */
  181472. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181473. #endif /* __BORLANDC__ */
  181474. /* Suggest testing for specific compiler first before testing for
  181475. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181476. * making reliance oncertain keywords suspect. (SJT)
  181477. */
  181478. /* MSC Medium model */
  181479. #if defined(FAR)
  181480. # if defined(M_I86MM)
  181481. # define USE_FAR_KEYWORD
  181482. # define FARDATA FAR
  181483. # include <dos.h>
  181484. # endif
  181485. #endif
  181486. /* SJT: default case */
  181487. #ifndef FAR
  181488. # define FAR
  181489. #endif
  181490. /* At this point FAR is always defined */
  181491. #ifndef FARDATA
  181492. # define FARDATA
  181493. #endif
  181494. /* Typedef for floating-point numbers that are converted
  181495. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181496. typedef png_int_32 png_fixed_point;
  181497. /* Add typedefs for pointers */
  181498. typedef void FAR * png_voidp;
  181499. typedef png_byte FAR * png_bytep;
  181500. typedef png_uint_32 FAR * png_uint_32p;
  181501. typedef png_int_32 FAR * png_int_32p;
  181502. typedef png_uint_16 FAR * png_uint_16p;
  181503. typedef png_int_16 FAR * png_int_16p;
  181504. typedef PNG_CONST char FAR * png_const_charp;
  181505. typedef char FAR * png_charp;
  181506. typedef png_fixed_point FAR * png_fixed_point_p;
  181507. #ifndef PNG_NO_STDIO
  181508. #if defined(_WIN32_WCE)
  181509. typedef HANDLE png_FILE_p;
  181510. #else
  181511. typedef FILE * png_FILE_p;
  181512. #endif
  181513. #endif
  181514. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181515. typedef double FAR * png_doublep;
  181516. #endif
  181517. /* Pointers to pointers; i.e. arrays */
  181518. typedef png_byte FAR * FAR * png_bytepp;
  181519. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181520. typedef png_int_32 FAR * FAR * png_int_32pp;
  181521. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181522. typedef png_int_16 FAR * FAR * png_int_16pp;
  181523. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181524. typedef char FAR * FAR * png_charpp;
  181525. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181526. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181527. typedef double FAR * FAR * png_doublepp;
  181528. #endif
  181529. /* Pointers to pointers to pointers; i.e., pointer to array */
  181530. typedef char FAR * FAR * FAR * png_charppp;
  181531. #if 0
  181532. /* SPC - Is this stuff deprecated? */
  181533. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181534. /* libpng typedefs for types in zlib. If zlib changes
  181535. * or another compression library is used, then change these.
  181536. * Eliminates need to change all the source files.
  181537. */
  181538. typedef charf * png_zcharp;
  181539. typedef charf * FAR * png_zcharpp;
  181540. typedef z_stream FAR * png_zstreamp;
  181541. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181542. /*
  181543. * Define PNG_BUILD_DLL if the module being built is a Windows
  181544. * LIBPNG DLL.
  181545. *
  181546. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181547. * It is equivalent to Microsoft predefined macro _DLL that is
  181548. * automatically defined when you compile using the share
  181549. * version of the CRT (C Run-Time library)
  181550. *
  181551. * The cygwin mods make this behavior a little different:
  181552. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181553. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181554. * -or- if you are building an application that you want to link to the
  181555. * static library.
  181556. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181557. * the other flags is defined.
  181558. */
  181559. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181560. # define PNG_DLL
  181561. #endif
  181562. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181563. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181564. * command-line override
  181565. */
  181566. #if defined(__CYGWIN__)
  181567. # if !defined(PNG_STATIC)
  181568. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181569. # undef PNG_USE_GLOBAL_ARRAYS
  181570. # endif
  181571. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181572. # define PNG_USE_LOCAL_ARRAYS
  181573. # endif
  181574. # else
  181575. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181576. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181577. # undef PNG_USE_GLOBAL_ARRAYS
  181578. # endif
  181579. # endif
  181580. # endif
  181581. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181582. # define PNG_USE_LOCAL_ARRAYS
  181583. # endif
  181584. #endif
  181585. /* Do not use global arrays (helps with building DLL's)
  181586. * They are no longer used in libpng itself, since version 1.0.5c,
  181587. * but might be required for some pre-1.0.5c applications.
  181588. */
  181589. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181590. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181591. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181592. # define PNG_USE_LOCAL_ARRAYS
  181593. # else
  181594. # define PNG_USE_GLOBAL_ARRAYS
  181595. # endif
  181596. #endif
  181597. #if defined(__CYGWIN__)
  181598. # undef PNGAPI
  181599. # define PNGAPI __cdecl
  181600. # undef PNG_IMPEXP
  181601. # define PNG_IMPEXP
  181602. #endif
  181603. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181604. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181605. * Don't ignore those warnings; you must also reset the default calling
  181606. * convention in your compiler to match your PNGAPI, and you must build
  181607. * zlib and your applications the same way you build libpng.
  181608. */
  181609. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181610. # ifndef PNG_NO_MODULEDEF
  181611. # define PNG_NO_MODULEDEF
  181612. # endif
  181613. #endif
  181614. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181615. # define PNG_IMPEXP
  181616. #endif
  181617. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181618. (( defined(_Windows) || defined(_WINDOWS) || \
  181619. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181620. # ifndef PNGAPI
  181621. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181622. # define PNGAPI __cdecl
  181623. # else
  181624. # define PNGAPI _cdecl
  181625. # endif
  181626. # endif
  181627. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181628. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181629. # define PNG_IMPEXP
  181630. # endif
  181631. # if !defined(PNG_IMPEXP)
  181632. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181633. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181634. /* Borland/Microsoft */
  181635. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181636. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181637. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181638. # else
  181639. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181640. # if defined(PNG_BUILD_DLL)
  181641. # define PNG_IMPEXP __export
  181642. # else
  181643. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181644. VC++ */
  181645. # endif /* Exists in Borland C++ for
  181646. C++ classes (== huge) */
  181647. # endif
  181648. # endif
  181649. # if !defined(PNG_IMPEXP)
  181650. # if defined(PNG_BUILD_DLL)
  181651. # define PNG_IMPEXP __declspec(dllexport)
  181652. # else
  181653. # define PNG_IMPEXP __declspec(dllimport)
  181654. # endif
  181655. # endif
  181656. # endif /* PNG_IMPEXP */
  181657. #else /* !(DLL || non-cygwin WINDOWS) */
  181658. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181659. # ifndef PNGAPI
  181660. # define PNGAPI _System
  181661. # endif
  181662. # else
  181663. # if 0 /* ... other platforms, with other meanings */
  181664. # endif
  181665. # endif
  181666. #endif
  181667. #ifndef PNGAPI
  181668. # define PNGAPI
  181669. #endif
  181670. #ifndef PNG_IMPEXP
  181671. # define PNG_IMPEXP
  181672. #endif
  181673. #ifdef PNG_BUILDSYMS
  181674. # ifndef PNG_EXPORT
  181675. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181676. # endif
  181677. # ifdef PNG_USE_GLOBAL_ARRAYS
  181678. # ifndef PNG_EXPORT_VAR
  181679. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181680. # endif
  181681. # endif
  181682. #endif
  181683. #ifndef PNG_EXPORT
  181684. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181685. #endif
  181686. #ifdef PNG_USE_GLOBAL_ARRAYS
  181687. # ifndef PNG_EXPORT_VAR
  181688. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181689. # endif
  181690. #endif
  181691. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181692. * functions that are passed far data must be model independent.
  181693. */
  181694. #ifndef PNG_ABORT
  181695. # define PNG_ABORT() abort()
  181696. #endif
  181697. #ifdef PNG_SETJMP_SUPPORTED
  181698. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181699. #else
  181700. # define png_jmpbuf(png_ptr) \
  181701. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181702. #endif
  181703. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181704. /* use this to make far-to-near assignments */
  181705. # define CHECK 1
  181706. # define NOCHECK 0
  181707. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181708. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181709. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181710. # define png_strcpy _fstrcpy
  181711. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181712. # define png_strlen _fstrlen
  181713. # define png_memcmp _fmemcmp /* SJT: added */
  181714. # define png_memcpy _fmemcpy
  181715. # define png_memset _fmemset
  181716. #else /* use the usual functions */
  181717. # define CVT_PTR(ptr) (ptr)
  181718. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181719. # ifndef PNG_NO_SNPRINTF
  181720. # ifdef _MSC_VER
  181721. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181722. # define png_snprintf2 _snprintf
  181723. # define png_snprintf6 _snprintf
  181724. # else
  181725. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181726. # define png_snprintf2 snprintf
  181727. # define png_snprintf6 snprintf
  181728. # endif
  181729. # else
  181730. /* You don't have or don't want to use snprintf(). Caution: Using
  181731. * sprintf instead of snprintf exposes your application to accidental
  181732. * or malevolent buffer overflows. If you don't have snprintf()
  181733. * as a general rule you should provide one (you can get one from
  181734. * Portable OpenSSH). */
  181735. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181736. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181737. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181738. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181739. # endif
  181740. # define png_strcpy strcpy
  181741. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181742. # define png_strlen strlen
  181743. # define png_memcmp memcmp /* SJT: added */
  181744. # define png_memcpy memcpy
  181745. # define png_memset memset
  181746. #endif
  181747. /* End of memory model independent support */
  181748. /* Just a little check that someone hasn't tried to define something
  181749. * contradictory.
  181750. */
  181751. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181752. # undef PNG_ZBUF_SIZE
  181753. # define PNG_ZBUF_SIZE 65536L
  181754. #endif
  181755. /* Added at libpng-1.2.8 */
  181756. #endif /* PNG_VERSION_INFO_ONLY */
  181757. #endif /* PNGCONF_H */
  181758. /*** End of inlined file: pngconf.h ***/
  181759. #ifdef _MSC_VER
  181760. #pragma warning (disable: 4996 4100)
  181761. #endif
  181762. /*
  181763. * Added at libpng-1.2.8 */
  181764. /* Ref MSDN: Private as priority over Special
  181765. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181766. * procedures. If this value is given, the StringFileInfo block must
  181767. * contain a PrivateBuild string.
  181768. *
  181769. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181770. * standard release procedures but is a variation of the standard
  181771. * file of the same version number. If this value is given, the
  181772. * StringFileInfo block must contain a SpecialBuild string.
  181773. */
  181774. #if defined(PNG_USER_PRIVATEBUILD)
  181775. # define PNG_LIBPNG_BUILD_TYPE \
  181776. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181777. #else
  181778. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181779. # define PNG_LIBPNG_BUILD_TYPE \
  181780. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181781. # else
  181782. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181783. # endif
  181784. #endif
  181785. #ifndef PNG_VERSION_INFO_ONLY
  181786. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181787. #ifdef __cplusplus
  181788. //extern "C" {
  181789. #endif /* __cplusplus */
  181790. /* This file is arranged in several sections. The first section contains
  181791. * structure and type definitions. The second section contains the external
  181792. * library functions, while the third has the internal library functions,
  181793. * which applications aren't expected to use directly.
  181794. */
  181795. #ifndef PNG_NO_TYPECAST_NULL
  181796. #define int_p_NULL (int *)NULL
  181797. #define png_bytep_NULL (png_bytep)NULL
  181798. #define png_bytepp_NULL (png_bytepp)NULL
  181799. #define png_doublep_NULL (png_doublep)NULL
  181800. #define png_error_ptr_NULL (png_error_ptr)NULL
  181801. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181802. #define png_free_ptr_NULL (png_free_ptr)NULL
  181803. #define png_infopp_NULL (png_infopp)NULL
  181804. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181805. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181806. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181807. #define png_structp_NULL (png_structp)NULL
  181808. #define png_uint_16p_NULL (png_uint_16p)NULL
  181809. #define png_voidp_NULL (png_voidp)NULL
  181810. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181811. #else
  181812. #define int_p_NULL NULL
  181813. #define png_bytep_NULL NULL
  181814. #define png_bytepp_NULL NULL
  181815. #define png_doublep_NULL NULL
  181816. #define png_error_ptr_NULL NULL
  181817. #define png_flush_ptr_NULL NULL
  181818. #define png_free_ptr_NULL NULL
  181819. #define png_infopp_NULL NULL
  181820. #define png_malloc_ptr_NULL NULL
  181821. #define png_read_status_ptr_NULL NULL
  181822. #define png_rw_ptr_NULL NULL
  181823. #define png_structp_NULL NULL
  181824. #define png_uint_16p_NULL NULL
  181825. #define png_voidp_NULL NULL
  181826. #define png_write_status_ptr_NULL NULL
  181827. #endif
  181828. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181829. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181830. /* Version information for C files, stored in png.c. This had better match
  181831. * the version above.
  181832. */
  181833. #ifdef PNG_USE_GLOBAL_ARRAYS
  181834. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181835. /* need room for 99.99.99beta99z */
  181836. #else
  181837. #define png_libpng_ver png_get_header_ver(NULL)
  181838. #endif
  181839. #ifdef PNG_USE_GLOBAL_ARRAYS
  181840. /* This was removed in version 1.0.5c */
  181841. /* Structures to facilitate easy interlacing. See png.c for more details */
  181842. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181843. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181844. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181845. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181846. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181847. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181848. /* This isn't currently used. If you need it, see png.c for more details.
  181849. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181850. */
  181851. #endif
  181852. #endif /* PNG_NO_EXTERN */
  181853. /* Three color definitions. The order of the red, green, and blue, (and the
  181854. * exact size) is not important, although the size of the fields need to
  181855. * be png_byte or png_uint_16 (as defined below).
  181856. */
  181857. typedef struct png_color_struct
  181858. {
  181859. png_byte red;
  181860. png_byte green;
  181861. png_byte blue;
  181862. } png_color;
  181863. typedef png_color FAR * png_colorp;
  181864. typedef png_color FAR * FAR * png_colorpp;
  181865. typedef struct png_color_16_struct
  181866. {
  181867. png_byte index; /* used for palette files */
  181868. png_uint_16 red; /* for use in red green blue files */
  181869. png_uint_16 green;
  181870. png_uint_16 blue;
  181871. png_uint_16 gray; /* for use in grayscale files */
  181872. } png_color_16;
  181873. typedef png_color_16 FAR * png_color_16p;
  181874. typedef png_color_16 FAR * FAR * png_color_16pp;
  181875. typedef struct png_color_8_struct
  181876. {
  181877. png_byte red; /* for use in red green blue files */
  181878. png_byte green;
  181879. png_byte blue;
  181880. png_byte gray; /* for use in grayscale files */
  181881. png_byte alpha; /* for alpha channel files */
  181882. } png_color_8;
  181883. typedef png_color_8 FAR * png_color_8p;
  181884. typedef png_color_8 FAR * FAR * png_color_8pp;
  181885. /*
  181886. * The following two structures are used for the in-core representation
  181887. * of sPLT chunks.
  181888. */
  181889. typedef struct png_sPLT_entry_struct
  181890. {
  181891. png_uint_16 red;
  181892. png_uint_16 green;
  181893. png_uint_16 blue;
  181894. png_uint_16 alpha;
  181895. png_uint_16 frequency;
  181896. } png_sPLT_entry;
  181897. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181898. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181899. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181900. * occupy the LSB of their respective members, and the MSB of each member
  181901. * is zero-filled. The frequency member always occupies the full 16 bits.
  181902. */
  181903. typedef struct png_sPLT_struct
  181904. {
  181905. png_charp name; /* palette name */
  181906. png_byte depth; /* depth of palette samples */
  181907. png_sPLT_entryp entries; /* palette entries */
  181908. png_int_32 nentries; /* number of palette entries */
  181909. } png_sPLT_t;
  181910. typedef png_sPLT_t FAR * png_sPLT_tp;
  181911. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181912. #ifdef PNG_TEXT_SUPPORTED
  181913. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181914. * and whether that contents is compressed or not. The "key" field
  181915. * points to a regular zero-terminated C string. The "text", "lang", and
  181916. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181917. * However, the * structure returned by png_get_text() will always contain
  181918. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181919. * so they can be safely used in printf() and other string-handling functions.
  181920. */
  181921. typedef struct png_text_struct
  181922. {
  181923. int compression; /* compression value:
  181924. -1: tEXt, none
  181925. 0: zTXt, deflate
  181926. 1: iTXt, none
  181927. 2: iTXt, deflate */
  181928. png_charp key; /* keyword, 1-79 character description of "text" */
  181929. png_charp text; /* comment, may be an empty string (ie "")
  181930. or a NULL pointer */
  181931. png_size_t text_length; /* length of the text string */
  181932. #ifdef PNG_iTXt_SUPPORTED
  181933. png_size_t itxt_length; /* length of the itxt string */
  181934. png_charp lang; /* language code, 0-79 characters
  181935. or a NULL pointer */
  181936. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181937. chars or a NULL pointer */
  181938. #endif
  181939. } png_text;
  181940. typedef png_text FAR * png_textp;
  181941. typedef png_text FAR * FAR * png_textpp;
  181942. #endif
  181943. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181944. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181945. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181946. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181947. #define PNG_TEXT_COMPRESSION_NONE -1
  181948. #define PNG_TEXT_COMPRESSION_zTXt 0
  181949. #define PNG_ITXT_COMPRESSION_NONE 1
  181950. #define PNG_ITXT_COMPRESSION_zTXt 2
  181951. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181952. /* png_time is a way to hold the time in an machine independent way.
  181953. * Two conversions are provided, both from time_t and struct tm. There
  181954. * is no portable way to convert to either of these structures, as far
  181955. * as I know. If you know of a portable way, send it to me. As a side
  181956. * note - PNG has always been Year 2000 compliant!
  181957. */
  181958. typedef struct png_time_struct
  181959. {
  181960. png_uint_16 year; /* full year, as in, 1995 */
  181961. png_byte month; /* month of year, 1 - 12 */
  181962. png_byte day; /* day of month, 1 - 31 */
  181963. png_byte hour; /* hour of day, 0 - 23 */
  181964. png_byte minute; /* minute of hour, 0 - 59 */
  181965. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181966. } png_time;
  181967. typedef png_time FAR * png_timep;
  181968. typedef png_time FAR * FAR * png_timepp;
  181969. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181970. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181971. * no specific support. The idea is that we can use this to queue
  181972. * up private chunks for output even though the library doesn't actually
  181973. * know about their semantics.
  181974. */
  181975. typedef struct png_unknown_chunk_t
  181976. {
  181977. png_byte name[5];
  181978. png_byte *data;
  181979. png_size_t size;
  181980. /* libpng-using applications should NOT directly modify this byte. */
  181981. png_byte location; /* mode of operation at read time */
  181982. }
  181983. png_unknown_chunk;
  181984. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181985. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181986. #endif
  181987. /* png_info is a structure that holds the information in a PNG file so
  181988. * that the application can find out the characteristics of the image.
  181989. * If you are reading the file, this structure will tell you what is
  181990. * in the PNG file. If you are writing the file, fill in the information
  181991. * you want to put into the PNG file, then call png_write_info().
  181992. * The names chosen should be very close to the PNG specification, so
  181993. * consult that document for information about the meaning of each field.
  181994. *
  181995. * With libpng < 0.95, it was only possible to directly set and read the
  181996. * the values in the png_info_struct, which meant that the contents and
  181997. * order of the values had to remain fixed. With libpng 0.95 and later,
  181998. * however, there are now functions that abstract the contents of
  181999. * png_info_struct from the application, so this makes it easier to use
  182000. * libpng with dynamic libraries, and even makes it possible to use
  182001. * libraries that don't have all of the libpng ancillary chunk-handing
  182002. * functionality.
  182003. *
  182004. * In any case, the order of the parameters in png_info_struct should NOT
  182005. * be changed for as long as possible to keep compatibility with applications
  182006. * that use the old direct-access method with png_info_struct.
  182007. *
  182008. * The following members may have allocated storage attached that should be
  182009. * cleaned up before the structure is discarded: palette, trans, text,
  182010. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182011. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182012. * are automatically freed when the info structure is deallocated, if they were
  182013. * allocated internally by libpng. This behavior can be changed by means
  182014. * of the png_data_freer() function.
  182015. *
  182016. * More allocation details: all the chunk-reading functions that
  182017. * change these members go through the corresponding png_set_*
  182018. * functions. A function to clear these members is available: see
  182019. * png_free_data(). The png_set_* functions do not depend on being
  182020. * able to point info structure members to any of the storage they are
  182021. * passed (they make their own copies), EXCEPT that the png_set_text
  182022. * functions use the same storage passed to them in the text_ptr or
  182023. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182024. * functions do not make their own copies.
  182025. */
  182026. typedef struct png_info_struct
  182027. {
  182028. /* the following are necessary for every PNG file */
  182029. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182030. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182031. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182032. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182033. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182034. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182035. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182036. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182037. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182038. /* The following three should have been named *_method not *_type */
  182039. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182040. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182041. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182042. /* The following is informational only on read, and not used on writes. */
  182043. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182044. png_byte pixel_depth; /* number of bits per pixel */
  182045. png_byte spare_byte; /* to align the data, and for future use */
  182046. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182047. /* The rest of the data is optional. If you are reading, check the
  182048. * valid field to see if the information in these are valid. If you
  182049. * are writing, set the valid field to those chunks you want written,
  182050. * and initialize the appropriate fields below.
  182051. */
  182052. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182053. /* The gAMA chunk describes the gamma characteristics of the system
  182054. * on which the image was created, normally in the range [1.0, 2.5].
  182055. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182056. */
  182057. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182058. #endif
  182059. #if defined(PNG_sRGB_SUPPORTED)
  182060. /* GR-P, 0.96a */
  182061. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182062. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182063. #endif
  182064. #if defined(PNG_TEXT_SUPPORTED)
  182065. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182066. * uncompressed, compressed, and optionally compressed forms, respectively.
  182067. * The data in "text" is an array of pointers to uncompressed,
  182068. * null-terminated C strings. Each chunk has a keyword that describes the
  182069. * textual data contained in that chunk. Keywords are not required to be
  182070. * unique, and the text string may be empty. Any number of text chunks may
  182071. * be in an image.
  182072. */
  182073. int num_text; /* number of comments read/to write */
  182074. int max_text; /* current size of text array */
  182075. png_textp text; /* array of comments read/to write */
  182076. #endif /* PNG_TEXT_SUPPORTED */
  182077. #if defined(PNG_tIME_SUPPORTED)
  182078. /* The tIME chunk holds the last time the displayed image data was
  182079. * modified. See the png_time struct for the contents of this struct.
  182080. */
  182081. png_time mod_time;
  182082. #endif
  182083. #if defined(PNG_sBIT_SUPPORTED)
  182084. /* The sBIT chunk specifies the number of significant high-order bits
  182085. * in the pixel data. Values are in the range [1, bit_depth], and are
  182086. * only specified for the channels in the pixel data. The contents of
  182087. * the low-order bits is not specified. Data is valid if
  182088. * (valid & PNG_INFO_sBIT) is non-zero.
  182089. */
  182090. png_color_8 sig_bit; /* significant bits in color channels */
  182091. #endif
  182092. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182093. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182094. /* The tRNS chunk supplies transparency data for paletted images and
  182095. * other image types that don't need a full alpha channel. There are
  182096. * "num_trans" transparency values for a paletted image, stored in the
  182097. * same order as the palette colors, starting from index 0. Values
  182098. * for the data are in the range [0, 255], ranging from fully transparent
  182099. * to fully opaque, respectively. For non-paletted images, there is a
  182100. * single color specified that should be treated as fully transparent.
  182101. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182102. */
  182103. png_bytep trans; /* transparent values for paletted image */
  182104. png_color_16 trans_values; /* transparent color for non-palette image */
  182105. #endif
  182106. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182107. /* The bKGD chunk gives the suggested image background color if the
  182108. * display program does not have its own background color and the image
  182109. * is needs to composited onto a background before display. The colors
  182110. * in "background" are normally in the same color space/depth as the
  182111. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182112. */
  182113. png_color_16 background;
  182114. #endif
  182115. #if defined(PNG_oFFs_SUPPORTED)
  182116. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182117. * and downwards from the top-left corner of the display, page, or other
  182118. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182119. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182120. */
  182121. png_int_32 x_offset; /* x offset on page */
  182122. png_int_32 y_offset; /* y offset on page */
  182123. png_byte offset_unit_type; /* offset units type */
  182124. #endif
  182125. #if defined(PNG_pHYs_SUPPORTED)
  182126. /* The pHYs chunk gives the physical pixel density of the image for
  182127. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182128. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182129. */
  182130. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182131. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182132. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182133. #endif
  182134. #if defined(PNG_hIST_SUPPORTED)
  182135. /* The hIST chunk contains the relative frequency or importance of the
  182136. * various palette entries, so that a viewer can intelligently select a
  182137. * reduced-color palette, if required. Data is an array of "num_palette"
  182138. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182139. * is non-zero.
  182140. */
  182141. png_uint_16p hist;
  182142. #endif
  182143. #ifdef PNG_cHRM_SUPPORTED
  182144. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182145. * on which the PNG was created. This data allows the viewer to do gamut
  182146. * mapping of the input image to ensure that the viewer sees the same
  182147. * colors in the image as the creator. Values are in the range
  182148. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182149. */
  182150. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182151. float x_white;
  182152. float y_white;
  182153. float x_red;
  182154. float y_red;
  182155. float x_green;
  182156. float y_green;
  182157. float x_blue;
  182158. float y_blue;
  182159. #endif
  182160. #endif
  182161. #if defined(PNG_pCAL_SUPPORTED)
  182162. /* The pCAL chunk describes a transformation between the stored pixel
  182163. * values and original physical data values used to create the image.
  182164. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182165. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182166. * (possibly non-linear) transformation function given by "pcal_type"
  182167. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182168. * defines below, and the PNG-Group's PNG extensions document for a
  182169. * complete description of the transformations and how they should be
  182170. * implemented, and for a description of the ASCII parameter strings.
  182171. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182172. */
  182173. png_charp pcal_purpose; /* pCAL chunk description string */
  182174. png_int_32 pcal_X0; /* minimum value */
  182175. png_int_32 pcal_X1; /* maximum value */
  182176. png_charp pcal_units; /* Latin-1 string giving physical units */
  182177. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182178. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182179. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182180. #endif
  182181. /* New members added in libpng-1.0.6 */
  182182. #ifdef PNG_FREE_ME_SUPPORTED
  182183. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182184. #endif
  182185. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182186. /* storage for unknown chunks that the library doesn't recognize. */
  182187. png_unknown_chunkp unknown_chunks;
  182188. png_size_t unknown_chunks_num;
  182189. #endif
  182190. #if defined(PNG_iCCP_SUPPORTED)
  182191. /* iCCP chunk data. */
  182192. png_charp iccp_name; /* profile name */
  182193. png_charp iccp_profile; /* International Color Consortium profile data */
  182194. /* Note to maintainer: should be png_bytep */
  182195. png_uint_32 iccp_proflen; /* ICC profile data length */
  182196. png_byte iccp_compression; /* Always zero */
  182197. #endif
  182198. #if defined(PNG_sPLT_SUPPORTED)
  182199. /* data on sPLT chunks (there may be more than one). */
  182200. png_sPLT_tp splt_palettes;
  182201. png_uint_32 splt_palettes_num;
  182202. #endif
  182203. #if defined(PNG_sCAL_SUPPORTED)
  182204. /* The sCAL chunk describes the actual physical dimensions of the
  182205. * subject matter of the graphic. The chunk contains a unit specification
  182206. * a byte value, and two ASCII strings representing floating-point
  182207. * values. The values are width and height corresponsing to one pixel
  182208. * in the image. This external representation is converted to double
  182209. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182210. */
  182211. png_byte scal_unit; /* unit of physical scale */
  182212. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182213. double scal_pixel_width; /* width of one pixel */
  182214. double scal_pixel_height; /* height of one pixel */
  182215. #endif
  182216. #ifdef PNG_FIXED_POINT_SUPPORTED
  182217. png_charp scal_s_width; /* string containing height */
  182218. png_charp scal_s_height; /* string containing width */
  182219. #endif
  182220. #endif
  182221. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182222. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182223. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182224. png_bytepp row_pointers; /* the image bits */
  182225. #endif
  182226. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182227. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182228. #endif
  182229. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182230. png_fixed_point int_x_white;
  182231. png_fixed_point int_y_white;
  182232. png_fixed_point int_x_red;
  182233. png_fixed_point int_y_red;
  182234. png_fixed_point int_x_green;
  182235. png_fixed_point int_y_green;
  182236. png_fixed_point int_x_blue;
  182237. png_fixed_point int_y_blue;
  182238. #endif
  182239. } png_info;
  182240. typedef png_info FAR * png_infop;
  182241. typedef png_info FAR * FAR * png_infopp;
  182242. /* Maximum positive integer used in PNG is (2^31)-1 */
  182243. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182244. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182245. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182246. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182247. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182248. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182249. #endif
  182250. /* These describe the color_type field in png_info. */
  182251. /* color type masks */
  182252. #define PNG_COLOR_MASK_PALETTE 1
  182253. #define PNG_COLOR_MASK_COLOR 2
  182254. #define PNG_COLOR_MASK_ALPHA 4
  182255. /* color types. Note that not all combinations are legal */
  182256. #define PNG_COLOR_TYPE_GRAY 0
  182257. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182258. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182259. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182260. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182261. /* aliases */
  182262. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182263. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182264. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182265. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182266. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182267. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182268. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182269. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182270. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182271. /* These are for the interlacing type. These values should NOT be changed. */
  182272. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182273. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182274. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182275. /* These are for the oFFs chunk. These values should NOT be changed. */
  182276. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182277. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182278. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182279. /* These are for the pCAL chunk. These values should NOT be changed. */
  182280. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182281. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182282. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182283. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182284. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182285. /* These are for the sCAL chunk. These values should NOT be changed. */
  182286. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182287. #define PNG_SCALE_METER 1 /* meters per pixel */
  182288. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182289. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182290. /* These are for the pHYs chunk. These values should NOT be changed. */
  182291. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182292. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182293. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182294. /* These are for the sRGB chunk. These values should NOT be changed. */
  182295. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182296. #define PNG_sRGB_INTENT_RELATIVE 1
  182297. #define PNG_sRGB_INTENT_SATURATION 2
  182298. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182299. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182300. /* This is for text chunks */
  182301. #define PNG_KEYWORD_MAX_LENGTH 79
  182302. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182303. #define PNG_MAX_PALETTE_LENGTH 256
  182304. /* These determine if an ancillary chunk's data has been successfully read
  182305. * from the PNG header, or if the application has filled in the corresponding
  182306. * data in the info_struct to be written into the output file. The values
  182307. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182308. */
  182309. #define PNG_INFO_gAMA 0x0001
  182310. #define PNG_INFO_sBIT 0x0002
  182311. #define PNG_INFO_cHRM 0x0004
  182312. #define PNG_INFO_PLTE 0x0008
  182313. #define PNG_INFO_tRNS 0x0010
  182314. #define PNG_INFO_bKGD 0x0020
  182315. #define PNG_INFO_hIST 0x0040
  182316. #define PNG_INFO_pHYs 0x0080
  182317. #define PNG_INFO_oFFs 0x0100
  182318. #define PNG_INFO_tIME 0x0200
  182319. #define PNG_INFO_pCAL 0x0400
  182320. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182321. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182322. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182323. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182324. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182325. /* This is used for the transformation routines, as some of them
  182326. * change these values for the row. It also should enable using
  182327. * the routines for other purposes.
  182328. */
  182329. typedef struct png_row_info_struct
  182330. {
  182331. png_uint_32 width; /* width of row */
  182332. png_uint_32 rowbytes; /* number of bytes in row */
  182333. png_byte color_type; /* color type of row */
  182334. png_byte bit_depth; /* bit depth of row */
  182335. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182336. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182337. } png_row_info;
  182338. typedef png_row_info FAR * png_row_infop;
  182339. typedef png_row_info FAR * FAR * png_row_infopp;
  182340. /* These are the function types for the I/O functions and for the functions
  182341. * that allow the user to override the default I/O functions with his or her
  182342. * own. The png_error_ptr type should match that of user-supplied warning
  182343. * and error functions, while the png_rw_ptr type should match that of the
  182344. * user read/write data functions.
  182345. */
  182346. typedef struct png_struct_def png_struct;
  182347. typedef png_struct FAR * png_structp;
  182348. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182349. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182350. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182351. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182352. int));
  182353. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182354. int));
  182355. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182356. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182357. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182358. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182359. png_uint_32, int));
  182360. #endif
  182361. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182362. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182363. defined(PNG_LEGACY_SUPPORTED)
  182364. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182365. png_row_infop, png_bytep));
  182366. #endif
  182367. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182368. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182369. #endif
  182370. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182371. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182372. #endif
  182373. /* Transform masks for the high-level interface */
  182374. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182375. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182376. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182377. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182378. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182379. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182380. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182381. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182382. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182383. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182384. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182385. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182386. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182387. /* Flags for MNG supported features */
  182388. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182389. #define PNG_FLAG_MNG_FILTER_64 0x04
  182390. #define PNG_ALL_MNG_FEATURES 0x05
  182391. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182392. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182393. /* The structure that holds the information to read and write PNG files.
  182394. * The only people who need to care about what is inside of this are the
  182395. * people who will be modifying the library for their own special needs.
  182396. * It should NOT be accessed directly by an application, except to store
  182397. * the jmp_buf.
  182398. */
  182399. struct png_struct_def
  182400. {
  182401. #ifdef PNG_SETJMP_SUPPORTED
  182402. jmp_buf jmpbuf; /* used in png_error */
  182403. #endif
  182404. png_error_ptr error_fn; /* function for printing errors and aborting */
  182405. png_error_ptr warning_fn; /* function for printing warnings */
  182406. png_voidp error_ptr; /* user supplied struct for error functions */
  182407. png_rw_ptr write_data_fn; /* function for writing output data */
  182408. png_rw_ptr read_data_fn; /* function for reading input data */
  182409. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182410. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182411. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182412. #endif
  182413. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182414. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182415. #endif
  182416. /* These were added in libpng-1.0.2 */
  182417. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182418. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182419. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182420. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182421. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182422. png_byte user_transform_channels; /* channels in user transformed pixels */
  182423. #endif
  182424. #endif
  182425. png_uint_32 mode; /* tells us where we are in the PNG file */
  182426. png_uint_32 flags; /* flags indicating various things to libpng */
  182427. png_uint_32 transformations; /* which transformations to perform */
  182428. z_stream zstream; /* pointer to decompression structure (below) */
  182429. png_bytep zbuf; /* buffer for zlib */
  182430. png_size_t zbuf_size; /* size of zbuf */
  182431. int zlib_level; /* holds zlib compression level */
  182432. int zlib_method; /* holds zlib compression method */
  182433. int zlib_window_bits; /* holds zlib compression window bits */
  182434. int zlib_mem_level; /* holds zlib compression memory level */
  182435. int zlib_strategy; /* holds zlib compression strategy */
  182436. png_uint_32 width; /* width of image in pixels */
  182437. png_uint_32 height; /* height of image in pixels */
  182438. png_uint_32 num_rows; /* number of rows in current pass */
  182439. png_uint_32 usr_width; /* width of row at start of write */
  182440. png_uint_32 rowbytes; /* size of row in bytes */
  182441. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182442. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182443. png_uint_32 row_number; /* current row in interlace pass */
  182444. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182445. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182446. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182447. png_bytep up_row; /* buffer to save "up" row when filtering */
  182448. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182449. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182450. png_row_info row_info; /* used for transformation routines */
  182451. png_uint_32 idat_size; /* current IDAT size for read */
  182452. png_uint_32 crc; /* current chunk CRC value */
  182453. png_colorp palette; /* palette from the input file */
  182454. png_uint_16 num_palette; /* number of color entries in palette */
  182455. png_uint_16 num_trans; /* number of transparency values */
  182456. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182457. png_byte compression; /* file compression type (always 0) */
  182458. png_byte filter; /* file filter type (always 0) */
  182459. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182460. png_byte pass; /* current interlace pass (0 - 6) */
  182461. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182462. png_byte color_type; /* color type of file */
  182463. png_byte bit_depth; /* bit depth of file */
  182464. png_byte usr_bit_depth; /* bit depth of users row */
  182465. png_byte pixel_depth; /* number of bits per pixel */
  182466. png_byte channels; /* number of channels in file */
  182467. png_byte usr_channels; /* channels at start of write */
  182468. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182469. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182470. #ifdef PNG_LEGACY_SUPPORTED
  182471. png_byte filler; /* filler byte for pixel expansion */
  182472. #else
  182473. png_uint_16 filler; /* filler bytes for pixel expansion */
  182474. #endif
  182475. #endif
  182476. #if defined(PNG_bKGD_SUPPORTED)
  182477. png_byte background_gamma_type;
  182478. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182479. float background_gamma;
  182480. # endif
  182481. png_color_16 background; /* background color in screen gamma space */
  182482. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182483. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182484. #endif
  182485. #endif /* PNG_bKGD_SUPPORTED */
  182486. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182487. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182488. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182489. png_uint_32 flush_rows; /* number of rows written since last flush */
  182490. #endif
  182491. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182492. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182493. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182494. float gamma; /* file gamma value */
  182495. float screen_gamma; /* screen gamma value (display_exponent) */
  182496. #endif
  182497. #endif
  182498. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182499. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182500. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182501. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182502. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182503. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182504. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182505. #endif
  182506. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182507. png_color_8 sig_bit; /* significant bits in each available channel */
  182508. #endif
  182509. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182510. png_color_8 shift; /* shift for significant bit tranformation */
  182511. #endif
  182512. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182513. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182514. png_bytep trans; /* transparency values for paletted files */
  182515. png_color_16 trans_values; /* transparency values for non-paletted files */
  182516. #endif
  182517. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182518. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182519. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182520. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182521. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182522. png_progressive_end_ptr end_fn; /* called after image is complete */
  182523. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182524. png_bytep save_buffer; /* buffer for previously read data */
  182525. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182526. png_bytep current_buffer; /* buffer for recently used data */
  182527. png_uint_32 push_length; /* size of current input chunk */
  182528. png_uint_32 skip_length; /* bytes to skip in input data */
  182529. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182530. png_size_t save_buffer_max; /* total size of save_buffer */
  182531. png_size_t buffer_size; /* total amount of available input data */
  182532. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182533. int process_mode; /* what push library is currently doing */
  182534. int cur_palette; /* current push library palette index */
  182535. # if defined(PNG_TEXT_SUPPORTED)
  182536. png_size_t current_text_size; /* current size of text input data */
  182537. png_size_t current_text_left; /* how much text left to read in input */
  182538. png_charp current_text; /* current text chunk buffer */
  182539. png_charp current_text_ptr; /* current location in current_text */
  182540. # endif /* PNG_TEXT_SUPPORTED */
  182541. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182542. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182543. /* for the Borland special 64K segment handler */
  182544. png_bytepp offset_table_ptr;
  182545. png_bytep offset_table;
  182546. png_uint_16 offset_table_number;
  182547. png_uint_16 offset_table_count;
  182548. png_uint_16 offset_table_count_free;
  182549. #endif
  182550. #if defined(PNG_READ_DITHER_SUPPORTED)
  182551. png_bytep palette_lookup; /* lookup table for dithering */
  182552. png_bytep dither_index; /* index translation for palette files */
  182553. #endif
  182554. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182555. png_uint_16p hist; /* histogram */
  182556. #endif
  182557. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182558. png_byte heuristic_method; /* heuristic for row filter selection */
  182559. png_byte num_prev_filters; /* number of weights for previous rows */
  182560. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182561. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182562. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182563. png_uint_16p filter_costs; /* relative filter calculation cost */
  182564. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182565. #endif
  182566. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182567. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182568. #endif
  182569. /* New members added in libpng-1.0.6 */
  182570. #ifdef PNG_FREE_ME_SUPPORTED
  182571. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182572. #endif
  182573. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182574. png_voidp user_chunk_ptr;
  182575. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182576. #endif
  182577. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182578. int num_chunk_list;
  182579. png_bytep chunk_list;
  182580. #endif
  182581. /* New members added in libpng-1.0.3 */
  182582. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182583. png_byte rgb_to_gray_status;
  182584. /* These were changed from png_byte in libpng-1.0.6 */
  182585. png_uint_16 rgb_to_gray_red_coeff;
  182586. png_uint_16 rgb_to_gray_green_coeff;
  182587. png_uint_16 rgb_to_gray_blue_coeff;
  182588. #endif
  182589. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182590. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182591. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182592. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182593. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182594. #ifdef PNG_1_0_X
  182595. png_byte mng_features_permitted;
  182596. #else
  182597. png_uint_32 mng_features_permitted;
  182598. #endif /* PNG_1_0_X */
  182599. #endif
  182600. /* New member added in libpng-1.0.7 */
  182601. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182602. png_fixed_point int_gamma;
  182603. #endif
  182604. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182605. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182606. png_byte filter_type;
  182607. #endif
  182608. #if defined(PNG_1_0_X)
  182609. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182610. png_uint_32 row_buf_size;
  182611. #endif
  182612. /* New members added in libpng-1.2.0 */
  182613. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182614. # if !defined(PNG_1_0_X)
  182615. # if defined(PNG_MMX_CODE_SUPPORTED)
  182616. png_byte mmx_bitdepth_threshold;
  182617. png_uint_32 mmx_rowbytes_threshold;
  182618. # endif
  182619. png_uint_32 asm_flags;
  182620. # endif
  182621. #endif
  182622. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182623. #ifdef PNG_USER_MEM_SUPPORTED
  182624. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182625. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182626. png_free_ptr free_fn; /* function for freeing memory */
  182627. #endif
  182628. /* New member added in libpng-1.0.13 and 1.2.0 */
  182629. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182630. #if defined(PNG_READ_DITHER_SUPPORTED)
  182631. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182632. png_bytep dither_sort; /* working sort array */
  182633. png_bytep index_to_palette; /* where the original index currently is */
  182634. /* in the palette */
  182635. png_bytep palette_to_index; /* which original index points to this */
  182636. /* palette color */
  182637. #endif
  182638. /* New members added in libpng-1.0.16 and 1.2.6 */
  182639. png_byte compression_type;
  182640. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182641. png_uint_32 user_width_max;
  182642. png_uint_32 user_height_max;
  182643. #endif
  182644. /* New member added in libpng-1.0.25 and 1.2.17 */
  182645. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182646. /* storage for unknown chunk that the library doesn't recognize. */
  182647. png_unknown_chunk unknown_chunk;
  182648. #endif
  182649. };
  182650. /* This triggers a compiler error in png.c, if png.c and png.h
  182651. * do not agree upon the version number.
  182652. */
  182653. typedef png_structp version_1_2_21;
  182654. typedef png_struct FAR * FAR * png_structpp;
  182655. /* Here are the function definitions most commonly used. This is not
  182656. * the place to find out how to use libpng. See libpng.txt for the
  182657. * full explanation, see example.c for the summary. This just provides
  182658. * a simple one line description of the use of each function.
  182659. */
  182660. /* Returns the version number of the library */
  182661. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182662. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182663. * Handling more than 8 bytes from the beginning of the file is an error.
  182664. */
  182665. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182666. int num_bytes));
  182667. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182668. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182669. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182670. * start > 7 will always fail (ie return non-zero).
  182671. */
  182672. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182673. png_size_t num_to_check));
  182674. /* Simple signature checking function. This is the same as calling
  182675. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182676. */
  182677. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182678. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182679. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182680. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182681. png_error_ptr error_fn, png_error_ptr warn_fn));
  182682. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182683. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182684. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182685. png_error_ptr error_fn, png_error_ptr warn_fn));
  182686. #ifdef PNG_WRITE_SUPPORTED
  182687. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182688. PNGARG((png_structp png_ptr));
  182689. #endif
  182690. #ifdef PNG_WRITE_SUPPORTED
  182691. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182692. PNGARG((png_structp png_ptr, png_uint_32 size));
  182693. #endif
  182694. /* Reset the compression stream */
  182695. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182696. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182697. #ifdef PNG_USER_MEM_SUPPORTED
  182698. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182699. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182700. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182701. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182702. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182703. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182704. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182705. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182706. #endif
  182707. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182708. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182709. png_bytep chunk_name, png_bytep data, png_size_t length));
  182710. /* Write the start of a PNG chunk - length and chunk name. */
  182711. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182712. png_bytep chunk_name, png_uint_32 length));
  182713. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182714. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182715. png_bytep data, png_size_t length));
  182716. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182717. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182718. /* Allocate and initialize the info structure */
  182719. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182720. PNGARG((png_structp png_ptr));
  182721. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182722. /* Initialize the info structure (old interface - DEPRECATED) */
  182723. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182724. #undef png_info_init
  182725. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182726. png_sizeof(png_info));
  182727. #endif
  182728. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182729. png_size_t png_info_struct_size));
  182730. /* Writes all the PNG information before the image. */
  182731. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182732. png_infop info_ptr));
  182733. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182734. png_infop info_ptr));
  182735. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182736. /* read the information before the actual image data. */
  182737. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182738. png_infop info_ptr));
  182739. #endif
  182740. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182741. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182742. PNGARG((png_structp png_ptr, png_timep ptime));
  182743. #endif
  182744. #if !defined(_WIN32_WCE)
  182745. /* "time.h" functions are not supported on WindowsCE */
  182746. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182747. /* convert from a struct tm to png_time */
  182748. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182749. struct tm FAR * ttime));
  182750. /* convert from time_t to png_time. Uses gmtime() */
  182751. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182752. time_t ttime));
  182753. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182754. #endif /* _WIN32_WCE */
  182755. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182756. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182757. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182758. #if !defined(PNG_1_0_X)
  182759. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182760. png_ptr));
  182761. #endif
  182762. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182763. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182764. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182765. /* Deprecated */
  182766. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182767. #endif
  182768. #endif
  182769. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182770. /* Use blue, green, red order for pixels. */
  182771. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182772. #endif
  182773. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182774. /* Expand the grayscale to 24-bit RGB if necessary. */
  182775. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182776. #endif
  182777. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182778. /* Reduce RGB to grayscale. */
  182779. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182780. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182781. int error_action, double red, double green ));
  182782. #endif
  182783. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182784. int error_action, png_fixed_point red, png_fixed_point green ));
  182785. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182786. png_ptr));
  182787. #endif
  182788. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182789. png_colorp palette));
  182790. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182791. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182792. #endif
  182793. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182794. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182795. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182796. #endif
  182797. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182798. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182799. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182800. #endif
  182801. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182802. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182803. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182804. png_uint_32 filler, int flags));
  182805. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182806. #define PNG_FILLER_BEFORE 0
  182807. #define PNG_FILLER_AFTER 1
  182808. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182809. #if !defined(PNG_1_0_X)
  182810. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182811. png_uint_32 filler, int flags));
  182812. #endif
  182813. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182814. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182815. /* Swap bytes in 16-bit depth files. */
  182816. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182817. #endif
  182818. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182819. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182820. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182821. #endif
  182822. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182823. /* Swap packing order of pixels in bytes. */
  182824. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182825. #endif
  182826. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182827. /* Converts files to legal bit depths. */
  182828. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182829. png_color_8p true_bits));
  182830. #endif
  182831. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182832. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182833. /* Have the code handle the interlacing. Returns the number of passes. */
  182834. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182835. #endif
  182836. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182837. /* Invert monochrome files */
  182838. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182839. #endif
  182840. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182841. /* Handle alpha and tRNS by replacing with a background color. */
  182842. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182843. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182844. png_color_16p background_color, int background_gamma_code,
  182845. int need_expand, double background_gamma));
  182846. #endif
  182847. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182848. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182849. #define PNG_BACKGROUND_GAMMA_FILE 2
  182850. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182851. #endif
  182852. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182853. /* strip the second byte of information from a 16-bit depth file. */
  182854. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182855. #endif
  182856. #if defined(PNG_READ_DITHER_SUPPORTED)
  182857. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182858. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182859. png_colorp palette, int num_palette, int maximum_colors,
  182860. png_uint_16p histogram, int full_dither));
  182861. #endif
  182862. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182863. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182864. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182865. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182866. double screen_gamma, double default_file_gamma));
  182867. #endif
  182868. #endif
  182869. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182870. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182871. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182872. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182873. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182874. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182875. int empty_plte_permitted));
  182876. #endif
  182877. #endif
  182878. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182879. /* Set how many lines between output flushes - 0 for no flushing */
  182880. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182881. /* Flush the current PNG output buffer */
  182882. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182883. #endif
  182884. /* optional update palette with requested transformations */
  182885. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182886. /* optional call to update the users info structure */
  182887. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182888. png_infop info_ptr));
  182889. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182890. /* read one or more rows of image data. */
  182891. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182892. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182893. #endif
  182894. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182895. /* read a row of data. */
  182896. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182897. png_bytep row,
  182898. png_bytep display_row));
  182899. #endif
  182900. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182901. /* read the whole image into memory at once. */
  182902. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182903. png_bytepp image));
  182904. #endif
  182905. /* write a row of image data */
  182906. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182907. png_bytep row));
  182908. /* write a few rows of image data */
  182909. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182910. png_bytepp row, png_uint_32 num_rows));
  182911. /* write the image data */
  182912. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182913. png_bytepp image));
  182914. /* writes the end of the PNG file. */
  182915. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182916. png_infop info_ptr));
  182917. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182918. /* read the end of the PNG file. */
  182919. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182920. png_infop info_ptr));
  182921. #endif
  182922. /* free any memory associated with the png_info_struct */
  182923. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182924. png_infopp info_ptr_ptr));
  182925. /* free any memory associated with the png_struct and the png_info_structs */
  182926. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182927. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182928. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182929. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182930. png_infop end_info_ptr));
  182931. /* free any memory associated with the png_struct and the png_info_structs */
  182932. extern PNG_EXPORT(void,png_destroy_write_struct)
  182933. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182934. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182935. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182936. /* set the libpng method of handling chunk CRC errors */
  182937. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182938. int crit_action, int ancil_action));
  182939. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182940. * ancillary and critical chunks, and whether to use the data contained
  182941. * therein. Note that it is impossible to "discard" data in a critical
  182942. * chunk. For versions prior to 0.90, the action was always error/quit,
  182943. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182944. * chunks is warn/discard. These values should NOT be changed.
  182945. *
  182946. * value action:critical action:ancillary
  182947. */
  182948. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182949. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182950. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182951. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182952. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182953. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182954. /* These functions give the user control over the scan-line filtering in
  182955. * libpng and the compression methods used by zlib. These functions are
  182956. * mainly useful for testing, as the defaults should work with most users.
  182957. * Those users who are tight on memory or want faster performance at the
  182958. * expense of compression can modify them. See the compression library
  182959. * header file (zlib.h) for an explination of the compression functions.
  182960. */
  182961. /* set the filtering method(s) used by libpng. Currently, the only valid
  182962. * value for "method" is 0.
  182963. */
  182964. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182965. int filters));
  182966. /* Flags for png_set_filter() to say which filters to use. The flags
  182967. * are chosen so that they don't conflict with real filter types
  182968. * below, in case they are supplied instead of the #defined constants.
  182969. * These values should NOT be changed.
  182970. */
  182971. #define PNG_NO_FILTERS 0x00
  182972. #define PNG_FILTER_NONE 0x08
  182973. #define PNG_FILTER_SUB 0x10
  182974. #define PNG_FILTER_UP 0x20
  182975. #define PNG_FILTER_AVG 0x40
  182976. #define PNG_FILTER_PAETH 0x80
  182977. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182978. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182979. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182980. * These defines should NOT be changed.
  182981. */
  182982. #define PNG_FILTER_VALUE_NONE 0
  182983. #define PNG_FILTER_VALUE_SUB 1
  182984. #define PNG_FILTER_VALUE_UP 2
  182985. #define PNG_FILTER_VALUE_AVG 3
  182986. #define PNG_FILTER_VALUE_PAETH 4
  182987. #define PNG_FILTER_VALUE_LAST 5
  182988. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182989. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182990. * defines, either the default (minimum-sum-of-absolute-differences), or
  182991. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182992. *
  182993. * Weights are factors >= 1.0, indicating how important it is to keep the
  182994. * filter type consistent between rows. Larger numbers mean the current
  182995. * filter is that many times as likely to be the same as the "num_weights"
  182996. * previous filters. This is cumulative for each previous row with a weight.
  182997. * There needs to be "num_weights" values in "filter_weights", or it can be
  182998. * NULL if the weights aren't being specified. Weights have no influence on
  182999. * the selection of the first row filter. Well chosen weights can (in theory)
  183000. * improve the compression for a given image.
  183001. *
  183002. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183003. * filter type. Higher costs indicate more decoding expense, and are
  183004. * therefore less likely to be selected over a filter with lower computational
  183005. * costs. There needs to be a value in "filter_costs" for each valid filter
  183006. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183007. * setting the costs. Costs try to improve the speed of decompression without
  183008. * unduly increasing the compressed image size.
  183009. *
  183010. * A negative weight or cost indicates the default value is to be used, and
  183011. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183012. * The default values for both weights and costs are currently 1.0, but may
  183013. * change if good general weighting/cost heuristics can be found. If both
  183014. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183015. * to the UNWEIGHTED method, but with added encoding time/computation.
  183016. */
  183017. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183018. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183019. int heuristic_method, int num_weights, png_doublep filter_weights,
  183020. png_doublep filter_costs));
  183021. #endif
  183022. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183023. /* Heuristic used for row filter selection. These defines should NOT be
  183024. * changed.
  183025. */
  183026. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183027. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183028. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183029. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183030. /* Set the library compression level. Currently, valid values range from
  183031. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183032. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183033. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183034. * for PNG images, and do considerably fewer caclulations. In the future,
  183035. * these values may not correspond directly to the zlib compression levels.
  183036. */
  183037. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183038. int level));
  183039. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183040. PNGARG((png_structp png_ptr, int mem_level));
  183041. extern PNG_EXPORT(void,png_set_compression_strategy)
  183042. PNGARG((png_structp png_ptr, int strategy));
  183043. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183044. PNGARG((png_structp png_ptr, int window_bits));
  183045. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183046. int method));
  183047. /* These next functions are called for input/output, memory, and error
  183048. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183049. * and call standard C I/O routines such as fread(), fwrite(), and
  183050. * fprintf(). These functions can be made to use other I/O routines
  183051. * at run time for those applications that need to handle I/O in a
  183052. * different manner by calling png_set_???_fn(). See libpng.txt for
  183053. * more information.
  183054. */
  183055. #if !defined(PNG_NO_STDIO)
  183056. /* Initialize the input/output for the PNG file to the default functions. */
  183057. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183058. #endif
  183059. /* Replace the (error and abort), and warning functions with user
  183060. * supplied functions. If no messages are to be printed you must still
  183061. * write and use replacement functions. The replacement error_fn should
  183062. * still do a longjmp to the last setjmp location if you are using this
  183063. * method of error handling. If error_fn or warning_fn is NULL, the
  183064. * default function will be used.
  183065. */
  183066. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183067. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183068. /* Return the user pointer associated with the error functions */
  183069. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183070. /* Replace the default data output functions with a user supplied one(s).
  183071. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183072. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183073. * output_flush_fn will be ignored (and thus can be NULL).
  183074. */
  183075. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183076. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183077. /* Replace the default data input function with a user supplied one. */
  183078. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183079. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183080. /* Return the user pointer associated with the I/O functions */
  183081. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183082. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183083. png_read_status_ptr read_row_fn));
  183084. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183085. png_write_status_ptr write_row_fn));
  183086. #ifdef PNG_USER_MEM_SUPPORTED
  183087. /* Replace the default memory allocation functions with user supplied one(s). */
  183088. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183089. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183090. /* Return the user pointer associated with the memory functions */
  183091. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183092. #endif
  183093. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183094. defined(PNG_LEGACY_SUPPORTED)
  183095. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183096. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183097. #endif
  183098. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183099. defined(PNG_LEGACY_SUPPORTED)
  183100. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183101. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183102. #endif
  183103. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183104. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183105. defined(PNG_LEGACY_SUPPORTED)
  183106. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183107. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183108. int user_transform_channels));
  183109. /* Return the user pointer associated with the user transform functions */
  183110. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183111. PNGARG((png_structp png_ptr));
  183112. #endif
  183113. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183114. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183115. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183116. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183117. png_ptr));
  183118. #endif
  183119. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183120. /* Sets the function callbacks for the push reader, and a pointer to a
  183121. * user-defined structure available to the callback functions.
  183122. */
  183123. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183124. png_voidp progressive_ptr,
  183125. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183126. png_progressive_end_ptr end_fn));
  183127. /* returns the user pointer associated with the push read functions */
  183128. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183129. PNGARG((png_structp png_ptr));
  183130. /* function to be called when data becomes available */
  183131. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183132. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183133. /* function that combines rows. Not very much different than the
  183134. * png_combine_row() call. Is this even used?????
  183135. */
  183136. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183137. png_bytep old_row, png_bytep new_row));
  183138. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183139. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183140. png_uint_32 size));
  183141. #if defined(PNG_1_0_X)
  183142. # define png_malloc_warn png_malloc
  183143. #else
  183144. /* Added at libpng version 1.2.4 */
  183145. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183146. png_uint_32 size));
  183147. #endif
  183148. /* frees a pointer allocated by png_malloc() */
  183149. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183150. #if defined(PNG_1_0_X)
  183151. /* Function to allocate memory for zlib. */
  183152. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183153. uInt size));
  183154. /* Function to free memory for zlib */
  183155. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183156. #endif
  183157. /* Free data that was allocated internally */
  183158. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183159. png_infop info_ptr, png_uint_32 free_me, int num));
  183160. #ifdef PNG_FREE_ME_SUPPORTED
  183161. /* Reassign responsibility for freeing existing data, whether allocated
  183162. * by libpng or by the application */
  183163. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183164. png_infop info_ptr, int freer, png_uint_32 mask));
  183165. #endif
  183166. /* assignments for png_data_freer */
  183167. #define PNG_DESTROY_WILL_FREE_DATA 1
  183168. #define PNG_SET_WILL_FREE_DATA 1
  183169. #define PNG_USER_WILL_FREE_DATA 2
  183170. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183171. #define PNG_FREE_HIST 0x0008
  183172. #define PNG_FREE_ICCP 0x0010
  183173. #define PNG_FREE_SPLT 0x0020
  183174. #define PNG_FREE_ROWS 0x0040
  183175. #define PNG_FREE_PCAL 0x0080
  183176. #define PNG_FREE_SCAL 0x0100
  183177. #define PNG_FREE_UNKN 0x0200
  183178. #define PNG_FREE_LIST 0x0400
  183179. #define PNG_FREE_PLTE 0x1000
  183180. #define PNG_FREE_TRNS 0x2000
  183181. #define PNG_FREE_TEXT 0x4000
  183182. #define PNG_FREE_ALL 0x7fff
  183183. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183184. #ifdef PNG_USER_MEM_SUPPORTED
  183185. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183186. png_uint_32 size));
  183187. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183188. png_voidp ptr));
  183189. #endif
  183190. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183191. png_voidp s1, png_voidp s2, png_uint_32 size));
  183192. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183193. png_voidp s1, int value, png_uint_32 size));
  183194. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183195. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183196. int check));
  183197. #endif /* USE_FAR_KEYWORD */
  183198. #ifndef PNG_NO_ERROR_TEXT
  183199. /* Fatal error in PNG image of libpng - can't continue */
  183200. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183201. png_const_charp error_message));
  183202. /* The same, but the chunk name is prepended to the error string. */
  183203. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183204. png_const_charp error_message));
  183205. #else
  183206. /* Fatal error in PNG image of libpng - can't continue */
  183207. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183208. #endif
  183209. #ifndef PNG_NO_WARNINGS
  183210. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183211. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183212. png_const_charp warning_message));
  183213. #ifdef PNG_READ_SUPPORTED
  183214. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183215. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183216. png_const_charp warning_message));
  183217. #endif /* PNG_READ_SUPPORTED */
  183218. #endif /* PNG_NO_WARNINGS */
  183219. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183220. * Similarly, the png_get_<chunk> calls are used to read values from the
  183221. * png_info_struct, either storing the parameters in the passed variables, or
  183222. * setting pointers into the png_info_struct where the data is stored. The
  183223. * png_get_<chunk> functions return a non-zero value if the data was available
  183224. * in info_ptr, or return zero and do not change any of the parameters if the
  183225. * data was not available.
  183226. *
  183227. * These functions should be used instead of directly accessing png_info
  183228. * to avoid problems with future changes in the size and internal layout of
  183229. * png_info_struct.
  183230. */
  183231. /* Returns "flag" if chunk data is valid in info_ptr. */
  183232. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183233. png_infop info_ptr, png_uint_32 flag));
  183234. /* Returns number of bytes needed to hold a transformed row. */
  183235. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183236. png_infop info_ptr));
  183237. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183238. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183239. returned from png_read_png(). */
  183240. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183241. png_infop info_ptr));
  183242. /* Set row_pointers, which is an array of pointers to scanlines for use
  183243. by png_write_png(). */
  183244. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183245. png_infop info_ptr, png_bytepp row_pointers));
  183246. #endif
  183247. /* Returns number of color channels in image. */
  183248. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183249. png_infop info_ptr));
  183250. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183251. /* Returns image width in pixels. */
  183252. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183253. png_ptr, png_infop info_ptr));
  183254. /* Returns image height in pixels. */
  183255. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183256. png_ptr, png_infop info_ptr));
  183257. /* Returns image bit_depth. */
  183258. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183259. png_ptr, png_infop info_ptr));
  183260. /* Returns image color_type. */
  183261. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183262. png_ptr, png_infop info_ptr));
  183263. /* Returns image filter_type. */
  183264. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183265. png_ptr, png_infop info_ptr));
  183266. /* Returns image interlace_type. */
  183267. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183268. png_ptr, png_infop info_ptr));
  183269. /* Returns image compression_type. */
  183270. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183271. png_ptr, png_infop info_ptr));
  183272. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183273. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183274. png_ptr, png_infop info_ptr));
  183275. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183276. png_ptr, png_infop info_ptr));
  183277. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183278. png_ptr, png_infop info_ptr));
  183279. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183280. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183281. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183282. png_ptr, png_infop info_ptr));
  183283. #endif
  183284. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183285. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183286. png_ptr, png_infop info_ptr));
  183287. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183288. png_ptr, png_infop info_ptr));
  183289. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183290. png_ptr, png_infop info_ptr));
  183291. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183292. png_ptr, png_infop info_ptr));
  183293. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183294. /* Returns pointer to signature string read from PNG header */
  183295. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183296. png_infop info_ptr));
  183297. #if defined(PNG_bKGD_SUPPORTED)
  183298. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183299. png_infop info_ptr, png_color_16p *background));
  183300. #endif
  183301. #if defined(PNG_bKGD_SUPPORTED)
  183302. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183303. png_infop info_ptr, png_color_16p background));
  183304. #endif
  183305. #if defined(PNG_cHRM_SUPPORTED)
  183306. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183307. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183308. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183309. double *red_y, double *green_x, double *green_y, double *blue_x,
  183310. double *blue_y));
  183311. #endif
  183312. #ifdef PNG_FIXED_POINT_SUPPORTED
  183313. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183314. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183315. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183316. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183317. *int_blue_x, png_fixed_point *int_blue_y));
  183318. #endif
  183319. #endif
  183320. #if defined(PNG_cHRM_SUPPORTED)
  183321. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183322. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183323. png_infop info_ptr, double white_x, double white_y, double red_x,
  183324. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183325. #endif
  183326. #ifdef PNG_FIXED_POINT_SUPPORTED
  183327. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183328. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183329. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183330. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183331. png_fixed_point int_blue_y));
  183332. #endif
  183333. #endif
  183334. #if defined(PNG_gAMA_SUPPORTED)
  183335. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183336. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183337. png_infop info_ptr, double *file_gamma));
  183338. #endif
  183339. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183340. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183341. #endif
  183342. #if defined(PNG_gAMA_SUPPORTED)
  183343. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183344. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183345. png_infop info_ptr, double file_gamma));
  183346. #endif
  183347. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183348. png_infop info_ptr, png_fixed_point int_file_gamma));
  183349. #endif
  183350. #if defined(PNG_hIST_SUPPORTED)
  183351. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183352. png_infop info_ptr, png_uint_16p *hist));
  183353. #endif
  183354. #if defined(PNG_hIST_SUPPORTED)
  183355. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183356. png_infop info_ptr, png_uint_16p hist));
  183357. #endif
  183358. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183359. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183360. int *bit_depth, int *color_type, int *interlace_method,
  183361. int *compression_method, int *filter_method));
  183362. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183363. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183364. int color_type, int interlace_method, int compression_method,
  183365. int filter_method));
  183366. #if defined(PNG_oFFs_SUPPORTED)
  183367. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183368. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183369. int *unit_type));
  183370. #endif
  183371. #if defined(PNG_oFFs_SUPPORTED)
  183372. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183373. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183374. int unit_type));
  183375. #endif
  183376. #if defined(PNG_pCAL_SUPPORTED)
  183377. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183378. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183379. int *type, int *nparams, png_charp *units, png_charpp *params));
  183380. #endif
  183381. #if defined(PNG_pCAL_SUPPORTED)
  183382. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183383. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183384. int type, int nparams, png_charp units, png_charpp params));
  183385. #endif
  183386. #if defined(PNG_pHYs_SUPPORTED)
  183387. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183388. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183389. #endif
  183390. #if defined(PNG_pHYs_SUPPORTED)
  183391. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183392. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183393. #endif
  183394. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183395. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183396. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183397. png_infop info_ptr, png_colorp palette, int num_palette));
  183398. #if defined(PNG_sBIT_SUPPORTED)
  183399. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183400. png_infop info_ptr, png_color_8p *sig_bit));
  183401. #endif
  183402. #if defined(PNG_sBIT_SUPPORTED)
  183403. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183404. png_infop info_ptr, png_color_8p sig_bit));
  183405. #endif
  183406. #if defined(PNG_sRGB_SUPPORTED)
  183407. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183408. png_infop info_ptr, int *intent));
  183409. #endif
  183410. #if defined(PNG_sRGB_SUPPORTED)
  183411. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183412. png_infop info_ptr, int intent));
  183413. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183414. png_infop info_ptr, int intent));
  183415. #endif
  183416. #if defined(PNG_iCCP_SUPPORTED)
  183417. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183418. png_infop info_ptr, png_charpp name, int *compression_type,
  183419. png_charpp profile, png_uint_32 *proflen));
  183420. /* Note to maintainer: profile should be png_bytepp */
  183421. #endif
  183422. #if defined(PNG_iCCP_SUPPORTED)
  183423. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183424. png_infop info_ptr, png_charp name, int compression_type,
  183425. png_charp profile, png_uint_32 proflen));
  183426. /* Note to maintainer: profile should be png_bytep */
  183427. #endif
  183428. #if defined(PNG_sPLT_SUPPORTED)
  183429. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183430. png_infop info_ptr, png_sPLT_tpp entries));
  183431. #endif
  183432. #if defined(PNG_sPLT_SUPPORTED)
  183433. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183434. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183435. #endif
  183436. #if defined(PNG_TEXT_SUPPORTED)
  183437. /* png_get_text also returns the number of text chunks in *num_text */
  183438. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183439. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183440. #endif
  183441. /*
  183442. * Note while png_set_text() will accept a structure whose text,
  183443. * language, and translated keywords are NULL pointers, the structure
  183444. * returned by png_get_text will always contain regular
  183445. * zero-terminated C strings. They might be empty strings but
  183446. * they will never be NULL pointers.
  183447. */
  183448. #if defined(PNG_TEXT_SUPPORTED)
  183449. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183450. png_infop info_ptr, png_textp text_ptr, int num_text));
  183451. #endif
  183452. #if defined(PNG_tIME_SUPPORTED)
  183453. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183454. png_infop info_ptr, png_timep *mod_time));
  183455. #endif
  183456. #if defined(PNG_tIME_SUPPORTED)
  183457. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183458. png_infop info_ptr, png_timep mod_time));
  183459. #endif
  183460. #if defined(PNG_tRNS_SUPPORTED)
  183461. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183462. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183463. png_color_16p *trans_values));
  183464. #endif
  183465. #if defined(PNG_tRNS_SUPPORTED)
  183466. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183467. png_infop info_ptr, png_bytep trans, int num_trans,
  183468. png_color_16p trans_values));
  183469. #endif
  183470. #if defined(PNG_tRNS_SUPPORTED)
  183471. #endif
  183472. #if defined(PNG_sCAL_SUPPORTED)
  183473. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183474. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183475. png_infop info_ptr, int *unit, double *width, double *height));
  183476. #else
  183477. #ifdef PNG_FIXED_POINT_SUPPORTED
  183478. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183479. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183480. #endif
  183481. #endif
  183482. #endif /* PNG_sCAL_SUPPORTED */
  183483. #if defined(PNG_sCAL_SUPPORTED)
  183484. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183485. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183486. png_infop info_ptr, int unit, double width, double height));
  183487. #else
  183488. #ifdef PNG_FIXED_POINT_SUPPORTED
  183489. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183490. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183491. #endif
  183492. #endif
  183493. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183494. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183495. /* provide a list of chunks and how they are to be handled, if the built-in
  183496. handling or default unknown chunk handling is not desired. Any chunks not
  183497. listed will be handled in the default manner. The IHDR and IEND chunks
  183498. must not be listed.
  183499. keep = 0: follow default behaviour
  183500. = 1: do not keep
  183501. = 2: keep only if safe-to-copy
  183502. = 3: keep even if unsafe-to-copy
  183503. */
  183504. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183505. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183506. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183507. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183508. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183509. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183510. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183511. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183512. #endif
  183513. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183514. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183515. chunk_name));
  183516. #endif
  183517. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183518. If you need to turn it off for a chunk that your application has freed,
  183519. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183520. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183521. png_infop info_ptr, int mask));
  183522. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183523. /* The "params" pointer is currently not used and is for future expansion. */
  183524. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183525. png_infop info_ptr,
  183526. int transforms,
  183527. png_voidp params));
  183528. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183529. png_infop info_ptr,
  183530. int transforms,
  183531. png_voidp params));
  183532. #endif
  183533. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183534. * numbers for PNG_DEBUG mean more debugging information. This has
  183535. * only been added since version 0.95 so it is not implemented throughout
  183536. * libpng yet, but more support will be added as needed.
  183537. */
  183538. #ifdef PNG_DEBUG
  183539. #if (PNG_DEBUG > 0)
  183540. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183541. #include <crtdbg.h>
  183542. #if (PNG_DEBUG > 1)
  183543. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183544. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183545. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183546. #endif
  183547. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183548. #ifndef PNG_DEBUG_FILE
  183549. #define PNG_DEBUG_FILE stderr
  183550. #endif /* PNG_DEBUG_FILE */
  183551. #if (PNG_DEBUG > 1)
  183552. #define png_debug(l,m) \
  183553. { \
  183554. int num_tabs=l; \
  183555. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183556. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183557. }
  183558. #define png_debug1(l,m,p1) \
  183559. { \
  183560. int num_tabs=l; \
  183561. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183562. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183563. }
  183564. #define png_debug2(l,m,p1,p2) \
  183565. { \
  183566. int num_tabs=l; \
  183567. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183568. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183569. }
  183570. #endif /* (PNG_DEBUG > 1) */
  183571. #endif /* _MSC_VER */
  183572. #endif /* (PNG_DEBUG > 0) */
  183573. #endif /* PNG_DEBUG */
  183574. #ifndef png_debug
  183575. #define png_debug(l, m)
  183576. #endif
  183577. #ifndef png_debug1
  183578. #define png_debug1(l, m, p1)
  183579. #endif
  183580. #ifndef png_debug2
  183581. #define png_debug2(l, m, p1, p2)
  183582. #endif
  183583. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183584. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183585. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183586. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183587. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183588. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183589. png_ptr, png_uint_32 mng_features_permitted));
  183590. #endif
  183591. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183592. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183593. #define PNG_HANDLE_CHUNK_NEVER 1
  183594. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183595. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183596. /* Added to version 1.2.0 */
  183597. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183598. #if defined(PNG_MMX_CODE_SUPPORTED)
  183599. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183600. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183601. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183602. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183603. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183604. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183605. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183606. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183607. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183608. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183609. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183610. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183611. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183612. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183613. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183614. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183615. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183616. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183617. | PNG_MMX_READ_FLAGS \
  183618. | PNG_MMX_WRITE_FLAGS )
  183619. #define PNG_SELECT_READ 1
  183620. #define PNG_SELECT_WRITE 2
  183621. #endif /* PNG_MMX_CODE_SUPPORTED */
  183622. #if !defined(PNG_1_0_X)
  183623. /* pngget.c */
  183624. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183625. PNGARG((int flag_select, int *compilerID));
  183626. /* pngget.c */
  183627. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183628. PNGARG((int flag_select));
  183629. /* pngget.c */
  183630. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183631. PNGARG((png_structp png_ptr));
  183632. /* pngget.c */
  183633. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183634. PNGARG((png_structp png_ptr));
  183635. /* pngget.c */
  183636. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183637. PNGARG((png_structp png_ptr));
  183638. /* pngset.c */
  183639. extern PNG_EXPORT(void,png_set_asm_flags)
  183640. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183641. /* pngset.c */
  183642. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183643. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183644. png_uint_32 mmx_rowbytes_threshold));
  183645. #endif /* PNG_1_0_X */
  183646. #if !defined(PNG_1_0_X)
  183647. /* png.c, pnggccrd.c, or pngvcrd.c */
  183648. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183649. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183650. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183651. * messages before passing them to the error or warning handler. */
  183652. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183653. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183654. png_ptr, png_uint_32 strip_mode));
  183655. #endif
  183656. #endif /* PNG_1_0_X */
  183657. /* Added at libpng-1.2.6 */
  183658. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183659. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183660. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183661. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183662. png_ptr));
  183663. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183664. png_ptr));
  183665. #endif
  183666. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183667. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183668. /* With these routines we avoid an integer divide, which will be slower on
  183669. * most machines. However, it does take more operations than the corresponding
  183670. * divide method, so it may be slower on a few RISC systems. There are two
  183671. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183672. *
  183673. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183674. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183675. * standard method.
  183676. *
  183677. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183678. */
  183679. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183680. # define png_composite(composite, fg, alpha, bg) \
  183681. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183682. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183683. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183684. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183685. # define png_composite_16(composite, fg, alpha, bg) \
  183686. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183687. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183688. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183689. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183690. #else /* standard method using integer division */
  183691. # define png_composite(composite, fg, alpha, bg) \
  183692. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183693. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183694. (png_uint_16)127) / 255)
  183695. # define png_composite_16(composite, fg, alpha, bg) \
  183696. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183697. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183698. (png_uint_32)32767) / (png_uint_32)65535L)
  183699. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183700. /* Inline macros to do direct reads of bytes from the input buffer. These
  183701. * require that you are using an architecture that uses PNG byte ordering
  183702. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183703. * in big-endian mode and 680x0 are the only ones that will support this.
  183704. * The x86 line of processors definitely do not. The png_get_int_32()
  183705. * routine also assumes we are using two's complement format for negative
  183706. * values, which is almost certainly true.
  183707. */
  183708. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183709. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183710. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183711. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183712. #else
  183713. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183714. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183715. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183716. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183717. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183718. PNGARG((png_structp png_ptr, png_bytep buf));
  183719. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183720. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183721. */
  183722. extern PNG_EXPORT(void,png_save_uint_32)
  183723. PNGARG((png_bytep buf, png_uint_32 i));
  183724. extern PNG_EXPORT(void,png_save_int_32)
  183725. PNGARG((png_bytep buf, png_int_32 i));
  183726. /* Place a 16-bit number into a buffer in PNG byte order.
  183727. * The parameter is declared unsigned int, not png_uint_16,
  183728. * just to avoid potential problems on pre-ANSI C compilers.
  183729. */
  183730. extern PNG_EXPORT(void,png_save_uint_16)
  183731. PNGARG((png_bytep buf, unsigned int i));
  183732. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183733. /* ************************************************************************* */
  183734. /* These next functions are used internally in the code. They generally
  183735. * shouldn't be used unless you are writing code to add or replace some
  183736. * functionality in libpng. More information about most functions can
  183737. * be found in the files where the functions are located.
  183738. */
  183739. /* Various modes of operation, that are visible to applications because
  183740. * they are used for unknown chunk location.
  183741. */
  183742. #define PNG_HAVE_IHDR 0x01
  183743. #define PNG_HAVE_PLTE 0x02
  183744. #define PNG_HAVE_IDAT 0x04
  183745. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183746. #define PNG_HAVE_IEND 0x10
  183747. #if defined(PNG_INTERNAL)
  183748. /* More modes of operation. Note that after an init, mode is set to
  183749. * zero automatically when the structure is created.
  183750. */
  183751. #define PNG_HAVE_gAMA 0x20
  183752. #define PNG_HAVE_cHRM 0x40
  183753. #define PNG_HAVE_sRGB 0x80
  183754. #define PNG_HAVE_CHUNK_HEADER 0x100
  183755. #define PNG_WROTE_tIME 0x200
  183756. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183757. #define PNG_BACKGROUND_IS_GRAY 0x800
  183758. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183759. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183760. /* flags for the transformations the PNG library does on the image data */
  183761. #define PNG_BGR 0x0001
  183762. #define PNG_INTERLACE 0x0002
  183763. #define PNG_PACK 0x0004
  183764. #define PNG_SHIFT 0x0008
  183765. #define PNG_SWAP_BYTES 0x0010
  183766. #define PNG_INVERT_MONO 0x0020
  183767. #define PNG_DITHER 0x0040
  183768. #define PNG_BACKGROUND 0x0080
  183769. #define PNG_BACKGROUND_EXPAND 0x0100
  183770. /* 0x0200 unused */
  183771. #define PNG_16_TO_8 0x0400
  183772. #define PNG_RGBA 0x0800
  183773. #define PNG_EXPAND 0x1000
  183774. #define PNG_GAMMA 0x2000
  183775. #define PNG_GRAY_TO_RGB 0x4000
  183776. #define PNG_FILLER 0x8000L
  183777. #define PNG_PACKSWAP 0x10000L
  183778. #define PNG_SWAP_ALPHA 0x20000L
  183779. #define PNG_STRIP_ALPHA 0x40000L
  183780. #define PNG_INVERT_ALPHA 0x80000L
  183781. #define PNG_USER_TRANSFORM 0x100000L
  183782. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183783. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183784. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183785. /* 0x800000L Unused */
  183786. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183787. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183788. /* 0x4000000L unused */
  183789. /* 0x8000000L unused */
  183790. /* 0x10000000L unused */
  183791. /* 0x20000000L unused */
  183792. /* 0x40000000L unused */
  183793. /* flags for png_create_struct */
  183794. #define PNG_STRUCT_PNG 0x0001
  183795. #define PNG_STRUCT_INFO 0x0002
  183796. /* Scaling factor for filter heuristic weighting calculations */
  183797. #define PNG_WEIGHT_SHIFT 8
  183798. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183799. #define PNG_COST_SHIFT 3
  183800. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183801. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183802. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183803. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183804. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183805. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183806. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183807. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183808. #define PNG_FLAG_ROW_INIT 0x0040
  183809. #define PNG_FLAG_FILLER_AFTER 0x0080
  183810. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183811. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183812. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183813. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183814. #define PNG_FLAG_FREE_PLTE 0x1000
  183815. #define PNG_FLAG_FREE_TRNS 0x2000
  183816. #define PNG_FLAG_FREE_HIST 0x4000
  183817. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183818. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183819. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183820. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183821. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183822. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183823. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183824. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183825. /* 0x800000L unused */
  183826. /* 0x1000000L unused */
  183827. /* 0x2000000L unused */
  183828. /* 0x4000000L unused */
  183829. /* 0x8000000L unused */
  183830. /* 0x10000000L unused */
  183831. /* 0x20000000L unused */
  183832. /* 0x40000000L unused */
  183833. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183834. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183835. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183836. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183837. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183838. PNG_FLAG_CRC_CRITICAL_MASK)
  183839. /* save typing and make code easier to understand */
  183840. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183841. abs((int)((c1).green) - (int)((c2).green)) + \
  183842. abs((int)((c1).blue) - (int)((c2).blue)))
  183843. /* Added to libpng-1.2.6 JB */
  183844. #define PNG_ROWBYTES(pixel_bits, width) \
  183845. ((pixel_bits) >= 8 ? \
  183846. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183847. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183848. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183849. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183850. "ideal" and "delta" should be constants, normally simple
  183851. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183852. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183853. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183854. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183855. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183856. /* place to hold the signature string for a PNG file. */
  183857. #ifdef PNG_USE_GLOBAL_ARRAYS
  183858. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183859. #else
  183860. #endif
  183861. #endif /* PNG_NO_EXTERN */
  183862. /* Constant strings for known chunk types. If you need to add a chunk,
  183863. * define the name here, and add an invocation of the macro in png.c and
  183864. * wherever it's needed.
  183865. */
  183866. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183867. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183868. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183869. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183870. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183871. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183872. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183873. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183874. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183875. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183876. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183877. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183878. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183879. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183880. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183881. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183882. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183883. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183884. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183885. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183886. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183887. #ifdef PNG_USE_GLOBAL_ARRAYS
  183888. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183889. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183890. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183891. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183892. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183893. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183894. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183895. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183896. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183897. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183898. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183899. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183900. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183901. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183902. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183903. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183904. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183905. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183906. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183907. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183908. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183909. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183910. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183911. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183912. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183913. */
  183914. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183915. #undef png_read_init
  183916. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183917. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183918. #endif
  183919. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183920. png_const_charp user_png_ver, png_size_t png_struct_size));
  183921. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183922. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183923. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183924. png_info_size));
  183925. #endif
  183926. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183927. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183928. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183929. */
  183930. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183931. #undef png_write_init
  183932. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183933. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183934. #endif
  183935. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183936. png_const_charp user_png_ver, png_size_t png_struct_size));
  183937. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183938. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183939. png_info_size));
  183940. /* Allocate memory for an internal libpng struct */
  183941. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183942. /* Free memory from internal libpng struct */
  183943. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183944. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183945. malloc_fn, png_voidp mem_ptr));
  183946. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183947. png_free_ptr free_fn, png_voidp mem_ptr));
  183948. /* Free any memory that info_ptr points to and reset struct. */
  183949. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183950. png_infop info_ptr));
  183951. #ifndef PNG_1_0_X
  183952. /* Function to allocate memory for zlib. */
  183953. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183954. /* Function to free memory for zlib */
  183955. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183956. #ifdef PNG_SIZE_T
  183957. /* Function to convert a sizeof an item to png_sizeof item */
  183958. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183959. #endif
  183960. /* Next four functions are used internally as callbacks. PNGAPI is required
  183961. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183962. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183963. png_bytep data, png_size_t length));
  183964. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183965. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183966. png_bytep buffer, png_size_t length));
  183967. #endif
  183968. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183969. png_bytep data, png_size_t length));
  183970. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183971. #if !defined(PNG_NO_STDIO)
  183972. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183973. #endif
  183974. #endif
  183975. #else /* PNG_1_0_X */
  183976. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183977. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183978. png_bytep buffer, png_size_t length));
  183979. #endif
  183980. #endif /* PNG_1_0_X */
  183981. /* Reset the CRC variable */
  183982. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183983. /* Write the "data" buffer to whatever output you are using. */
  183984. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183985. png_size_t length));
  183986. /* Read data from whatever input you are using into the "data" buffer */
  183987. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183988. png_size_t length));
  183989. /* Read bytes into buf, and update png_ptr->crc */
  183990. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183991. png_size_t length));
  183992. /* Decompress data in a chunk that uses compression */
  183993. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183994. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183995. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183996. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183997. png_size_t prefix_length, png_size_t *data_length));
  183998. #endif
  183999. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184000. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184001. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184002. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184003. /* Calculate the CRC over a section of data. Note that we are only
  184004. * passing a maximum of 64K on systems that have this as a memory limit,
  184005. * since this is the maximum buffer size we can specify.
  184006. */
  184007. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184008. png_size_t length));
  184009. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184010. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184011. #endif
  184012. /* simple function to write the signature */
  184013. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184014. /* write various chunks */
  184015. /* Write the IHDR chunk, and update the png_struct with the necessary
  184016. * information.
  184017. */
  184018. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184019. png_uint_32 height,
  184020. int bit_depth, int color_type, int compression_method, int filter_method,
  184021. int interlace_method));
  184022. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184023. png_uint_32 num_pal));
  184024. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184025. png_size_t length));
  184026. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184027. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184028. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184029. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184030. #endif
  184031. #ifdef PNG_FIXED_POINT_SUPPORTED
  184032. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184033. file_gamma));
  184034. #endif
  184035. #endif
  184036. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184037. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184038. int color_type));
  184039. #endif
  184040. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184041. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184042. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184043. double white_x, double white_y,
  184044. double red_x, double red_y, double green_x, double green_y,
  184045. double blue_x, double blue_y));
  184046. #endif
  184047. #ifdef PNG_FIXED_POINT_SUPPORTED
  184048. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184049. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184050. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184051. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184052. png_fixed_point int_blue_y));
  184053. #endif
  184054. #endif
  184055. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184056. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184057. int intent));
  184058. #endif
  184059. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184060. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184061. png_charp name, int compression_type,
  184062. png_charp profile, int proflen));
  184063. /* Note to maintainer: profile should be png_bytep */
  184064. #endif
  184065. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184066. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184067. png_sPLT_tp palette));
  184068. #endif
  184069. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184070. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184071. png_color_16p values, int number, int color_type));
  184072. #endif
  184073. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184074. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184075. png_color_16p values, int color_type));
  184076. #endif
  184077. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184078. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184079. int num_hist));
  184080. #endif
  184081. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184082. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184083. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184084. png_charp key, png_charpp new_key));
  184085. #endif
  184086. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184087. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184088. png_charp text, png_size_t text_len));
  184089. #endif
  184090. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184091. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184092. png_charp text, png_size_t text_len, int compression));
  184093. #endif
  184094. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184095. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184096. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184097. png_charp text));
  184098. #endif
  184099. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184100. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184101. png_infop info_ptr, png_textp text_ptr, int num_text));
  184102. #endif
  184103. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184104. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184105. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184106. #endif
  184107. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184108. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184109. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184110. png_charp units, png_charpp params));
  184111. #endif
  184112. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184113. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184114. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184115. int unit_type));
  184116. #endif
  184117. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184118. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184119. png_timep mod_time));
  184120. #endif
  184121. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184122. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184123. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184124. int unit, double width, double height));
  184125. #else
  184126. #ifdef PNG_FIXED_POINT_SUPPORTED
  184127. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184128. int unit, png_charp width, png_charp height));
  184129. #endif
  184130. #endif
  184131. #endif
  184132. /* Called when finished processing a row of data */
  184133. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184134. /* Internal use only. Called before first row of data */
  184135. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184136. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184137. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184138. #endif
  184139. /* combine a row of data, dealing with alpha, etc. if requested */
  184140. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184141. int mask));
  184142. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184143. /* expand an interlaced row */
  184144. /* OLD pre-1.0.9 interface:
  184145. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184146. png_bytep row, int pass, png_uint_32 transformations));
  184147. */
  184148. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184149. #endif
  184150. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184151. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184152. /* grab pixels out of a row for an interlaced pass */
  184153. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184154. png_bytep row, int pass));
  184155. #endif
  184156. /* unfilter a row */
  184157. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184158. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184159. /* Choose the best filter to use and filter the row data */
  184160. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184161. png_row_infop row_info));
  184162. /* Write out the filtered row. */
  184163. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184164. png_bytep filtered_row));
  184165. /* finish a row while reading, dealing with interlacing passes, etc. */
  184166. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184167. /* initialize the row buffers, etc. */
  184168. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184169. /* optional call to update the users info structure */
  184170. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184171. png_infop info_ptr));
  184172. /* these are the functions that do the transformations */
  184173. #if defined(PNG_READ_FILLER_SUPPORTED)
  184174. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184175. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184176. #endif
  184177. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184178. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184179. png_bytep row));
  184180. #endif
  184181. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184182. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184183. png_bytep row));
  184184. #endif
  184185. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184186. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184187. png_bytep row));
  184188. #endif
  184189. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184190. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184191. png_bytep row));
  184192. #endif
  184193. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184194. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184195. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184196. png_bytep row, png_uint_32 flags));
  184197. #endif
  184198. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184199. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184200. #endif
  184201. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184202. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184203. #endif
  184204. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184205. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184206. row_info, png_bytep row));
  184207. #endif
  184208. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184209. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184210. png_bytep row));
  184211. #endif
  184212. #if defined(PNG_READ_PACK_SUPPORTED)
  184213. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184214. #endif
  184215. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184216. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184217. png_color_8p sig_bits));
  184218. #endif
  184219. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184220. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184221. #endif
  184222. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184223. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184224. #endif
  184225. #if defined(PNG_READ_DITHER_SUPPORTED)
  184226. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184227. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184228. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184229. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184230. png_colorp palette, int num_palette));
  184231. # endif
  184232. #endif
  184233. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184234. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184235. #endif
  184236. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184237. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184238. png_bytep row, png_uint_32 bit_depth));
  184239. #endif
  184240. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184241. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184242. png_color_8p bit_depth));
  184243. #endif
  184244. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184245. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184246. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184247. png_color_16p trans_values, png_color_16p background,
  184248. png_color_16p background_1,
  184249. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184250. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184251. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184252. #else
  184253. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184254. png_color_16p trans_values, png_color_16p background));
  184255. #endif
  184256. #endif
  184257. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184258. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184259. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184260. int gamma_shift));
  184261. #endif
  184262. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184263. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184264. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184265. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184266. png_bytep row, png_color_16p trans_value));
  184267. #endif
  184268. /* The following decodes the appropriate chunks, and does error correction,
  184269. * then calls the appropriate callback for the chunk if it is valid.
  184270. */
  184271. /* decode the IHDR chunk */
  184272. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184273. png_uint_32 length));
  184274. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184275. png_uint_32 length));
  184276. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184277. png_uint_32 length));
  184278. #if defined(PNG_READ_bKGD_SUPPORTED)
  184279. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184280. png_uint_32 length));
  184281. #endif
  184282. #if defined(PNG_READ_cHRM_SUPPORTED)
  184283. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184284. png_uint_32 length));
  184285. #endif
  184286. #if defined(PNG_READ_gAMA_SUPPORTED)
  184287. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184288. png_uint_32 length));
  184289. #endif
  184290. #if defined(PNG_READ_hIST_SUPPORTED)
  184291. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184292. png_uint_32 length));
  184293. #endif
  184294. #if defined(PNG_READ_iCCP_SUPPORTED)
  184295. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184296. png_uint_32 length));
  184297. #endif /* PNG_READ_iCCP_SUPPORTED */
  184298. #if defined(PNG_READ_iTXt_SUPPORTED)
  184299. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184300. png_uint_32 length));
  184301. #endif
  184302. #if defined(PNG_READ_oFFs_SUPPORTED)
  184303. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184304. png_uint_32 length));
  184305. #endif
  184306. #if defined(PNG_READ_pCAL_SUPPORTED)
  184307. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184308. png_uint_32 length));
  184309. #endif
  184310. #if defined(PNG_READ_pHYs_SUPPORTED)
  184311. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184312. png_uint_32 length));
  184313. #endif
  184314. #if defined(PNG_READ_sBIT_SUPPORTED)
  184315. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184316. png_uint_32 length));
  184317. #endif
  184318. #if defined(PNG_READ_sCAL_SUPPORTED)
  184319. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184320. png_uint_32 length));
  184321. #endif
  184322. #if defined(PNG_READ_sPLT_SUPPORTED)
  184323. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184324. png_uint_32 length));
  184325. #endif /* PNG_READ_sPLT_SUPPORTED */
  184326. #if defined(PNG_READ_sRGB_SUPPORTED)
  184327. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184328. png_uint_32 length));
  184329. #endif
  184330. #if defined(PNG_READ_tEXt_SUPPORTED)
  184331. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184332. png_uint_32 length));
  184333. #endif
  184334. #if defined(PNG_READ_tIME_SUPPORTED)
  184335. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184336. png_uint_32 length));
  184337. #endif
  184338. #if defined(PNG_READ_tRNS_SUPPORTED)
  184339. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184340. png_uint_32 length));
  184341. #endif
  184342. #if defined(PNG_READ_zTXt_SUPPORTED)
  184343. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184344. png_uint_32 length));
  184345. #endif
  184346. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184347. png_infop info_ptr, png_uint_32 length));
  184348. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184349. png_bytep chunk_name));
  184350. /* handle the transformations for reading and writing */
  184351. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184352. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184353. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184354. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184355. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184356. png_infop info_ptr));
  184357. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184358. png_infop info_ptr));
  184359. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184360. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184361. png_uint_32 length));
  184362. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184363. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184364. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184365. png_bytep buffer, png_size_t buffer_length));
  184366. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184367. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184368. png_bytep buffer, png_size_t buffer_length));
  184369. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184370. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184371. png_infop info_ptr, png_uint_32 length));
  184372. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184373. png_infop info_ptr));
  184374. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184375. png_infop info_ptr));
  184376. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184377. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184378. png_infop info_ptr));
  184379. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184380. png_infop info_ptr));
  184381. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184382. #if defined(PNG_READ_tEXt_SUPPORTED)
  184383. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184384. png_infop info_ptr, png_uint_32 length));
  184385. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184386. png_infop info_ptr));
  184387. #endif
  184388. #if defined(PNG_READ_zTXt_SUPPORTED)
  184389. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184390. png_infop info_ptr, png_uint_32 length));
  184391. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184392. png_infop info_ptr));
  184393. #endif
  184394. #if defined(PNG_READ_iTXt_SUPPORTED)
  184395. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184396. png_infop info_ptr, png_uint_32 length));
  184397. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184398. png_infop info_ptr));
  184399. #endif
  184400. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184401. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184402. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184403. png_bytep row));
  184404. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184405. png_bytep row));
  184406. #endif
  184407. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184408. #if defined(PNG_MMX_CODE_SUPPORTED)
  184409. /* png.c */ /* PRIVATE */
  184410. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184411. #endif
  184412. #endif
  184413. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184414. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184415. png_infop info_ptr));
  184416. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184417. png_infop info_ptr));
  184418. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184419. png_infop info_ptr));
  184420. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184421. png_infop info_ptr));
  184422. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184423. png_infop info_ptr));
  184424. #if defined(PNG_pHYs_SUPPORTED)
  184425. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184426. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184427. #endif /* PNG_pHYs_SUPPORTED */
  184428. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184429. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184430. #endif /* PNG_INTERNAL */
  184431. #ifdef __cplusplus
  184432. //}
  184433. #endif
  184434. #endif /* PNG_VERSION_INFO_ONLY */
  184435. /* do not put anything past this line */
  184436. #endif /* PNG_H */
  184437. /*** End of inlined file: png.h ***/
  184438. #define PNG_NO_EXTERN
  184439. /*** Start of inlined file: png.c ***/
  184440. /* png.c - location for general purpose libpng functions
  184441. *
  184442. * Last changed in libpng 1.2.21 [October 4, 2007]
  184443. * For conditions of distribution and use, see copyright notice in png.h
  184444. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184445. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184446. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184447. */
  184448. #define PNG_INTERNAL
  184449. #define PNG_NO_EXTERN
  184450. /* Generate a compiler error if there is an old png.h in the search path. */
  184451. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184452. /* Version information for C files. This had better match the version
  184453. * string defined in png.h. */
  184454. #ifdef PNG_USE_GLOBAL_ARRAYS
  184455. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184456. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184457. #ifdef PNG_READ_SUPPORTED
  184458. /* png_sig was changed to a function in version 1.0.5c */
  184459. /* Place to hold the signature string for a PNG file. */
  184460. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184461. #endif /* PNG_READ_SUPPORTED */
  184462. /* Invoke global declarations for constant strings for known chunk types */
  184463. PNG_IHDR;
  184464. PNG_IDAT;
  184465. PNG_IEND;
  184466. PNG_PLTE;
  184467. PNG_bKGD;
  184468. PNG_cHRM;
  184469. PNG_gAMA;
  184470. PNG_hIST;
  184471. PNG_iCCP;
  184472. PNG_iTXt;
  184473. PNG_oFFs;
  184474. PNG_pCAL;
  184475. PNG_sCAL;
  184476. PNG_pHYs;
  184477. PNG_sBIT;
  184478. PNG_sPLT;
  184479. PNG_sRGB;
  184480. PNG_tEXt;
  184481. PNG_tIME;
  184482. PNG_tRNS;
  184483. PNG_zTXt;
  184484. #ifdef PNG_READ_SUPPORTED
  184485. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184486. /* start of interlace block */
  184487. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184488. /* offset to next interlace block */
  184489. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184490. /* start of interlace block in the y direction */
  184491. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184492. /* offset to next interlace block in the y direction */
  184493. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184494. /* Height of interlace block. This is not currently used - if you need
  184495. * it, uncomment it here and in png.h
  184496. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184497. */
  184498. /* Mask to determine which pixels are valid in a pass */
  184499. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184500. /* Mask to determine which pixels to overwrite while displaying */
  184501. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184502. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184503. #endif /* PNG_READ_SUPPORTED */
  184504. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184505. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184506. * of the PNG file signature. If the PNG data is embedded into another
  184507. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184508. * or write any of the magic bytes before it starts on the IHDR.
  184509. */
  184510. #ifdef PNG_READ_SUPPORTED
  184511. void PNGAPI
  184512. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184513. {
  184514. if(png_ptr == NULL) return;
  184515. png_debug(1, "in png_set_sig_bytes\n");
  184516. if (num_bytes > 8)
  184517. png_error(png_ptr, "Too many bytes for PNG signature.");
  184518. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184519. }
  184520. /* Checks whether the supplied bytes match the PNG signature. We allow
  184521. * checking less than the full 8-byte signature so that those apps that
  184522. * already read the first few bytes of a file to determine the file type
  184523. * can simply check the remaining bytes for extra assurance. Returns
  184524. * an integer less than, equal to, or greater than zero if sig is found,
  184525. * respectively, to be less than, to match, or be greater than the correct
  184526. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184527. */
  184528. int PNGAPI
  184529. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184530. {
  184531. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184532. if (num_to_check > 8)
  184533. num_to_check = 8;
  184534. else if (num_to_check < 1)
  184535. return (-1);
  184536. if (start > 7)
  184537. return (-1);
  184538. if (start + num_to_check > 8)
  184539. num_to_check = 8 - start;
  184540. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184541. }
  184542. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184543. /* (Obsolete) function to check signature bytes. It does not allow one
  184544. * to check a partial signature. This function might be removed in the
  184545. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184546. */
  184547. int PNGAPI
  184548. png_check_sig(png_bytep sig, int num)
  184549. {
  184550. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184551. }
  184552. #endif
  184553. #endif /* PNG_READ_SUPPORTED */
  184554. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184555. /* Function to allocate memory for zlib and clear it to 0. */
  184556. #ifdef PNG_1_0_X
  184557. voidpf PNGAPI
  184558. #else
  184559. voidpf /* private */
  184560. #endif
  184561. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184562. {
  184563. png_voidp ptr;
  184564. png_structp p=(png_structp)png_ptr;
  184565. png_uint_32 save_flags=p->flags;
  184566. png_uint_32 num_bytes;
  184567. if(png_ptr == NULL) return (NULL);
  184568. if (items > PNG_UINT_32_MAX/size)
  184569. {
  184570. png_warning (p, "Potential overflow in png_zalloc()");
  184571. return (NULL);
  184572. }
  184573. num_bytes = (png_uint_32)items * size;
  184574. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184575. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184576. p->flags=save_flags;
  184577. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184578. if (ptr == NULL)
  184579. return ((voidpf)ptr);
  184580. if (num_bytes > (png_uint_32)0x8000L)
  184581. {
  184582. png_memset(ptr, 0, (png_size_t)0x8000L);
  184583. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184584. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184585. }
  184586. else
  184587. {
  184588. png_memset(ptr, 0, (png_size_t)num_bytes);
  184589. }
  184590. #endif
  184591. return ((voidpf)ptr);
  184592. }
  184593. /* function to free memory for zlib */
  184594. #ifdef PNG_1_0_X
  184595. void PNGAPI
  184596. #else
  184597. void /* private */
  184598. #endif
  184599. png_zfree(voidpf png_ptr, voidpf ptr)
  184600. {
  184601. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184602. }
  184603. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184604. * in case CRC is > 32 bits to leave the top bits 0.
  184605. */
  184606. void /* PRIVATE */
  184607. png_reset_crc(png_structp png_ptr)
  184608. {
  184609. png_ptr->crc = crc32(0, Z_NULL, 0);
  184610. }
  184611. /* Calculate the CRC over a section of data. We can only pass as
  184612. * much data to this routine as the largest single buffer size. We
  184613. * also check that this data will actually be used before going to the
  184614. * trouble of calculating it.
  184615. */
  184616. void /* PRIVATE */
  184617. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184618. {
  184619. int need_crc = 1;
  184620. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184621. {
  184622. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184623. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184624. need_crc = 0;
  184625. }
  184626. else /* critical */
  184627. {
  184628. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184629. need_crc = 0;
  184630. }
  184631. if (need_crc)
  184632. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184633. }
  184634. /* Allocate the memory for an info_struct for the application. We don't
  184635. * really need the png_ptr, but it could potentially be useful in the
  184636. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184637. * and png_info_init() so that applications that want to use a shared
  184638. * libpng don't have to be recompiled if png_info changes size.
  184639. */
  184640. png_infop PNGAPI
  184641. png_create_info_struct(png_structp png_ptr)
  184642. {
  184643. png_infop info_ptr;
  184644. png_debug(1, "in png_create_info_struct\n");
  184645. if(png_ptr == NULL) return (NULL);
  184646. #ifdef PNG_USER_MEM_SUPPORTED
  184647. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184648. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184649. #else
  184650. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184651. #endif
  184652. if (info_ptr != NULL)
  184653. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184654. return (info_ptr);
  184655. }
  184656. /* This function frees the memory associated with a single info struct.
  184657. * Normally, one would use either png_destroy_read_struct() or
  184658. * png_destroy_write_struct() to free an info struct, but this may be
  184659. * useful for some applications.
  184660. */
  184661. void PNGAPI
  184662. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184663. {
  184664. png_infop info_ptr = NULL;
  184665. if(png_ptr == NULL) return;
  184666. png_debug(1, "in png_destroy_info_struct\n");
  184667. if (info_ptr_ptr != NULL)
  184668. info_ptr = *info_ptr_ptr;
  184669. if (info_ptr != NULL)
  184670. {
  184671. png_info_destroy(png_ptr, info_ptr);
  184672. #ifdef PNG_USER_MEM_SUPPORTED
  184673. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184674. png_ptr->mem_ptr);
  184675. #else
  184676. png_destroy_struct((png_voidp)info_ptr);
  184677. #endif
  184678. *info_ptr_ptr = NULL;
  184679. }
  184680. }
  184681. /* Initialize the info structure. This is now an internal function (0.89)
  184682. * and applications using it are urged to use png_create_info_struct()
  184683. * instead.
  184684. */
  184685. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184686. #undef png_info_init
  184687. void PNGAPI
  184688. png_info_init(png_infop info_ptr)
  184689. {
  184690. /* We only come here via pre-1.0.12-compiled applications */
  184691. png_info_init_3(&info_ptr, 0);
  184692. }
  184693. #endif
  184694. void PNGAPI
  184695. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184696. {
  184697. png_infop info_ptr = *ptr_ptr;
  184698. if(info_ptr == NULL) return;
  184699. png_debug(1, "in png_info_init_3\n");
  184700. if(png_sizeof(png_info) > png_info_struct_size)
  184701. {
  184702. png_destroy_struct(info_ptr);
  184703. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184704. *ptr_ptr = info_ptr;
  184705. }
  184706. /* set everything to 0 */
  184707. png_memset(info_ptr, 0, png_sizeof (png_info));
  184708. }
  184709. #ifdef PNG_FREE_ME_SUPPORTED
  184710. void PNGAPI
  184711. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184712. int freer, png_uint_32 mask)
  184713. {
  184714. png_debug(1, "in png_data_freer\n");
  184715. if (png_ptr == NULL || info_ptr == NULL)
  184716. return;
  184717. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184718. info_ptr->free_me |= mask;
  184719. else if(freer == PNG_USER_WILL_FREE_DATA)
  184720. info_ptr->free_me &= ~mask;
  184721. else
  184722. png_warning(png_ptr,
  184723. "Unknown freer parameter in png_data_freer.");
  184724. }
  184725. #endif
  184726. void PNGAPI
  184727. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184728. int num)
  184729. {
  184730. png_debug(1, "in png_free_data\n");
  184731. if (png_ptr == NULL || info_ptr == NULL)
  184732. return;
  184733. #if defined(PNG_TEXT_SUPPORTED)
  184734. /* free text item num or (if num == -1) all text items */
  184735. #ifdef PNG_FREE_ME_SUPPORTED
  184736. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184737. #else
  184738. if (mask & PNG_FREE_TEXT)
  184739. #endif
  184740. {
  184741. if (num != -1)
  184742. {
  184743. if (info_ptr->text && info_ptr->text[num].key)
  184744. {
  184745. png_free(png_ptr, info_ptr->text[num].key);
  184746. info_ptr->text[num].key = NULL;
  184747. }
  184748. }
  184749. else
  184750. {
  184751. int i;
  184752. for (i = 0; i < info_ptr->num_text; i++)
  184753. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184754. png_free(png_ptr, info_ptr->text);
  184755. info_ptr->text = NULL;
  184756. info_ptr->num_text=0;
  184757. }
  184758. }
  184759. #endif
  184760. #if defined(PNG_tRNS_SUPPORTED)
  184761. /* free any tRNS entry */
  184762. #ifdef PNG_FREE_ME_SUPPORTED
  184763. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184764. #else
  184765. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184766. #endif
  184767. {
  184768. png_free(png_ptr, info_ptr->trans);
  184769. info_ptr->valid &= ~PNG_INFO_tRNS;
  184770. #ifndef PNG_FREE_ME_SUPPORTED
  184771. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184772. #endif
  184773. info_ptr->trans = NULL;
  184774. }
  184775. #endif
  184776. #if defined(PNG_sCAL_SUPPORTED)
  184777. /* free any sCAL entry */
  184778. #ifdef PNG_FREE_ME_SUPPORTED
  184779. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184780. #else
  184781. if (mask & PNG_FREE_SCAL)
  184782. #endif
  184783. {
  184784. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184785. png_free(png_ptr, info_ptr->scal_s_width);
  184786. png_free(png_ptr, info_ptr->scal_s_height);
  184787. info_ptr->scal_s_width = NULL;
  184788. info_ptr->scal_s_height = NULL;
  184789. #endif
  184790. info_ptr->valid &= ~PNG_INFO_sCAL;
  184791. }
  184792. #endif
  184793. #if defined(PNG_pCAL_SUPPORTED)
  184794. /* free any pCAL entry */
  184795. #ifdef PNG_FREE_ME_SUPPORTED
  184796. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184797. #else
  184798. if (mask & PNG_FREE_PCAL)
  184799. #endif
  184800. {
  184801. png_free(png_ptr, info_ptr->pcal_purpose);
  184802. png_free(png_ptr, info_ptr->pcal_units);
  184803. info_ptr->pcal_purpose = NULL;
  184804. info_ptr->pcal_units = NULL;
  184805. if (info_ptr->pcal_params != NULL)
  184806. {
  184807. int i;
  184808. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184809. {
  184810. png_free(png_ptr, info_ptr->pcal_params[i]);
  184811. info_ptr->pcal_params[i]=NULL;
  184812. }
  184813. png_free(png_ptr, info_ptr->pcal_params);
  184814. info_ptr->pcal_params = NULL;
  184815. }
  184816. info_ptr->valid &= ~PNG_INFO_pCAL;
  184817. }
  184818. #endif
  184819. #if defined(PNG_iCCP_SUPPORTED)
  184820. /* free any iCCP entry */
  184821. #ifdef PNG_FREE_ME_SUPPORTED
  184822. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184823. #else
  184824. if (mask & PNG_FREE_ICCP)
  184825. #endif
  184826. {
  184827. png_free(png_ptr, info_ptr->iccp_name);
  184828. png_free(png_ptr, info_ptr->iccp_profile);
  184829. info_ptr->iccp_name = NULL;
  184830. info_ptr->iccp_profile = NULL;
  184831. info_ptr->valid &= ~PNG_INFO_iCCP;
  184832. }
  184833. #endif
  184834. #if defined(PNG_sPLT_SUPPORTED)
  184835. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184836. #ifdef PNG_FREE_ME_SUPPORTED
  184837. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184838. #else
  184839. if (mask & PNG_FREE_SPLT)
  184840. #endif
  184841. {
  184842. if (num != -1)
  184843. {
  184844. if(info_ptr->splt_palettes)
  184845. {
  184846. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184847. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184848. info_ptr->splt_palettes[num].name = NULL;
  184849. info_ptr->splt_palettes[num].entries = NULL;
  184850. }
  184851. }
  184852. else
  184853. {
  184854. if(info_ptr->splt_palettes_num)
  184855. {
  184856. int i;
  184857. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184858. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184859. png_free(png_ptr, info_ptr->splt_palettes);
  184860. info_ptr->splt_palettes = NULL;
  184861. info_ptr->splt_palettes_num = 0;
  184862. }
  184863. info_ptr->valid &= ~PNG_INFO_sPLT;
  184864. }
  184865. }
  184866. #endif
  184867. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184868. if(png_ptr->unknown_chunk.data)
  184869. {
  184870. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184871. png_ptr->unknown_chunk.data = NULL;
  184872. }
  184873. #ifdef PNG_FREE_ME_SUPPORTED
  184874. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184875. #else
  184876. if (mask & PNG_FREE_UNKN)
  184877. #endif
  184878. {
  184879. if (num != -1)
  184880. {
  184881. if(info_ptr->unknown_chunks)
  184882. {
  184883. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184884. info_ptr->unknown_chunks[num].data = NULL;
  184885. }
  184886. }
  184887. else
  184888. {
  184889. int i;
  184890. if(info_ptr->unknown_chunks_num)
  184891. {
  184892. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184893. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184894. png_free(png_ptr, info_ptr->unknown_chunks);
  184895. info_ptr->unknown_chunks = NULL;
  184896. info_ptr->unknown_chunks_num = 0;
  184897. }
  184898. }
  184899. }
  184900. #endif
  184901. #if defined(PNG_hIST_SUPPORTED)
  184902. /* free any hIST entry */
  184903. #ifdef PNG_FREE_ME_SUPPORTED
  184904. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184905. #else
  184906. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184907. #endif
  184908. {
  184909. png_free(png_ptr, info_ptr->hist);
  184910. info_ptr->hist = NULL;
  184911. info_ptr->valid &= ~PNG_INFO_hIST;
  184912. #ifndef PNG_FREE_ME_SUPPORTED
  184913. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184914. #endif
  184915. }
  184916. #endif
  184917. /* free any PLTE entry that was internally allocated */
  184918. #ifdef PNG_FREE_ME_SUPPORTED
  184919. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184920. #else
  184921. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184922. #endif
  184923. {
  184924. png_zfree(png_ptr, info_ptr->palette);
  184925. info_ptr->palette = NULL;
  184926. info_ptr->valid &= ~PNG_INFO_PLTE;
  184927. #ifndef PNG_FREE_ME_SUPPORTED
  184928. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184929. #endif
  184930. info_ptr->num_palette = 0;
  184931. }
  184932. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184933. /* free any image bits attached to the info structure */
  184934. #ifdef PNG_FREE_ME_SUPPORTED
  184935. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184936. #else
  184937. if (mask & PNG_FREE_ROWS)
  184938. #endif
  184939. {
  184940. if(info_ptr->row_pointers)
  184941. {
  184942. int row;
  184943. for (row = 0; row < (int)info_ptr->height; row++)
  184944. {
  184945. png_free(png_ptr, info_ptr->row_pointers[row]);
  184946. info_ptr->row_pointers[row]=NULL;
  184947. }
  184948. png_free(png_ptr, info_ptr->row_pointers);
  184949. info_ptr->row_pointers=NULL;
  184950. }
  184951. info_ptr->valid &= ~PNG_INFO_IDAT;
  184952. }
  184953. #endif
  184954. #ifdef PNG_FREE_ME_SUPPORTED
  184955. if(num == -1)
  184956. info_ptr->free_me &= ~mask;
  184957. else
  184958. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184959. #endif
  184960. }
  184961. /* This is an internal routine to free any memory that the info struct is
  184962. * pointing to before re-using it or freeing the struct itself. Recall
  184963. * that png_free() checks for NULL pointers for us.
  184964. */
  184965. void /* PRIVATE */
  184966. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184967. {
  184968. png_debug(1, "in png_info_destroy\n");
  184969. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184970. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184971. if (png_ptr->num_chunk_list)
  184972. {
  184973. png_free(png_ptr, png_ptr->chunk_list);
  184974. png_ptr->chunk_list=NULL;
  184975. png_ptr->num_chunk_list=0;
  184976. }
  184977. #endif
  184978. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184979. }
  184980. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184981. /* This function returns a pointer to the io_ptr associated with the user
  184982. * functions. The application should free any memory associated with this
  184983. * pointer before png_write_destroy() or png_read_destroy() are called.
  184984. */
  184985. png_voidp PNGAPI
  184986. png_get_io_ptr(png_structp png_ptr)
  184987. {
  184988. if(png_ptr == NULL) return (NULL);
  184989. return (png_ptr->io_ptr);
  184990. }
  184991. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184992. #if !defined(PNG_NO_STDIO)
  184993. /* Initialize the default input/output functions for the PNG file. If you
  184994. * use your own read or write routines, you can call either png_set_read_fn()
  184995. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184996. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184997. * necessarily available.
  184998. */
  184999. void PNGAPI
  185000. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185001. {
  185002. png_debug(1, "in png_init_io\n");
  185003. if(png_ptr == NULL) return;
  185004. png_ptr->io_ptr = (png_voidp)fp;
  185005. }
  185006. #endif
  185007. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185008. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185009. * a "Creation Time" or other text-based time string.
  185010. */
  185011. png_charp PNGAPI
  185012. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185013. {
  185014. static PNG_CONST char short_months[12][4] =
  185015. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185016. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185017. if(png_ptr == NULL) return (NULL);
  185018. if (png_ptr->time_buffer == NULL)
  185019. {
  185020. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185021. png_sizeof(char)));
  185022. }
  185023. #if defined(_WIN32_WCE)
  185024. {
  185025. wchar_t time_buf[29];
  185026. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185027. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185028. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185029. ptime->second % 61);
  185030. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185031. NULL, NULL);
  185032. }
  185033. #else
  185034. #ifdef USE_FAR_KEYWORD
  185035. {
  185036. char near_time_buf[29];
  185037. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185038. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185039. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185040. ptime->second % 61);
  185041. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185042. 29*png_sizeof(char));
  185043. }
  185044. #else
  185045. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185046. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185047. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185048. ptime->second % 61);
  185049. #endif
  185050. #endif /* _WIN32_WCE */
  185051. return ((png_charp)png_ptr->time_buffer);
  185052. }
  185053. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185054. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185055. png_charp PNGAPI
  185056. png_get_copyright(png_structp png_ptr)
  185057. {
  185058. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185059. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185060. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185061. Copyright (c) 1996-1997 Andreas Dilger\n\
  185062. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185063. }
  185064. /* The following return the library version as a short string in the
  185065. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185066. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185067. * is defined in png.h.
  185068. * Note: now there is no difference between png_get_libpng_ver() and
  185069. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185070. * it is guaranteed that png.c uses the correct version of png.h.
  185071. */
  185072. png_charp PNGAPI
  185073. png_get_libpng_ver(png_structp png_ptr)
  185074. {
  185075. /* Version of *.c files used when building libpng */
  185076. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185077. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185078. }
  185079. png_charp PNGAPI
  185080. png_get_header_ver(png_structp png_ptr)
  185081. {
  185082. /* Version of *.h files used when building libpng */
  185083. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185084. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185085. }
  185086. png_charp PNGAPI
  185087. png_get_header_version(png_structp png_ptr)
  185088. {
  185089. /* Returns longer string containing both version and date */
  185090. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185091. return ((png_charp) PNG_HEADER_VERSION_STRING
  185092. #ifndef PNG_READ_SUPPORTED
  185093. " (NO READ SUPPORT)"
  185094. #endif
  185095. "\n");
  185096. }
  185097. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185098. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185099. int PNGAPI
  185100. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185101. {
  185102. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185103. int i;
  185104. png_bytep p;
  185105. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185106. return 0;
  185107. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185108. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185109. if (!png_memcmp(chunk_name, p, 4))
  185110. return ((int)*(p+4));
  185111. return 0;
  185112. }
  185113. #endif
  185114. /* This function, added to libpng-1.0.6g, is untested. */
  185115. int PNGAPI
  185116. png_reset_zstream(png_structp png_ptr)
  185117. {
  185118. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185119. return (inflateReset(&png_ptr->zstream));
  185120. }
  185121. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185122. /* This function was added to libpng-1.0.7 */
  185123. png_uint_32 PNGAPI
  185124. png_access_version_number(void)
  185125. {
  185126. /* Version of *.c files used when building libpng */
  185127. return((png_uint_32) PNG_LIBPNG_VER);
  185128. }
  185129. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185130. #if !defined(PNG_1_0_X)
  185131. /* this function was added to libpng 1.2.0 */
  185132. int PNGAPI
  185133. png_mmx_support(void)
  185134. {
  185135. /* obsolete, to be removed from libpng-1.4.0 */
  185136. return -1;
  185137. }
  185138. #endif /* PNG_1_0_X */
  185139. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185140. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185141. #ifdef PNG_SIZE_T
  185142. /* Added at libpng version 1.2.6 */
  185143. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185144. png_size_t PNGAPI
  185145. png_convert_size(size_t size)
  185146. {
  185147. if (size > (png_size_t)-1)
  185148. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185149. return ((png_size_t)size);
  185150. }
  185151. #endif /* PNG_SIZE_T */
  185152. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185153. /*** End of inlined file: png.c ***/
  185154. /*** Start of inlined file: pngerror.c ***/
  185155. /* pngerror.c - stub functions for i/o and memory allocation
  185156. *
  185157. * Last changed in libpng 1.2.20 October 4, 2007
  185158. * For conditions of distribution and use, see copyright notice in png.h
  185159. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185160. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185161. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185162. *
  185163. * This file provides a location for all error handling. Users who
  185164. * need special error handling are expected to write replacement functions
  185165. * and use png_set_error_fn() to use those functions. See the instructions
  185166. * at each function.
  185167. */
  185168. #define PNG_INTERNAL
  185169. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185170. static void /* PRIVATE */
  185171. png_default_error PNGARG((png_structp png_ptr,
  185172. png_const_charp error_message));
  185173. #ifndef PNG_NO_WARNINGS
  185174. static void /* PRIVATE */
  185175. png_default_warning PNGARG((png_structp png_ptr,
  185176. png_const_charp warning_message));
  185177. #endif /* PNG_NO_WARNINGS */
  185178. /* This function is called whenever there is a fatal error. This function
  185179. * should not be changed. If there is a need to handle errors differently,
  185180. * you should supply a replacement error function and use png_set_error_fn()
  185181. * to replace the error function at run-time.
  185182. */
  185183. #ifndef PNG_NO_ERROR_TEXT
  185184. void PNGAPI
  185185. png_error(png_structp png_ptr, png_const_charp error_message)
  185186. {
  185187. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185188. char msg[16];
  185189. if (png_ptr != NULL)
  185190. {
  185191. if (png_ptr->flags&
  185192. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185193. {
  185194. if (*error_message == '#')
  185195. {
  185196. int offset;
  185197. for (offset=1; offset<15; offset++)
  185198. if (*(error_message+offset) == ' ')
  185199. break;
  185200. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185201. {
  185202. int i;
  185203. for (i=0; i<offset-1; i++)
  185204. msg[i]=error_message[i+1];
  185205. msg[i]='\0';
  185206. error_message=msg;
  185207. }
  185208. else
  185209. error_message+=offset;
  185210. }
  185211. else
  185212. {
  185213. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185214. {
  185215. msg[0]='0';
  185216. msg[1]='\0';
  185217. error_message=msg;
  185218. }
  185219. }
  185220. }
  185221. }
  185222. #endif
  185223. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185224. (*(png_ptr->error_fn))(png_ptr, error_message);
  185225. /* If the custom handler doesn't exist, or if it returns,
  185226. use the default handler, which will not return. */
  185227. png_default_error(png_ptr, error_message);
  185228. }
  185229. #else
  185230. void PNGAPI
  185231. png_err(png_structp png_ptr)
  185232. {
  185233. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185234. (*(png_ptr->error_fn))(png_ptr, '\0');
  185235. /* If the custom handler doesn't exist, or if it returns,
  185236. use the default handler, which will not return. */
  185237. png_default_error(png_ptr, '\0');
  185238. }
  185239. #endif /* PNG_NO_ERROR_TEXT */
  185240. #ifndef PNG_NO_WARNINGS
  185241. /* This function is called whenever there is a non-fatal error. This function
  185242. * should not be changed. If there is a need to handle warnings differently,
  185243. * you should supply a replacement warning function and use
  185244. * png_set_error_fn() to replace the warning function at run-time.
  185245. */
  185246. void PNGAPI
  185247. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185248. {
  185249. int offset = 0;
  185250. if (png_ptr != NULL)
  185251. {
  185252. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185253. if (png_ptr->flags&
  185254. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185255. #endif
  185256. {
  185257. if (*warning_message == '#')
  185258. {
  185259. for (offset=1; offset<15; offset++)
  185260. if (*(warning_message+offset) == ' ')
  185261. break;
  185262. }
  185263. }
  185264. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185265. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185266. }
  185267. else
  185268. png_default_warning(png_ptr, warning_message+offset);
  185269. }
  185270. #endif /* PNG_NO_WARNINGS */
  185271. /* These utilities are used internally to build an error message that relates
  185272. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185273. * this is used to prefix the message. The message is limited in length
  185274. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185275. * if the character is invalid.
  185276. */
  185277. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185278. /*static PNG_CONST char png_digit[16] = {
  185279. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185280. 'A', 'B', 'C', 'D', 'E', 'F'
  185281. };*/
  185282. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185283. static void /* PRIVATE */
  185284. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185285. error_message)
  185286. {
  185287. int iout = 0, iin = 0;
  185288. while (iin < 4)
  185289. {
  185290. int c = png_ptr->chunk_name[iin++];
  185291. if (isnonalpha(c))
  185292. {
  185293. buffer[iout++] = '[';
  185294. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185295. buffer[iout++] = png_digit[c & 0x0f];
  185296. buffer[iout++] = ']';
  185297. }
  185298. else
  185299. {
  185300. buffer[iout++] = (png_byte)c;
  185301. }
  185302. }
  185303. if (error_message == NULL)
  185304. buffer[iout] = 0;
  185305. else
  185306. {
  185307. buffer[iout++] = ':';
  185308. buffer[iout++] = ' ';
  185309. png_strncpy(buffer+iout, error_message, 63);
  185310. buffer[iout+63] = 0;
  185311. }
  185312. }
  185313. #ifdef PNG_READ_SUPPORTED
  185314. void PNGAPI
  185315. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185316. {
  185317. char msg[18+64];
  185318. if (png_ptr == NULL)
  185319. png_error(png_ptr, error_message);
  185320. else
  185321. {
  185322. png_format_buffer(png_ptr, msg, error_message);
  185323. png_error(png_ptr, msg);
  185324. }
  185325. }
  185326. #endif /* PNG_READ_SUPPORTED */
  185327. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185328. #ifndef PNG_NO_WARNINGS
  185329. void PNGAPI
  185330. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185331. {
  185332. char msg[18+64];
  185333. if (png_ptr == NULL)
  185334. png_warning(png_ptr, warning_message);
  185335. else
  185336. {
  185337. png_format_buffer(png_ptr, msg, warning_message);
  185338. png_warning(png_ptr, msg);
  185339. }
  185340. }
  185341. #endif /* PNG_NO_WARNINGS */
  185342. /* This is the default error handling function. Note that replacements for
  185343. * this function MUST NOT RETURN, or the program will likely crash. This
  185344. * function is used by default, or if the program supplies NULL for the
  185345. * error function pointer in png_set_error_fn().
  185346. */
  185347. static void /* PRIVATE */
  185348. png_default_error(png_structp, png_const_charp error_message)
  185349. {
  185350. #ifndef PNG_NO_CONSOLE_IO
  185351. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185352. if (*error_message == '#')
  185353. {
  185354. int offset;
  185355. char error_number[16];
  185356. for (offset=0; offset<15; offset++)
  185357. {
  185358. error_number[offset] = *(error_message+offset+1);
  185359. if (*(error_message+offset) == ' ')
  185360. break;
  185361. }
  185362. if((offset > 1) && (offset < 15))
  185363. {
  185364. error_number[offset-1]='\0';
  185365. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185366. error_message+offset);
  185367. }
  185368. else
  185369. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185370. }
  185371. else
  185372. #endif
  185373. fprintf(stderr, "libpng error: %s\n", error_message);
  185374. #endif
  185375. #ifdef PNG_SETJMP_SUPPORTED
  185376. if (png_ptr)
  185377. {
  185378. # ifdef USE_FAR_KEYWORD
  185379. {
  185380. jmp_buf jmpbuf;
  185381. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185382. longjmp(jmpbuf, 1);
  185383. }
  185384. # else
  185385. longjmp(png_ptr->jmpbuf, 1);
  185386. # endif
  185387. }
  185388. #else
  185389. PNG_ABORT();
  185390. #endif
  185391. #ifdef PNG_NO_CONSOLE_IO
  185392. error_message = error_message; /* make compiler happy */
  185393. #endif
  185394. }
  185395. #ifndef PNG_NO_WARNINGS
  185396. /* This function is called when there is a warning, but the library thinks
  185397. * it can continue anyway. Replacement functions don't have to do anything
  185398. * here if you don't want them to. In the default configuration, png_ptr is
  185399. * not used, but it is passed in case it may be useful.
  185400. */
  185401. static void /* PRIVATE */
  185402. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185403. {
  185404. #ifndef PNG_NO_CONSOLE_IO
  185405. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185406. if (*warning_message == '#')
  185407. {
  185408. int offset;
  185409. char warning_number[16];
  185410. for (offset=0; offset<15; offset++)
  185411. {
  185412. warning_number[offset]=*(warning_message+offset+1);
  185413. if (*(warning_message+offset) == ' ')
  185414. break;
  185415. }
  185416. if((offset > 1) && (offset < 15))
  185417. {
  185418. warning_number[offset-1]='\0';
  185419. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185420. warning_message+offset);
  185421. }
  185422. else
  185423. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185424. }
  185425. else
  185426. # endif
  185427. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185428. #else
  185429. warning_message = warning_message; /* make compiler happy */
  185430. #endif
  185431. png_ptr = png_ptr; /* make compiler happy */
  185432. }
  185433. #endif /* PNG_NO_WARNINGS */
  185434. /* This function is called when the application wants to use another method
  185435. * of handling errors and warnings. Note that the error function MUST NOT
  185436. * return to the calling routine or serious problems will occur. The return
  185437. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185438. */
  185439. void PNGAPI
  185440. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185441. png_error_ptr error_fn, png_error_ptr warning_fn)
  185442. {
  185443. if (png_ptr == NULL)
  185444. return;
  185445. png_ptr->error_ptr = error_ptr;
  185446. png_ptr->error_fn = error_fn;
  185447. png_ptr->warning_fn = warning_fn;
  185448. }
  185449. /* This function returns a pointer to the error_ptr associated with the user
  185450. * functions. The application should free any memory associated with this
  185451. * pointer before png_write_destroy and png_read_destroy are called.
  185452. */
  185453. png_voidp PNGAPI
  185454. png_get_error_ptr(png_structp png_ptr)
  185455. {
  185456. if (png_ptr == NULL)
  185457. return NULL;
  185458. return ((png_voidp)png_ptr->error_ptr);
  185459. }
  185460. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185461. void PNGAPI
  185462. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185463. {
  185464. if(png_ptr != NULL)
  185465. {
  185466. png_ptr->flags &=
  185467. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185468. }
  185469. }
  185470. #endif
  185471. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185472. /*** End of inlined file: pngerror.c ***/
  185473. /*** Start of inlined file: pngget.c ***/
  185474. /* pngget.c - retrieval of values from info struct
  185475. *
  185476. * Last changed in libpng 1.2.15 January 5, 2007
  185477. * For conditions of distribution and use, see copyright notice in png.h
  185478. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185479. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185480. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185481. */
  185482. #define PNG_INTERNAL
  185483. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185484. png_uint_32 PNGAPI
  185485. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185486. {
  185487. if (png_ptr != NULL && info_ptr != NULL)
  185488. return(info_ptr->valid & flag);
  185489. else
  185490. return(0);
  185491. }
  185492. png_uint_32 PNGAPI
  185493. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185494. {
  185495. if (png_ptr != NULL && info_ptr != NULL)
  185496. return(info_ptr->rowbytes);
  185497. else
  185498. return(0);
  185499. }
  185500. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185501. png_bytepp PNGAPI
  185502. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185503. {
  185504. if (png_ptr != NULL && info_ptr != NULL)
  185505. return(info_ptr->row_pointers);
  185506. else
  185507. return(0);
  185508. }
  185509. #endif
  185510. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185511. /* easy access to info, added in libpng-0.99 */
  185512. png_uint_32 PNGAPI
  185513. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185514. {
  185515. if (png_ptr != NULL && info_ptr != NULL)
  185516. {
  185517. return info_ptr->width;
  185518. }
  185519. return (0);
  185520. }
  185521. png_uint_32 PNGAPI
  185522. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185523. {
  185524. if (png_ptr != NULL && info_ptr != NULL)
  185525. {
  185526. return info_ptr->height;
  185527. }
  185528. return (0);
  185529. }
  185530. png_byte PNGAPI
  185531. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185532. {
  185533. if (png_ptr != NULL && info_ptr != NULL)
  185534. {
  185535. return info_ptr->bit_depth;
  185536. }
  185537. return (0);
  185538. }
  185539. png_byte PNGAPI
  185540. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185541. {
  185542. if (png_ptr != NULL && info_ptr != NULL)
  185543. {
  185544. return info_ptr->color_type;
  185545. }
  185546. return (0);
  185547. }
  185548. png_byte PNGAPI
  185549. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185550. {
  185551. if (png_ptr != NULL && info_ptr != NULL)
  185552. {
  185553. return info_ptr->filter_type;
  185554. }
  185555. return (0);
  185556. }
  185557. png_byte PNGAPI
  185558. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185559. {
  185560. if (png_ptr != NULL && info_ptr != NULL)
  185561. {
  185562. return info_ptr->interlace_type;
  185563. }
  185564. return (0);
  185565. }
  185566. png_byte PNGAPI
  185567. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185568. {
  185569. if (png_ptr != NULL && info_ptr != NULL)
  185570. {
  185571. return info_ptr->compression_type;
  185572. }
  185573. return (0);
  185574. }
  185575. png_uint_32 PNGAPI
  185576. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185577. {
  185578. if (png_ptr != NULL && info_ptr != NULL)
  185579. #if defined(PNG_pHYs_SUPPORTED)
  185580. if (info_ptr->valid & PNG_INFO_pHYs)
  185581. {
  185582. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185583. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185584. return (0);
  185585. else return (info_ptr->x_pixels_per_unit);
  185586. }
  185587. #else
  185588. return (0);
  185589. #endif
  185590. return (0);
  185591. }
  185592. png_uint_32 PNGAPI
  185593. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185594. {
  185595. if (png_ptr != NULL && info_ptr != NULL)
  185596. #if defined(PNG_pHYs_SUPPORTED)
  185597. if (info_ptr->valid & PNG_INFO_pHYs)
  185598. {
  185599. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185600. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185601. return (0);
  185602. else return (info_ptr->y_pixels_per_unit);
  185603. }
  185604. #else
  185605. return (0);
  185606. #endif
  185607. return (0);
  185608. }
  185609. png_uint_32 PNGAPI
  185610. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185611. {
  185612. if (png_ptr != NULL && info_ptr != NULL)
  185613. #if defined(PNG_pHYs_SUPPORTED)
  185614. if (info_ptr->valid & PNG_INFO_pHYs)
  185615. {
  185616. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185617. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185618. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185619. return (0);
  185620. else return (info_ptr->x_pixels_per_unit);
  185621. }
  185622. #else
  185623. return (0);
  185624. #endif
  185625. return (0);
  185626. }
  185627. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185628. float PNGAPI
  185629. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185630. {
  185631. if (png_ptr != NULL && info_ptr != NULL)
  185632. #if defined(PNG_pHYs_SUPPORTED)
  185633. if (info_ptr->valid & PNG_INFO_pHYs)
  185634. {
  185635. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185636. if (info_ptr->x_pixels_per_unit == 0)
  185637. return ((float)0.0);
  185638. else
  185639. return ((float)((float)info_ptr->y_pixels_per_unit
  185640. /(float)info_ptr->x_pixels_per_unit));
  185641. }
  185642. #else
  185643. return (0.0);
  185644. #endif
  185645. return ((float)0.0);
  185646. }
  185647. #endif
  185648. png_int_32 PNGAPI
  185649. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185650. {
  185651. if (png_ptr != NULL && info_ptr != NULL)
  185652. #if defined(PNG_oFFs_SUPPORTED)
  185653. if (info_ptr->valid & PNG_INFO_oFFs)
  185654. {
  185655. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185656. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185657. return (0);
  185658. else return (info_ptr->x_offset);
  185659. }
  185660. #else
  185661. return (0);
  185662. #endif
  185663. return (0);
  185664. }
  185665. png_int_32 PNGAPI
  185666. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185667. {
  185668. if (png_ptr != NULL && info_ptr != NULL)
  185669. #if defined(PNG_oFFs_SUPPORTED)
  185670. if (info_ptr->valid & PNG_INFO_oFFs)
  185671. {
  185672. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185673. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185674. return (0);
  185675. else return (info_ptr->y_offset);
  185676. }
  185677. #else
  185678. return (0);
  185679. #endif
  185680. return (0);
  185681. }
  185682. png_int_32 PNGAPI
  185683. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185684. {
  185685. if (png_ptr != NULL && info_ptr != NULL)
  185686. #if defined(PNG_oFFs_SUPPORTED)
  185687. if (info_ptr->valid & PNG_INFO_oFFs)
  185688. {
  185689. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185690. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185691. return (0);
  185692. else return (info_ptr->x_offset);
  185693. }
  185694. #else
  185695. return (0);
  185696. #endif
  185697. return (0);
  185698. }
  185699. png_int_32 PNGAPI
  185700. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185701. {
  185702. if (png_ptr != NULL && info_ptr != NULL)
  185703. #if defined(PNG_oFFs_SUPPORTED)
  185704. if (info_ptr->valid & PNG_INFO_oFFs)
  185705. {
  185706. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185707. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185708. return (0);
  185709. else return (info_ptr->y_offset);
  185710. }
  185711. #else
  185712. return (0);
  185713. #endif
  185714. return (0);
  185715. }
  185716. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185717. png_uint_32 PNGAPI
  185718. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185719. {
  185720. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185721. *.0254 +.5));
  185722. }
  185723. png_uint_32 PNGAPI
  185724. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185725. {
  185726. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185727. *.0254 +.5));
  185728. }
  185729. png_uint_32 PNGAPI
  185730. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185731. {
  185732. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185733. *.0254 +.5));
  185734. }
  185735. float PNGAPI
  185736. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185737. {
  185738. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185739. *.00003937);
  185740. }
  185741. float PNGAPI
  185742. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185743. {
  185744. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185745. *.00003937);
  185746. }
  185747. #if defined(PNG_pHYs_SUPPORTED)
  185748. png_uint_32 PNGAPI
  185749. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185750. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185751. {
  185752. png_uint_32 retval = 0;
  185753. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185754. {
  185755. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185756. if (res_x != NULL)
  185757. {
  185758. *res_x = info_ptr->x_pixels_per_unit;
  185759. retval |= PNG_INFO_pHYs;
  185760. }
  185761. if (res_y != NULL)
  185762. {
  185763. *res_y = info_ptr->y_pixels_per_unit;
  185764. retval |= PNG_INFO_pHYs;
  185765. }
  185766. if (unit_type != NULL)
  185767. {
  185768. *unit_type = (int)info_ptr->phys_unit_type;
  185769. retval |= PNG_INFO_pHYs;
  185770. if(*unit_type == 1)
  185771. {
  185772. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185773. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185774. }
  185775. }
  185776. }
  185777. return (retval);
  185778. }
  185779. #endif /* PNG_pHYs_SUPPORTED */
  185780. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185781. /* png_get_channels really belongs in here, too, but it's been around longer */
  185782. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185783. png_byte PNGAPI
  185784. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185785. {
  185786. if (png_ptr != NULL && info_ptr != NULL)
  185787. return(info_ptr->channels);
  185788. else
  185789. return (0);
  185790. }
  185791. png_bytep PNGAPI
  185792. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185793. {
  185794. if (png_ptr != NULL && info_ptr != NULL)
  185795. return(info_ptr->signature);
  185796. else
  185797. return (NULL);
  185798. }
  185799. #if defined(PNG_bKGD_SUPPORTED)
  185800. png_uint_32 PNGAPI
  185801. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185802. png_color_16p *background)
  185803. {
  185804. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185805. && background != NULL)
  185806. {
  185807. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185808. *background = &(info_ptr->background);
  185809. return (PNG_INFO_bKGD);
  185810. }
  185811. return (0);
  185812. }
  185813. #endif
  185814. #if defined(PNG_cHRM_SUPPORTED)
  185815. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185816. png_uint_32 PNGAPI
  185817. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185818. double *white_x, double *white_y, double *red_x, double *red_y,
  185819. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185820. {
  185821. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185822. {
  185823. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185824. if (white_x != NULL)
  185825. *white_x = (double)info_ptr->x_white;
  185826. if (white_y != NULL)
  185827. *white_y = (double)info_ptr->y_white;
  185828. if (red_x != NULL)
  185829. *red_x = (double)info_ptr->x_red;
  185830. if (red_y != NULL)
  185831. *red_y = (double)info_ptr->y_red;
  185832. if (green_x != NULL)
  185833. *green_x = (double)info_ptr->x_green;
  185834. if (green_y != NULL)
  185835. *green_y = (double)info_ptr->y_green;
  185836. if (blue_x != NULL)
  185837. *blue_x = (double)info_ptr->x_blue;
  185838. if (blue_y != NULL)
  185839. *blue_y = (double)info_ptr->y_blue;
  185840. return (PNG_INFO_cHRM);
  185841. }
  185842. return (0);
  185843. }
  185844. #endif
  185845. #ifdef PNG_FIXED_POINT_SUPPORTED
  185846. png_uint_32 PNGAPI
  185847. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185848. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185849. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185850. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185851. {
  185852. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185853. {
  185854. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185855. if (white_x != NULL)
  185856. *white_x = info_ptr->int_x_white;
  185857. if (white_y != NULL)
  185858. *white_y = info_ptr->int_y_white;
  185859. if (red_x != NULL)
  185860. *red_x = info_ptr->int_x_red;
  185861. if (red_y != NULL)
  185862. *red_y = info_ptr->int_y_red;
  185863. if (green_x != NULL)
  185864. *green_x = info_ptr->int_x_green;
  185865. if (green_y != NULL)
  185866. *green_y = info_ptr->int_y_green;
  185867. if (blue_x != NULL)
  185868. *blue_x = info_ptr->int_x_blue;
  185869. if (blue_y != NULL)
  185870. *blue_y = info_ptr->int_y_blue;
  185871. return (PNG_INFO_cHRM);
  185872. }
  185873. return (0);
  185874. }
  185875. #endif
  185876. #endif
  185877. #if defined(PNG_gAMA_SUPPORTED)
  185878. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185879. png_uint_32 PNGAPI
  185880. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185881. {
  185882. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185883. && file_gamma != NULL)
  185884. {
  185885. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185886. *file_gamma = (double)info_ptr->gamma;
  185887. return (PNG_INFO_gAMA);
  185888. }
  185889. return (0);
  185890. }
  185891. #endif
  185892. #ifdef PNG_FIXED_POINT_SUPPORTED
  185893. png_uint_32 PNGAPI
  185894. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185895. png_fixed_point *int_file_gamma)
  185896. {
  185897. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185898. && int_file_gamma != NULL)
  185899. {
  185900. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185901. *int_file_gamma = info_ptr->int_gamma;
  185902. return (PNG_INFO_gAMA);
  185903. }
  185904. return (0);
  185905. }
  185906. #endif
  185907. #endif
  185908. #if defined(PNG_sRGB_SUPPORTED)
  185909. png_uint_32 PNGAPI
  185910. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185911. {
  185912. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185913. && file_srgb_intent != NULL)
  185914. {
  185915. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185916. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185917. return (PNG_INFO_sRGB);
  185918. }
  185919. return (0);
  185920. }
  185921. #endif
  185922. #if defined(PNG_iCCP_SUPPORTED)
  185923. png_uint_32 PNGAPI
  185924. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185925. png_charpp name, int *compression_type,
  185926. png_charpp profile, png_uint_32 *proflen)
  185927. {
  185928. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185929. && name != NULL && profile != NULL && proflen != NULL)
  185930. {
  185931. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185932. *name = info_ptr->iccp_name;
  185933. *profile = info_ptr->iccp_profile;
  185934. /* compression_type is a dummy so the API won't have to change
  185935. if we introduce multiple compression types later. */
  185936. *proflen = (int)info_ptr->iccp_proflen;
  185937. *compression_type = (int)info_ptr->iccp_compression;
  185938. return (PNG_INFO_iCCP);
  185939. }
  185940. return (0);
  185941. }
  185942. #endif
  185943. #if defined(PNG_sPLT_SUPPORTED)
  185944. png_uint_32 PNGAPI
  185945. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185946. png_sPLT_tpp spalettes)
  185947. {
  185948. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185949. {
  185950. *spalettes = info_ptr->splt_palettes;
  185951. return ((png_uint_32)info_ptr->splt_palettes_num);
  185952. }
  185953. return (0);
  185954. }
  185955. #endif
  185956. #if defined(PNG_hIST_SUPPORTED)
  185957. png_uint_32 PNGAPI
  185958. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185959. {
  185960. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185961. && hist != NULL)
  185962. {
  185963. png_debug1(1, "in %s retrieval function\n", "hIST");
  185964. *hist = info_ptr->hist;
  185965. return (PNG_INFO_hIST);
  185966. }
  185967. return (0);
  185968. }
  185969. #endif
  185970. png_uint_32 PNGAPI
  185971. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185972. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185973. int *color_type, int *interlace_type, int *compression_type,
  185974. int *filter_type)
  185975. {
  185976. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185977. bit_depth != NULL && color_type != NULL)
  185978. {
  185979. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185980. *width = info_ptr->width;
  185981. *height = info_ptr->height;
  185982. *bit_depth = info_ptr->bit_depth;
  185983. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185984. png_error(png_ptr, "Invalid bit depth");
  185985. *color_type = info_ptr->color_type;
  185986. if (info_ptr->color_type > 6)
  185987. png_error(png_ptr, "Invalid color type");
  185988. if (compression_type != NULL)
  185989. *compression_type = info_ptr->compression_type;
  185990. if (filter_type != NULL)
  185991. *filter_type = info_ptr->filter_type;
  185992. if (interlace_type != NULL)
  185993. *interlace_type = info_ptr->interlace_type;
  185994. /* check for potential overflow of rowbytes */
  185995. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185996. png_error(png_ptr, "Invalid image width");
  185997. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185998. png_error(png_ptr, "Invalid image height");
  185999. if (info_ptr->width > (PNG_UINT_32_MAX
  186000. >> 3) /* 8-byte RGBA pixels */
  186001. - 64 /* bigrowbuf hack */
  186002. - 1 /* filter byte */
  186003. - 7*8 /* rounding of width to multiple of 8 pixels */
  186004. - 8) /* extra max_pixel_depth pad */
  186005. {
  186006. png_warning(png_ptr,
  186007. "Width too large for libpng to process image data.");
  186008. }
  186009. return (1);
  186010. }
  186011. return (0);
  186012. }
  186013. #if defined(PNG_oFFs_SUPPORTED)
  186014. png_uint_32 PNGAPI
  186015. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186016. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186017. {
  186018. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186019. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186020. {
  186021. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186022. *offset_x = info_ptr->x_offset;
  186023. *offset_y = info_ptr->y_offset;
  186024. *unit_type = (int)info_ptr->offset_unit_type;
  186025. return (PNG_INFO_oFFs);
  186026. }
  186027. return (0);
  186028. }
  186029. #endif
  186030. #if defined(PNG_pCAL_SUPPORTED)
  186031. png_uint_32 PNGAPI
  186032. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186033. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186034. png_charp *units, png_charpp *params)
  186035. {
  186036. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186037. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186038. nparams != NULL && units != NULL && params != NULL)
  186039. {
  186040. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186041. *purpose = info_ptr->pcal_purpose;
  186042. *X0 = info_ptr->pcal_X0;
  186043. *X1 = info_ptr->pcal_X1;
  186044. *type = (int)info_ptr->pcal_type;
  186045. *nparams = (int)info_ptr->pcal_nparams;
  186046. *units = info_ptr->pcal_units;
  186047. *params = info_ptr->pcal_params;
  186048. return (PNG_INFO_pCAL);
  186049. }
  186050. return (0);
  186051. }
  186052. #endif
  186053. #if defined(PNG_sCAL_SUPPORTED)
  186054. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186055. png_uint_32 PNGAPI
  186056. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186057. int *unit, double *width, double *height)
  186058. {
  186059. if (png_ptr != NULL && info_ptr != NULL &&
  186060. (info_ptr->valid & PNG_INFO_sCAL))
  186061. {
  186062. *unit = info_ptr->scal_unit;
  186063. *width = info_ptr->scal_pixel_width;
  186064. *height = info_ptr->scal_pixel_height;
  186065. return (PNG_INFO_sCAL);
  186066. }
  186067. return(0);
  186068. }
  186069. #else
  186070. #ifdef PNG_FIXED_POINT_SUPPORTED
  186071. png_uint_32 PNGAPI
  186072. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186073. int *unit, png_charpp width, png_charpp height)
  186074. {
  186075. if (png_ptr != NULL && info_ptr != NULL &&
  186076. (info_ptr->valid & PNG_INFO_sCAL))
  186077. {
  186078. *unit = info_ptr->scal_unit;
  186079. *width = info_ptr->scal_s_width;
  186080. *height = info_ptr->scal_s_height;
  186081. return (PNG_INFO_sCAL);
  186082. }
  186083. return(0);
  186084. }
  186085. #endif
  186086. #endif
  186087. #endif
  186088. #if defined(PNG_pHYs_SUPPORTED)
  186089. png_uint_32 PNGAPI
  186090. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186091. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186092. {
  186093. png_uint_32 retval = 0;
  186094. if (png_ptr != NULL && info_ptr != NULL &&
  186095. (info_ptr->valid & PNG_INFO_pHYs))
  186096. {
  186097. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186098. if (res_x != NULL)
  186099. {
  186100. *res_x = info_ptr->x_pixels_per_unit;
  186101. retval |= PNG_INFO_pHYs;
  186102. }
  186103. if (res_y != NULL)
  186104. {
  186105. *res_y = info_ptr->y_pixels_per_unit;
  186106. retval |= PNG_INFO_pHYs;
  186107. }
  186108. if (unit_type != NULL)
  186109. {
  186110. *unit_type = (int)info_ptr->phys_unit_type;
  186111. retval |= PNG_INFO_pHYs;
  186112. }
  186113. }
  186114. return (retval);
  186115. }
  186116. #endif
  186117. png_uint_32 PNGAPI
  186118. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186119. int *num_palette)
  186120. {
  186121. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186122. && palette != NULL)
  186123. {
  186124. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186125. *palette = info_ptr->palette;
  186126. *num_palette = info_ptr->num_palette;
  186127. png_debug1(3, "num_palette = %d\n", *num_palette);
  186128. return (PNG_INFO_PLTE);
  186129. }
  186130. return (0);
  186131. }
  186132. #if defined(PNG_sBIT_SUPPORTED)
  186133. png_uint_32 PNGAPI
  186134. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186135. {
  186136. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186137. && sig_bit != NULL)
  186138. {
  186139. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186140. *sig_bit = &(info_ptr->sig_bit);
  186141. return (PNG_INFO_sBIT);
  186142. }
  186143. return (0);
  186144. }
  186145. #endif
  186146. #if defined(PNG_TEXT_SUPPORTED)
  186147. png_uint_32 PNGAPI
  186148. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186149. int *num_text)
  186150. {
  186151. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186152. {
  186153. png_debug1(1, "in %s retrieval function\n",
  186154. (png_ptr->chunk_name[0] == '\0' ? "text"
  186155. : (png_const_charp)png_ptr->chunk_name));
  186156. if (text_ptr != NULL)
  186157. *text_ptr = info_ptr->text;
  186158. if (num_text != NULL)
  186159. *num_text = info_ptr->num_text;
  186160. return ((png_uint_32)info_ptr->num_text);
  186161. }
  186162. if (num_text != NULL)
  186163. *num_text = 0;
  186164. return(0);
  186165. }
  186166. #endif
  186167. #if defined(PNG_tIME_SUPPORTED)
  186168. png_uint_32 PNGAPI
  186169. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186170. {
  186171. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186172. && mod_time != NULL)
  186173. {
  186174. png_debug1(1, "in %s retrieval function\n", "tIME");
  186175. *mod_time = &(info_ptr->mod_time);
  186176. return (PNG_INFO_tIME);
  186177. }
  186178. return (0);
  186179. }
  186180. #endif
  186181. #if defined(PNG_tRNS_SUPPORTED)
  186182. png_uint_32 PNGAPI
  186183. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186184. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186185. {
  186186. png_uint_32 retval = 0;
  186187. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186188. {
  186189. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186190. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186191. {
  186192. if (trans != NULL)
  186193. {
  186194. *trans = info_ptr->trans;
  186195. retval |= PNG_INFO_tRNS;
  186196. }
  186197. if (trans_values != NULL)
  186198. *trans_values = &(info_ptr->trans_values);
  186199. }
  186200. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186201. {
  186202. if (trans_values != NULL)
  186203. {
  186204. *trans_values = &(info_ptr->trans_values);
  186205. retval |= PNG_INFO_tRNS;
  186206. }
  186207. if(trans != NULL)
  186208. *trans = NULL;
  186209. }
  186210. if(num_trans != NULL)
  186211. {
  186212. *num_trans = info_ptr->num_trans;
  186213. retval |= PNG_INFO_tRNS;
  186214. }
  186215. }
  186216. return (retval);
  186217. }
  186218. #endif
  186219. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186220. png_uint_32 PNGAPI
  186221. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186222. png_unknown_chunkpp unknowns)
  186223. {
  186224. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186225. {
  186226. *unknowns = info_ptr->unknown_chunks;
  186227. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186228. }
  186229. return (0);
  186230. }
  186231. #endif
  186232. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186233. png_byte PNGAPI
  186234. png_get_rgb_to_gray_status (png_structp png_ptr)
  186235. {
  186236. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186237. }
  186238. #endif
  186239. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186240. png_voidp PNGAPI
  186241. png_get_user_chunk_ptr(png_structp png_ptr)
  186242. {
  186243. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186244. }
  186245. #endif
  186246. #ifdef PNG_WRITE_SUPPORTED
  186247. png_uint_32 PNGAPI
  186248. png_get_compression_buffer_size(png_structp png_ptr)
  186249. {
  186250. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186251. }
  186252. #endif
  186253. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186254. #ifndef PNG_1_0_X
  186255. /* this function was added to libpng 1.2.0 and should exist by default */
  186256. png_uint_32 PNGAPI
  186257. png_get_asm_flags (png_structp png_ptr)
  186258. {
  186259. /* obsolete, to be removed from libpng-1.4.0 */
  186260. return (png_ptr? 0L: 0L);
  186261. }
  186262. /* this function was added to libpng 1.2.0 and should exist by default */
  186263. png_uint_32 PNGAPI
  186264. png_get_asm_flagmask (int flag_select)
  186265. {
  186266. /* obsolete, to be removed from libpng-1.4.0 */
  186267. flag_select=flag_select;
  186268. return 0L;
  186269. }
  186270. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186271. /* this function was added to libpng 1.2.0 */
  186272. png_uint_32 PNGAPI
  186273. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186274. {
  186275. /* obsolete, to be removed from libpng-1.4.0 */
  186276. flag_select=flag_select;
  186277. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186278. return 0L;
  186279. }
  186280. /* this function was added to libpng 1.2.0 */
  186281. png_byte PNGAPI
  186282. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186283. {
  186284. /* obsolete, to be removed from libpng-1.4.0 */
  186285. return (png_ptr? 0: 0);
  186286. }
  186287. /* this function was added to libpng 1.2.0 */
  186288. png_uint_32 PNGAPI
  186289. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186290. {
  186291. /* obsolete, to be removed from libpng-1.4.0 */
  186292. return (png_ptr? 0L: 0L);
  186293. }
  186294. #endif /* ?PNG_1_0_X */
  186295. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186296. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186297. /* these functions were added to libpng 1.2.6 */
  186298. png_uint_32 PNGAPI
  186299. png_get_user_width_max (png_structp png_ptr)
  186300. {
  186301. return (png_ptr? png_ptr->user_width_max : 0);
  186302. }
  186303. png_uint_32 PNGAPI
  186304. png_get_user_height_max (png_structp png_ptr)
  186305. {
  186306. return (png_ptr? png_ptr->user_height_max : 0);
  186307. }
  186308. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186309. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186310. /*** End of inlined file: pngget.c ***/
  186311. /*** Start of inlined file: pngmem.c ***/
  186312. /* pngmem.c - stub functions for memory allocation
  186313. *
  186314. * Last changed in libpng 1.2.13 November 13, 2006
  186315. * For conditions of distribution and use, see copyright notice in png.h
  186316. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186317. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186318. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186319. *
  186320. * This file provides a location for all memory allocation. Users who
  186321. * need special memory handling are expected to supply replacement
  186322. * functions for png_malloc() and png_free(), and to use
  186323. * png_create_read_struct_2() and png_create_write_struct_2() to
  186324. * identify the replacement functions.
  186325. */
  186326. #define PNG_INTERNAL
  186327. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186328. /* Borland DOS special memory handler */
  186329. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186330. /* if you change this, be sure to change the one in png.h also */
  186331. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186332. by a single call to calloc() if this is thought to improve performance. */
  186333. png_voidp /* PRIVATE */
  186334. png_create_struct(int type)
  186335. {
  186336. #ifdef PNG_USER_MEM_SUPPORTED
  186337. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186338. }
  186339. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186340. png_voidp /* PRIVATE */
  186341. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186342. {
  186343. #endif /* PNG_USER_MEM_SUPPORTED */
  186344. png_size_t size;
  186345. png_voidp struct_ptr;
  186346. if (type == PNG_STRUCT_INFO)
  186347. size = png_sizeof(png_info);
  186348. else if (type == PNG_STRUCT_PNG)
  186349. size = png_sizeof(png_struct);
  186350. else
  186351. return (png_get_copyright(NULL));
  186352. #ifdef PNG_USER_MEM_SUPPORTED
  186353. if(malloc_fn != NULL)
  186354. {
  186355. png_struct dummy_struct;
  186356. png_structp png_ptr = &dummy_struct;
  186357. png_ptr->mem_ptr=mem_ptr;
  186358. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186359. }
  186360. else
  186361. #endif /* PNG_USER_MEM_SUPPORTED */
  186362. struct_ptr = (png_voidp)farmalloc(size);
  186363. if (struct_ptr != NULL)
  186364. png_memset(struct_ptr, 0, size);
  186365. return (struct_ptr);
  186366. }
  186367. /* Free memory allocated by a png_create_struct() call */
  186368. void /* PRIVATE */
  186369. png_destroy_struct(png_voidp struct_ptr)
  186370. {
  186371. #ifdef PNG_USER_MEM_SUPPORTED
  186372. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186373. }
  186374. /* Free memory allocated by a png_create_struct() call */
  186375. void /* PRIVATE */
  186376. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186377. png_voidp mem_ptr)
  186378. {
  186379. #endif
  186380. if (struct_ptr != NULL)
  186381. {
  186382. #ifdef PNG_USER_MEM_SUPPORTED
  186383. if(free_fn != NULL)
  186384. {
  186385. png_struct dummy_struct;
  186386. png_structp png_ptr = &dummy_struct;
  186387. png_ptr->mem_ptr=mem_ptr;
  186388. (*(free_fn))(png_ptr, struct_ptr);
  186389. return;
  186390. }
  186391. #endif /* PNG_USER_MEM_SUPPORTED */
  186392. farfree (struct_ptr);
  186393. }
  186394. }
  186395. /* Allocate memory. For reasonable files, size should never exceed
  186396. * 64K. However, zlib may allocate more then 64K if you don't tell
  186397. * it not to. See zconf.h and png.h for more information. zlib does
  186398. * need to allocate exactly 64K, so whatever you call here must
  186399. * have the ability to do that.
  186400. *
  186401. * Borland seems to have a problem in DOS mode for exactly 64K.
  186402. * It gives you a segment with an offset of 8 (perhaps to store its
  186403. * memory stuff). zlib doesn't like this at all, so we have to
  186404. * detect and deal with it. This code should not be needed in
  186405. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186406. * been updated by Alexander Lehmann for version 0.89 to waste less
  186407. * memory.
  186408. *
  186409. * Note that we can't use png_size_t for the "size" declaration,
  186410. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186411. * result, we would be truncating potentially larger memory requests
  186412. * (which should cause a fatal error) and introducing major problems.
  186413. */
  186414. png_voidp PNGAPI
  186415. png_malloc(png_structp png_ptr, png_uint_32 size)
  186416. {
  186417. png_voidp ret;
  186418. if (png_ptr == NULL || size == 0)
  186419. return (NULL);
  186420. #ifdef PNG_USER_MEM_SUPPORTED
  186421. if(png_ptr->malloc_fn != NULL)
  186422. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186423. else
  186424. ret = (png_malloc_default(png_ptr, size));
  186425. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186426. png_error(png_ptr, "Out of memory!");
  186427. return (ret);
  186428. }
  186429. png_voidp PNGAPI
  186430. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186431. {
  186432. png_voidp ret;
  186433. #endif /* PNG_USER_MEM_SUPPORTED */
  186434. if (png_ptr == NULL || size == 0)
  186435. return (NULL);
  186436. #ifdef PNG_MAX_MALLOC_64K
  186437. if (size > (png_uint_32)65536L)
  186438. {
  186439. png_warning(png_ptr, "Cannot Allocate > 64K");
  186440. ret = NULL;
  186441. }
  186442. else
  186443. #endif
  186444. if (size != (size_t)size)
  186445. ret = NULL;
  186446. else if (size == (png_uint_32)65536L)
  186447. {
  186448. if (png_ptr->offset_table == NULL)
  186449. {
  186450. /* try to see if we need to do any of this fancy stuff */
  186451. ret = farmalloc(size);
  186452. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186453. {
  186454. int num_blocks;
  186455. png_uint_32 total_size;
  186456. png_bytep table;
  186457. int i;
  186458. png_byte huge * hptr;
  186459. if (ret != NULL)
  186460. {
  186461. farfree(ret);
  186462. ret = NULL;
  186463. }
  186464. if(png_ptr->zlib_window_bits > 14)
  186465. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186466. else
  186467. num_blocks = 1;
  186468. if (png_ptr->zlib_mem_level >= 7)
  186469. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186470. else
  186471. num_blocks++;
  186472. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186473. table = farmalloc(total_size);
  186474. if (table == NULL)
  186475. {
  186476. #ifndef PNG_USER_MEM_SUPPORTED
  186477. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186478. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186479. else
  186480. png_warning(png_ptr, "Out Of Memory.");
  186481. #endif
  186482. return (NULL);
  186483. }
  186484. if ((png_size_t)table & 0xfff0)
  186485. {
  186486. #ifndef PNG_USER_MEM_SUPPORTED
  186487. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186488. png_error(png_ptr,
  186489. "Farmalloc didn't return normalized pointer");
  186490. else
  186491. png_warning(png_ptr,
  186492. "Farmalloc didn't return normalized pointer");
  186493. #endif
  186494. return (NULL);
  186495. }
  186496. png_ptr->offset_table = table;
  186497. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186498. png_sizeof (png_bytep));
  186499. if (png_ptr->offset_table_ptr == NULL)
  186500. {
  186501. #ifndef PNG_USER_MEM_SUPPORTED
  186502. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186503. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186504. else
  186505. png_warning(png_ptr, "Out Of memory.");
  186506. #endif
  186507. return (NULL);
  186508. }
  186509. hptr = (png_byte huge *)table;
  186510. if ((png_size_t)hptr & 0xf)
  186511. {
  186512. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186513. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186514. }
  186515. for (i = 0; i < num_blocks; i++)
  186516. {
  186517. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186518. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186519. }
  186520. png_ptr->offset_table_number = num_blocks;
  186521. png_ptr->offset_table_count = 0;
  186522. png_ptr->offset_table_count_free = 0;
  186523. }
  186524. }
  186525. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186526. {
  186527. #ifndef PNG_USER_MEM_SUPPORTED
  186528. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186529. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186530. else
  186531. png_warning(png_ptr, "Out of Memory.");
  186532. #endif
  186533. return (NULL);
  186534. }
  186535. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186536. }
  186537. else
  186538. ret = farmalloc(size);
  186539. #ifndef PNG_USER_MEM_SUPPORTED
  186540. if (ret == NULL)
  186541. {
  186542. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186543. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186544. else
  186545. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186546. }
  186547. #endif
  186548. return (ret);
  186549. }
  186550. /* free a pointer allocated by png_malloc(). In the default
  186551. configuration, png_ptr is not used, but is passed in case it
  186552. is needed. If ptr is NULL, return without taking any action. */
  186553. void PNGAPI
  186554. png_free(png_structp png_ptr, png_voidp ptr)
  186555. {
  186556. if (png_ptr == NULL || ptr == NULL)
  186557. return;
  186558. #ifdef PNG_USER_MEM_SUPPORTED
  186559. if (png_ptr->free_fn != NULL)
  186560. {
  186561. (*(png_ptr->free_fn))(png_ptr, ptr);
  186562. return;
  186563. }
  186564. else png_free_default(png_ptr, ptr);
  186565. }
  186566. void PNGAPI
  186567. png_free_default(png_structp png_ptr, png_voidp ptr)
  186568. {
  186569. #endif /* PNG_USER_MEM_SUPPORTED */
  186570. if(png_ptr == NULL) return;
  186571. if (png_ptr->offset_table != NULL)
  186572. {
  186573. int i;
  186574. for (i = 0; i < png_ptr->offset_table_count; i++)
  186575. {
  186576. if (ptr == png_ptr->offset_table_ptr[i])
  186577. {
  186578. ptr = NULL;
  186579. png_ptr->offset_table_count_free++;
  186580. break;
  186581. }
  186582. }
  186583. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186584. {
  186585. farfree(png_ptr->offset_table);
  186586. farfree(png_ptr->offset_table_ptr);
  186587. png_ptr->offset_table = NULL;
  186588. png_ptr->offset_table_ptr = NULL;
  186589. }
  186590. }
  186591. if (ptr != NULL)
  186592. {
  186593. farfree(ptr);
  186594. }
  186595. }
  186596. #else /* Not the Borland DOS special memory handler */
  186597. /* Allocate memory for a png_struct or a png_info. The malloc and
  186598. memset can be replaced by a single call to calloc() if this is thought
  186599. to improve performance noticably. */
  186600. png_voidp /* PRIVATE */
  186601. png_create_struct(int type)
  186602. {
  186603. #ifdef PNG_USER_MEM_SUPPORTED
  186604. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186605. }
  186606. /* Allocate memory for a png_struct or a png_info. The malloc and
  186607. memset can be replaced by a single call to calloc() if this is thought
  186608. to improve performance noticably. */
  186609. png_voidp /* PRIVATE */
  186610. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186611. {
  186612. #endif /* PNG_USER_MEM_SUPPORTED */
  186613. png_size_t size;
  186614. png_voidp struct_ptr;
  186615. if (type == PNG_STRUCT_INFO)
  186616. size = png_sizeof(png_info);
  186617. else if (type == PNG_STRUCT_PNG)
  186618. size = png_sizeof(png_struct);
  186619. else
  186620. return (NULL);
  186621. #ifdef PNG_USER_MEM_SUPPORTED
  186622. if(malloc_fn != NULL)
  186623. {
  186624. png_struct dummy_struct;
  186625. png_structp png_ptr = &dummy_struct;
  186626. png_ptr->mem_ptr=mem_ptr;
  186627. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186628. if (struct_ptr != NULL)
  186629. png_memset(struct_ptr, 0, size);
  186630. return (struct_ptr);
  186631. }
  186632. #endif /* PNG_USER_MEM_SUPPORTED */
  186633. #if defined(__TURBOC__) && !defined(__FLAT__)
  186634. struct_ptr = (png_voidp)farmalloc(size);
  186635. #else
  186636. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186637. struct_ptr = (png_voidp)halloc(size,1);
  186638. # else
  186639. struct_ptr = (png_voidp)malloc(size);
  186640. # endif
  186641. #endif
  186642. if (struct_ptr != NULL)
  186643. png_memset(struct_ptr, 0, size);
  186644. return (struct_ptr);
  186645. }
  186646. /* Free memory allocated by a png_create_struct() call */
  186647. void /* PRIVATE */
  186648. png_destroy_struct(png_voidp struct_ptr)
  186649. {
  186650. #ifdef PNG_USER_MEM_SUPPORTED
  186651. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186652. }
  186653. /* Free memory allocated by a png_create_struct() call */
  186654. void /* PRIVATE */
  186655. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186656. png_voidp mem_ptr)
  186657. {
  186658. #endif /* PNG_USER_MEM_SUPPORTED */
  186659. if (struct_ptr != NULL)
  186660. {
  186661. #ifdef PNG_USER_MEM_SUPPORTED
  186662. if(free_fn != NULL)
  186663. {
  186664. png_struct dummy_struct;
  186665. png_structp png_ptr = &dummy_struct;
  186666. png_ptr->mem_ptr=mem_ptr;
  186667. (*(free_fn))(png_ptr, struct_ptr);
  186668. return;
  186669. }
  186670. #endif /* PNG_USER_MEM_SUPPORTED */
  186671. #if defined(__TURBOC__) && !defined(__FLAT__)
  186672. farfree(struct_ptr);
  186673. #else
  186674. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186675. hfree(struct_ptr);
  186676. # else
  186677. free(struct_ptr);
  186678. # endif
  186679. #endif
  186680. }
  186681. }
  186682. /* Allocate memory. For reasonable files, size should never exceed
  186683. 64K. However, zlib may allocate more then 64K if you don't tell
  186684. it not to. See zconf.h and png.h for more information. zlib does
  186685. need to allocate exactly 64K, so whatever you call here must
  186686. have the ability to do that. */
  186687. png_voidp PNGAPI
  186688. png_malloc(png_structp png_ptr, png_uint_32 size)
  186689. {
  186690. png_voidp ret;
  186691. #ifdef PNG_USER_MEM_SUPPORTED
  186692. if (png_ptr == NULL || size == 0)
  186693. return (NULL);
  186694. if(png_ptr->malloc_fn != NULL)
  186695. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186696. else
  186697. ret = (png_malloc_default(png_ptr, size));
  186698. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186699. png_error(png_ptr, "Out of Memory!");
  186700. return (ret);
  186701. }
  186702. png_voidp PNGAPI
  186703. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186704. {
  186705. png_voidp ret;
  186706. #endif /* PNG_USER_MEM_SUPPORTED */
  186707. if (png_ptr == NULL || size == 0)
  186708. return (NULL);
  186709. #ifdef PNG_MAX_MALLOC_64K
  186710. if (size > (png_uint_32)65536L)
  186711. {
  186712. #ifndef PNG_USER_MEM_SUPPORTED
  186713. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186714. png_error(png_ptr, "Cannot Allocate > 64K");
  186715. else
  186716. #endif
  186717. return NULL;
  186718. }
  186719. #endif
  186720. /* Check for overflow */
  186721. #if defined(__TURBOC__) && !defined(__FLAT__)
  186722. if (size != (unsigned long)size)
  186723. ret = NULL;
  186724. else
  186725. ret = farmalloc(size);
  186726. #else
  186727. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186728. if (size != (unsigned long)size)
  186729. ret = NULL;
  186730. else
  186731. ret = halloc(size, 1);
  186732. # else
  186733. if (size != (size_t)size)
  186734. ret = NULL;
  186735. else
  186736. ret = malloc((size_t)size);
  186737. # endif
  186738. #endif
  186739. #ifndef PNG_USER_MEM_SUPPORTED
  186740. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186741. png_error(png_ptr, "Out of Memory");
  186742. #endif
  186743. return (ret);
  186744. }
  186745. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186746. without taking any action. */
  186747. void PNGAPI
  186748. png_free(png_structp png_ptr, png_voidp ptr)
  186749. {
  186750. if (png_ptr == NULL || ptr == NULL)
  186751. return;
  186752. #ifdef PNG_USER_MEM_SUPPORTED
  186753. if (png_ptr->free_fn != NULL)
  186754. {
  186755. (*(png_ptr->free_fn))(png_ptr, ptr);
  186756. return;
  186757. }
  186758. else png_free_default(png_ptr, ptr);
  186759. }
  186760. void PNGAPI
  186761. png_free_default(png_structp png_ptr, png_voidp ptr)
  186762. {
  186763. if (png_ptr == NULL || ptr == NULL)
  186764. return;
  186765. #endif /* PNG_USER_MEM_SUPPORTED */
  186766. #if defined(__TURBOC__) && !defined(__FLAT__)
  186767. farfree(ptr);
  186768. #else
  186769. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186770. hfree(ptr);
  186771. # else
  186772. free(ptr);
  186773. # endif
  186774. #endif
  186775. }
  186776. #endif /* Not Borland DOS special memory handler */
  186777. #if defined(PNG_1_0_X)
  186778. # define png_malloc_warn png_malloc
  186779. #else
  186780. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186781. * function will set up png_malloc() to issue a png_warning and return NULL
  186782. * instead of issuing a png_error, if it fails to allocate the requested
  186783. * memory.
  186784. */
  186785. png_voidp PNGAPI
  186786. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186787. {
  186788. png_voidp ptr;
  186789. png_uint_32 save_flags;
  186790. if(png_ptr == NULL) return (NULL);
  186791. save_flags=png_ptr->flags;
  186792. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186793. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186794. png_ptr->flags=save_flags;
  186795. return(ptr);
  186796. }
  186797. #endif
  186798. png_voidp PNGAPI
  186799. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186800. png_uint_32 length)
  186801. {
  186802. png_size_t size;
  186803. size = (png_size_t)length;
  186804. if ((png_uint_32)size != length)
  186805. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186806. return(png_memcpy (s1, s2, size));
  186807. }
  186808. png_voidp PNGAPI
  186809. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186810. png_uint_32 length)
  186811. {
  186812. png_size_t size;
  186813. size = (png_size_t)length;
  186814. if ((png_uint_32)size != length)
  186815. png_error(png_ptr,"Overflow in png_memset_check.");
  186816. return (png_memset (s1, value, size));
  186817. }
  186818. #ifdef PNG_USER_MEM_SUPPORTED
  186819. /* This function is called when the application wants to use another method
  186820. * of allocating and freeing memory.
  186821. */
  186822. void PNGAPI
  186823. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186824. malloc_fn, png_free_ptr free_fn)
  186825. {
  186826. if(png_ptr != NULL) {
  186827. png_ptr->mem_ptr = mem_ptr;
  186828. png_ptr->malloc_fn = malloc_fn;
  186829. png_ptr->free_fn = free_fn;
  186830. }
  186831. }
  186832. /* This function returns a pointer to the mem_ptr associated with the user
  186833. * functions. The application should free any memory associated with this
  186834. * pointer before png_write_destroy and png_read_destroy are called.
  186835. */
  186836. png_voidp PNGAPI
  186837. png_get_mem_ptr(png_structp png_ptr)
  186838. {
  186839. if(png_ptr == NULL) return (NULL);
  186840. return ((png_voidp)png_ptr->mem_ptr);
  186841. }
  186842. #endif /* PNG_USER_MEM_SUPPORTED */
  186843. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186844. /*** End of inlined file: pngmem.c ***/
  186845. /*** Start of inlined file: pngread.c ***/
  186846. /* pngread.c - read a PNG file
  186847. *
  186848. * Last changed in libpng 1.2.20 September 7, 2007
  186849. * For conditions of distribution and use, see copyright notice in png.h
  186850. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186851. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186852. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186853. *
  186854. * This file contains routines that an application calls directly to
  186855. * read a PNG file or stream.
  186856. */
  186857. #define PNG_INTERNAL
  186858. #if defined(PNG_READ_SUPPORTED)
  186859. /* Create a PNG structure for reading, and allocate any memory needed. */
  186860. png_structp PNGAPI
  186861. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186862. png_error_ptr error_fn, png_error_ptr warn_fn)
  186863. {
  186864. #ifdef PNG_USER_MEM_SUPPORTED
  186865. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186866. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186867. }
  186868. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186869. png_structp PNGAPI
  186870. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186871. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186872. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186873. {
  186874. #endif /* PNG_USER_MEM_SUPPORTED */
  186875. png_structp png_ptr;
  186876. #ifdef PNG_SETJMP_SUPPORTED
  186877. #ifdef USE_FAR_KEYWORD
  186878. jmp_buf jmpbuf;
  186879. #endif
  186880. #endif
  186881. int i;
  186882. png_debug(1, "in png_create_read_struct\n");
  186883. #ifdef PNG_USER_MEM_SUPPORTED
  186884. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186885. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186886. #else
  186887. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186888. #endif
  186889. if (png_ptr == NULL)
  186890. return (NULL);
  186891. /* added at libpng-1.2.6 */
  186892. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186893. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186894. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186895. #endif
  186896. #ifdef PNG_SETJMP_SUPPORTED
  186897. #ifdef USE_FAR_KEYWORD
  186898. if (setjmp(jmpbuf))
  186899. #else
  186900. if (setjmp(png_ptr->jmpbuf))
  186901. #endif
  186902. {
  186903. png_free(png_ptr, png_ptr->zbuf);
  186904. png_ptr->zbuf=NULL;
  186905. #ifdef PNG_USER_MEM_SUPPORTED
  186906. png_destroy_struct_2((png_voidp)png_ptr,
  186907. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186908. #else
  186909. png_destroy_struct((png_voidp)png_ptr);
  186910. #endif
  186911. return (NULL);
  186912. }
  186913. #ifdef USE_FAR_KEYWORD
  186914. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186915. #endif
  186916. #endif
  186917. #ifdef PNG_USER_MEM_SUPPORTED
  186918. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186919. #endif
  186920. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186921. i=0;
  186922. do
  186923. {
  186924. if(user_png_ver[i] != png_libpng_ver[i])
  186925. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186926. } while (png_libpng_ver[i++]);
  186927. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186928. {
  186929. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186930. * we must recompile any applications that use any older library version.
  186931. * For versions after libpng 1.0, we will be compatible, so we need
  186932. * only check the first digit.
  186933. */
  186934. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186935. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186936. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186937. {
  186938. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186939. char msg[80];
  186940. if (user_png_ver)
  186941. {
  186942. png_snprintf(msg, 80,
  186943. "Application was compiled with png.h from libpng-%.20s",
  186944. user_png_ver);
  186945. png_warning(png_ptr, msg);
  186946. }
  186947. png_snprintf(msg, 80,
  186948. "Application is running with png.c from libpng-%.20s",
  186949. png_libpng_ver);
  186950. png_warning(png_ptr, msg);
  186951. #endif
  186952. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186953. png_ptr->flags=0;
  186954. #endif
  186955. png_error(png_ptr,
  186956. "Incompatible libpng version in application and library");
  186957. }
  186958. }
  186959. /* initialize zbuf - compression buffer */
  186960. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186961. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186962. (png_uint_32)png_ptr->zbuf_size);
  186963. png_ptr->zstream.zalloc = png_zalloc;
  186964. png_ptr->zstream.zfree = png_zfree;
  186965. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186966. switch (inflateInit(&png_ptr->zstream))
  186967. {
  186968. case Z_OK: /* Do nothing */ break;
  186969. case Z_MEM_ERROR:
  186970. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186971. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186972. default: png_error(png_ptr, "Unknown zlib error");
  186973. }
  186974. png_ptr->zstream.next_out = png_ptr->zbuf;
  186975. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186976. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186977. #ifdef PNG_SETJMP_SUPPORTED
  186978. /* Applications that neglect to set up their own setjmp() and then encounter
  186979. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186980. abort instead of returning. */
  186981. #ifdef USE_FAR_KEYWORD
  186982. if (setjmp(jmpbuf))
  186983. PNG_ABORT();
  186984. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186985. #else
  186986. if (setjmp(png_ptr->jmpbuf))
  186987. PNG_ABORT();
  186988. #endif
  186989. #endif
  186990. return (png_ptr);
  186991. }
  186992. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186993. /* Initialize PNG structure for reading, and allocate any memory needed.
  186994. This interface is deprecated in favour of the png_create_read_struct(),
  186995. and it will disappear as of libpng-1.3.0. */
  186996. #undef png_read_init
  186997. void PNGAPI
  186998. png_read_init(png_structp png_ptr)
  186999. {
  187000. /* We only come here via pre-1.0.7-compiled applications */
  187001. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187002. }
  187003. void PNGAPI
  187004. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187005. png_size_t png_struct_size, png_size_t png_info_size)
  187006. {
  187007. /* We only come here via pre-1.0.12-compiled applications */
  187008. if(png_ptr == NULL) return;
  187009. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187010. if(png_sizeof(png_struct) > png_struct_size ||
  187011. png_sizeof(png_info) > png_info_size)
  187012. {
  187013. char msg[80];
  187014. png_ptr->warning_fn=NULL;
  187015. if (user_png_ver)
  187016. {
  187017. png_snprintf(msg, 80,
  187018. "Application was compiled with png.h from libpng-%.20s",
  187019. user_png_ver);
  187020. png_warning(png_ptr, msg);
  187021. }
  187022. png_snprintf(msg, 80,
  187023. "Application is running with png.c from libpng-%.20s",
  187024. png_libpng_ver);
  187025. png_warning(png_ptr, msg);
  187026. }
  187027. #endif
  187028. if(png_sizeof(png_struct) > png_struct_size)
  187029. {
  187030. png_ptr->error_fn=NULL;
  187031. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187032. png_ptr->flags=0;
  187033. #endif
  187034. png_error(png_ptr,
  187035. "The png struct allocated by the application for reading is too small.");
  187036. }
  187037. if(png_sizeof(png_info) > png_info_size)
  187038. {
  187039. png_ptr->error_fn=NULL;
  187040. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187041. png_ptr->flags=0;
  187042. #endif
  187043. png_error(png_ptr,
  187044. "The info struct allocated by application for reading is too small.");
  187045. }
  187046. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187047. }
  187048. #endif /* PNG_1_0_X || PNG_1_2_X */
  187049. void PNGAPI
  187050. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187051. png_size_t png_struct_size)
  187052. {
  187053. #ifdef PNG_SETJMP_SUPPORTED
  187054. jmp_buf tmp_jmp; /* to save current jump buffer */
  187055. #endif
  187056. int i=0;
  187057. png_structp png_ptr=*ptr_ptr;
  187058. if(png_ptr == NULL) return;
  187059. do
  187060. {
  187061. if(user_png_ver[i] != png_libpng_ver[i])
  187062. {
  187063. #ifdef PNG_LEGACY_SUPPORTED
  187064. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187065. #else
  187066. png_ptr->warning_fn=NULL;
  187067. png_warning(png_ptr,
  187068. "Application uses deprecated png_read_init() and should be recompiled.");
  187069. break;
  187070. #endif
  187071. }
  187072. } while (png_libpng_ver[i++]);
  187073. png_debug(1, "in png_read_init_3\n");
  187074. #ifdef PNG_SETJMP_SUPPORTED
  187075. /* save jump buffer and error functions */
  187076. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187077. #endif
  187078. if(png_sizeof(png_struct) > png_struct_size)
  187079. {
  187080. png_destroy_struct(png_ptr);
  187081. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187082. png_ptr = *ptr_ptr;
  187083. }
  187084. /* reset all variables to 0 */
  187085. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187086. #ifdef PNG_SETJMP_SUPPORTED
  187087. /* restore jump buffer */
  187088. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187089. #endif
  187090. /* added at libpng-1.2.6 */
  187091. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187092. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187093. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187094. #endif
  187095. /* initialize zbuf - compression buffer */
  187096. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187097. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187098. (png_uint_32)png_ptr->zbuf_size);
  187099. png_ptr->zstream.zalloc = png_zalloc;
  187100. png_ptr->zstream.zfree = png_zfree;
  187101. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187102. switch (inflateInit(&png_ptr->zstream))
  187103. {
  187104. case Z_OK: /* Do nothing */ break;
  187105. case Z_MEM_ERROR:
  187106. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187107. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187108. default: png_error(png_ptr, "Unknown zlib error");
  187109. }
  187110. png_ptr->zstream.next_out = png_ptr->zbuf;
  187111. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187112. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187113. }
  187114. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187115. /* Read the information before the actual image data. This has been
  187116. * changed in v0.90 to allow reading a file that already has the magic
  187117. * bytes read from the stream. You can tell libpng how many bytes have
  187118. * been read from the beginning of the stream (up to the maximum of 8)
  187119. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187120. * here. The application can then have access to the signature bytes we
  187121. * read if it is determined that this isn't a valid PNG file.
  187122. */
  187123. void PNGAPI
  187124. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187125. {
  187126. if(png_ptr == NULL) return;
  187127. png_debug(1, "in png_read_info\n");
  187128. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187129. if (png_ptr->sig_bytes < 8)
  187130. {
  187131. png_size_t num_checked = png_ptr->sig_bytes,
  187132. num_to_check = 8 - num_checked;
  187133. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187134. png_ptr->sig_bytes = 8;
  187135. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187136. {
  187137. if (num_checked < 4 &&
  187138. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187139. png_error(png_ptr, "Not a PNG file");
  187140. else
  187141. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187142. }
  187143. if (num_checked < 3)
  187144. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187145. }
  187146. for(;;)
  187147. {
  187148. #ifdef PNG_USE_LOCAL_ARRAYS
  187149. PNG_CONST PNG_IHDR;
  187150. PNG_CONST PNG_IDAT;
  187151. PNG_CONST PNG_IEND;
  187152. PNG_CONST PNG_PLTE;
  187153. #if defined(PNG_READ_bKGD_SUPPORTED)
  187154. PNG_CONST PNG_bKGD;
  187155. #endif
  187156. #if defined(PNG_READ_cHRM_SUPPORTED)
  187157. PNG_CONST PNG_cHRM;
  187158. #endif
  187159. #if defined(PNG_READ_gAMA_SUPPORTED)
  187160. PNG_CONST PNG_gAMA;
  187161. #endif
  187162. #if defined(PNG_READ_hIST_SUPPORTED)
  187163. PNG_CONST PNG_hIST;
  187164. #endif
  187165. #if defined(PNG_READ_iCCP_SUPPORTED)
  187166. PNG_CONST PNG_iCCP;
  187167. #endif
  187168. #if defined(PNG_READ_iTXt_SUPPORTED)
  187169. PNG_CONST PNG_iTXt;
  187170. #endif
  187171. #if defined(PNG_READ_oFFs_SUPPORTED)
  187172. PNG_CONST PNG_oFFs;
  187173. #endif
  187174. #if defined(PNG_READ_pCAL_SUPPORTED)
  187175. PNG_CONST PNG_pCAL;
  187176. #endif
  187177. #if defined(PNG_READ_pHYs_SUPPORTED)
  187178. PNG_CONST PNG_pHYs;
  187179. #endif
  187180. #if defined(PNG_READ_sBIT_SUPPORTED)
  187181. PNG_CONST PNG_sBIT;
  187182. #endif
  187183. #if defined(PNG_READ_sCAL_SUPPORTED)
  187184. PNG_CONST PNG_sCAL;
  187185. #endif
  187186. #if defined(PNG_READ_sPLT_SUPPORTED)
  187187. PNG_CONST PNG_sPLT;
  187188. #endif
  187189. #if defined(PNG_READ_sRGB_SUPPORTED)
  187190. PNG_CONST PNG_sRGB;
  187191. #endif
  187192. #if defined(PNG_READ_tEXt_SUPPORTED)
  187193. PNG_CONST PNG_tEXt;
  187194. #endif
  187195. #if defined(PNG_READ_tIME_SUPPORTED)
  187196. PNG_CONST PNG_tIME;
  187197. #endif
  187198. #if defined(PNG_READ_tRNS_SUPPORTED)
  187199. PNG_CONST PNG_tRNS;
  187200. #endif
  187201. #if defined(PNG_READ_zTXt_SUPPORTED)
  187202. PNG_CONST PNG_zTXt;
  187203. #endif
  187204. #endif /* PNG_USE_LOCAL_ARRAYS */
  187205. png_byte chunk_length[4];
  187206. png_uint_32 length;
  187207. png_read_data(png_ptr, chunk_length, 4);
  187208. length = png_get_uint_31(png_ptr,chunk_length);
  187209. png_reset_crc(png_ptr);
  187210. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187211. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187212. length);
  187213. /* This should be a binary subdivision search or a hash for
  187214. * matching the chunk name rather than a linear search.
  187215. */
  187216. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187217. if(png_ptr->mode & PNG_AFTER_IDAT)
  187218. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187219. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187220. png_handle_IHDR(png_ptr, info_ptr, length);
  187221. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187222. png_handle_IEND(png_ptr, info_ptr, length);
  187223. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187224. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187225. {
  187226. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187227. png_ptr->mode |= PNG_HAVE_IDAT;
  187228. png_handle_unknown(png_ptr, info_ptr, length);
  187229. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187230. png_ptr->mode |= PNG_HAVE_PLTE;
  187231. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187232. {
  187233. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187234. png_error(png_ptr, "Missing IHDR before IDAT");
  187235. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187236. !(png_ptr->mode & PNG_HAVE_PLTE))
  187237. png_error(png_ptr, "Missing PLTE before IDAT");
  187238. break;
  187239. }
  187240. }
  187241. #endif
  187242. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187243. png_handle_PLTE(png_ptr, info_ptr, length);
  187244. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187245. {
  187246. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187247. png_error(png_ptr, "Missing IHDR before IDAT");
  187248. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187249. !(png_ptr->mode & PNG_HAVE_PLTE))
  187250. png_error(png_ptr, "Missing PLTE before IDAT");
  187251. png_ptr->idat_size = length;
  187252. png_ptr->mode |= PNG_HAVE_IDAT;
  187253. break;
  187254. }
  187255. #if defined(PNG_READ_bKGD_SUPPORTED)
  187256. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187257. png_handle_bKGD(png_ptr, info_ptr, length);
  187258. #endif
  187259. #if defined(PNG_READ_cHRM_SUPPORTED)
  187260. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187261. png_handle_cHRM(png_ptr, info_ptr, length);
  187262. #endif
  187263. #if defined(PNG_READ_gAMA_SUPPORTED)
  187264. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187265. png_handle_gAMA(png_ptr, info_ptr, length);
  187266. #endif
  187267. #if defined(PNG_READ_hIST_SUPPORTED)
  187268. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187269. png_handle_hIST(png_ptr, info_ptr, length);
  187270. #endif
  187271. #if defined(PNG_READ_oFFs_SUPPORTED)
  187272. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187273. png_handle_oFFs(png_ptr, info_ptr, length);
  187274. #endif
  187275. #if defined(PNG_READ_pCAL_SUPPORTED)
  187276. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187277. png_handle_pCAL(png_ptr, info_ptr, length);
  187278. #endif
  187279. #if defined(PNG_READ_sCAL_SUPPORTED)
  187280. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187281. png_handle_sCAL(png_ptr, info_ptr, length);
  187282. #endif
  187283. #if defined(PNG_READ_pHYs_SUPPORTED)
  187284. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187285. png_handle_pHYs(png_ptr, info_ptr, length);
  187286. #endif
  187287. #if defined(PNG_READ_sBIT_SUPPORTED)
  187288. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187289. png_handle_sBIT(png_ptr, info_ptr, length);
  187290. #endif
  187291. #if defined(PNG_READ_sRGB_SUPPORTED)
  187292. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187293. png_handle_sRGB(png_ptr, info_ptr, length);
  187294. #endif
  187295. #if defined(PNG_READ_iCCP_SUPPORTED)
  187296. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187297. png_handle_iCCP(png_ptr, info_ptr, length);
  187298. #endif
  187299. #if defined(PNG_READ_sPLT_SUPPORTED)
  187300. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187301. png_handle_sPLT(png_ptr, info_ptr, length);
  187302. #endif
  187303. #if defined(PNG_READ_tEXt_SUPPORTED)
  187304. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187305. png_handle_tEXt(png_ptr, info_ptr, length);
  187306. #endif
  187307. #if defined(PNG_READ_tIME_SUPPORTED)
  187308. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187309. png_handle_tIME(png_ptr, info_ptr, length);
  187310. #endif
  187311. #if defined(PNG_READ_tRNS_SUPPORTED)
  187312. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187313. png_handle_tRNS(png_ptr, info_ptr, length);
  187314. #endif
  187315. #if defined(PNG_READ_zTXt_SUPPORTED)
  187316. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187317. png_handle_zTXt(png_ptr, info_ptr, length);
  187318. #endif
  187319. #if defined(PNG_READ_iTXt_SUPPORTED)
  187320. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187321. png_handle_iTXt(png_ptr, info_ptr, length);
  187322. #endif
  187323. else
  187324. png_handle_unknown(png_ptr, info_ptr, length);
  187325. }
  187326. }
  187327. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187328. /* optional call to update the users info_ptr structure */
  187329. void PNGAPI
  187330. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187331. {
  187332. png_debug(1, "in png_read_update_info\n");
  187333. if(png_ptr == NULL) return;
  187334. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187335. png_read_start_row(png_ptr);
  187336. else
  187337. png_warning(png_ptr,
  187338. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187339. png_read_transform_info(png_ptr, info_ptr);
  187340. }
  187341. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187342. /* Initialize palette, background, etc, after transformations
  187343. * are set, but before any reading takes place. This allows
  187344. * the user to obtain a gamma-corrected palette, for example.
  187345. * If the user doesn't call this, we will do it ourselves.
  187346. */
  187347. void PNGAPI
  187348. png_start_read_image(png_structp png_ptr)
  187349. {
  187350. png_debug(1, "in png_start_read_image\n");
  187351. if(png_ptr == NULL) return;
  187352. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187353. png_read_start_row(png_ptr);
  187354. }
  187355. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187356. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187357. void PNGAPI
  187358. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187359. {
  187360. #ifdef PNG_USE_LOCAL_ARRAYS
  187361. PNG_CONST PNG_IDAT;
  187362. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187363. 0xff};
  187364. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187365. #endif
  187366. int ret;
  187367. if(png_ptr == NULL) return;
  187368. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187369. png_ptr->row_number, png_ptr->pass);
  187370. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187371. png_read_start_row(png_ptr);
  187372. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187373. {
  187374. /* check for transforms that have been set but were defined out */
  187375. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187376. if (png_ptr->transformations & PNG_INVERT_MONO)
  187377. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187378. #endif
  187379. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187380. if (png_ptr->transformations & PNG_FILLER)
  187381. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187382. #endif
  187383. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187384. if (png_ptr->transformations & PNG_PACKSWAP)
  187385. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187386. #endif
  187387. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187388. if (png_ptr->transformations & PNG_PACK)
  187389. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187390. #endif
  187391. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187392. if (png_ptr->transformations & PNG_SHIFT)
  187393. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187394. #endif
  187395. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187396. if (png_ptr->transformations & PNG_BGR)
  187397. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187398. #endif
  187399. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187400. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187401. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187402. #endif
  187403. }
  187404. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187405. /* if interlaced and we do not need a new row, combine row and return */
  187406. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187407. {
  187408. switch (png_ptr->pass)
  187409. {
  187410. case 0:
  187411. if (png_ptr->row_number & 0x07)
  187412. {
  187413. if (dsp_row != NULL)
  187414. png_combine_row(png_ptr, dsp_row,
  187415. png_pass_dsp_mask[png_ptr->pass]);
  187416. png_read_finish_row(png_ptr);
  187417. return;
  187418. }
  187419. break;
  187420. case 1:
  187421. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187422. {
  187423. if (dsp_row != NULL)
  187424. png_combine_row(png_ptr, dsp_row,
  187425. png_pass_dsp_mask[png_ptr->pass]);
  187426. png_read_finish_row(png_ptr);
  187427. return;
  187428. }
  187429. break;
  187430. case 2:
  187431. if ((png_ptr->row_number & 0x07) != 4)
  187432. {
  187433. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187434. png_combine_row(png_ptr, dsp_row,
  187435. png_pass_dsp_mask[png_ptr->pass]);
  187436. png_read_finish_row(png_ptr);
  187437. return;
  187438. }
  187439. break;
  187440. case 3:
  187441. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187442. {
  187443. if (dsp_row != NULL)
  187444. png_combine_row(png_ptr, dsp_row,
  187445. png_pass_dsp_mask[png_ptr->pass]);
  187446. png_read_finish_row(png_ptr);
  187447. return;
  187448. }
  187449. break;
  187450. case 4:
  187451. if ((png_ptr->row_number & 3) != 2)
  187452. {
  187453. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187454. png_combine_row(png_ptr, dsp_row,
  187455. png_pass_dsp_mask[png_ptr->pass]);
  187456. png_read_finish_row(png_ptr);
  187457. return;
  187458. }
  187459. break;
  187460. case 5:
  187461. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187462. {
  187463. if (dsp_row != NULL)
  187464. png_combine_row(png_ptr, dsp_row,
  187465. png_pass_dsp_mask[png_ptr->pass]);
  187466. png_read_finish_row(png_ptr);
  187467. return;
  187468. }
  187469. break;
  187470. case 6:
  187471. if (!(png_ptr->row_number & 1))
  187472. {
  187473. png_read_finish_row(png_ptr);
  187474. return;
  187475. }
  187476. break;
  187477. }
  187478. }
  187479. #endif
  187480. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187481. png_error(png_ptr, "Invalid attempt to read row data");
  187482. png_ptr->zstream.next_out = png_ptr->row_buf;
  187483. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187484. do
  187485. {
  187486. if (!(png_ptr->zstream.avail_in))
  187487. {
  187488. while (!png_ptr->idat_size)
  187489. {
  187490. png_byte chunk_length[4];
  187491. png_crc_finish(png_ptr, 0);
  187492. png_read_data(png_ptr, chunk_length, 4);
  187493. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187494. png_reset_crc(png_ptr);
  187495. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187496. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187497. png_error(png_ptr, "Not enough image data");
  187498. }
  187499. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187500. png_ptr->zstream.next_in = png_ptr->zbuf;
  187501. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187502. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187503. png_crc_read(png_ptr, png_ptr->zbuf,
  187504. (png_size_t)png_ptr->zstream.avail_in);
  187505. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187506. }
  187507. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187508. if (ret == Z_STREAM_END)
  187509. {
  187510. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187511. png_ptr->idat_size)
  187512. png_error(png_ptr, "Extra compressed data");
  187513. png_ptr->mode |= PNG_AFTER_IDAT;
  187514. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187515. break;
  187516. }
  187517. if (ret != Z_OK)
  187518. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187519. "Decompression error");
  187520. } while (png_ptr->zstream.avail_out);
  187521. png_ptr->row_info.color_type = png_ptr->color_type;
  187522. png_ptr->row_info.width = png_ptr->iwidth;
  187523. png_ptr->row_info.channels = png_ptr->channels;
  187524. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187525. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187526. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187527. png_ptr->row_info.width);
  187528. if(png_ptr->row_buf[0])
  187529. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187530. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187531. (int)(png_ptr->row_buf[0]));
  187532. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187533. png_ptr->rowbytes + 1);
  187534. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187535. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187536. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187537. {
  187538. /* Intrapixel differencing */
  187539. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187540. }
  187541. #endif
  187542. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187543. png_do_read_transformations(png_ptr);
  187544. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187545. /* blow up interlaced rows to full size */
  187546. if (png_ptr->interlaced &&
  187547. (png_ptr->transformations & PNG_INTERLACE))
  187548. {
  187549. if (png_ptr->pass < 6)
  187550. /* old interface (pre-1.0.9):
  187551. png_do_read_interlace(&(png_ptr->row_info),
  187552. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187553. */
  187554. png_do_read_interlace(png_ptr);
  187555. if (dsp_row != NULL)
  187556. png_combine_row(png_ptr, dsp_row,
  187557. png_pass_dsp_mask[png_ptr->pass]);
  187558. if (row != NULL)
  187559. png_combine_row(png_ptr, row,
  187560. png_pass_mask[png_ptr->pass]);
  187561. }
  187562. else
  187563. #endif
  187564. {
  187565. if (row != NULL)
  187566. png_combine_row(png_ptr, row, 0xff);
  187567. if (dsp_row != NULL)
  187568. png_combine_row(png_ptr, dsp_row, 0xff);
  187569. }
  187570. png_read_finish_row(png_ptr);
  187571. if (png_ptr->read_row_fn != NULL)
  187572. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187573. }
  187574. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187575. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187576. /* Read one or more rows of image data. If the image is interlaced,
  187577. * and png_set_interlace_handling() has been called, the rows need to
  187578. * contain the contents of the rows from the previous pass. If the
  187579. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187580. * called, the rows contents must be initialized to the contents of the
  187581. * screen.
  187582. *
  187583. * "row" holds the actual image, and pixels are placed in it
  187584. * as they arrive. If the image is displayed after each pass, it will
  187585. * appear to "sparkle" in. "display_row" can be used to display a
  187586. * "chunky" progressive image, with finer detail added as it becomes
  187587. * available. If you do not want this "chunky" display, you may pass
  187588. * NULL for display_row. If you do not want the sparkle display, and
  187589. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187590. * If you have called png_handle_alpha(), and the image has either an
  187591. * alpha channel or a transparency chunk, you must provide a buffer for
  187592. * rows. In this case, you do not have to provide a display_row buffer
  187593. * also, but you may. If the image is not interlaced, or if you have
  187594. * not called png_set_interlace_handling(), the display_row buffer will
  187595. * be ignored, so pass NULL to it.
  187596. *
  187597. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187598. */
  187599. void PNGAPI
  187600. png_read_rows(png_structp png_ptr, png_bytepp row,
  187601. png_bytepp display_row, png_uint_32 num_rows)
  187602. {
  187603. png_uint_32 i;
  187604. png_bytepp rp;
  187605. png_bytepp dp;
  187606. png_debug(1, "in png_read_rows\n");
  187607. if(png_ptr == NULL) return;
  187608. rp = row;
  187609. dp = display_row;
  187610. if (rp != NULL && dp != NULL)
  187611. for (i = 0; i < num_rows; i++)
  187612. {
  187613. png_bytep rptr = *rp++;
  187614. png_bytep dptr = *dp++;
  187615. png_read_row(png_ptr, rptr, dptr);
  187616. }
  187617. else if(rp != NULL)
  187618. for (i = 0; i < num_rows; i++)
  187619. {
  187620. png_bytep rptr = *rp;
  187621. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187622. rp++;
  187623. }
  187624. else if(dp != NULL)
  187625. for (i = 0; i < num_rows; i++)
  187626. {
  187627. png_bytep dptr = *dp;
  187628. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187629. dp++;
  187630. }
  187631. }
  187632. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187633. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187634. /* Read the entire image. If the image has an alpha channel or a tRNS
  187635. * chunk, and you have called png_handle_alpha()[*], you will need to
  187636. * initialize the image to the current image that PNG will be overlaying.
  187637. * We set the num_rows again here, in case it was incorrectly set in
  187638. * png_read_start_row() by a call to png_read_update_info() or
  187639. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187640. * prior to either of these functions like it should have been. You can
  187641. * only call this function once. If you desire to have an image for
  187642. * each pass of a interlaced image, use png_read_rows() instead.
  187643. *
  187644. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187645. */
  187646. void PNGAPI
  187647. png_read_image(png_structp png_ptr, png_bytepp image)
  187648. {
  187649. png_uint_32 i,image_height;
  187650. int pass, j;
  187651. png_bytepp rp;
  187652. png_debug(1, "in png_read_image\n");
  187653. if(png_ptr == NULL) return;
  187654. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187655. pass = png_set_interlace_handling(png_ptr);
  187656. #else
  187657. if (png_ptr->interlaced)
  187658. png_error(png_ptr,
  187659. "Cannot read interlaced image -- interlace handler disabled.");
  187660. pass = 1;
  187661. #endif
  187662. image_height=png_ptr->height;
  187663. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187664. for (j = 0; j < pass; j++)
  187665. {
  187666. rp = image;
  187667. for (i = 0; i < image_height; i++)
  187668. {
  187669. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187670. rp++;
  187671. }
  187672. }
  187673. }
  187674. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187675. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187676. /* Read the end of the PNG file. Will not read past the end of the
  187677. * file, will verify the end is accurate, and will read any comments
  187678. * or time information at the end of the file, if info is not NULL.
  187679. */
  187680. void PNGAPI
  187681. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187682. {
  187683. png_byte chunk_length[4];
  187684. png_uint_32 length;
  187685. png_debug(1, "in png_read_end\n");
  187686. if(png_ptr == NULL) return;
  187687. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187688. do
  187689. {
  187690. #ifdef PNG_USE_LOCAL_ARRAYS
  187691. PNG_CONST PNG_IHDR;
  187692. PNG_CONST PNG_IDAT;
  187693. PNG_CONST PNG_IEND;
  187694. PNG_CONST PNG_PLTE;
  187695. #if defined(PNG_READ_bKGD_SUPPORTED)
  187696. PNG_CONST PNG_bKGD;
  187697. #endif
  187698. #if defined(PNG_READ_cHRM_SUPPORTED)
  187699. PNG_CONST PNG_cHRM;
  187700. #endif
  187701. #if defined(PNG_READ_gAMA_SUPPORTED)
  187702. PNG_CONST PNG_gAMA;
  187703. #endif
  187704. #if defined(PNG_READ_hIST_SUPPORTED)
  187705. PNG_CONST PNG_hIST;
  187706. #endif
  187707. #if defined(PNG_READ_iCCP_SUPPORTED)
  187708. PNG_CONST PNG_iCCP;
  187709. #endif
  187710. #if defined(PNG_READ_iTXt_SUPPORTED)
  187711. PNG_CONST PNG_iTXt;
  187712. #endif
  187713. #if defined(PNG_READ_oFFs_SUPPORTED)
  187714. PNG_CONST PNG_oFFs;
  187715. #endif
  187716. #if defined(PNG_READ_pCAL_SUPPORTED)
  187717. PNG_CONST PNG_pCAL;
  187718. #endif
  187719. #if defined(PNG_READ_pHYs_SUPPORTED)
  187720. PNG_CONST PNG_pHYs;
  187721. #endif
  187722. #if defined(PNG_READ_sBIT_SUPPORTED)
  187723. PNG_CONST PNG_sBIT;
  187724. #endif
  187725. #if defined(PNG_READ_sCAL_SUPPORTED)
  187726. PNG_CONST PNG_sCAL;
  187727. #endif
  187728. #if defined(PNG_READ_sPLT_SUPPORTED)
  187729. PNG_CONST PNG_sPLT;
  187730. #endif
  187731. #if defined(PNG_READ_sRGB_SUPPORTED)
  187732. PNG_CONST PNG_sRGB;
  187733. #endif
  187734. #if defined(PNG_READ_tEXt_SUPPORTED)
  187735. PNG_CONST PNG_tEXt;
  187736. #endif
  187737. #if defined(PNG_READ_tIME_SUPPORTED)
  187738. PNG_CONST PNG_tIME;
  187739. #endif
  187740. #if defined(PNG_READ_tRNS_SUPPORTED)
  187741. PNG_CONST PNG_tRNS;
  187742. #endif
  187743. #if defined(PNG_READ_zTXt_SUPPORTED)
  187744. PNG_CONST PNG_zTXt;
  187745. #endif
  187746. #endif /* PNG_USE_LOCAL_ARRAYS */
  187747. png_read_data(png_ptr, chunk_length, 4);
  187748. length = png_get_uint_31(png_ptr,chunk_length);
  187749. png_reset_crc(png_ptr);
  187750. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187751. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187752. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187753. png_handle_IHDR(png_ptr, info_ptr, length);
  187754. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187755. png_handle_IEND(png_ptr, info_ptr, length);
  187756. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187757. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187758. {
  187759. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187760. {
  187761. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187762. png_error(png_ptr, "Too many IDAT's found");
  187763. }
  187764. png_handle_unknown(png_ptr, info_ptr, length);
  187765. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187766. png_ptr->mode |= PNG_HAVE_PLTE;
  187767. }
  187768. #endif
  187769. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187770. {
  187771. /* Zero length IDATs are legal after the last IDAT has been
  187772. * read, but not after other chunks have been read.
  187773. */
  187774. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187775. png_error(png_ptr, "Too many IDAT's found");
  187776. png_crc_finish(png_ptr, length);
  187777. }
  187778. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187779. png_handle_PLTE(png_ptr, info_ptr, length);
  187780. #if defined(PNG_READ_bKGD_SUPPORTED)
  187781. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187782. png_handle_bKGD(png_ptr, info_ptr, length);
  187783. #endif
  187784. #if defined(PNG_READ_cHRM_SUPPORTED)
  187785. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187786. png_handle_cHRM(png_ptr, info_ptr, length);
  187787. #endif
  187788. #if defined(PNG_READ_gAMA_SUPPORTED)
  187789. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187790. png_handle_gAMA(png_ptr, info_ptr, length);
  187791. #endif
  187792. #if defined(PNG_READ_hIST_SUPPORTED)
  187793. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187794. png_handle_hIST(png_ptr, info_ptr, length);
  187795. #endif
  187796. #if defined(PNG_READ_oFFs_SUPPORTED)
  187797. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187798. png_handle_oFFs(png_ptr, info_ptr, length);
  187799. #endif
  187800. #if defined(PNG_READ_pCAL_SUPPORTED)
  187801. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187802. png_handle_pCAL(png_ptr, info_ptr, length);
  187803. #endif
  187804. #if defined(PNG_READ_sCAL_SUPPORTED)
  187805. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187806. png_handle_sCAL(png_ptr, info_ptr, length);
  187807. #endif
  187808. #if defined(PNG_READ_pHYs_SUPPORTED)
  187809. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187810. png_handle_pHYs(png_ptr, info_ptr, length);
  187811. #endif
  187812. #if defined(PNG_READ_sBIT_SUPPORTED)
  187813. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187814. png_handle_sBIT(png_ptr, info_ptr, length);
  187815. #endif
  187816. #if defined(PNG_READ_sRGB_SUPPORTED)
  187817. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187818. png_handle_sRGB(png_ptr, info_ptr, length);
  187819. #endif
  187820. #if defined(PNG_READ_iCCP_SUPPORTED)
  187821. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187822. png_handle_iCCP(png_ptr, info_ptr, length);
  187823. #endif
  187824. #if defined(PNG_READ_sPLT_SUPPORTED)
  187825. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187826. png_handle_sPLT(png_ptr, info_ptr, length);
  187827. #endif
  187828. #if defined(PNG_READ_tEXt_SUPPORTED)
  187829. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187830. png_handle_tEXt(png_ptr, info_ptr, length);
  187831. #endif
  187832. #if defined(PNG_READ_tIME_SUPPORTED)
  187833. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187834. png_handle_tIME(png_ptr, info_ptr, length);
  187835. #endif
  187836. #if defined(PNG_READ_tRNS_SUPPORTED)
  187837. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187838. png_handle_tRNS(png_ptr, info_ptr, length);
  187839. #endif
  187840. #if defined(PNG_READ_zTXt_SUPPORTED)
  187841. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187842. png_handle_zTXt(png_ptr, info_ptr, length);
  187843. #endif
  187844. #if defined(PNG_READ_iTXt_SUPPORTED)
  187845. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187846. png_handle_iTXt(png_ptr, info_ptr, length);
  187847. #endif
  187848. else
  187849. png_handle_unknown(png_ptr, info_ptr, length);
  187850. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187851. }
  187852. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187853. /* free all memory used by the read */
  187854. void PNGAPI
  187855. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187856. png_infopp end_info_ptr_ptr)
  187857. {
  187858. png_structp png_ptr = NULL;
  187859. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187860. #ifdef PNG_USER_MEM_SUPPORTED
  187861. png_free_ptr free_fn;
  187862. png_voidp mem_ptr;
  187863. #endif
  187864. png_debug(1, "in png_destroy_read_struct\n");
  187865. if (png_ptr_ptr != NULL)
  187866. png_ptr = *png_ptr_ptr;
  187867. if (info_ptr_ptr != NULL)
  187868. info_ptr = *info_ptr_ptr;
  187869. if (end_info_ptr_ptr != NULL)
  187870. end_info_ptr = *end_info_ptr_ptr;
  187871. #ifdef PNG_USER_MEM_SUPPORTED
  187872. free_fn = png_ptr->free_fn;
  187873. mem_ptr = png_ptr->mem_ptr;
  187874. #endif
  187875. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187876. if (info_ptr != NULL)
  187877. {
  187878. #if defined(PNG_TEXT_SUPPORTED)
  187879. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187880. #endif
  187881. #ifdef PNG_USER_MEM_SUPPORTED
  187882. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187883. (png_voidp)mem_ptr);
  187884. #else
  187885. png_destroy_struct((png_voidp)info_ptr);
  187886. #endif
  187887. *info_ptr_ptr = NULL;
  187888. }
  187889. if (end_info_ptr != NULL)
  187890. {
  187891. #if defined(PNG_READ_TEXT_SUPPORTED)
  187892. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187893. #endif
  187894. #ifdef PNG_USER_MEM_SUPPORTED
  187895. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187896. (png_voidp)mem_ptr);
  187897. #else
  187898. png_destroy_struct((png_voidp)end_info_ptr);
  187899. #endif
  187900. *end_info_ptr_ptr = NULL;
  187901. }
  187902. if (png_ptr != NULL)
  187903. {
  187904. #ifdef PNG_USER_MEM_SUPPORTED
  187905. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187906. (png_voidp)mem_ptr);
  187907. #else
  187908. png_destroy_struct((png_voidp)png_ptr);
  187909. #endif
  187910. *png_ptr_ptr = NULL;
  187911. }
  187912. }
  187913. /* free all memory used by the read (old method) */
  187914. void /* PRIVATE */
  187915. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187916. {
  187917. #ifdef PNG_SETJMP_SUPPORTED
  187918. jmp_buf tmp_jmp;
  187919. #endif
  187920. png_error_ptr error_fn;
  187921. png_error_ptr warning_fn;
  187922. png_voidp error_ptr;
  187923. #ifdef PNG_USER_MEM_SUPPORTED
  187924. png_free_ptr free_fn;
  187925. #endif
  187926. png_debug(1, "in png_read_destroy\n");
  187927. if (info_ptr != NULL)
  187928. png_info_destroy(png_ptr, info_ptr);
  187929. if (end_info_ptr != NULL)
  187930. png_info_destroy(png_ptr, end_info_ptr);
  187931. png_free(png_ptr, png_ptr->zbuf);
  187932. png_free(png_ptr, png_ptr->big_row_buf);
  187933. png_free(png_ptr, png_ptr->prev_row);
  187934. #if defined(PNG_READ_DITHER_SUPPORTED)
  187935. png_free(png_ptr, png_ptr->palette_lookup);
  187936. png_free(png_ptr, png_ptr->dither_index);
  187937. #endif
  187938. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187939. png_free(png_ptr, png_ptr->gamma_table);
  187940. #endif
  187941. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187942. png_free(png_ptr, png_ptr->gamma_from_1);
  187943. png_free(png_ptr, png_ptr->gamma_to_1);
  187944. #endif
  187945. #ifdef PNG_FREE_ME_SUPPORTED
  187946. if (png_ptr->free_me & PNG_FREE_PLTE)
  187947. png_zfree(png_ptr, png_ptr->palette);
  187948. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187949. #else
  187950. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187951. png_zfree(png_ptr, png_ptr->palette);
  187952. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187953. #endif
  187954. #if defined(PNG_tRNS_SUPPORTED) || \
  187955. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187956. #ifdef PNG_FREE_ME_SUPPORTED
  187957. if (png_ptr->free_me & PNG_FREE_TRNS)
  187958. png_free(png_ptr, png_ptr->trans);
  187959. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187960. #else
  187961. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187962. png_free(png_ptr, png_ptr->trans);
  187963. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187964. #endif
  187965. #endif
  187966. #if defined(PNG_READ_hIST_SUPPORTED)
  187967. #ifdef PNG_FREE_ME_SUPPORTED
  187968. if (png_ptr->free_me & PNG_FREE_HIST)
  187969. png_free(png_ptr, png_ptr->hist);
  187970. png_ptr->free_me &= ~PNG_FREE_HIST;
  187971. #else
  187972. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187973. png_free(png_ptr, png_ptr->hist);
  187974. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187975. #endif
  187976. #endif
  187977. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187978. if (png_ptr->gamma_16_table != NULL)
  187979. {
  187980. int i;
  187981. int istop = (1 << (8 - png_ptr->gamma_shift));
  187982. for (i = 0; i < istop; i++)
  187983. {
  187984. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187985. }
  187986. png_free(png_ptr, png_ptr->gamma_16_table);
  187987. }
  187988. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187989. if (png_ptr->gamma_16_from_1 != NULL)
  187990. {
  187991. int i;
  187992. int istop = (1 << (8 - png_ptr->gamma_shift));
  187993. for (i = 0; i < istop; i++)
  187994. {
  187995. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187996. }
  187997. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187998. }
  187999. if (png_ptr->gamma_16_to_1 != NULL)
  188000. {
  188001. int i;
  188002. int istop = (1 << (8 - png_ptr->gamma_shift));
  188003. for (i = 0; i < istop; i++)
  188004. {
  188005. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188006. }
  188007. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188008. }
  188009. #endif
  188010. #endif
  188011. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188012. png_free(png_ptr, png_ptr->time_buffer);
  188013. #endif
  188014. inflateEnd(&png_ptr->zstream);
  188015. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188016. png_free(png_ptr, png_ptr->save_buffer);
  188017. #endif
  188018. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188019. #ifdef PNG_TEXT_SUPPORTED
  188020. png_free(png_ptr, png_ptr->current_text);
  188021. #endif /* PNG_TEXT_SUPPORTED */
  188022. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188023. /* Save the important info out of the png_struct, in case it is
  188024. * being used again.
  188025. */
  188026. #ifdef PNG_SETJMP_SUPPORTED
  188027. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188028. #endif
  188029. error_fn = png_ptr->error_fn;
  188030. warning_fn = png_ptr->warning_fn;
  188031. error_ptr = png_ptr->error_ptr;
  188032. #ifdef PNG_USER_MEM_SUPPORTED
  188033. free_fn = png_ptr->free_fn;
  188034. #endif
  188035. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188036. png_ptr->error_fn = error_fn;
  188037. png_ptr->warning_fn = warning_fn;
  188038. png_ptr->error_ptr = error_ptr;
  188039. #ifdef PNG_USER_MEM_SUPPORTED
  188040. png_ptr->free_fn = free_fn;
  188041. #endif
  188042. #ifdef PNG_SETJMP_SUPPORTED
  188043. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188044. #endif
  188045. }
  188046. void PNGAPI
  188047. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188048. {
  188049. if(png_ptr == NULL) return;
  188050. png_ptr->read_row_fn = read_row_fn;
  188051. }
  188052. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188053. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188054. void PNGAPI
  188055. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188056. int transforms,
  188057. voidp params)
  188058. {
  188059. int row;
  188060. if(png_ptr == NULL) return;
  188061. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188062. /* invert the alpha channel from opacity to transparency
  188063. */
  188064. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188065. png_set_invert_alpha(png_ptr);
  188066. #endif
  188067. /* png_read_info() gives us all of the information from the
  188068. * PNG file before the first IDAT (image data chunk).
  188069. */
  188070. png_read_info(png_ptr, info_ptr);
  188071. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188072. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188073. /* -------------- image transformations start here ------------------- */
  188074. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188075. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188076. */
  188077. if (transforms & PNG_TRANSFORM_STRIP_16)
  188078. png_set_strip_16(png_ptr);
  188079. #endif
  188080. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188081. /* Strip alpha bytes from the input data without combining with
  188082. * the background (not recommended).
  188083. */
  188084. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188085. png_set_strip_alpha(png_ptr);
  188086. #endif
  188087. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188088. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188089. * byte into separate bytes (useful for paletted and grayscale images).
  188090. */
  188091. if (transforms & PNG_TRANSFORM_PACKING)
  188092. png_set_packing(png_ptr);
  188093. #endif
  188094. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188095. /* Change the order of packed pixels to least significant bit first
  188096. * (not useful if you are using png_set_packing).
  188097. */
  188098. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188099. png_set_packswap(png_ptr);
  188100. #endif
  188101. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188102. /* Expand paletted colors into true RGB triplets
  188103. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188104. * Expand paletted or RGB images with transparency to full alpha
  188105. * channels so the data will be available as RGBA quartets.
  188106. */
  188107. if (transforms & PNG_TRANSFORM_EXPAND)
  188108. if ((png_ptr->bit_depth < 8) ||
  188109. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188110. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188111. png_set_expand(png_ptr);
  188112. #endif
  188113. /* We don't handle background color or gamma transformation or dithering.
  188114. */
  188115. #if defined(PNG_READ_INVERT_SUPPORTED)
  188116. /* invert monochrome files to have 0 as white and 1 as black
  188117. */
  188118. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188119. png_set_invert_mono(png_ptr);
  188120. #endif
  188121. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188122. /* If you want to shift the pixel values from the range [0,255] or
  188123. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188124. * colors were originally in:
  188125. */
  188126. if ((transforms & PNG_TRANSFORM_SHIFT)
  188127. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188128. {
  188129. png_color_8p sig_bit;
  188130. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188131. png_set_shift(png_ptr, sig_bit);
  188132. }
  188133. #endif
  188134. #if defined(PNG_READ_BGR_SUPPORTED)
  188135. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188136. */
  188137. if (transforms & PNG_TRANSFORM_BGR)
  188138. png_set_bgr(png_ptr);
  188139. #endif
  188140. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188141. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188142. */
  188143. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188144. png_set_swap_alpha(png_ptr);
  188145. #endif
  188146. #if defined(PNG_READ_SWAP_SUPPORTED)
  188147. /* swap bytes of 16 bit files to least significant byte first
  188148. */
  188149. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188150. png_set_swap(png_ptr);
  188151. #endif
  188152. /* We don't handle adding filler bytes */
  188153. /* Optional call to gamma correct and add the background to the palette
  188154. * and update info structure. REQUIRED if you are expecting libpng to
  188155. * update the palette for you (i.e., you selected such a transform above).
  188156. */
  188157. png_read_update_info(png_ptr, info_ptr);
  188158. /* -------------- image transformations end here ------------------- */
  188159. #ifdef PNG_FREE_ME_SUPPORTED
  188160. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188161. #endif
  188162. if(info_ptr->row_pointers == NULL)
  188163. {
  188164. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188165. info_ptr->height * png_sizeof(png_bytep));
  188166. #ifdef PNG_FREE_ME_SUPPORTED
  188167. info_ptr->free_me |= PNG_FREE_ROWS;
  188168. #endif
  188169. for (row = 0; row < (int)info_ptr->height; row++)
  188170. {
  188171. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188172. png_get_rowbytes(png_ptr, info_ptr));
  188173. }
  188174. }
  188175. png_read_image(png_ptr, info_ptr->row_pointers);
  188176. info_ptr->valid |= PNG_INFO_IDAT;
  188177. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188178. png_read_end(png_ptr, info_ptr);
  188179. transforms = transforms; /* quiet compiler warnings */
  188180. params = params;
  188181. }
  188182. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188183. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188184. #endif /* PNG_READ_SUPPORTED */
  188185. /*** End of inlined file: pngread.c ***/
  188186. /*** Start of inlined file: pngpread.c ***/
  188187. /* pngpread.c - read a png file in push mode
  188188. *
  188189. * Last changed in libpng 1.2.21 October 4, 2007
  188190. * For conditions of distribution and use, see copyright notice in png.h
  188191. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188192. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188193. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188194. */
  188195. #define PNG_INTERNAL
  188196. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188197. /* push model modes */
  188198. #define PNG_READ_SIG_MODE 0
  188199. #define PNG_READ_CHUNK_MODE 1
  188200. #define PNG_READ_IDAT_MODE 2
  188201. #define PNG_SKIP_MODE 3
  188202. #define PNG_READ_tEXt_MODE 4
  188203. #define PNG_READ_zTXt_MODE 5
  188204. #define PNG_READ_DONE_MODE 6
  188205. #define PNG_READ_iTXt_MODE 7
  188206. #define PNG_ERROR_MODE 8
  188207. void PNGAPI
  188208. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188209. png_bytep buffer, png_size_t buffer_size)
  188210. {
  188211. if(png_ptr == NULL) return;
  188212. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188213. while (png_ptr->buffer_size)
  188214. {
  188215. png_process_some_data(png_ptr, info_ptr);
  188216. }
  188217. }
  188218. /* What we do with the incoming data depends on what we were previously
  188219. * doing before we ran out of data...
  188220. */
  188221. void /* PRIVATE */
  188222. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188223. {
  188224. if(png_ptr == NULL) return;
  188225. switch (png_ptr->process_mode)
  188226. {
  188227. case PNG_READ_SIG_MODE:
  188228. {
  188229. png_push_read_sig(png_ptr, info_ptr);
  188230. break;
  188231. }
  188232. case PNG_READ_CHUNK_MODE:
  188233. {
  188234. png_push_read_chunk(png_ptr, info_ptr);
  188235. break;
  188236. }
  188237. case PNG_READ_IDAT_MODE:
  188238. {
  188239. png_push_read_IDAT(png_ptr);
  188240. break;
  188241. }
  188242. #if defined(PNG_READ_tEXt_SUPPORTED)
  188243. case PNG_READ_tEXt_MODE:
  188244. {
  188245. png_push_read_tEXt(png_ptr, info_ptr);
  188246. break;
  188247. }
  188248. #endif
  188249. #if defined(PNG_READ_zTXt_SUPPORTED)
  188250. case PNG_READ_zTXt_MODE:
  188251. {
  188252. png_push_read_zTXt(png_ptr, info_ptr);
  188253. break;
  188254. }
  188255. #endif
  188256. #if defined(PNG_READ_iTXt_SUPPORTED)
  188257. case PNG_READ_iTXt_MODE:
  188258. {
  188259. png_push_read_iTXt(png_ptr, info_ptr);
  188260. break;
  188261. }
  188262. #endif
  188263. case PNG_SKIP_MODE:
  188264. {
  188265. png_push_crc_finish(png_ptr);
  188266. break;
  188267. }
  188268. default:
  188269. {
  188270. png_ptr->buffer_size = 0;
  188271. break;
  188272. }
  188273. }
  188274. }
  188275. /* Read any remaining signature bytes from the stream and compare them with
  188276. * the correct PNG signature. It is possible that this routine is called
  188277. * with bytes already read from the signature, either because they have been
  188278. * checked by the calling application, or because of multiple calls to this
  188279. * routine.
  188280. */
  188281. void /* PRIVATE */
  188282. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188283. {
  188284. png_size_t num_checked = png_ptr->sig_bytes,
  188285. num_to_check = 8 - num_checked;
  188286. if (png_ptr->buffer_size < num_to_check)
  188287. {
  188288. num_to_check = png_ptr->buffer_size;
  188289. }
  188290. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188291. num_to_check);
  188292. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188293. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188294. {
  188295. if (num_checked < 4 &&
  188296. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188297. png_error(png_ptr, "Not a PNG file");
  188298. else
  188299. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188300. }
  188301. else
  188302. {
  188303. if (png_ptr->sig_bytes >= 8)
  188304. {
  188305. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188306. }
  188307. }
  188308. }
  188309. void /* PRIVATE */
  188310. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188311. {
  188312. #ifdef PNG_USE_LOCAL_ARRAYS
  188313. PNG_CONST PNG_IHDR;
  188314. PNG_CONST PNG_IDAT;
  188315. PNG_CONST PNG_IEND;
  188316. PNG_CONST PNG_PLTE;
  188317. #if defined(PNG_READ_bKGD_SUPPORTED)
  188318. PNG_CONST PNG_bKGD;
  188319. #endif
  188320. #if defined(PNG_READ_cHRM_SUPPORTED)
  188321. PNG_CONST PNG_cHRM;
  188322. #endif
  188323. #if defined(PNG_READ_gAMA_SUPPORTED)
  188324. PNG_CONST PNG_gAMA;
  188325. #endif
  188326. #if defined(PNG_READ_hIST_SUPPORTED)
  188327. PNG_CONST PNG_hIST;
  188328. #endif
  188329. #if defined(PNG_READ_iCCP_SUPPORTED)
  188330. PNG_CONST PNG_iCCP;
  188331. #endif
  188332. #if defined(PNG_READ_iTXt_SUPPORTED)
  188333. PNG_CONST PNG_iTXt;
  188334. #endif
  188335. #if defined(PNG_READ_oFFs_SUPPORTED)
  188336. PNG_CONST PNG_oFFs;
  188337. #endif
  188338. #if defined(PNG_READ_pCAL_SUPPORTED)
  188339. PNG_CONST PNG_pCAL;
  188340. #endif
  188341. #if defined(PNG_READ_pHYs_SUPPORTED)
  188342. PNG_CONST PNG_pHYs;
  188343. #endif
  188344. #if defined(PNG_READ_sBIT_SUPPORTED)
  188345. PNG_CONST PNG_sBIT;
  188346. #endif
  188347. #if defined(PNG_READ_sCAL_SUPPORTED)
  188348. PNG_CONST PNG_sCAL;
  188349. #endif
  188350. #if defined(PNG_READ_sRGB_SUPPORTED)
  188351. PNG_CONST PNG_sRGB;
  188352. #endif
  188353. #if defined(PNG_READ_sPLT_SUPPORTED)
  188354. PNG_CONST PNG_sPLT;
  188355. #endif
  188356. #if defined(PNG_READ_tEXt_SUPPORTED)
  188357. PNG_CONST PNG_tEXt;
  188358. #endif
  188359. #if defined(PNG_READ_tIME_SUPPORTED)
  188360. PNG_CONST PNG_tIME;
  188361. #endif
  188362. #if defined(PNG_READ_tRNS_SUPPORTED)
  188363. PNG_CONST PNG_tRNS;
  188364. #endif
  188365. #if defined(PNG_READ_zTXt_SUPPORTED)
  188366. PNG_CONST PNG_zTXt;
  188367. #endif
  188368. #endif /* PNG_USE_LOCAL_ARRAYS */
  188369. /* First we make sure we have enough data for the 4 byte chunk name
  188370. * and the 4 byte chunk length before proceeding with decoding the
  188371. * chunk data. To fully decode each of these chunks, we also make
  188372. * sure we have enough data in the buffer for the 4 byte CRC at the
  188373. * end of every chunk (except IDAT, which is handled separately).
  188374. */
  188375. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188376. {
  188377. png_byte chunk_length[4];
  188378. if (png_ptr->buffer_size < 8)
  188379. {
  188380. png_push_save_buffer(png_ptr);
  188381. return;
  188382. }
  188383. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188384. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188385. png_reset_crc(png_ptr);
  188386. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188387. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188388. }
  188389. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188390. if(png_ptr->mode & PNG_AFTER_IDAT)
  188391. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188392. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188393. {
  188394. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188395. {
  188396. png_push_save_buffer(png_ptr);
  188397. return;
  188398. }
  188399. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188400. }
  188401. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188402. {
  188403. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188404. {
  188405. png_push_save_buffer(png_ptr);
  188406. return;
  188407. }
  188408. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188409. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188410. png_push_have_end(png_ptr, info_ptr);
  188411. }
  188412. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188413. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188414. {
  188415. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188416. {
  188417. png_push_save_buffer(png_ptr);
  188418. return;
  188419. }
  188420. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188421. png_ptr->mode |= PNG_HAVE_IDAT;
  188422. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188423. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188424. png_ptr->mode |= PNG_HAVE_PLTE;
  188425. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188426. {
  188427. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188428. png_error(png_ptr, "Missing IHDR before IDAT");
  188429. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188430. !(png_ptr->mode & PNG_HAVE_PLTE))
  188431. png_error(png_ptr, "Missing PLTE before IDAT");
  188432. }
  188433. }
  188434. #endif
  188435. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188436. {
  188437. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188438. {
  188439. png_push_save_buffer(png_ptr);
  188440. return;
  188441. }
  188442. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188443. }
  188444. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188445. {
  188446. /* If we reach an IDAT chunk, this means we have read all of the
  188447. * header chunks, and we can start reading the image (or if this
  188448. * is called after the image has been read - we have an error).
  188449. */
  188450. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188451. png_error(png_ptr, "Missing IHDR before IDAT");
  188452. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188453. !(png_ptr->mode & PNG_HAVE_PLTE))
  188454. png_error(png_ptr, "Missing PLTE before IDAT");
  188455. if (png_ptr->mode & PNG_HAVE_IDAT)
  188456. {
  188457. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188458. if (png_ptr->push_length == 0)
  188459. return;
  188460. if (png_ptr->mode & PNG_AFTER_IDAT)
  188461. png_error(png_ptr, "Too many IDAT's found");
  188462. }
  188463. png_ptr->idat_size = png_ptr->push_length;
  188464. png_ptr->mode |= PNG_HAVE_IDAT;
  188465. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188466. png_push_have_info(png_ptr, info_ptr);
  188467. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188468. png_ptr->zstream.next_out = png_ptr->row_buf;
  188469. return;
  188470. }
  188471. #if defined(PNG_READ_gAMA_SUPPORTED)
  188472. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188473. {
  188474. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188475. {
  188476. png_push_save_buffer(png_ptr);
  188477. return;
  188478. }
  188479. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188480. }
  188481. #endif
  188482. #if defined(PNG_READ_sBIT_SUPPORTED)
  188483. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188484. {
  188485. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188486. {
  188487. png_push_save_buffer(png_ptr);
  188488. return;
  188489. }
  188490. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188491. }
  188492. #endif
  188493. #if defined(PNG_READ_cHRM_SUPPORTED)
  188494. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188495. {
  188496. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188497. {
  188498. png_push_save_buffer(png_ptr);
  188499. return;
  188500. }
  188501. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188502. }
  188503. #endif
  188504. #if defined(PNG_READ_sRGB_SUPPORTED)
  188505. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188506. {
  188507. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188508. {
  188509. png_push_save_buffer(png_ptr);
  188510. return;
  188511. }
  188512. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188513. }
  188514. #endif
  188515. #if defined(PNG_READ_iCCP_SUPPORTED)
  188516. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188517. {
  188518. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188519. {
  188520. png_push_save_buffer(png_ptr);
  188521. return;
  188522. }
  188523. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188524. }
  188525. #endif
  188526. #if defined(PNG_READ_sPLT_SUPPORTED)
  188527. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188528. {
  188529. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188530. {
  188531. png_push_save_buffer(png_ptr);
  188532. return;
  188533. }
  188534. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188535. }
  188536. #endif
  188537. #if defined(PNG_READ_tRNS_SUPPORTED)
  188538. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188539. {
  188540. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188541. {
  188542. png_push_save_buffer(png_ptr);
  188543. return;
  188544. }
  188545. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188546. }
  188547. #endif
  188548. #if defined(PNG_READ_bKGD_SUPPORTED)
  188549. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188550. {
  188551. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188552. {
  188553. png_push_save_buffer(png_ptr);
  188554. return;
  188555. }
  188556. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188557. }
  188558. #endif
  188559. #if defined(PNG_READ_hIST_SUPPORTED)
  188560. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188561. {
  188562. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188563. {
  188564. png_push_save_buffer(png_ptr);
  188565. return;
  188566. }
  188567. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188568. }
  188569. #endif
  188570. #if defined(PNG_READ_pHYs_SUPPORTED)
  188571. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188572. {
  188573. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188574. {
  188575. png_push_save_buffer(png_ptr);
  188576. return;
  188577. }
  188578. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188579. }
  188580. #endif
  188581. #if defined(PNG_READ_oFFs_SUPPORTED)
  188582. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188583. {
  188584. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188585. {
  188586. png_push_save_buffer(png_ptr);
  188587. return;
  188588. }
  188589. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188590. }
  188591. #endif
  188592. #if defined(PNG_READ_pCAL_SUPPORTED)
  188593. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188594. {
  188595. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188596. {
  188597. png_push_save_buffer(png_ptr);
  188598. return;
  188599. }
  188600. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188601. }
  188602. #endif
  188603. #if defined(PNG_READ_sCAL_SUPPORTED)
  188604. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188605. {
  188606. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188607. {
  188608. png_push_save_buffer(png_ptr);
  188609. return;
  188610. }
  188611. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188612. }
  188613. #endif
  188614. #if defined(PNG_READ_tIME_SUPPORTED)
  188615. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188616. {
  188617. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188618. {
  188619. png_push_save_buffer(png_ptr);
  188620. return;
  188621. }
  188622. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188623. }
  188624. #endif
  188625. #if defined(PNG_READ_tEXt_SUPPORTED)
  188626. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188627. {
  188628. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188629. {
  188630. png_push_save_buffer(png_ptr);
  188631. return;
  188632. }
  188633. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188634. }
  188635. #endif
  188636. #if defined(PNG_READ_zTXt_SUPPORTED)
  188637. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188638. {
  188639. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188640. {
  188641. png_push_save_buffer(png_ptr);
  188642. return;
  188643. }
  188644. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188645. }
  188646. #endif
  188647. #if defined(PNG_READ_iTXt_SUPPORTED)
  188648. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188649. {
  188650. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188651. {
  188652. png_push_save_buffer(png_ptr);
  188653. return;
  188654. }
  188655. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188656. }
  188657. #endif
  188658. else
  188659. {
  188660. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188661. {
  188662. png_push_save_buffer(png_ptr);
  188663. return;
  188664. }
  188665. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188666. }
  188667. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188668. }
  188669. void /* PRIVATE */
  188670. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188671. {
  188672. png_ptr->process_mode = PNG_SKIP_MODE;
  188673. png_ptr->skip_length = skip;
  188674. }
  188675. void /* PRIVATE */
  188676. png_push_crc_finish(png_structp png_ptr)
  188677. {
  188678. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188679. {
  188680. png_size_t save_size;
  188681. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188682. save_size = (png_size_t)png_ptr->skip_length;
  188683. else
  188684. save_size = png_ptr->save_buffer_size;
  188685. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188686. png_ptr->skip_length -= save_size;
  188687. png_ptr->buffer_size -= save_size;
  188688. png_ptr->save_buffer_size -= save_size;
  188689. png_ptr->save_buffer_ptr += save_size;
  188690. }
  188691. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188692. {
  188693. png_size_t save_size;
  188694. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188695. save_size = (png_size_t)png_ptr->skip_length;
  188696. else
  188697. save_size = png_ptr->current_buffer_size;
  188698. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188699. png_ptr->skip_length -= save_size;
  188700. png_ptr->buffer_size -= save_size;
  188701. png_ptr->current_buffer_size -= save_size;
  188702. png_ptr->current_buffer_ptr += save_size;
  188703. }
  188704. if (!png_ptr->skip_length)
  188705. {
  188706. if (png_ptr->buffer_size < 4)
  188707. {
  188708. png_push_save_buffer(png_ptr);
  188709. return;
  188710. }
  188711. png_crc_finish(png_ptr, 0);
  188712. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188713. }
  188714. }
  188715. void PNGAPI
  188716. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188717. {
  188718. png_bytep ptr;
  188719. if(png_ptr == NULL) return;
  188720. ptr = buffer;
  188721. if (png_ptr->save_buffer_size)
  188722. {
  188723. png_size_t save_size;
  188724. if (length < png_ptr->save_buffer_size)
  188725. save_size = length;
  188726. else
  188727. save_size = png_ptr->save_buffer_size;
  188728. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188729. length -= save_size;
  188730. ptr += save_size;
  188731. png_ptr->buffer_size -= save_size;
  188732. png_ptr->save_buffer_size -= save_size;
  188733. png_ptr->save_buffer_ptr += save_size;
  188734. }
  188735. if (length && png_ptr->current_buffer_size)
  188736. {
  188737. png_size_t save_size;
  188738. if (length < png_ptr->current_buffer_size)
  188739. save_size = length;
  188740. else
  188741. save_size = png_ptr->current_buffer_size;
  188742. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188743. png_ptr->buffer_size -= save_size;
  188744. png_ptr->current_buffer_size -= save_size;
  188745. png_ptr->current_buffer_ptr += save_size;
  188746. }
  188747. }
  188748. void /* PRIVATE */
  188749. png_push_save_buffer(png_structp png_ptr)
  188750. {
  188751. if (png_ptr->save_buffer_size)
  188752. {
  188753. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188754. {
  188755. png_size_t i,istop;
  188756. png_bytep sp;
  188757. png_bytep dp;
  188758. istop = png_ptr->save_buffer_size;
  188759. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188760. i < istop; i++, sp++, dp++)
  188761. {
  188762. *dp = *sp;
  188763. }
  188764. }
  188765. }
  188766. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188767. png_ptr->save_buffer_max)
  188768. {
  188769. png_size_t new_max;
  188770. png_bytep old_buffer;
  188771. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188772. (png_ptr->current_buffer_size + 256))
  188773. {
  188774. png_error(png_ptr, "Potential overflow of save_buffer");
  188775. }
  188776. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188777. old_buffer = png_ptr->save_buffer;
  188778. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188779. (png_uint_32)new_max);
  188780. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188781. png_free(png_ptr, old_buffer);
  188782. png_ptr->save_buffer_max = new_max;
  188783. }
  188784. if (png_ptr->current_buffer_size)
  188785. {
  188786. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188787. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188788. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188789. png_ptr->current_buffer_size = 0;
  188790. }
  188791. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188792. png_ptr->buffer_size = 0;
  188793. }
  188794. void /* PRIVATE */
  188795. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188796. png_size_t buffer_length)
  188797. {
  188798. png_ptr->current_buffer = buffer;
  188799. png_ptr->current_buffer_size = buffer_length;
  188800. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188801. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188802. }
  188803. void /* PRIVATE */
  188804. png_push_read_IDAT(png_structp png_ptr)
  188805. {
  188806. #ifdef PNG_USE_LOCAL_ARRAYS
  188807. PNG_CONST PNG_IDAT;
  188808. #endif
  188809. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188810. {
  188811. png_byte chunk_length[4];
  188812. if (png_ptr->buffer_size < 8)
  188813. {
  188814. png_push_save_buffer(png_ptr);
  188815. return;
  188816. }
  188817. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188818. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188819. png_reset_crc(png_ptr);
  188820. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188821. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188822. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188823. {
  188824. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188825. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188826. png_error(png_ptr, "Not enough compressed data");
  188827. return;
  188828. }
  188829. png_ptr->idat_size = png_ptr->push_length;
  188830. }
  188831. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188832. {
  188833. png_size_t save_size;
  188834. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188835. {
  188836. save_size = (png_size_t)png_ptr->idat_size;
  188837. /* check for overflow */
  188838. if((png_uint_32)save_size != png_ptr->idat_size)
  188839. png_error(png_ptr, "save_size overflowed in pngpread");
  188840. }
  188841. else
  188842. save_size = png_ptr->save_buffer_size;
  188843. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188844. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188845. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188846. png_ptr->idat_size -= save_size;
  188847. png_ptr->buffer_size -= save_size;
  188848. png_ptr->save_buffer_size -= save_size;
  188849. png_ptr->save_buffer_ptr += save_size;
  188850. }
  188851. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188852. {
  188853. png_size_t save_size;
  188854. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188855. {
  188856. save_size = (png_size_t)png_ptr->idat_size;
  188857. /* check for overflow */
  188858. if((png_uint_32)save_size != png_ptr->idat_size)
  188859. png_error(png_ptr, "save_size overflowed in pngpread");
  188860. }
  188861. else
  188862. save_size = png_ptr->current_buffer_size;
  188863. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188864. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188865. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188866. png_ptr->idat_size -= save_size;
  188867. png_ptr->buffer_size -= save_size;
  188868. png_ptr->current_buffer_size -= save_size;
  188869. png_ptr->current_buffer_ptr += save_size;
  188870. }
  188871. if (!png_ptr->idat_size)
  188872. {
  188873. if (png_ptr->buffer_size < 4)
  188874. {
  188875. png_push_save_buffer(png_ptr);
  188876. return;
  188877. }
  188878. png_crc_finish(png_ptr, 0);
  188879. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188880. png_ptr->mode |= PNG_AFTER_IDAT;
  188881. }
  188882. }
  188883. void /* PRIVATE */
  188884. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188885. png_size_t buffer_length)
  188886. {
  188887. int ret;
  188888. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188889. png_error(png_ptr, "Extra compression data");
  188890. png_ptr->zstream.next_in = buffer;
  188891. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188892. for(;;)
  188893. {
  188894. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188895. if (ret != Z_OK)
  188896. {
  188897. if (ret == Z_STREAM_END)
  188898. {
  188899. if (png_ptr->zstream.avail_in)
  188900. png_error(png_ptr, "Extra compressed data");
  188901. if (!(png_ptr->zstream.avail_out))
  188902. {
  188903. png_push_process_row(png_ptr);
  188904. }
  188905. png_ptr->mode |= PNG_AFTER_IDAT;
  188906. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188907. break;
  188908. }
  188909. else if (ret == Z_BUF_ERROR)
  188910. break;
  188911. else
  188912. png_error(png_ptr, "Decompression Error");
  188913. }
  188914. if (!(png_ptr->zstream.avail_out))
  188915. {
  188916. if ((
  188917. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188918. png_ptr->interlaced && png_ptr->pass > 6) ||
  188919. (!png_ptr->interlaced &&
  188920. #endif
  188921. png_ptr->row_number == png_ptr->num_rows))
  188922. {
  188923. if (png_ptr->zstream.avail_in)
  188924. {
  188925. png_warning(png_ptr, "Too much data in IDAT chunks");
  188926. }
  188927. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188928. break;
  188929. }
  188930. png_push_process_row(png_ptr);
  188931. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188932. png_ptr->zstream.next_out = png_ptr->row_buf;
  188933. }
  188934. else
  188935. break;
  188936. }
  188937. }
  188938. void /* PRIVATE */
  188939. png_push_process_row(png_structp png_ptr)
  188940. {
  188941. png_ptr->row_info.color_type = png_ptr->color_type;
  188942. png_ptr->row_info.width = png_ptr->iwidth;
  188943. png_ptr->row_info.channels = png_ptr->channels;
  188944. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188945. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188946. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188947. png_ptr->row_info.width);
  188948. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188949. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188950. (int)(png_ptr->row_buf[0]));
  188951. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188952. png_ptr->rowbytes + 1);
  188953. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188954. png_do_read_transformations(png_ptr);
  188955. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188956. /* blow up interlaced rows to full size */
  188957. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188958. {
  188959. if (png_ptr->pass < 6)
  188960. /* old interface (pre-1.0.9):
  188961. png_do_read_interlace(&(png_ptr->row_info),
  188962. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188963. */
  188964. png_do_read_interlace(png_ptr);
  188965. switch (png_ptr->pass)
  188966. {
  188967. case 0:
  188968. {
  188969. int i;
  188970. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188971. {
  188972. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188973. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188974. }
  188975. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188976. {
  188977. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188978. {
  188979. png_push_have_row(png_ptr, png_bytep_NULL);
  188980. png_read_push_finish_row(png_ptr);
  188981. }
  188982. }
  188983. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188984. {
  188985. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188986. {
  188987. png_push_have_row(png_ptr, png_bytep_NULL);
  188988. png_read_push_finish_row(png_ptr);
  188989. }
  188990. }
  188991. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188992. {
  188993. png_push_have_row(png_ptr, png_bytep_NULL);
  188994. png_read_push_finish_row(png_ptr);
  188995. }
  188996. break;
  188997. }
  188998. case 1:
  188999. {
  189000. int i;
  189001. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189002. {
  189003. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189004. png_read_push_finish_row(png_ptr);
  189005. }
  189006. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189007. {
  189008. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189009. {
  189010. png_push_have_row(png_ptr, png_bytep_NULL);
  189011. png_read_push_finish_row(png_ptr);
  189012. }
  189013. }
  189014. break;
  189015. }
  189016. case 2:
  189017. {
  189018. int i;
  189019. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189020. {
  189021. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189022. png_read_push_finish_row(png_ptr);
  189023. }
  189024. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189025. {
  189026. png_push_have_row(png_ptr, png_bytep_NULL);
  189027. png_read_push_finish_row(png_ptr);
  189028. }
  189029. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189030. {
  189031. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189032. {
  189033. png_push_have_row(png_ptr, png_bytep_NULL);
  189034. png_read_push_finish_row(png_ptr);
  189035. }
  189036. }
  189037. break;
  189038. }
  189039. case 3:
  189040. {
  189041. int i;
  189042. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189043. {
  189044. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189045. png_read_push_finish_row(png_ptr);
  189046. }
  189047. if (png_ptr->pass == 4) /* skip top two generated rows */
  189048. {
  189049. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189050. {
  189051. png_push_have_row(png_ptr, png_bytep_NULL);
  189052. png_read_push_finish_row(png_ptr);
  189053. }
  189054. }
  189055. break;
  189056. }
  189057. case 4:
  189058. {
  189059. int i;
  189060. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189061. {
  189062. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189063. png_read_push_finish_row(png_ptr);
  189064. }
  189065. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189066. {
  189067. png_push_have_row(png_ptr, png_bytep_NULL);
  189068. png_read_push_finish_row(png_ptr);
  189069. }
  189070. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189071. {
  189072. png_push_have_row(png_ptr, png_bytep_NULL);
  189073. png_read_push_finish_row(png_ptr);
  189074. }
  189075. break;
  189076. }
  189077. case 5:
  189078. {
  189079. int i;
  189080. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189081. {
  189082. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189083. png_read_push_finish_row(png_ptr);
  189084. }
  189085. if (png_ptr->pass == 6) /* skip top generated row */
  189086. {
  189087. png_push_have_row(png_ptr, png_bytep_NULL);
  189088. png_read_push_finish_row(png_ptr);
  189089. }
  189090. break;
  189091. }
  189092. case 6:
  189093. {
  189094. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189095. png_read_push_finish_row(png_ptr);
  189096. if (png_ptr->pass != 6)
  189097. break;
  189098. png_push_have_row(png_ptr, png_bytep_NULL);
  189099. png_read_push_finish_row(png_ptr);
  189100. }
  189101. }
  189102. }
  189103. else
  189104. #endif
  189105. {
  189106. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189107. png_read_push_finish_row(png_ptr);
  189108. }
  189109. }
  189110. void /* PRIVATE */
  189111. png_read_push_finish_row(png_structp png_ptr)
  189112. {
  189113. #ifdef PNG_USE_LOCAL_ARRAYS
  189114. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189115. /* start of interlace block */
  189116. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189117. /* offset to next interlace block */
  189118. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189119. /* start of interlace block in the y direction */
  189120. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189121. /* offset to next interlace block in the y direction */
  189122. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189123. /* Height of interlace block. This is not currently used - if you need
  189124. * it, uncomment it here and in png.h
  189125. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189126. */
  189127. #endif
  189128. png_ptr->row_number++;
  189129. if (png_ptr->row_number < png_ptr->num_rows)
  189130. return;
  189131. if (png_ptr->interlaced)
  189132. {
  189133. png_ptr->row_number = 0;
  189134. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189135. png_ptr->rowbytes + 1);
  189136. do
  189137. {
  189138. png_ptr->pass++;
  189139. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189140. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189141. (png_ptr->pass == 5 && png_ptr->width < 2))
  189142. png_ptr->pass++;
  189143. if (png_ptr->pass > 7)
  189144. png_ptr->pass--;
  189145. if (png_ptr->pass >= 7)
  189146. break;
  189147. png_ptr->iwidth = (png_ptr->width +
  189148. png_pass_inc[png_ptr->pass] - 1 -
  189149. png_pass_start[png_ptr->pass]) /
  189150. png_pass_inc[png_ptr->pass];
  189151. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189152. png_ptr->iwidth) + 1;
  189153. if (png_ptr->transformations & PNG_INTERLACE)
  189154. break;
  189155. png_ptr->num_rows = (png_ptr->height +
  189156. png_pass_yinc[png_ptr->pass] - 1 -
  189157. png_pass_ystart[png_ptr->pass]) /
  189158. png_pass_yinc[png_ptr->pass];
  189159. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189160. }
  189161. }
  189162. #if defined(PNG_READ_tEXt_SUPPORTED)
  189163. void /* PRIVATE */
  189164. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189165. length)
  189166. {
  189167. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189168. {
  189169. png_error(png_ptr, "Out of place tEXt");
  189170. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189171. }
  189172. #ifdef PNG_MAX_MALLOC_64K
  189173. png_ptr->skip_length = 0; /* This may not be necessary */
  189174. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189175. {
  189176. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189177. png_ptr->skip_length = length - (png_uint_32)65535L;
  189178. length = (png_uint_32)65535L;
  189179. }
  189180. #endif
  189181. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189182. (png_uint_32)(length+1));
  189183. png_ptr->current_text[length] = '\0';
  189184. png_ptr->current_text_ptr = png_ptr->current_text;
  189185. png_ptr->current_text_size = (png_size_t)length;
  189186. png_ptr->current_text_left = (png_size_t)length;
  189187. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189188. }
  189189. void /* PRIVATE */
  189190. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189191. {
  189192. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189193. {
  189194. png_size_t text_size;
  189195. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189196. text_size = png_ptr->buffer_size;
  189197. else
  189198. text_size = png_ptr->current_text_left;
  189199. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189200. png_ptr->current_text_left -= text_size;
  189201. png_ptr->current_text_ptr += text_size;
  189202. }
  189203. if (!(png_ptr->current_text_left))
  189204. {
  189205. png_textp text_ptr;
  189206. png_charp text;
  189207. png_charp key;
  189208. int ret;
  189209. if (png_ptr->buffer_size < 4)
  189210. {
  189211. png_push_save_buffer(png_ptr);
  189212. return;
  189213. }
  189214. png_push_crc_finish(png_ptr);
  189215. #if defined(PNG_MAX_MALLOC_64K)
  189216. if (png_ptr->skip_length)
  189217. return;
  189218. #endif
  189219. key = png_ptr->current_text;
  189220. for (text = key; *text; text++)
  189221. /* empty loop */ ;
  189222. if (text < key + png_ptr->current_text_size)
  189223. text++;
  189224. text_ptr = (png_textp)png_malloc(png_ptr,
  189225. (png_uint_32)png_sizeof(png_text));
  189226. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189227. text_ptr->key = key;
  189228. #ifdef PNG_iTXt_SUPPORTED
  189229. text_ptr->lang = NULL;
  189230. text_ptr->lang_key = NULL;
  189231. #endif
  189232. text_ptr->text = text;
  189233. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189234. png_free(png_ptr, key);
  189235. png_free(png_ptr, text_ptr);
  189236. png_ptr->current_text = NULL;
  189237. if (ret)
  189238. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189239. }
  189240. }
  189241. #endif
  189242. #if defined(PNG_READ_zTXt_SUPPORTED)
  189243. void /* PRIVATE */
  189244. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189245. length)
  189246. {
  189247. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189248. {
  189249. png_error(png_ptr, "Out of place zTXt");
  189250. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189251. }
  189252. #ifdef PNG_MAX_MALLOC_64K
  189253. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189254. * to be able to store the uncompressed data. Actually, the threshold
  189255. * is probably around 32K, but it isn't as definite as 64K is.
  189256. */
  189257. if (length > (png_uint_32)65535L)
  189258. {
  189259. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189260. png_push_crc_skip(png_ptr, length);
  189261. return;
  189262. }
  189263. #endif
  189264. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189265. (png_uint_32)(length+1));
  189266. png_ptr->current_text[length] = '\0';
  189267. png_ptr->current_text_ptr = png_ptr->current_text;
  189268. png_ptr->current_text_size = (png_size_t)length;
  189269. png_ptr->current_text_left = (png_size_t)length;
  189270. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189271. }
  189272. void /* PRIVATE */
  189273. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189274. {
  189275. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189276. {
  189277. png_size_t text_size;
  189278. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189279. text_size = png_ptr->buffer_size;
  189280. else
  189281. text_size = png_ptr->current_text_left;
  189282. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189283. png_ptr->current_text_left -= text_size;
  189284. png_ptr->current_text_ptr += text_size;
  189285. }
  189286. if (!(png_ptr->current_text_left))
  189287. {
  189288. png_textp text_ptr;
  189289. png_charp text;
  189290. png_charp key;
  189291. int ret;
  189292. png_size_t text_size, key_size;
  189293. if (png_ptr->buffer_size < 4)
  189294. {
  189295. png_push_save_buffer(png_ptr);
  189296. return;
  189297. }
  189298. png_push_crc_finish(png_ptr);
  189299. key = png_ptr->current_text;
  189300. for (text = key; *text; text++)
  189301. /* empty loop */ ;
  189302. /* zTXt can't have zero text */
  189303. if (text >= key + png_ptr->current_text_size)
  189304. {
  189305. png_ptr->current_text = NULL;
  189306. png_free(png_ptr, key);
  189307. return;
  189308. }
  189309. text++;
  189310. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189311. {
  189312. png_ptr->current_text = NULL;
  189313. png_free(png_ptr, key);
  189314. return;
  189315. }
  189316. text++;
  189317. png_ptr->zstream.next_in = (png_bytep )text;
  189318. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189319. (text - key));
  189320. png_ptr->zstream.next_out = png_ptr->zbuf;
  189321. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189322. key_size = text - key;
  189323. text_size = 0;
  189324. text = NULL;
  189325. ret = Z_STREAM_END;
  189326. while (png_ptr->zstream.avail_in)
  189327. {
  189328. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189329. if (ret != Z_OK && ret != Z_STREAM_END)
  189330. {
  189331. inflateReset(&png_ptr->zstream);
  189332. png_ptr->zstream.avail_in = 0;
  189333. png_ptr->current_text = NULL;
  189334. png_free(png_ptr, key);
  189335. png_free(png_ptr, text);
  189336. return;
  189337. }
  189338. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189339. {
  189340. if (text == NULL)
  189341. {
  189342. text = (png_charp)png_malloc(png_ptr,
  189343. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189344. + key_size + 1));
  189345. png_memcpy(text + key_size, png_ptr->zbuf,
  189346. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189347. png_memcpy(text, key, key_size);
  189348. text_size = key_size + png_ptr->zbuf_size -
  189349. png_ptr->zstream.avail_out;
  189350. *(text + text_size) = '\0';
  189351. }
  189352. else
  189353. {
  189354. png_charp tmp;
  189355. tmp = text;
  189356. text = (png_charp)png_malloc(png_ptr, text_size +
  189357. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189358. + 1));
  189359. png_memcpy(text, tmp, text_size);
  189360. png_free(png_ptr, tmp);
  189361. png_memcpy(text + text_size, png_ptr->zbuf,
  189362. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189363. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189364. *(text + text_size) = '\0';
  189365. }
  189366. if (ret != Z_STREAM_END)
  189367. {
  189368. png_ptr->zstream.next_out = png_ptr->zbuf;
  189369. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189370. }
  189371. }
  189372. else
  189373. {
  189374. break;
  189375. }
  189376. if (ret == Z_STREAM_END)
  189377. break;
  189378. }
  189379. inflateReset(&png_ptr->zstream);
  189380. png_ptr->zstream.avail_in = 0;
  189381. if (ret != Z_STREAM_END)
  189382. {
  189383. png_ptr->current_text = NULL;
  189384. png_free(png_ptr, key);
  189385. png_free(png_ptr, text);
  189386. return;
  189387. }
  189388. png_ptr->current_text = NULL;
  189389. png_free(png_ptr, key);
  189390. key = text;
  189391. text += key_size;
  189392. text_ptr = (png_textp)png_malloc(png_ptr,
  189393. (png_uint_32)png_sizeof(png_text));
  189394. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189395. text_ptr->key = key;
  189396. #ifdef PNG_iTXt_SUPPORTED
  189397. text_ptr->lang = NULL;
  189398. text_ptr->lang_key = NULL;
  189399. #endif
  189400. text_ptr->text = text;
  189401. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189402. png_free(png_ptr, key);
  189403. png_free(png_ptr, text_ptr);
  189404. if (ret)
  189405. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189406. }
  189407. }
  189408. #endif
  189409. #if defined(PNG_READ_iTXt_SUPPORTED)
  189410. void /* PRIVATE */
  189411. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189412. length)
  189413. {
  189414. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189415. {
  189416. png_error(png_ptr, "Out of place iTXt");
  189417. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189418. }
  189419. #ifdef PNG_MAX_MALLOC_64K
  189420. png_ptr->skip_length = 0; /* This may not be necessary */
  189421. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189422. {
  189423. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189424. png_ptr->skip_length = length - (png_uint_32)65535L;
  189425. length = (png_uint_32)65535L;
  189426. }
  189427. #endif
  189428. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189429. (png_uint_32)(length+1));
  189430. png_ptr->current_text[length] = '\0';
  189431. png_ptr->current_text_ptr = png_ptr->current_text;
  189432. png_ptr->current_text_size = (png_size_t)length;
  189433. png_ptr->current_text_left = (png_size_t)length;
  189434. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189435. }
  189436. void /* PRIVATE */
  189437. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189438. {
  189439. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189440. {
  189441. png_size_t text_size;
  189442. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189443. text_size = png_ptr->buffer_size;
  189444. else
  189445. text_size = png_ptr->current_text_left;
  189446. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189447. png_ptr->current_text_left -= text_size;
  189448. png_ptr->current_text_ptr += text_size;
  189449. }
  189450. if (!(png_ptr->current_text_left))
  189451. {
  189452. png_textp text_ptr;
  189453. png_charp key;
  189454. int comp_flag;
  189455. png_charp lang;
  189456. png_charp lang_key;
  189457. png_charp text;
  189458. int ret;
  189459. if (png_ptr->buffer_size < 4)
  189460. {
  189461. png_push_save_buffer(png_ptr);
  189462. return;
  189463. }
  189464. png_push_crc_finish(png_ptr);
  189465. #if defined(PNG_MAX_MALLOC_64K)
  189466. if (png_ptr->skip_length)
  189467. return;
  189468. #endif
  189469. key = png_ptr->current_text;
  189470. for (lang = key; *lang; lang++)
  189471. /* empty loop */ ;
  189472. if (lang < key + png_ptr->current_text_size - 3)
  189473. lang++;
  189474. comp_flag = *lang++;
  189475. lang++; /* skip comp_type, always zero */
  189476. for (lang_key = lang; *lang_key; lang_key++)
  189477. /* empty loop */ ;
  189478. lang_key++; /* skip NUL separator */
  189479. text=lang_key;
  189480. if (lang_key < key + png_ptr->current_text_size - 1)
  189481. {
  189482. for (; *text; text++)
  189483. /* empty loop */ ;
  189484. }
  189485. if (text < key + png_ptr->current_text_size)
  189486. text++;
  189487. text_ptr = (png_textp)png_malloc(png_ptr,
  189488. (png_uint_32)png_sizeof(png_text));
  189489. text_ptr->compression = comp_flag + 2;
  189490. text_ptr->key = key;
  189491. text_ptr->lang = lang;
  189492. text_ptr->lang_key = lang_key;
  189493. text_ptr->text = text;
  189494. text_ptr->text_length = 0;
  189495. text_ptr->itxt_length = png_strlen(text);
  189496. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189497. png_ptr->current_text = NULL;
  189498. png_free(png_ptr, text_ptr);
  189499. if (ret)
  189500. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189501. }
  189502. }
  189503. #endif
  189504. /* This function is called when we haven't found a handler for this
  189505. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189506. * name or a critical chunk), the chunk is (currently) silently ignored.
  189507. */
  189508. void /* PRIVATE */
  189509. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189510. length)
  189511. {
  189512. png_uint_32 skip=0;
  189513. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189514. if (!(png_ptr->chunk_name[0] & 0x20))
  189515. {
  189516. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189517. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189518. PNG_HANDLE_CHUNK_ALWAYS
  189519. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189520. && png_ptr->read_user_chunk_fn == NULL
  189521. #endif
  189522. )
  189523. #endif
  189524. png_chunk_error(png_ptr, "unknown critical chunk");
  189525. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189526. }
  189527. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189528. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189529. {
  189530. #ifdef PNG_MAX_MALLOC_64K
  189531. if (length > (png_uint_32)65535L)
  189532. {
  189533. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189534. skip = length - (png_uint_32)65535L;
  189535. length = (png_uint_32)65535L;
  189536. }
  189537. #endif
  189538. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189539. (png_charp)png_ptr->chunk_name, 5);
  189540. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189541. png_ptr->unknown_chunk.size = (png_size_t)length;
  189542. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189543. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189544. if(png_ptr->read_user_chunk_fn != NULL)
  189545. {
  189546. /* callback to user unknown chunk handler */
  189547. int ret;
  189548. ret = (*(png_ptr->read_user_chunk_fn))
  189549. (png_ptr, &png_ptr->unknown_chunk);
  189550. if (ret < 0)
  189551. png_chunk_error(png_ptr, "error in user chunk");
  189552. if (ret == 0)
  189553. {
  189554. if (!(png_ptr->chunk_name[0] & 0x20))
  189555. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189556. PNG_HANDLE_CHUNK_ALWAYS)
  189557. png_chunk_error(png_ptr, "unknown critical chunk");
  189558. png_set_unknown_chunks(png_ptr, info_ptr,
  189559. &png_ptr->unknown_chunk, 1);
  189560. }
  189561. }
  189562. #else
  189563. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189564. #endif
  189565. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189566. png_ptr->unknown_chunk.data = NULL;
  189567. }
  189568. else
  189569. #endif
  189570. skip=length;
  189571. png_push_crc_skip(png_ptr, skip);
  189572. }
  189573. void /* PRIVATE */
  189574. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189575. {
  189576. if (png_ptr->info_fn != NULL)
  189577. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189578. }
  189579. void /* PRIVATE */
  189580. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189581. {
  189582. if (png_ptr->end_fn != NULL)
  189583. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189584. }
  189585. void /* PRIVATE */
  189586. png_push_have_row(png_structp png_ptr, png_bytep row)
  189587. {
  189588. if (png_ptr->row_fn != NULL)
  189589. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189590. (int)png_ptr->pass);
  189591. }
  189592. void PNGAPI
  189593. png_progressive_combine_row (png_structp png_ptr,
  189594. png_bytep old_row, png_bytep new_row)
  189595. {
  189596. #ifdef PNG_USE_LOCAL_ARRAYS
  189597. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189598. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189599. #endif
  189600. if(png_ptr == NULL) return;
  189601. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189602. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189603. }
  189604. void PNGAPI
  189605. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189606. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189607. png_progressive_end_ptr end_fn)
  189608. {
  189609. if(png_ptr == NULL) return;
  189610. png_ptr->info_fn = info_fn;
  189611. png_ptr->row_fn = row_fn;
  189612. png_ptr->end_fn = end_fn;
  189613. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189614. }
  189615. png_voidp PNGAPI
  189616. png_get_progressive_ptr(png_structp png_ptr)
  189617. {
  189618. if(png_ptr == NULL) return (NULL);
  189619. return png_ptr->io_ptr;
  189620. }
  189621. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189622. /*** End of inlined file: pngpread.c ***/
  189623. /*** Start of inlined file: pngrio.c ***/
  189624. /* pngrio.c - functions for data input
  189625. *
  189626. * Last changed in libpng 1.2.13 November 13, 2006
  189627. * For conditions of distribution and use, see copyright notice in png.h
  189628. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189629. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189630. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189631. *
  189632. * This file provides a location for all input. Users who need
  189633. * special handling are expected to write a function that has the same
  189634. * arguments as this and performs a similar function, but that possibly
  189635. * has a different input method. Note that you shouldn't change this
  189636. * function, but rather write a replacement function and then make
  189637. * libpng use it at run time with png_set_read_fn(...).
  189638. */
  189639. #define PNG_INTERNAL
  189640. #if defined(PNG_READ_SUPPORTED)
  189641. /* Read the data from whatever input you are using. The default routine
  189642. reads from a file pointer. Note that this routine sometimes gets called
  189643. with very small lengths, so you should implement some kind of simple
  189644. buffering if you are using unbuffered reads. This should never be asked
  189645. to read more then 64K on a 16 bit machine. */
  189646. void /* PRIVATE */
  189647. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189648. {
  189649. png_debug1(4,"reading %d bytes\n", (int)length);
  189650. if (png_ptr->read_data_fn != NULL)
  189651. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189652. else
  189653. png_error(png_ptr, "Call to NULL read function");
  189654. }
  189655. #if !defined(PNG_NO_STDIO)
  189656. /* This is the function that does the actual reading of data. If you are
  189657. not reading from a standard C stream, you should create a replacement
  189658. read_data function and use it at run time with png_set_read_fn(), rather
  189659. than changing the library. */
  189660. #ifndef USE_FAR_KEYWORD
  189661. void PNGAPI
  189662. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189663. {
  189664. png_size_t check;
  189665. if(png_ptr == NULL) return;
  189666. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189667. * instead of an int, which is what fread() actually returns.
  189668. */
  189669. #if defined(_WIN32_WCE)
  189670. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189671. check = 0;
  189672. #else
  189673. check = (png_size_t)fread(data, (png_size_t)1, length,
  189674. (png_FILE_p)png_ptr->io_ptr);
  189675. #endif
  189676. if (check != length)
  189677. png_error(png_ptr, "Read Error");
  189678. }
  189679. #else
  189680. /* this is the model-independent version. Since the standard I/O library
  189681. can't handle far buffers in the medium and small models, we have to copy
  189682. the data.
  189683. */
  189684. #define NEAR_BUF_SIZE 1024
  189685. #define MIN(a,b) (a <= b ? a : b)
  189686. static void PNGAPI
  189687. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189688. {
  189689. int check;
  189690. png_byte *n_data;
  189691. png_FILE_p io_ptr;
  189692. if(png_ptr == NULL) return;
  189693. /* Check if data really is near. If so, use usual code. */
  189694. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189695. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189696. if ((png_bytep)n_data == data)
  189697. {
  189698. #if defined(_WIN32_WCE)
  189699. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189700. check = 0;
  189701. #else
  189702. check = fread(n_data, 1, length, io_ptr);
  189703. #endif
  189704. }
  189705. else
  189706. {
  189707. png_byte buf[NEAR_BUF_SIZE];
  189708. png_size_t read, remaining, err;
  189709. check = 0;
  189710. remaining = length;
  189711. do
  189712. {
  189713. read = MIN(NEAR_BUF_SIZE, remaining);
  189714. #if defined(_WIN32_WCE)
  189715. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189716. err = 0;
  189717. #else
  189718. err = fread(buf, (png_size_t)1, read, io_ptr);
  189719. #endif
  189720. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189721. if(err != read)
  189722. break;
  189723. else
  189724. check += err;
  189725. data += read;
  189726. remaining -= read;
  189727. }
  189728. while (remaining != 0);
  189729. }
  189730. if ((png_uint_32)check != (png_uint_32)length)
  189731. png_error(png_ptr, "read Error");
  189732. }
  189733. #endif
  189734. #endif
  189735. /* This function allows the application to supply a new input function
  189736. for libpng if standard C streams aren't being used.
  189737. This function takes as its arguments:
  189738. png_ptr - pointer to a png input data structure
  189739. io_ptr - pointer to user supplied structure containing info about
  189740. the input functions. May be NULL.
  189741. read_data_fn - pointer to a new input function that takes as its
  189742. arguments a pointer to a png_struct, a pointer to
  189743. a location where input data can be stored, and a 32-bit
  189744. unsigned int that is the number of bytes to be read.
  189745. To exit and output any fatal error messages the new write
  189746. function should call png_error(png_ptr, "Error msg"). */
  189747. void PNGAPI
  189748. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189749. png_rw_ptr read_data_fn)
  189750. {
  189751. if(png_ptr == NULL) return;
  189752. png_ptr->io_ptr = io_ptr;
  189753. #if !defined(PNG_NO_STDIO)
  189754. if (read_data_fn != NULL)
  189755. png_ptr->read_data_fn = read_data_fn;
  189756. else
  189757. png_ptr->read_data_fn = png_default_read_data;
  189758. #else
  189759. png_ptr->read_data_fn = read_data_fn;
  189760. #endif
  189761. /* It is an error to write to a read device */
  189762. if (png_ptr->write_data_fn != NULL)
  189763. {
  189764. png_ptr->write_data_fn = NULL;
  189765. png_warning(png_ptr,
  189766. "It's an error to set both read_data_fn and write_data_fn in the ");
  189767. png_warning(png_ptr,
  189768. "same structure. Resetting write_data_fn to NULL.");
  189769. }
  189770. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189771. png_ptr->output_flush_fn = NULL;
  189772. #endif
  189773. }
  189774. #endif /* PNG_READ_SUPPORTED */
  189775. /*** End of inlined file: pngrio.c ***/
  189776. /*** Start of inlined file: pngrtran.c ***/
  189777. /* pngrtran.c - transforms the data in a row for PNG readers
  189778. *
  189779. * Last changed in libpng 1.2.21 [October 4, 2007]
  189780. * For conditions of distribution and use, see copyright notice in png.h
  189781. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189782. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189783. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189784. *
  189785. * This file contains functions optionally called by an application
  189786. * in order to tell libpng how to handle data when reading a PNG.
  189787. * Transformations that are used in both reading and writing are
  189788. * in pngtrans.c.
  189789. */
  189790. #define PNG_INTERNAL
  189791. #if defined(PNG_READ_SUPPORTED)
  189792. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189793. void PNGAPI
  189794. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189795. {
  189796. png_debug(1, "in png_set_crc_action\n");
  189797. /* Tell libpng how we react to CRC errors in critical chunks */
  189798. if(png_ptr == NULL) return;
  189799. switch (crit_action)
  189800. {
  189801. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189802. break;
  189803. case PNG_CRC_WARN_USE: /* warn/use data */
  189804. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189805. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189806. break;
  189807. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189808. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189809. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189810. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189811. break;
  189812. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189813. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189814. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189815. case PNG_CRC_DEFAULT:
  189816. default:
  189817. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189818. break;
  189819. }
  189820. switch (ancil_action)
  189821. {
  189822. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189823. break;
  189824. case PNG_CRC_WARN_USE: /* warn/use data */
  189825. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189826. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189827. break;
  189828. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189829. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189830. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189831. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189832. break;
  189833. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189834. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189835. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189836. break;
  189837. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189838. case PNG_CRC_DEFAULT:
  189839. default:
  189840. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189841. break;
  189842. }
  189843. }
  189844. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189845. defined(PNG_FLOATING_POINT_SUPPORTED)
  189846. /* handle alpha and tRNS via a background color */
  189847. void PNGAPI
  189848. png_set_background(png_structp png_ptr,
  189849. png_color_16p background_color, int background_gamma_code,
  189850. int need_expand, double background_gamma)
  189851. {
  189852. png_debug(1, "in png_set_background\n");
  189853. if(png_ptr == NULL) return;
  189854. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189855. {
  189856. png_warning(png_ptr, "Application must supply a known background gamma");
  189857. return;
  189858. }
  189859. png_ptr->transformations |= PNG_BACKGROUND;
  189860. png_memcpy(&(png_ptr->background), background_color,
  189861. png_sizeof(png_color_16));
  189862. png_ptr->background_gamma = (float)background_gamma;
  189863. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189864. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189865. }
  189866. #endif
  189867. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189868. /* strip 16 bit depth files to 8 bit depth */
  189869. void PNGAPI
  189870. png_set_strip_16(png_structp png_ptr)
  189871. {
  189872. png_debug(1, "in png_set_strip_16\n");
  189873. if(png_ptr == NULL) return;
  189874. png_ptr->transformations |= PNG_16_TO_8;
  189875. }
  189876. #endif
  189877. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189878. void PNGAPI
  189879. png_set_strip_alpha(png_structp png_ptr)
  189880. {
  189881. png_debug(1, "in png_set_strip_alpha\n");
  189882. if(png_ptr == NULL) return;
  189883. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189884. }
  189885. #endif
  189886. #if defined(PNG_READ_DITHER_SUPPORTED)
  189887. /* Dither file to 8 bit. Supply a palette, the current number
  189888. * of elements in the palette, the maximum number of elements
  189889. * allowed, and a histogram if possible. If the current number
  189890. * of colors is greater then the maximum number, the palette will be
  189891. * modified to fit in the maximum number. "full_dither" indicates
  189892. * whether we need a dithering cube set up for RGB images, or if we
  189893. * simply are reducing the number of colors in a paletted image.
  189894. */
  189895. typedef struct png_dsort_struct
  189896. {
  189897. struct png_dsort_struct FAR * next;
  189898. png_byte left;
  189899. png_byte right;
  189900. } png_dsort;
  189901. typedef png_dsort FAR * png_dsortp;
  189902. typedef png_dsort FAR * FAR * png_dsortpp;
  189903. void PNGAPI
  189904. png_set_dither(png_structp png_ptr, png_colorp palette,
  189905. int num_palette, int maximum_colors, png_uint_16p histogram,
  189906. int full_dither)
  189907. {
  189908. png_debug(1, "in png_set_dither\n");
  189909. if(png_ptr == NULL) return;
  189910. png_ptr->transformations |= PNG_DITHER;
  189911. if (!full_dither)
  189912. {
  189913. int i;
  189914. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189915. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189916. for (i = 0; i < num_palette; i++)
  189917. png_ptr->dither_index[i] = (png_byte)i;
  189918. }
  189919. if (num_palette > maximum_colors)
  189920. {
  189921. if (histogram != NULL)
  189922. {
  189923. /* This is easy enough, just throw out the least used colors.
  189924. Perhaps not the best solution, but good enough. */
  189925. int i;
  189926. /* initialize an array to sort colors */
  189927. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189928. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189929. /* initialize the dither_sort array */
  189930. for (i = 0; i < num_palette; i++)
  189931. png_ptr->dither_sort[i] = (png_byte)i;
  189932. /* Find the least used palette entries by starting a
  189933. bubble sort, and running it until we have sorted
  189934. out enough colors. Note that we don't care about
  189935. sorting all the colors, just finding which are
  189936. least used. */
  189937. for (i = num_palette - 1; i >= maximum_colors; i--)
  189938. {
  189939. int done; /* to stop early if the list is pre-sorted */
  189940. int j;
  189941. done = 1;
  189942. for (j = 0; j < i; j++)
  189943. {
  189944. if (histogram[png_ptr->dither_sort[j]]
  189945. < histogram[png_ptr->dither_sort[j + 1]])
  189946. {
  189947. png_byte t;
  189948. t = png_ptr->dither_sort[j];
  189949. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189950. png_ptr->dither_sort[j + 1] = t;
  189951. done = 0;
  189952. }
  189953. }
  189954. if (done)
  189955. break;
  189956. }
  189957. /* swap the palette around, and set up a table, if necessary */
  189958. if (full_dither)
  189959. {
  189960. int j = num_palette;
  189961. /* put all the useful colors within the max, but don't
  189962. move the others */
  189963. for (i = 0; i < maximum_colors; i++)
  189964. {
  189965. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189966. {
  189967. do
  189968. j--;
  189969. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189970. palette[i] = palette[j];
  189971. }
  189972. }
  189973. }
  189974. else
  189975. {
  189976. int j = num_palette;
  189977. /* move all the used colors inside the max limit, and
  189978. develop a translation table */
  189979. for (i = 0; i < maximum_colors; i++)
  189980. {
  189981. /* only move the colors we need to */
  189982. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189983. {
  189984. png_color tmp_color;
  189985. do
  189986. j--;
  189987. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189988. tmp_color = palette[j];
  189989. palette[j] = palette[i];
  189990. palette[i] = tmp_color;
  189991. /* indicate where the color went */
  189992. png_ptr->dither_index[j] = (png_byte)i;
  189993. png_ptr->dither_index[i] = (png_byte)j;
  189994. }
  189995. }
  189996. /* find closest color for those colors we are not using */
  189997. for (i = 0; i < num_palette; i++)
  189998. {
  189999. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190000. {
  190001. int min_d, k, min_k, d_index;
  190002. /* find the closest color to one we threw out */
  190003. d_index = png_ptr->dither_index[i];
  190004. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190005. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190006. {
  190007. int d;
  190008. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190009. if (d < min_d)
  190010. {
  190011. min_d = d;
  190012. min_k = k;
  190013. }
  190014. }
  190015. /* point to closest color */
  190016. png_ptr->dither_index[i] = (png_byte)min_k;
  190017. }
  190018. }
  190019. }
  190020. png_free(png_ptr, png_ptr->dither_sort);
  190021. png_ptr->dither_sort=NULL;
  190022. }
  190023. else
  190024. {
  190025. /* This is much harder to do simply (and quickly). Perhaps
  190026. we need to go through a median cut routine, but those
  190027. don't always behave themselves with only a few colors
  190028. as input. So we will just find the closest two colors,
  190029. and throw out one of them (chosen somewhat randomly).
  190030. [We don't understand this at all, so if someone wants to
  190031. work on improving it, be our guest - AED, GRP]
  190032. */
  190033. int i;
  190034. int max_d;
  190035. int num_new_palette;
  190036. png_dsortp t;
  190037. png_dsortpp hash;
  190038. t=NULL;
  190039. /* initialize palette index arrays */
  190040. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190041. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190042. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190043. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190044. /* initialize the sort array */
  190045. for (i = 0; i < num_palette; i++)
  190046. {
  190047. png_ptr->index_to_palette[i] = (png_byte)i;
  190048. png_ptr->palette_to_index[i] = (png_byte)i;
  190049. }
  190050. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190051. png_sizeof (png_dsortp)));
  190052. for (i = 0; i < 769; i++)
  190053. hash[i] = NULL;
  190054. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190055. num_new_palette = num_palette;
  190056. /* initial wild guess at how far apart the farthest pixel
  190057. pair we will be eliminating will be. Larger
  190058. numbers mean more areas will be allocated, Smaller
  190059. numbers run the risk of not saving enough data, and
  190060. having to do this all over again.
  190061. I have not done extensive checking on this number.
  190062. */
  190063. max_d = 96;
  190064. while (num_new_palette > maximum_colors)
  190065. {
  190066. for (i = 0; i < num_new_palette - 1; i++)
  190067. {
  190068. int j;
  190069. for (j = i + 1; j < num_new_palette; j++)
  190070. {
  190071. int d;
  190072. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190073. if (d <= max_d)
  190074. {
  190075. t = (png_dsortp)png_malloc_warn(png_ptr,
  190076. (png_uint_32)(png_sizeof(png_dsort)));
  190077. if (t == NULL)
  190078. break;
  190079. t->next = hash[d];
  190080. t->left = (png_byte)i;
  190081. t->right = (png_byte)j;
  190082. hash[d] = t;
  190083. }
  190084. }
  190085. if (t == NULL)
  190086. break;
  190087. }
  190088. if (t != NULL)
  190089. for (i = 0; i <= max_d; i++)
  190090. {
  190091. if (hash[i] != NULL)
  190092. {
  190093. png_dsortp p;
  190094. for (p = hash[i]; p; p = p->next)
  190095. {
  190096. if ((int)png_ptr->index_to_palette[p->left]
  190097. < num_new_palette &&
  190098. (int)png_ptr->index_to_palette[p->right]
  190099. < num_new_palette)
  190100. {
  190101. int j, next_j;
  190102. if (num_new_palette & 0x01)
  190103. {
  190104. j = p->left;
  190105. next_j = p->right;
  190106. }
  190107. else
  190108. {
  190109. j = p->right;
  190110. next_j = p->left;
  190111. }
  190112. num_new_palette--;
  190113. palette[png_ptr->index_to_palette[j]]
  190114. = palette[num_new_palette];
  190115. if (!full_dither)
  190116. {
  190117. int k;
  190118. for (k = 0; k < num_palette; k++)
  190119. {
  190120. if (png_ptr->dither_index[k] ==
  190121. png_ptr->index_to_palette[j])
  190122. png_ptr->dither_index[k] =
  190123. png_ptr->index_to_palette[next_j];
  190124. if ((int)png_ptr->dither_index[k] ==
  190125. num_new_palette)
  190126. png_ptr->dither_index[k] =
  190127. png_ptr->index_to_palette[j];
  190128. }
  190129. }
  190130. png_ptr->index_to_palette[png_ptr->palette_to_index
  190131. [num_new_palette]] = png_ptr->index_to_palette[j];
  190132. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190133. = png_ptr->palette_to_index[num_new_palette];
  190134. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190135. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190136. }
  190137. if (num_new_palette <= maximum_colors)
  190138. break;
  190139. }
  190140. if (num_new_palette <= maximum_colors)
  190141. break;
  190142. }
  190143. }
  190144. for (i = 0; i < 769; i++)
  190145. {
  190146. if (hash[i] != NULL)
  190147. {
  190148. png_dsortp p = hash[i];
  190149. while (p)
  190150. {
  190151. t = p->next;
  190152. png_free(png_ptr, p);
  190153. p = t;
  190154. }
  190155. }
  190156. hash[i] = 0;
  190157. }
  190158. max_d += 96;
  190159. }
  190160. png_free(png_ptr, hash);
  190161. png_free(png_ptr, png_ptr->palette_to_index);
  190162. png_free(png_ptr, png_ptr->index_to_palette);
  190163. png_ptr->palette_to_index=NULL;
  190164. png_ptr->index_to_palette=NULL;
  190165. }
  190166. num_palette = maximum_colors;
  190167. }
  190168. if (png_ptr->palette == NULL)
  190169. {
  190170. png_ptr->palette = palette;
  190171. }
  190172. png_ptr->num_palette = (png_uint_16)num_palette;
  190173. if (full_dither)
  190174. {
  190175. int i;
  190176. png_bytep distance;
  190177. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190178. PNG_DITHER_BLUE_BITS;
  190179. int num_red = (1 << PNG_DITHER_RED_BITS);
  190180. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190181. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190182. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190183. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190184. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190185. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190186. png_sizeof (png_byte));
  190187. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190188. png_sizeof(png_byte)));
  190189. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190190. for (i = 0; i < num_palette; i++)
  190191. {
  190192. int ir, ig, ib;
  190193. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190194. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190195. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190196. for (ir = 0; ir < num_red; ir++)
  190197. {
  190198. /* int dr = abs(ir - r); */
  190199. int dr = ((ir > r) ? ir - r : r - ir);
  190200. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190201. for (ig = 0; ig < num_green; ig++)
  190202. {
  190203. /* int dg = abs(ig - g); */
  190204. int dg = ((ig > g) ? ig - g : g - ig);
  190205. int dt = dr + dg;
  190206. int dm = ((dr > dg) ? dr : dg);
  190207. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190208. for (ib = 0; ib < num_blue; ib++)
  190209. {
  190210. int d_index = index_g | ib;
  190211. /* int db = abs(ib - b); */
  190212. int db = ((ib > b) ? ib - b : b - ib);
  190213. int dmax = ((dm > db) ? dm : db);
  190214. int d = dmax + dt + db;
  190215. if (d < (int)distance[d_index])
  190216. {
  190217. distance[d_index] = (png_byte)d;
  190218. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190219. }
  190220. }
  190221. }
  190222. }
  190223. }
  190224. png_free(png_ptr, distance);
  190225. }
  190226. }
  190227. #endif
  190228. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190229. /* Transform the image from the file_gamma to the screen_gamma. We
  190230. * only do transformations on images where the file_gamma and screen_gamma
  190231. * are not close reciprocals, otherwise it slows things down slightly, and
  190232. * also needlessly introduces small errors.
  190233. *
  190234. * We will turn off gamma transformation later if no semitransparent entries
  190235. * are present in the tRNS array for palette images. We can't do it here
  190236. * because we don't necessarily have the tRNS chunk yet.
  190237. */
  190238. void PNGAPI
  190239. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190240. {
  190241. png_debug(1, "in png_set_gamma\n");
  190242. if(png_ptr == NULL) return;
  190243. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190244. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190245. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190246. png_ptr->transformations |= PNG_GAMMA;
  190247. png_ptr->gamma = (float)file_gamma;
  190248. png_ptr->screen_gamma = (float)scrn_gamma;
  190249. }
  190250. #endif
  190251. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190252. /* Expand paletted images to RGB, expand grayscale images of
  190253. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190254. * to alpha channels.
  190255. */
  190256. void PNGAPI
  190257. png_set_expand(png_structp png_ptr)
  190258. {
  190259. png_debug(1, "in png_set_expand\n");
  190260. if(png_ptr == NULL) return;
  190261. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190262. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190263. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190264. #endif
  190265. }
  190266. /* GRR 19990627: the following three functions currently are identical
  190267. * to png_set_expand(). However, it is entirely reasonable that someone
  190268. * might wish to expand an indexed image to RGB but *not* expand a single,
  190269. * fully transparent palette entry to a full alpha channel--perhaps instead
  190270. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190271. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190272. * IOW, a future version of the library may make the transformations flag
  190273. * a bit more fine-grained, with separate bits for each of these three
  190274. * functions.
  190275. *
  190276. * More to the point, these functions make it obvious what libpng will be
  190277. * doing, whereas "expand" can (and does) mean any number of things.
  190278. *
  190279. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190280. * to expand only the sample depth but not to expand the tRNS to alpha.
  190281. */
  190282. /* Expand paletted images to RGB. */
  190283. void PNGAPI
  190284. png_set_palette_to_rgb(png_structp png_ptr)
  190285. {
  190286. png_debug(1, "in png_set_palette_to_rgb\n");
  190287. if(png_ptr == NULL) return;
  190288. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190289. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190290. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190291. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190292. #endif
  190293. }
  190294. #if !defined(PNG_1_0_X)
  190295. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190296. void PNGAPI
  190297. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190298. {
  190299. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190300. if(png_ptr == NULL) return;
  190301. png_ptr->transformations |= PNG_EXPAND;
  190302. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190303. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190304. #endif
  190305. }
  190306. #endif
  190307. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190308. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190309. /* Deprecated as of libpng-1.2.9 */
  190310. void PNGAPI
  190311. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190312. {
  190313. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190314. if(png_ptr == NULL) return;
  190315. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190316. }
  190317. #endif
  190318. /* Expand tRNS chunks to alpha channels. */
  190319. void PNGAPI
  190320. png_set_tRNS_to_alpha(png_structp png_ptr)
  190321. {
  190322. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190323. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190324. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190325. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190326. #endif
  190327. }
  190328. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190329. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190330. void PNGAPI
  190331. png_set_gray_to_rgb(png_structp png_ptr)
  190332. {
  190333. png_debug(1, "in png_set_gray_to_rgb\n");
  190334. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190335. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190336. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190337. #endif
  190338. }
  190339. #endif
  190340. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190341. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190342. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190343. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190344. */
  190345. void PNGAPI
  190346. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190347. double green)
  190348. {
  190349. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190350. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190351. if(png_ptr == NULL) return;
  190352. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190353. }
  190354. #endif
  190355. void PNGAPI
  190356. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190357. png_fixed_point red, png_fixed_point green)
  190358. {
  190359. png_debug(1, "in png_set_rgb_to_gray\n");
  190360. if(png_ptr == NULL) return;
  190361. switch(error_action)
  190362. {
  190363. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190364. break;
  190365. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190366. break;
  190367. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190368. }
  190369. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190370. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190371. png_ptr->transformations |= PNG_EXPAND;
  190372. #else
  190373. {
  190374. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190375. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190376. }
  190377. #endif
  190378. {
  190379. png_uint_16 red_int, green_int;
  190380. if(red < 0 || green < 0)
  190381. {
  190382. red_int = 6968; /* .212671 * 32768 + .5 */
  190383. green_int = 23434; /* .715160 * 32768 + .5 */
  190384. }
  190385. else if(red + green < 100000L)
  190386. {
  190387. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190388. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190389. }
  190390. else
  190391. {
  190392. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190393. red_int = 6968;
  190394. green_int = 23434;
  190395. }
  190396. png_ptr->rgb_to_gray_red_coeff = red_int;
  190397. png_ptr->rgb_to_gray_green_coeff = green_int;
  190398. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190399. }
  190400. }
  190401. #endif
  190402. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190403. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190404. defined(PNG_LEGACY_SUPPORTED)
  190405. void PNGAPI
  190406. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190407. read_user_transform_fn)
  190408. {
  190409. png_debug(1, "in png_set_read_user_transform_fn\n");
  190410. if(png_ptr == NULL) return;
  190411. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190412. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190413. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190414. #endif
  190415. #ifdef PNG_LEGACY_SUPPORTED
  190416. if(read_user_transform_fn)
  190417. png_warning(png_ptr,
  190418. "This version of libpng does not support user transforms");
  190419. #endif
  190420. }
  190421. #endif
  190422. /* Initialize everything needed for the read. This includes modifying
  190423. * the palette.
  190424. */
  190425. void /* PRIVATE */
  190426. png_init_read_transformations(png_structp png_ptr)
  190427. {
  190428. png_debug(1, "in png_init_read_transformations\n");
  190429. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190430. if(png_ptr != NULL)
  190431. #endif
  190432. {
  190433. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190434. || defined(PNG_READ_GAMMA_SUPPORTED)
  190435. int color_type = png_ptr->color_type;
  190436. #endif
  190437. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190438. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190439. /* Detect gray background and attempt to enable optimization
  190440. * for gray --> RGB case */
  190441. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190442. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190443. * background color might actually be gray yet not be flagged as such.
  190444. * This is not a problem for the current code, which uses
  190445. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190446. * png_do_gray_to_rgb() transformation.
  190447. */
  190448. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190449. !(color_type & PNG_COLOR_MASK_COLOR))
  190450. {
  190451. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190452. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190453. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190454. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190455. png_ptr->background.red == png_ptr->background.green &&
  190456. png_ptr->background.red == png_ptr->background.blue)
  190457. {
  190458. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190459. png_ptr->background.gray = png_ptr->background.red;
  190460. }
  190461. #endif
  190462. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190463. (png_ptr->transformations & PNG_EXPAND))
  190464. {
  190465. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190466. {
  190467. /* expand background and tRNS chunks */
  190468. switch (png_ptr->bit_depth)
  190469. {
  190470. case 1:
  190471. png_ptr->background.gray *= (png_uint_16)0xff;
  190472. png_ptr->background.red = png_ptr->background.green
  190473. = png_ptr->background.blue = png_ptr->background.gray;
  190474. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190475. {
  190476. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190477. png_ptr->trans_values.red = png_ptr->trans_values.green
  190478. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190479. }
  190480. break;
  190481. case 2:
  190482. png_ptr->background.gray *= (png_uint_16)0x55;
  190483. png_ptr->background.red = png_ptr->background.green
  190484. = png_ptr->background.blue = png_ptr->background.gray;
  190485. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190486. {
  190487. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190488. png_ptr->trans_values.red = png_ptr->trans_values.green
  190489. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190490. }
  190491. break;
  190492. case 4:
  190493. png_ptr->background.gray *= (png_uint_16)0x11;
  190494. png_ptr->background.red = png_ptr->background.green
  190495. = png_ptr->background.blue = png_ptr->background.gray;
  190496. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190497. {
  190498. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190499. png_ptr->trans_values.red = png_ptr->trans_values.green
  190500. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190501. }
  190502. break;
  190503. case 8:
  190504. case 16:
  190505. png_ptr->background.red = png_ptr->background.green
  190506. = png_ptr->background.blue = png_ptr->background.gray;
  190507. break;
  190508. }
  190509. }
  190510. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190511. {
  190512. png_ptr->background.red =
  190513. png_ptr->palette[png_ptr->background.index].red;
  190514. png_ptr->background.green =
  190515. png_ptr->palette[png_ptr->background.index].green;
  190516. png_ptr->background.blue =
  190517. png_ptr->palette[png_ptr->background.index].blue;
  190518. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190519. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190520. {
  190521. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190522. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190523. #endif
  190524. {
  190525. /* invert the alpha channel (in tRNS) unless the pixels are
  190526. going to be expanded, in which case leave it for later */
  190527. int i,istop;
  190528. istop=(int)png_ptr->num_trans;
  190529. for (i=0; i<istop; i++)
  190530. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190531. }
  190532. }
  190533. #endif
  190534. }
  190535. }
  190536. #endif
  190537. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190538. png_ptr->background_1 = png_ptr->background;
  190539. #endif
  190540. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190541. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190542. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190543. < PNG_GAMMA_THRESHOLD))
  190544. {
  190545. int i,k;
  190546. k=0;
  190547. for (i=0; i<png_ptr->num_trans; i++)
  190548. {
  190549. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190550. k=1; /* partial transparency is present */
  190551. }
  190552. if (k == 0)
  190553. png_ptr->transformations &= (~PNG_GAMMA);
  190554. }
  190555. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190556. png_ptr->gamma != 0.0)
  190557. {
  190558. png_build_gamma_table(png_ptr);
  190559. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190560. if (png_ptr->transformations & PNG_BACKGROUND)
  190561. {
  190562. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190563. {
  190564. /* could skip if no transparency and
  190565. */
  190566. png_color back, back_1;
  190567. png_colorp palette = png_ptr->palette;
  190568. int num_palette = png_ptr->num_palette;
  190569. int i;
  190570. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190571. {
  190572. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190573. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190574. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190575. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190576. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190577. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190578. }
  190579. else
  190580. {
  190581. double g, gs;
  190582. switch (png_ptr->background_gamma_type)
  190583. {
  190584. case PNG_BACKGROUND_GAMMA_SCREEN:
  190585. g = (png_ptr->screen_gamma);
  190586. gs = 1.0;
  190587. break;
  190588. case PNG_BACKGROUND_GAMMA_FILE:
  190589. g = 1.0 / (png_ptr->gamma);
  190590. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190591. break;
  190592. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190593. g = 1.0 / (png_ptr->background_gamma);
  190594. gs = 1.0 / (png_ptr->background_gamma *
  190595. png_ptr->screen_gamma);
  190596. break;
  190597. default:
  190598. g = 1.0; /* back_1 */
  190599. gs = 1.0; /* back */
  190600. }
  190601. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190602. {
  190603. back.red = (png_byte)png_ptr->background.red;
  190604. back.green = (png_byte)png_ptr->background.green;
  190605. back.blue = (png_byte)png_ptr->background.blue;
  190606. }
  190607. else
  190608. {
  190609. back.red = (png_byte)(pow(
  190610. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190611. back.green = (png_byte)(pow(
  190612. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190613. back.blue = (png_byte)(pow(
  190614. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190615. }
  190616. back_1.red = (png_byte)(pow(
  190617. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190618. back_1.green = (png_byte)(pow(
  190619. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190620. back_1.blue = (png_byte)(pow(
  190621. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190622. }
  190623. for (i = 0; i < num_palette; i++)
  190624. {
  190625. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190626. {
  190627. if (png_ptr->trans[i] == 0)
  190628. {
  190629. palette[i] = back;
  190630. }
  190631. else /* if (png_ptr->trans[i] != 0xff) */
  190632. {
  190633. png_byte v, w;
  190634. v = png_ptr->gamma_to_1[palette[i].red];
  190635. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190636. palette[i].red = png_ptr->gamma_from_1[w];
  190637. v = png_ptr->gamma_to_1[palette[i].green];
  190638. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190639. palette[i].green = png_ptr->gamma_from_1[w];
  190640. v = png_ptr->gamma_to_1[palette[i].blue];
  190641. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190642. palette[i].blue = png_ptr->gamma_from_1[w];
  190643. }
  190644. }
  190645. else
  190646. {
  190647. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190648. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190649. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190650. }
  190651. }
  190652. }
  190653. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190654. else
  190655. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190656. {
  190657. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190658. double g = 1.0;
  190659. double gs = 1.0;
  190660. switch (png_ptr->background_gamma_type)
  190661. {
  190662. case PNG_BACKGROUND_GAMMA_SCREEN:
  190663. g = (png_ptr->screen_gamma);
  190664. gs = 1.0;
  190665. break;
  190666. case PNG_BACKGROUND_GAMMA_FILE:
  190667. g = 1.0 / (png_ptr->gamma);
  190668. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190669. break;
  190670. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190671. g = 1.0 / (png_ptr->background_gamma);
  190672. gs = 1.0 / (png_ptr->background_gamma *
  190673. png_ptr->screen_gamma);
  190674. break;
  190675. }
  190676. png_ptr->background_1.gray = (png_uint_16)(pow(
  190677. (double)png_ptr->background.gray / m, g) * m + .5);
  190678. png_ptr->background.gray = (png_uint_16)(pow(
  190679. (double)png_ptr->background.gray / m, gs) * m + .5);
  190680. if ((png_ptr->background.red != png_ptr->background.green) ||
  190681. (png_ptr->background.red != png_ptr->background.blue) ||
  190682. (png_ptr->background.red != png_ptr->background.gray))
  190683. {
  190684. /* RGB or RGBA with color background */
  190685. png_ptr->background_1.red = (png_uint_16)(pow(
  190686. (double)png_ptr->background.red / m, g) * m + .5);
  190687. png_ptr->background_1.green = (png_uint_16)(pow(
  190688. (double)png_ptr->background.green / m, g) * m + .5);
  190689. png_ptr->background_1.blue = (png_uint_16)(pow(
  190690. (double)png_ptr->background.blue / m, g) * m + .5);
  190691. png_ptr->background.red = (png_uint_16)(pow(
  190692. (double)png_ptr->background.red / m, gs) * m + .5);
  190693. png_ptr->background.green = (png_uint_16)(pow(
  190694. (double)png_ptr->background.green / m, gs) * m + .5);
  190695. png_ptr->background.blue = (png_uint_16)(pow(
  190696. (double)png_ptr->background.blue / m, gs) * m + .5);
  190697. }
  190698. else
  190699. {
  190700. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190701. png_ptr->background_1.red = png_ptr->background_1.green
  190702. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190703. png_ptr->background.red = png_ptr->background.green
  190704. = png_ptr->background.blue = png_ptr->background.gray;
  190705. }
  190706. }
  190707. }
  190708. else
  190709. /* transformation does not include PNG_BACKGROUND */
  190710. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190711. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190712. {
  190713. png_colorp palette = png_ptr->palette;
  190714. int num_palette = png_ptr->num_palette;
  190715. int i;
  190716. for (i = 0; i < num_palette; i++)
  190717. {
  190718. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190719. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190720. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190721. }
  190722. }
  190723. }
  190724. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190725. else
  190726. #endif
  190727. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190728. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190729. /* No GAMMA transformation */
  190730. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190731. (color_type == PNG_COLOR_TYPE_PALETTE))
  190732. {
  190733. int i;
  190734. int istop = (int)png_ptr->num_trans;
  190735. png_color back;
  190736. png_colorp palette = png_ptr->palette;
  190737. back.red = (png_byte)png_ptr->background.red;
  190738. back.green = (png_byte)png_ptr->background.green;
  190739. back.blue = (png_byte)png_ptr->background.blue;
  190740. for (i = 0; i < istop; i++)
  190741. {
  190742. if (png_ptr->trans[i] == 0)
  190743. {
  190744. palette[i] = back;
  190745. }
  190746. else if (png_ptr->trans[i] != 0xff)
  190747. {
  190748. /* The png_composite() macro is defined in png.h */
  190749. png_composite(palette[i].red, palette[i].red,
  190750. png_ptr->trans[i], back.red);
  190751. png_composite(palette[i].green, palette[i].green,
  190752. png_ptr->trans[i], back.green);
  190753. png_composite(palette[i].blue, palette[i].blue,
  190754. png_ptr->trans[i], back.blue);
  190755. }
  190756. }
  190757. }
  190758. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190759. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190760. if ((png_ptr->transformations & PNG_SHIFT) &&
  190761. (color_type == PNG_COLOR_TYPE_PALETTE))
  190762. {
  190763. png_uint_16 i;
  190764. png_uint_16 istop = png_ptr->num_palette;
  190765. int sr = 8 - png_ptr->sig_bit.red;
  190766. int sg = 8 - png_ptr->sig_bit.green;
  190767. int sb = 8 - png_ptr->sig_bit.blue;
  190768. if (sr < 0 || sr > 8)
  190769. sr = 0;
  190770. if (sg < 0 || sg > 8)
  190771. sg = 0;
  190772. if (sb < 0 || sb > 8)
  190773. sb = 0;
  190774. for (i = 0; i < istop; i++)
  190775. {
  190776. png_ptr->palette[i].red >>= sr;
  190777. png_ptr->palette[i].green >>= sg;
  190778. png_ptr->palette[i].blue >>= sb;
  190779. }
  190780. }
  190781. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190782. }
  190783. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190784. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190785. if(png_ptr)
  190786. return;
  190787. #endif
  190788. }
  190789. /* Modify the info structure to reflect the transformations. The
  190790. * info should be updated so a PNG file could be written with it,
  190791. * assuming the transformations result in valid PNG data.
  190792. */
  190793. void /* PRIVATE */
  190794. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190795. {
  190796. png_debug(1, "in png_read_transform_info\n");
  190797. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190798. if (png_ptr->transformations & PNG_EXPAND)
  190799. {
  190800. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190801. {
  190802. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190803. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190804. else
  190805. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190806. info_ptr->bit_depth = 8;
  190807. info_ptr->num_trans = 0;
  190808. }
  190809. else
  190810. {
  190811. if (png_ptr->num_trans)
  190812. {
  190813. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190814. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190815. else
  190816. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190817. }
  190818. if (info_ptr->bit_depth < 8)
  190819. info_ptr->bit_depth = 8;
  190820. info_ptr->num_trans = 0;
  190821. }
  190822. }
  190823. #endif
  190824. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190825. if (png_ptr->transformations & PNG_BACKGROUND)
  190826. {
  190827. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190828. info_ptr->num_trans = 0;
  190829. info_ptr->background = png_ptr->background;
  190830. }
  190831. #endif
  190832. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190833. if (png_ptr->transformations & PNG_GAMMA)
  190834. {
  190835. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190836. info_ptr->gamma = png_ptr->gamma;
  190837. #endif
  190838. #ifdef PNG_FIXED_POINT_SUPPORTED
  190839. info_ptr->int_gamma = png_ptr->int_gamma;
  190840. #endif
  190841. }
  190842. #endif
  190843. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190844. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190845. info_ptr->bit_depth = 8;
  190846. #endif
  190847. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190848. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190849. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190850. #endif
  190851. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190852. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190853. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190854. #endif
  190855. #if defined(PNG_READ_DITHER_SUPPORTED)
  190856. if (png_ptr->transformations & PNG_DITHER)
  190857. {
  190858. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190859. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190860. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190861. {
  190862. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190863. }
  190864. }
  190865. #endif
  190866. #if defined(PNG_READ_PACK_SUPPORTED)
  190867. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190868. info_ptr->bit_depth = 8;
  190869. #endif
  190870. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190871. info_ptr->channels = 1;
  190872. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190873. info_ptr->channels = 3;
  190874. else
  190875. info_ptr->channels = 1;
  190876. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190877. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190878. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190879. #endif
  190880. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190881. info_ptr->channels++;
  190882. #if defined(PNG_READ_FILLER_SUPPORTED)
  190883. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190884. if ((png_ptr->transformations & PNG_FILLER) &&
  190885. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190886. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190887. {
  190888. info_ptr->channels++;
  190889. /* if adding a true alpha channel not just filler */
  190890. #if !defined(PNG_1_0_X)
  190891. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190892. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190893. #endif
  190894. }
  190895. #endif
  190896. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190897. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190898. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190899. {
  190900. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190901. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190902. if(info_ptr->channels < png_ptr->user_transform_channels)
  190903. info_ptr->channels = png_ptr->user_transform_channels;
  190904. }
  190905. #endif
  190906. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190907. info_ptr->bit_depth);
  190908. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190909. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190910. if(png_ptr)
  190911. return;
  190912. #endif
  190913. }
  190914. /* Transform the row. The order of transformations is significant,
  190915. * and is very touchy. If you add a transformation, take care to
  190916. * decide how it fits in with the other transformations here.
  190917. */
  190918. void /* PRIVATE */
  190919. png_do_read_transformations(png_structp png_ptr)
  190920. {
  190921. png_debug(1, "in png_do_read_transformations\n");
  190922. if (png_ptr->row_buf == NULL)
  190923. {
  190924. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190925. char msg[50];
  190926. png_snprintf2(msg, 50,
  190927. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190928. png_ptr->pass);
  190929. png_error(png_ptr, msg);
  190930. #else
  190931. png_error(png_ptr, "NULL row buffer");
  190932. #endif
  190933. }
  190934. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190935. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190936. /* Application has failed to call either png_read_start_image()
  190937. * or png_read_update_info() after setting transforms that expand
  190938. * pixels. This check added to libpng-1.2.19 */
  190939. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190940. png_error(png_ptr, "Uninitialized row");
  190941. #else
  190942. png_warning(png_ptr, "Uninitialized row");
  190943. #endif
  190944. #endif
  190945. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190946. if (png_ptr->transformations & PNG_EXPAND)
  190947. {
  190948. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190949. {
  190950. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190951. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190952. }
  190953. else
  190954. {
  190955. if (png_ptr->num_trans &&
  190956. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190957. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190958. &(png_ptr->trans_values));
  190959. else
  190960. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190961. NULL);
  190962. }
  190963. }
  190964. #endif
  190965. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190966. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190967. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190968. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190969. #endif
  190970. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190971. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190972. {
  190973. int rgb_error =
  190974. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190975. if(rgb_error)
  190976. {
  190977. png_ptr->rgb_to_gray_status=1;
  190978. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190979. PNG_RGB_TO_GRAY_WARN)
  190980. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190981. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190982. PNG_RGB_TO_GRAY_ERR)
  190983. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190984. }
  190985. }
  190986. #endif
  190987. /*
  190988. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190989. In most cases, the "simple transparency" should be done prior to doing
  190990. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190991. pixel is transparent. You would also need to make sure that the
  190992. transparency information is upgraded to RGB.
  190993. To summarize, the current flow is:
  190994. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190995. with background "in place" if transparent,
  190996. convert to RGB if necessary
  190997. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190998. convert to RGB if necessary
  190999. To support RGB backgrounds for gray images we need:
  191000. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191001. 3 or 6 bytes and composite with background
  191002. "in place" if transparent (3x compare/pixel
  191003. compared to doing composite with gray bkgrnd)
  191004. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191005. remove alpha bytes (3x float operations/pixel
  191006. compared with composite on gray background)
  191007. Greg's change will do this. The reason it wasn't done before is for
  191008. performance, as this increases the per-pixel operations. If we would check
  191009. in advance if the background was gray or RGB, and position the gray-to-RGB
  191010. transform appropriately, then it would save a lot of work/time.
  191011. */
  191012. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191013. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191014. * for performance reasons */
  191015. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191016. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191017. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191018. #endif
  191019. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191020. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191021. ((png_ptr->num_trans != 0 ) ||
  191022. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191023. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191024. &(png_ptr->trans_values), &(png_ptr->background)
  191025. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191026. , &(png_ptr->background_1),
  191027. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191028. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191029. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191030. png_ptr->gamma_shift
  191031. #endif
  191032. );
  191033. #endif
  191034. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191035. if ((png_ptr->transformations & PNG_GAMMA) &&
  191036. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191037. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191038. ((png_ptr->num_trans != 0) ||
  191039. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191040. #endif
  191041. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191042. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191043. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191044. png_ptr->gamma_shift);
  191045. #endif
  191046. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191047. if (png_ptr->transformations & PNG_16_TO_8)
  191048. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191049. #endif
  191050. #if defined(PNG_READ_DITHER_SUPPORTED)
  191051. if (png_ptr->transformations & PNG_DITHER)
  191052. {
  191053. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191054. png_ptr->palette_lookup, png_ptr->dither_index);
  191055. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191056. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191057. }
  191058. #endif
  191059. #if defined(PNG_READ_INVERT_SUPPORTED)
  191060. if (png_ptr->transformations & PNG_INVERT_MONO)
  191061. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191062. #endif
  191063. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191064. if (png_ptr->transformations & PNG_SHIFT)
  191065. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191066. &(png_ptr->shift));
  191067. #endif
  191068. #if defined(PNG_READ_PACK_SUPPORTED)
  191069. if (png_ptr->transformations & PNG_PACK)
  191070. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191071. #endif
  191072. #if defined(PNG_READ_BGR_SUPPORTED)
  191073. if (png_ptr->transformations & PNG_BGR)
  191074. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191075. #endif
  191076. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191077. if (png_ptr->transformations & PNG_PACKSWAP)
  191078. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191079. #endif
  191080. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191081. /* if gray -> RGB, do so now only if we did not do so above */
  191082. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191083. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191084. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191085. #endif
  191086. #if defined(PNG_READ_FILLER_SUPPORTED)
  191087. if (png_ptr->transformations & PNG_FILLER)
  191088. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191089. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191090. #endif
  191091. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191092. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191093. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191094. #endif
  191095. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191096. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191097. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191098. #endif
  191099. #if defined(PNG_READ_SWAP_SUPPORTED)
  191100. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191101. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191102. #endif
  191103. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191104. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191105. {
  191106. if(png_ptr->read_user_transform_fn != NULL)
  191107. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191108. (png_ptr, /* png_ptr */
  191109. &(png_ptr->row_info), /* row_info: */
  191110. /* png_uint_32 width; width of row */
  191111. /* png_uint_32 rowbytes; number of bytes in row */
  191112. /* png_byte color_type; color type of pixels */
  191113. /* png_byte bit_depth; bit depth of samples */
  191114. /* png_byte channels; number of channels (1-4) */
  191115. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191116. png_ptr->row_buf + 1); /* start of pixel data for row */
  191117. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191118. if(png_ptr->user_transform_depth)
  191119. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191120. if(png_ptr->user_transform_channels)
  191121. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191122. #endif
  191123. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191124. png_ptr->row_info.channels);
  191125. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191126. png_ptr->row_info.width);
  191127. }
  191128. #endif
  191129. }
  191130. #if defined(PNG_READ_PACK_SUPPORTED)
  191131. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191132. * without changing the actual values. Thus, if you had a row with
  191133. * a bit depth of 1, you would end up with bytes that only contained
  191134. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191135. * png_do_shift() after this.
  191136. */
  191137. void /* PRIVATE */
  191138. png_do_unpack(png_row_infop row_info, png_bytep row)
  191139. {
  191140. png_debug(1, "in png_do_unpack\n");
  191141. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191142. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191143. #else
  191144. if (row_info->bit_depth < 8)
  191145. #endif
  191146. {
  191147. png_uint_32 i;
  191148. png_uint_32 row_width=row_info->width;
  191149. switch (row_info->bit_depth)
  191150. {
  191151. case 1:
  191152. {
  191153. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191154. png_bytep dp = row + (png_size_t)row_width - 1;
  191155. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191156. for (i = 0; i < row_width; i++)
  191157. {
  191158. *dp = (png_byte)((*sp >> shift) & 0x01);
  191159. if (shift == 7)
  191160. {
  191161. shift = 0;
  191162. sp--;
  191163. }
  191164. else
  191165. shift++;
  191166. dp--;
  191167. }
  191168. break;
  191169. }
  191170. case 2:
  191171. {
  191172. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191173. png_bytep dp = row + (png_size_t)row_width - 1;
  191174. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191175. for (i = 0; i < row_width; i++)
  191176. {
  191177. *dp = (png_byte)((*sp >> shift) & 0x03);
  191178. if (shift == 6)
  191179. {
  191180. shift = 0;
  191181. sp--;
  191182. }
  191183. else
  191184. shift += 2;
  191185. dp--;
  191186. }
  191187. break;
  191188. }
  191189. case 4:
  191190. {
  191191. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191192. png_bytep dp = row + (png_size_t)row_width - 1;
  191193. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191194. for (i = 0; i < row_width; i++)
  191195. {
  191196. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191197. if (shift == 4)
  191198. {
  191199. shift = 0;
  191200. sp--;
  191201. }
  191202. else
  191203. shift = 4;
  191204. dp--;
  191205. }
  191206. break;
  191207. }
  191208. }
  191209. row_info->bit_depth = 8;
  191210. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191211. row_info->rowbytes = row_width * row_info->channels;
  191212. }
  191213. }
  191214. #endif
  191215. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191216. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191217. * pixels back to their significant bits values. Thus, if you have
  191218. * a row of bit depth 8, but only 5 are significant, this will shift
  191219. * the values back to 0 through 31.
  191220. */
  191221. void /* PRIVATE */
  191222. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191223. {
  191224. png_debug(1, "in png_do_unshift\n");
  191225. if (
  191226. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191227. row != NULL && row_info != NULL && sig_bits != NULL &&
  191228. #endif
  191229. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191230. {
  191231. int shift[4];
  191232. int channels = 0;
  191233. int c;
  191234. png_uint_16 value = 0;
  191235. png_uint_32 row_width = row_info->width;
  191236. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191237. {
  191238. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191239. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191240. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191241. }
  191242. else
  191243. {
  191244. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191245. }
  191246. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191247. {
  191248. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191249. }
  191250. for (c = 0; c < channels; c++)
  191251. {
  191252. if (shift[c] <= 0)
  191253. shift[c] = 0;
  191254. else
  191255. value = 1;
  191256. }
  191257. if (!value)
  191258. return;
  191259. switch (row_info->bit_depth)
  191260. {
  191261. case 2:
  191262. {
  191263. png_bytep bp;
  191264. png_uint_32 i;
  191265. png_uint_32 istop = row_info->rowbytes;
  191266. for (bp = row, i = 0; i < istop; i++)
  191267. {
  191268. *bp >>= 1;
  191269. *bp++ &= 0x55;
  191270. }
  191271. break;
  191272. }
  191273. case 4:
  191274. {
  191275. png_bytep bp = row;
  191276. png_uint_32 i;
  191277. png_uint_32 istop = row_info->rowbytes;
  191278. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191279. (png_byte)((int)0xf >> shift[0]));
  191280. for (i = 0; i < istop; i++)
  191281. {
  191282. *bp >>= shift[0];
  191283. *bp++ &= mask;
  191284. }
  191285. break;
  191286. }
  191287. case 8:
  191288. {
  191289. png_bytep bp = row;
  191290. png_uint_32 i;
  191291. png_uint_32 istop = row_width * channels;
  191292. for (i = 0; i < istop; i++)
  191293. {
  191294. *bp++ >>= shift[i%channels];
  191295. }
  191296. break;
  191297. }
  191298. case 16:
  191299. {
  191300. png_bytep bp = row;
  191301. png_uint_32 i;
  191302. png_uint_32 istop = channels * row_width;
  191303. for (i = 0; i < istop; i++)
  191304. {
  191305. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191306. value >>= shift[i%channels];
  191307. *bp++ = (png_byte)(value >> 8);
  191308. *bp++ = (png_byte)(value & 0xff);
  191309. }
  191310. break;
  191311. }
  191312. }
  191313. }
  191314. }
  191315. #endif
  191316. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191317. /* chop rows of bit depth 16 down to 8 */
  191318. void /* PRIVATE */
  191319. png_do_chop(png_row_infop row_info, png_bytep row)
  191320. {
  191321. png_debug(1, "in png_do_chop\n");
  191322. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191323. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191324. #else
  191325. if (row_info->bit_depth == 16)
  191326. #endif
  191327. {
  191328. png_bytep sp = row;
  191329. png_bytep dp = row;
  191330. png_uint_32 i;
  191331. png_uint_32 istop = row_info->width * row_info->channels;
  191332. for (i = 0; i<istop; i++, sp += 2, dp++)
  191333. {
  191334. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191335. /* This does a more accurate scaling of the 16-bit color
  191336. * value, rather than a simple low-byte truncation.
  191337. *
  191338. * What the ideal calculation should be:
  191339. * *dp = (((((png_uint_32)(*sp) << 8) |
  191340. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191341. *
  191342. * GRR: no, I think this is what it really should be:
  191343. * *dp = (((((png_uint_32)(*sp) << 8) |
  191344. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191345. *
  191346. * GRR: here's the exact calculation with shifts:
  191347. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191348. * *dp = (temp - (temp >> 8)) >> 8;
  191349. *
  191350. * Approximate calculation with shift/add instead of multiply/divide:
  191351. * *dp = ((((png_uint_32)(*sp) << 8) |
  191352. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191353. *
  191354. * What we actually do to avoid extra shifting and conversion:
  191355. */
  191356. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191357. #else
  191358. /* Simply discard the low order byte */
  191359. *dp = *sp;
  191360. #endif
  191361. }
  191362. row_info->bit_depth = 8;
  191363. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191364. row_info->rowbytes = row_info->width * row_info->channels;
  191365. }
  191366. }
  191367. #endif
  191368. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191369. void /* PRIVATE */
  191370. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191371. {
  191372. png_debug(1, "in png_do_read_swap_alpha\n");
  191373. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191374. if (row != NULL && row_info != NULL)
  191375. #endif
  191376. {
  191377. png_uint_32 row_width = row_info->width;
  191378. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191379. {
  191380. /* This converts from RGBA to ARGB */
  191381. if (row_info->bit_depth == 8)
  191382. {
  191383. png_bytep sp = row + row_info->rowbytes;
  191384. png_bytep dp = sp;
  191385. png_byte save;
  191386. png_uint_32 i;
  191387. for (i = 0; i < row_width; i++)
  191388. {
  191389. save = *(--sp);
  191390. *(--dp) = *(--sp);
  191391. *(--dp) = *(--sp);
  191392. *(--dp) = *(--sp);
  191393. *(--dp) = save;
  191394. }
  191395. }
  191396. /* This converts from RRGGBBAA to AARRGGBB */
  191397. else
  191398. {
  191399. png_bytep sp = row + row_info->rowbytes;
  191400. png_bytep dp = sp;
  191401. png_byte save[2];
  191402. png_uint_32 i;
  191403. for (i = 0; i < row_width; i++)
  191404. {
  191405. save[0] = *(--sp);
  191406. save[1] = *(--sp);
  191407. *(--dp) = *(--sp);
  191408. *(--dp) = *(--sp);
  191409. *(--dp) = *(--sp);
  191410. *(--dp) = *(--sp);
  191411. *(--dp) = *(--sp);
  191412. *(--dp) = *(--sp);
  191413. *(--dp) = save[0];
  191414. *(--dp) = save[1];
  191415. }
  191416. }
  191417. }
  191418. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191419. {
  191420. /* This converts from GA to AG */
  191421. if (row_info->bit_depth == 8)
  191422. {
  191423. png_bytep sp = row + row_info->rowbytes;
  191424. png_bytep dp = sp;
  191425. png_byte save;
  191426. png_uint_32 i;
  191427. for (i = 0; i < row_width; i++)
  191428. {
  191429. save = *(--sp);
  191430. *(--dp) = *(--sp);
  191431. *(--dp) = save;
  191432. }
  191433. }
  191434. /* This converts from GGAA to AAGG */
  191435. else
  191436. {
  191437. png_bytep sp = row + row_info->rowbytes;
  191438. png_bytep dp = sp;
  191439. png_byte save[2];
  191440. png_uint_32 i;
  191441. for (i = 0; i < row_width; i++)
  191442. {
  191443. save[0] = *(--sp);
  191444. save[1] = *(--sp);
  191445. *(--dp) = *(--sp);
  191446. *(--dp) = *(--sp);
  191447. *(--dp) = save[0];
  191448. *(--dp) = save[1];
  191449. }
  191450. }
  191451. }
  191452. }
  191453. }
  191454. #endif
  191455. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191456. void /* PRIVATE */
  191457. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191458. {
  191459. png_debug(1, "in png_do_read_invert_alpha\n");
  191460. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191461. if (row != NULL && row_info != NULL)
  191462. #endif
  191463. {
  191464. png_uint_32 row_width = row_info->width;
  191465. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191466. {
  191467. /* This inverts the alpha channel in RGBA */
  191468. if (row_info->bit_depth == 8)
  191469. {
  191470. png_bytep sp = row + row_info->rowbytes;
  191471. png_bytep dp = sp;
  191472. png_uint_32 i;
  191473. for (i = 0; i < row_width; i++)
  191474. {
  191475. *(--dp) = (png_byte)(255 - *(--sp));
  191476. /* This does nothing:
  191477. *(--dp) = *(--sp);
  191478. *(--dp) = *(--sp);
  191479. *(--dp) = *(--sp);
  191480. We can replace it with:
  191481. */
  191482. sp-=3;
  191483. dp=sp;
  191484. }
  191485. }
  191486. /* This inverts the alpha channel in RRGGBBAA */
  191487. else
  191488. {
  191489. png_bytep sp = row + row_info->rowbytes;
  191490. png_bytep dp = sp;
  191491. png_uint_32 i;
  191492. for (i = 0; i < row_width; i++)
  191493. {
  191494. *(--dp) = (png_byte)(255 - *(--sp));
  191495. *(--dp) = (png_byte)(255 - *(--sp));
  191496. /* This does nothing:
  191497. *(--dp) = *(--sp);
  191498. *(--dp) = *(--sp);
  191499. *(--dp) = *(--sp);
  191500. *(--dp) = *(--sp);
  191501. *(--dp) = *(--sp);
  191502. *(--dp) = *(--sp);
  191503. We can replace it with:
  191504. */
  191505. sp-=6;
  191506. dp=sp;
  191507. }
  191508. }
  191509. }
  191510. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191511. {
  191512. /* This inverts the alpha channel in GA */
  191513. if (row_info->bit_depth == 8)
  191514. {
  191515. png_bytep sp = row + row_info->rowbytes;
  191516. png_bytep dp = sp;
  191517. png_uint_32 i;
  191518. for (i = 0; i < row_width; i++)
  191519. {
  191520. *(--dp) = (png_byte)(255 - *(--sp));
  191521. *(--dp) = *(--sp);
  191522. }
  191523. }
  191524. /* This inverts the alpha channel in GGAA */
  191525. else
  191526. {
  191527. png_bytep sp = row + row_info->rowbytes;
  191528. png_bytep dp = sp;
  191529. png_uint_32 i;
  191530. for (i = 0; i < row_width; i++)
  191531. {
  191532. *(--dp) = (png_byte)(255 - *(--sp));
  191533. *(--dp) = (png_byte)(255 - *(--sp));
  191534. /*
  191535. *(--dp) = *(--sp);
  191536. *(--dp) = *(--sp);
  191537. */
  191538. sp-=2;
  191539. dp=sp;
  191540. }
  191541. }
  191542. }
  191543. }
  191544. }
  191545. #endif
  191546. #if defined(PNG_READ_FILLER_SUPPORTED)
  191547. /* Add filler channel if we have RGB color */
  191548. void /* PRIVATE */
  191549. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191550. png_uint_32 filler, png_uint_32 flags)
  191551. {
  191552. png_uint_32 i;
  191553. png_uint_32 row_width = row_info->width;
  191554. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191555. png_byte lo_filler = (png_byte)(filler & 0xff);
  191556. png_debug(1, "in png_do_read_filler\n");
  191557. if (
  191558. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191559. row != NULL && row_info != NULL &&
  191560. #endif
  191561. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191562. {
  191563. if(row_info->bit_depth == 8)
  191564. {
  191565. /* This changes the data from G to GX */
  191566. if (flags & PNG_FLAG_FILLER_AFTER)
  191567. {
  191568. png_bytep sp = row + (png_size_t)row_width;
  191569. png_bytep dp = sp + (png_size_t)row_width;
  191570. for (i = 1; i < row_width; i++)
  191571. {
  191572. *(--dp) = lo_filler;
  191573. *(--dp) = *(--sp);
  191574. }
  191575. *(--dp) = lo_filler;
  191576. row_info->channels = 2;
  191577. row_info->pixel_depth = 16;
  191578. row_info->rowbytes = row_width * 2;
  191579. }
  191580. /* This changes the data from G to XG */
  191581. else
  191582. {
  191583. png_bytep sp = row + (png_size_t)row_width;
  191584. png_bytep dp = sp + (png_size_t)row_width;
  191585. for (i = 0; i < row_width; i++)
  191586. {
  191587. *(--dp) = *(--sp);
  191588. *(--dp) = lo_filler;
  191589. }
  191590. row_info->channels = 2;
  191591. row_info->pixel_depth = 16;
  191592. row_info->rowbytes = row_width * 2;
  191593. }
  191594. }
  191595. else if(row_info->bit_depth == 16)
  191596. {
  191597. /* This changes the data from GG to GGXX */
  191598. if (flags & PNG_FLAG_FILLER_AFTER)
  191599. {
  191600. png_bytep sp = row + (png_size_t)row_width * 2;
  191601. png_bytep dp = sp + (png_size_t)row_width * 2;
  191602. for (i = 1; i < row_width; i++)
  191603. {
  191604. *(--dp) = hi_filler;
  191605. *(--dp) = lo_filler;
  191606. *(--dp) = *(--sp);
  191607. *(--dp) = *(--sp);
  191608. }
  191609. *(--dp) = hi_filler;
  191610. *(--dp) = lo_filler;
  191611. row_info->channels = 2;
  191612. row_info->pixel_depth = 32;
  191613. row_info->rowbytes = row_width * 4;
  191614. }
  191615. /* This changes the data from GG to XXGG */
  191616. else
  191617. {
  191618. png_bytep sp = row + (png_size_t)row_width * 2;
  191619. png_bytep dp = sp + (png_size_t)row_width * 2;
  191620. for (i = 0; i < row_width; i++)
  191621. {
  191622. *(--dp) = *(--sp);
  191623. *(--dp) = *(--sp);
  191624. *(--dp) = hi_filler;
  191625. *(--dp) = lo_filler;
  191626. }
  191627. row_info->channels = 2;
  191628. row_info->pixel_depth = 32;
  191629. row_info->rowbytes = row_width * 4;
  191630. }
  191631. }
  191632. } /* COLOR_TYPE == GRAY */
  191633. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191634. {
  191635. if(row_info->bit_depth == 8)
  191636. {
  191637. /* This changes the data from RGB to RGBX */
  191638. if (flags & PNG_FLAG_FILLER_AFTER)
  191639. {
  191640. png_bytep sp = row + (png_size_t)row_width * 3;
  191641. png_bytep dp = sp + (png_size_t)row_width;
  191642. for (i = 1; i < row_width; i++)
  191643. {
  191644. *(--dp) = lo_filler;
  191645. *(--dp) = *(--sp);
  191646. *(--dp) = *(--sp);
  191647. *(--dp) = *(--sp);
  191648. }
  191649. *(--dp) = lo_filler;
  191650. row_info->channels = 4;
  191651. row_info->pixel_depth = 32;
  191652. row_info->rowbytes = row_width * 4;
  191653. }
  191654. /* This changes the data from RGB to XRGB */
  191655. else
  191656. {
  191657. png_bytep sp = row + (png_size_t)row_width * 3;
  191658. png_bytep dp = sp + (png_size_t)row_width;
  191659. for (i = 0; i < row_width; i++)
  191660. {
  191661. *(--dp) = *(--sp);
  191662. *(--dp) = *(--sp);
  191663. *(--dp) = *(--sp);
  191664. *(--dp) = lo_filler;
  191665. }
  191666. row_info->channels = 4;
  191667. row_info->pixel_depth = 32;
  191668. row_info->rowbytes = row_width * 4;
  191669. }
  191670. }
  191671. else if(row_info->bit_depth == 16)
  191672. {
  191673. /* This changes the data from RRGGBB to RRGGBBXX */
  191674. if (flags & PNG_FLAG_FILLER_AFTER)
  191675. {
  191676. png_bytep sp = row + (png_size_t)row_width * 6;
  191677. png_bytep dp = sp + (png_size_t)row_width * 2;
  191678. for (i = 1; i < row_width; i++)
  191679. {
  191680. *(--dp) = hi_filler;
  191681. *(--dp) = lo_filler;
  191682. *(--dp) = *(--sp);
  191683. *(--dp) = *(--sp);
  191684. *(--dp) = *(--sp);
  191685. *(--dp) = *(--sp);
  191686. *(--dp) = *(--sp);
  191687. *(--dp) = *(--sp);
  191688. }
  191689. *(--dp) = hi_filler;
  191690. *(--dp) = lo_filler;
  191691. row_info->channels = 4;
  191692. row_info->pixel_depth = 64;
  191693. row_info->rowbytes = row_width * 8;
  191694. }
  191695. /* This changes the data from RRGGBB to XXRRGGBB */
  191696. else
  191697. {
  191698. png_bytep sp = row + (png_size_t)row_width * 6;
  191699. png_bytep dp = sp + (png_size_t)row_width * 2;
  191700. for (i = 0; i < row_width; i++)
  191701. {
  191702. *(--dp) = *(--sp);
  191703. *(--dp) = *(--sp);
  191704. *(--dp) = *(--sp);
  191705. *(--dp) = *(--sp);
  191706. *(--dp) = *(--sp);
  191707. *(--dp) = *(--sp);
  191708. *(--dp) = hi_filler;
  191709. *(--dp) = lo_filler;
  191710. }
  191711. row_info->channels = 4;
  191712. row_info->pixel_depth = 64;
  191713. row_info->rowbytes = row_width * 8;
  191714. }
  191715. }
  191716. } /* COLOR_TYPE == RGB */
  191717. }
  191718. #endif
  191719. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191720. /* expand grayscale files to RGB, with or without alpha */
  191721. void /* PRIVATE */
  191722. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191723. {
  191724. png_uint_32 i;
  191725. png_uint_32 row_width = row_info->width;
  191726. png_debug(1, "in png_do_gray_to_rgb\n");
  191727. if (row_info->bit_depth >= 8 &&
  191728. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191729. row != NULL && row_info != NULL &&
  191730. #endif
  191731. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191732. {
  191733. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191734. {
  191735. if (row_info->bit_depth == 8)
  191736. {
  191737. png_bytep sp = row + (png_size_t)row_width - 1;
  191738. png_bytep dp = sp + (png_size_t)row_width * 2;
  191739. for (i = 0; i < row_width; i++)
  191740. {
  191741. *(dp--) = *sp;
  191742. *(dp--) = *sp;
  191743. *(dp--) = *(sp--);
  191744. }
  191745. }
  191746. else
  191747. {
  191748. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191749. png_bytep dp = sp + (png_size_t)row_width * 4;
  191750. for (i = 0; i < row_width; i++)
  191751. {
  191752. *(dp--) = *sp;
  191753. *(dp--) = *(sp - 1);
  191754. *(dp--) = *sp;
  191755. *(dp--) = *(sp - 1);
  191756. *(dp--) = *(sp--);
  191757. *(dp--) = *(sp--);
  191758. }
  191759. }
  191760. }
  191761. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191762. {
  191763. if (row_info->bit_depth == 8)
  191764. {
  191765. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191766. png_bytep dp = sp + (png_size_t)row_width * 2;
  191767. for (i = 0; i < row_width; i++)
  191768. {
  191769. *(dp--) = *(sp--);
  191770. *(dp--) = *sp;
  191771. *(dp--) = *sp;
  191772. *(dp--) = *(sp--);
  191773. }
  191774. }
  191775. else
  191776. {
  191777. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191778. png_bytep dp = sp + (png_size_t)row_width * 4;
  191779. for (i = 0; i < row_width; i++)
  191780. {
  191781. *(dp--) = *(sp--);
  191782. *(dp--) = *(sp--);
  191783. *(dp--) = *sp;
  191784. *(dp--) = *(sp - 1);
  191785. *(dp--) = *sp;
  191786. *(dp--) = *(sp - 1);
  191787. *(dp--) = *(sp--);
  191788. *(dp--) = *(sp--);
  191789. }
  191790. }
  191791. }
  191792. row_info->channels += (png_byte)2;
  191793. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191794. row_info->pixel_depth = (png_byte)(row_info->channels *
  191795. row_info->bit_depth);
  191796. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191797. }
  191798. }
  191799. #endif
  191800. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191801. /* reduce RGB files to grayscale, with or without alpha
  191802. * using the equation given in Poynton's ColorFAQ at
  191803. * <http://www.inforamp.net/~poynton/>
  191804. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191805. *
  191806. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191807. *
  191808. * We approximate this with
  191809. *
  191810. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191811. *
  191812. * which can be expressed with integers as
  191813. *
  191814. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191815. *
  191816. * The calculation is to be done in a linear colorspace.
  191817. *
  191818. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191819. */
  191820. int /* PRIVATE */
  191821. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191822. {
  191823. png_uint_32 i;
  191824. png_uint_32 row_width = row_info->width;
  191825. int rgb_error = 0;
  191826. png_debug(1, "in png_do_rgb_to_gray\n");
  191827. if (
  191828. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191829. row != NULL && row_info != NULL &&
  191830. #endif
  191831. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191832. {
  191833. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191834. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191835. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191836. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191837. {
  191838. if (row_info->bit_depth == 8)
  191839. {
  191840. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191841. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191842. {
  191843. png_bytep sp = row;
  191844. png_bytep dp = row;
  191845. for (i = 0; i < row_width; i++)
  191846. {
  191847. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191848. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191849. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191850. if(red != green || red != blue)
  191851. {
  191852. rgb_error |= 1;
  191853. *(dp++) = png_ptr->gamma_from_1[
  191854. (rc*red+gc*green+bc*blue)>>15];
  191855. }
  191856. else
  191857. *(dp++) = *(sp-1);
  191858. }
  191859. }
  191860. else
  191861. #endif
  191862. {
  191863. png_bytep sp = row;
  191864. png_bytep dp = row;
  191865. for (i = 0; i < row_width; i++)
  191866. {
  191867. png_byte red = *(sp++);
  191868. png_byte green = *(sp++);
  191869. png_byte blue = *(sp++);
  191870. if(red != green || red != blue)
  191871. {
  191872. rgb_error |= 1;
  191873. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191874. }
  191875. else
  191876. *(dp++) = *(sp-1);
  191877. }
  191878. }
  191879. }
  191880. else /* RGB bit_depth == 16 */
  191881. {
  191882. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191883. if (png_ptr->gamma_16_to_1 != NULL &&
  191884. png_ptr->gamma_16_from_1 != NULL)
  191885. {
  191886. png_bytep sp = row;
  191887. png_bytep dp = row;
  191888. for (i = 0; i < row_width; i++)
  191889. {
  191890. png_uint_16 red, green, blue, w;
  191891. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191892. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191893. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191894. if(red == green && red == blue)
  191895. w = red;
  191896. else
  191897. {
  191898. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191899. png_ptr->gamma_shift][red>>8];
  191900. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191901. png_ptr->gamma_shift][green>>8];
  191902. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191903. png_ptr->gamma_shift][blue>>8];
  191904. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191905. + bc*blue_1)>>15);
  191906. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191907. png_ptr->gamma_shift][gray16 >> 8];
  191908. rgb_error |= 1;
  191909. }
  191910. *(dp++) = (png_byte)((w>>8) & 0xff);
  191911. *(dp++) = (png_byte)(w & 0xff);
  191912. }
  191913. }
  191914. else
  191915. #endif
  191916. {
  191917. png_bytep sp = row;
  191918. png_bytep dp = row;
  191919. for (i = 0; i < row_width; i++)
  191920. {
  191921. png_uint_16 red, green, blue, gray16;
  191922. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191923. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191924. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191925. if(red != green || red != blue)
  191926. rgb_error |= 1;
  191927. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191928. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191929. *(dp++) = (png_byte)(gray16 & 0xff);
  191930. }
  191931. }
  191932. }
  191933. }
  191934. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191935. {
  191936. if (row_info->bit_depth == 8)
  191937. {
  191938. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191939. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191940. {
  191941. png_bytep sp = row;
  191942. png_bytep dp = row;
  191943. for (i = 0; i < row_width; i++)
  191944. {
  191945. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191946. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191947. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191948. if(red != green || red != blue)
  191949. rgb_error |= 1;
  191950. *(dp++) = png_ptr->gamma_from_1
  191951. [(rc*red + gc*green + bc*blue)>>15];
  191952. *(dp++) = *(sp++); /* alpha */
  191953. }
  191954. }
  191955. else
  191956. #endif
  191957. {
  191958. png_bytep sp = row;
  191959. png_bytep dp = row;
  191960. for (i = 0; i < row_width; i++)
  191961. {
  191962. png_byte red = *(sp++);
  191963. png_byte green = *(sp++);
  191964. png_byte blue = *(sp++);
  191965. if(red != green || red != blue)
  191966. rgb_error |= 1;
  191967. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191968. *(dp++) = *(sp++); /* alpha */
  191969. }
  191970. }
  191971. }
  191972. else /* RGBA bit_depth == 16 */
  191973. {
  191974. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191975. if (png_ptr->gamma_16_to_1 != NULL &&
  191976. png_ptr->gamma_16_from_1 != NULL)
  191977. {
  191978. png_bytep sp = row;
  191979. png_bytep dp = row;
  191980. for (i = 0; i < row_width; i++)
  191981. {
  191982. png_uint_16 red, green, blue, w;
  191983. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191984. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191985. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191986. if(red == green && red == blue)
  191987. w = red;
  191988. else
  191989. {
  191990. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191991. png_ptr->gamma_shift][red>>8];
  191992. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191993. png_ptr->gamma_shift][green>>8];
  191994. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191995. png_ptr->gamma_shift][blue>>8];
  191996. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191997. + gc * green_1 + bc * blue_1)>>15);
  191998. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191999. png_ptr->gamma_shift][gray16 >> 8];
  192000. rgb_error |= 1;
  192001. }
  192002. *(dp++) = (png_byte)((w>>8) & 0xff);
  192003. *(dp++) = (png_byte)(w & 0xff);
  192004. *(dp++) = *(sp++); /* alpha */
  192005. *(dp++) = *(sp++);
  192006. }
  192007. }
  192008. else
  192009. #endif
  192010. {
  192011. png_bytep sp = row;
  192012. png_bytep dp = row;
  192013. for (i = 0; i < row_width; i++)
  192014. {
  192015. png_uint_16 red, green, blue, gray16;
  192016. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192017. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192018. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192019. if(red != green || red != blue)
  192020. rgb_error |= 1;
  192021. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192022. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192023. *(dp++) = (png_byte)(gray16 & 0xff);
  192024. *(dp++) = *(sp++); /* alpha */
  192025. *(dp++) = *(sp++);
  192026. }
  192027. }
  192028. }
  192029. }
  192030. row_info->channels -= (png_byte)2;
  192031. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192032. row_info->pixel_depth = (png_byte)(row_info->channels *
  192033. row_info->bit_depth);
  192034. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192035. }
  192036. return rgb_error;
  192037. }
  192038. #endif
  192039. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192040. * large of png_color. This lets grayscale images be treated as
  192041. * paletted. Most useful for gamma correction and simplification
  192042. * of code.
  192043. */
  192044. void PNGAPI
  192045. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192046. {
  192047. int num_palette;
  192048. int color_inc;
  192049. int i;
  192050. int v;
  192051. png_debug(1, "in png_do_build_grayscale_palette\n");
  192052. if (palette == NULL)
  192053. return;
  192054. switch (bit_depth)
  192055. {
  192056. case 1:
  192057. num_palette = 2;
  192058. color_inc = 0xff;
  192059. break;
  192060. case 2:
  192061. num_palette = 4;
  192062. color_inc = 0x55;
  192063. break;
  192064. case 4:
  192065. num_palette = 16;
  192066. color_inc = 0x11;
  192067. break;
  192068. case 8:
  192069. num_palette = 256;
  192070. color_inc = 1;
  192071. break;
  192072. default:
  192073. num_palette = 0;
  192074. color_inc = 0;
  192075. break;
  192076. }
  192077. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192078. {
  192079. palette[i].red = (png_byte)v;
  192080. palette[i].green = (png_byte)v;
  192081. palette[i].blue = (png_byte)v;
  192082. }
  192083. }
  192084. /* This function is currently unused. Do we really need it? */
  192085. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192086. void /* PRIVATE */
  192087. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192088. int num_palette)
  192089. {
  192090. png_debug(1, "in png_correct_palette\n");
  192091. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192092. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192093. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192094. {
  192095. png_color back, back_1;
  192096. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192097. {
  192098. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192099. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192100. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192101. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192102. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192103. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192104. }
  192105. else
  192106. {
  192107. double g;
  192108. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192109. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192110. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192111. {
  192112. back.red = png_ptr->background.red;
  192113. back.green = png_ptr->background.green;
  192114. back.blue = png_ptr->background.blue;
  192115. }
  192116. else
  192117. {
  192118. back.red =
  192119. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192120. 255.0 + 0.5);
  192121. back.green =
  192122. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192123. 255.0 + 0.5);
  192124. back.blue =
  192125. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192126. 255.0 + 0.5);
  192127. }
  192128. g = 1.0 / png_ptr->background_gamma;
  192129. back_1.red =
  192130. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192131. 255.0 + 0.5);
  192132. back_1.green =
  192133. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192134. 255.0 + 0.5);
  192135. back_1.blue =
  192136. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192137. 255.0 + 0.5);
  192138. }
  192139. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192140. {
  192141. png_uint_32 i;
  192142. for (i = 0; i < (png_uint_32)num_palette; i++)
  192143. {
  192144. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192145. {
  192146. palette[i] = back;
  192147. }
  192148. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192149. {
  192150. png_byte v, w;
  192151. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192152. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192153. palette[i].red = png_ptr->gamma_from_1[w];
  192154. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192155. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192156. palette[i].green = png_ptr->gamma_from_1[w];
  192157. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192158. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192159. palette[i].blue = png_ptr->gamma_from_1[w];
  192160. }
  192161. else
  192162. {
  192163. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192164. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192165. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192166. }
  192167. }
  192168. }
  192169. else
  192170. {
  192171. int i;
  192172. for (i = 0; i < num_palette; i++)
  192173. {
  192174. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192175. {
  192176. palette[i] = back;
  192177. }
  192178. else
  192179. {
  192180. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192181. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192182. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192183. }
  192184. }
  192185. }
  192186. }
  192187. else
  192188. #endif
  192189. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192190. if (png_ptr->transformations & PNG_GAMMA)
  192191. {
  192192. int i;
  192193. for (i = 0; i < num_palette; i++)
  192194. {
  192195. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192196. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192197. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192198. }
  192199. }
  192200. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192201. else
  192202. #endif
  192203. #endif
  192204. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192205. if (png_ptr->transformations & PNG_BACKGROUND)
  192206. {
  192207. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192208. {
  192209. png_color back;
  192210. back.red = (png_byte)png_ptr->background.red;
  192211. back.green = (png_byte)png_ptr->background.green;
  192212. back.blue = (png_byte)png_ptr->background.blue;
  192213. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192214. {
  192215. if (png_ptr->trans[i] == 0)
  192216. {
  192217. palette[i].red = back.red;
  192218. palette[i].green = back.green;
  192219. palette[i].blue = back.blue;
  192220. }
  192221. else if (png_ptr->trans[i] != 0xff)
  192222. {
  192223. png_composite(palette[i].red, png_ptr->palette[i].red,
  192224. png_ptr->trans[i], back.red);
  192225. png_composite(palette[i].green, png_ptr->palette[i].green,
  192226. png_ptr->trans[i], back.green);
  192227. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192228. png_ptr->trans[i], back.blue);
  192229. }
  192230. }
  192231. }
  192232. else /* assume grayscale palette (what else could it be?) */
  192233. {
  192234. int i;
  192235. for (i = 0; i < num_palette; i++)
  192236. {
  192237. if (i == (png_byte)png_ptr->trans_values.gray)
  192238. {
  192239. palette[i].red = (png_byte)png_ptr->background.red;
  192240. palette[i].green = (png_byte)png_ptr->background.green;
  192241. palette[i].blue = (png_byte)png_ptr->background.blue;
  192242. }
  192243. }
  192244. }
  192245. }
  192246. #endif
  192247. }
  192248. #endif
  192249. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192250. /* Replace any alpha or transparency with the supplied background color.
  192251. * "background" is already in the screen gamma, while "background_1" is
  192252. * at a gamma of 1.0. Paletted files have already been taken care of.
  192253. */
  192254. void /* PRIVATE */
  192255. png_do_background(png_row_infop row_info, png_bytep row,
  192256. png_color_16p trans_values, png_color_16p background
  192257. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192258. , png_color_16p background_1,
  192259. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192260. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192261. png_uint_16pp gamma_16_to_1, int gamma_shift
  192262. #endif
  192263. )
  192264. {
  192265. png_bytep sp, dp;
  192266. png_uint_32 i;
  192267. png_uint_32 row_width=row_info->width;
  192268. int shift;
  192269. png_debug(1, "in png_do_background\n");
  192270. if (background != NULL &&
  192271. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192272. row != NULL && row_info != NULL &&
  192273. #endif
  192274. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192275. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192276. {
  192277. switch (row_info->color_type)
  192278. {
  192279. case PNG_COLOR_TYPE_GRAY:
  192280. {
  192281. switch (row_info->bit_depth)
  192282. {
  192283. case 1:
  192284. {
  192285. sp = row;
  192286. shift = 7;
  192287. for (i = 0; i < row_width; i++)
  192288. {
  192289. if ((png_uint_16)((*sp >> shift) & 0x01)
  192290. == trans_values->gray)
  192291. {
  192292. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192293. *sp |= (png_byte)(background->gray << shift);
  192294. }
  192295. if (!shift)
  192296. {
  192297. shift = 7;
  192298. sp++;
  192299. }
  192300. else
  192301. shift--;
  192302. }
  192303. break;
  192304. }
  192305. case 2:
  192306. {
  192307. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192308. if (gamma_table != NULL)
  192309. {
  192310. sp = row;
  192311. shift = 6;
  192312. for (i = 0; i < row_width; i++)
  192313. {
  192314. if ((png_uint_16)((*sp >> shift) & 0x03)
  192315. == trans_values->gray)
  192316. {
  192317. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192318. *sp |= (png_byte)(background->gray << shift);
  192319. }
  192320. else
  192321. {
  192322. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192323. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192324. (p << 4) | (p << 6)] >> 6) & 0x03);
  192325. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192326. *sp |= (png_byte)(g << shift);
  192327. }
  192328. if (!shift)
  192329. {
  192330. shift = 6;
  192331. sp++;
  192332. }
  192333. else
  192334. shift -= 2;
  192335. }
  192336. }
  192337. else
  192338. #endif
  192339. {
  192340. sp = row;
  192341. shift = 6;
  192342. for (i = 0; i < row_width; i++)
  192343. {
  192344. if ((png_uint_16)((*sp >> shift) & 0x03)
  192345. == trans_values->gray)
  192346. {
  192347. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192348. *sp |= (png_byte)(background->gray << shift);
  192349. }
  192350. if (!shift)
  192351. {
  192352. shift = 6;
  192353. sp++;
  192354. }
  192355. else
  192356. shift -= 2;
  192357. }
  192358. }
  192359. break;
  192360. }
  192361. case 4:
  192362. {
  192363. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192364. if (gamma_table != NULL)
  192365. {
  192366. sp = row;
  192367. shift = 4;
  192368. for (i = 0; i < row_width; i++)
  192369. {
  192370. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192371. == trans_values->gray)
  192372. {
  192373. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192374. *sp |= (png_byte)(background->gray << shift);
  192375. }
  192376. else
  192377. {
  192378. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192379. png_byte g = (png_byte)((gamma_table[p |
  192380. (p << 4)] >> 4) & 0x0f);
  192381. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192382. *sp |= (png_byte)(g << shift);
  192383. }
  192384. if (!shift)
  192385. {
  192386. shift = 4;
  192387. sp++;
  192388. }
  192389. else
  192390. shift -= 4;
  192391. }
  192392. }
  192393. else
  192394. #endif
  192395. {
  192396. sp = row;
  192397. shift = 4;
  192398. for (i = 0; i < row_width; i++)
  192399. {
  192400. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192401. == trans_values->gray)
  192402. {
  192403. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192404. *sp |= (png_byte)(background->gray << shift);
  192405. }
  192406. if (!shift)
  192407. {
  192408. shift = 4;
  192409. sp++;
  192410. }
  192411. else
  192412. shift -= 4;
  192413. }
  192414. }
  192415. break;
  192416. }
  192417. case 8:
  192418. {
  192419. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192420. if (gamma_table != NULL)
  192421. {
  192422. sp = row;
  192423. for (i = 0; i < row_width; i++, sp++)
  192424. {
  192425. if (*sp == trans_values->gray)
  192426. {
  192427. *sp = (png_byte)background->gray;
  192428. }
  192429. else
  192430. {
  192431. *sp = gamma_table[*sp];
  192432. }
  192433. }
  192434. }
  192435. else
  192436. #endif
  192437. {
  192438. sp = row;
  192439. for (i = 0; i < row_width; i++, sp++)
  192440. {
  192441. if (*sp == trans_values->gray)
  192442. {
  192443. *sp = (png_byte)background->gray;
  192444. }
  192445. }
  192446. }
  192447. break;
  192448. }
  192449. case 16:
  192450. {
  192451. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192452. if (gamma_16 != NULL)
  192453. {
  192454. sp = row;
  192455. for (i = 0; i < row_width; i++, sp += 2)
  192456. {
  192457. png_uint_16 v;
  192458. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192459. if (v == trans_values->gray)
  192460. {
  192461. /* background is already in screen gamma */
  192462. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192463. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192464. }
  192465. else
  192466. {
  192467. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192468. *sp = (png_byte)((v >> 8) & 0xff);
  192469. *(sp + 1) = (png_byte)(v & 0xff);
  192470. }
  192471. }
  192472. }
  192473. else
  192474. #endif
  192475. {
  192476. sp = row;
  192477. for (i = 0; i < row_width; i++, sp += 2)
  192478. {
  192479. png_uint_16 v;
  192480. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192481. if (v == trans_values->gray)
  192482. {
  192483. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192484. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192485. }
  192486. }
  192487. }
  192488. break;
  192489. }
  192490. }
  192491. break;
  192492. }
  192493. case PNG_COLOR_TYPE_RGB:
  192494. {
  192495. if (row_info->bit_depth == 8)
  192496. {
  192497. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192498. if (gamma_table != NULL)
  192499. {
  192500. sp = row;
  192501. for (i = 0; i < row_width; i++, sp += 3)
  192502. {
  192503. if (*sp == trans_values->red &&
  192504. *(sp + 1) == trans_values->green &&
  192505. *(sp + 2) == trans_values->blue)
  192506. {
  192507. *sp = (png_byte)background->red;
  192508. *(sp + 1) = (png_byte)background->green;
  192509. *(sp + 2) = (png_byte)background->blue;
  192510. }
  192511. else
  192512. {
  192513. *sp = gamma_table[*sp];
  192514. *(sp + 1) = gamma_table[*(sp + 1)];
  192515. *(sp + 2) = gamma_table[*(sp + 2)];
  192516. }
  192517. }
  192518. }
  192519. else
  192520. #endif
  192521. {
  192522. sp = row;
  192523. for (i = 0; i < row_width; i++, sp += 3)
  192524. {
  192525. if (*sp == trans_values->red &&
  192526. *(sp + 1) == trans_values->green &&
  192527. *(sp + 2) == trans_values->blue)
  192528. {
  192529. *sp = (png_byte)background->red;
  192530. *(sp + 1) = (png_byte)background->green;
  192531. *(sp + 2) = (png_byte)background->blue;
  192532. }
  192533. }
  192534. }
  192535. }
  192536. else /* if (row_info->bit_depth == 16) */
  192537. {
  192538. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192539. if (gamma_16 != NULL)
  192540. {
  192541. sp = row;
  192542. for (i = 0; i < row_width; i++, sp += 6)
  192543. {
  192544. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192545. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192546. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192547. if (r == trans_values->red && g == trans_values->green &&
  192548. b == trans_values->blue)
  192549. {
  192550. /* background is already in screen gamma */
  192551. *sp = (png_byte)((background->red >> 8) & 0xff);
  192552. *(sp + 1) = (png_byte)(background->red & 0xff);
  192553. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192554. *(sp + 3) = (png_byte)(background->green & 0xff);
  192555. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192556. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192557. }
  192558. else
  192559. {
  192560. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192561. *sp = (png_byte)((v >> 8) & 0xff);
  192562. *(sp + 1) = (png_byte)(v & 0xff);
  192563. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192564. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192565. *(sp + 3) = (png_byte)(v & 0xff);
  192566. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192567. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192568. *(sp + 5) = (png_byte)(v & 0xff);
  192569. }
  192570. }
  192571. }
  192572. else
  192573. #endif
  192574. {
  192575. sp = row;
  192576. for (i = 0; i < row_width; i++, sp += 6)
  192577. {
  192578. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192579. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192580. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192581. if (r == trans_values->red && g == trans_values->green &&
  192582. b == trans_values->blue)
  192583. {
  192584. *sp = (png_byte)((background->red >> 8) & 0xff);
  192585. *(sp + 1) = (png_byte)(background->red & 0xff);
  192586. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192587. *(sp + 3) = (png_byte)(background->green & 0xff);
  192588. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192589. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192590. }
  192591. }
  192592. }
  192593. }
  192594. break;
  192595. }
  192596. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192597. {
  192598. if (row_info->bit_depth == 8)
  192599. {
  192600. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192601. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192602. gamma_table != NULL)
  192603. {
  192604. sp = row;
  192605. dp = row;
  192606. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192607. {
  192608. png_uint_16 a = *(sp + 1);
  192609. if (a == 0xff)
  192610. {
  192611. *dp = gamma_table[*sp];
  192612. }
  192613. else if (a == 0)
  192614. {
  192615. /* background is already in screen gamma */
  192616. *dp = (png_byte)background->gray;
  192617. }
  192618. else
  192619. {
  192620. png_byte v, w;
  192621. v = gamma_to_1[*sp];
  192622. png_composite(w, v, a, background_1->gray);
  192623. *dp = gamma_from_1[w];
  192624. }
  192625. }
  192626. }
  192627. else
  192628. #endif
  192629. {
  192630. sp = row;
  192631. dp = row;
  192632. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192633. {
  192634. png_byte a = *(sp + 1);
  192635. if (a == 0xff)
  192636. {
  192637. *dp = *sp;
  192638. }
  192639. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192640. else if (a == 0)
  192641. {
  192642. *dp = (png_byte)background->gray;
  192643. }
  192644. else
  192645. {
  192646. png_composite(*dp, *sp, a, background_1->gray);
  192647. }
  192648. #else
  192649. *dp = (png_byte)background->gray;
  192650. #endif
  192651. }
  192652. }
  192653. }
  192654. else /* if (png_ptr->bit_depth == 16) */
  192655. {
  192656. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192657. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192658. gamma_16_to_1 != NULL)
  192659. {
  192660. sp = row;
  192661. dp = row;
  192662. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192663. {
  192664. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192665. if (a == (png_uint_16)0xffff)
  192666. {
  192667. png_uint_16 v;
  192668. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192669. *dp = (png_byte)((v >> 8) & 0xff);
  192670. *(dp + 1) = (png_byte)(v & 0xff);
  192671. }
  192672. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192673. else if (a == 0)
  192674. #else
  192675. else
  192676. #endif
  192677. {
  192678. /* background is already in screen gamma */
  192679. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192680. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192681. }
  192682. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192683. else
  192684. {
  192685. png_uint_16 g, v, w;
  192686. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192687. png_composite_16(v, g, a, background_1->gray);
  192688. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192689. *dp = (png_byte)((w >> 8) & 0xff);
  192690. *(dp + 1) = (png_byte)(w & 0xff);
  192691. }
  192692. #endif
  192693. }
  192694. }
  192695. else
  192696. #endif
  192697. {
  192698. sp = row;
  192699. dp = row;
  192700. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192701. {
  192702. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192703. if (a == (png_uint_16)0xffff)
  192704. {
  192705. png_memcpy(dp, sp, 2);
  192706. }
  192707. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192708. else if (a == 0)
  192709. #else
  192710. else
  192711. #endif
  192712. {
  192713. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192714. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192715. }
  192716. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192717. else
  192718. {
  192719. png_uint_16 g, v;
  192720. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192721. png_composite_16(v, g, a, background_1->gray);
  192722. *dp = (png_byte)((v >> 8) & 0xff);
  192723. *(dp + 1) = (png_byte)(v & 0xff);
  192724. }
  192725. #endif
  192726. }
  192727. }
  192728. }
  192729. break;
  192730. }
  192731. case PNG_COLOR_TYPE_RGB_ALPHA:
  192732. {
  192733. if (row_info->bit_depth == 8)
  192734. {
  192735. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192736. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192737. gamma_table != NULL)
  192738. {
  192739. sp = row;
  192740. dp = row;
  192741. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192742. {
  192743. png_byte a = *(sp + 3);
  192744. if (a == 0xff)
  192745. {
  192746. *dp = gamma_table[*sp];
  192747. *(dp + 1) = gamma_table[*(sp + 1)];
  192748. *(dp + 2) = gamma_table[*(sp + 2)];
  192749. }
  192750. else if (a == 0)
  192751. {
  192752. /* background is already in screen gamma */
  192753. *dp = (png_byte)background->red;
  192754. *(dp + 1) = (png_byte)background->green;
  192755. *(dp + 2) = (png_byte)background->blue;
  192756. }
  192757. else
  192758. {
  192759. png_byte v, w;
  192760. v = gamma_to_1[*sp];
  192761. png_composite(w, v, a, background_1->red);
  192762. *dp = gamma_from_1[w];
  192763. v = gamma_to_1[*(sp + 1)];
  192764. png_composite(w, v, a, background_1->green);
  192765. *(dp + 1) = gamma_from_1[w];
  192766. v = gamma_to_1[*(sp + 2)];
  192767. png_composite(w, v, a, background_1->blue);
  192768. *(dp + 2) = gamma_from_1[w];
  192769. }
  192770. }
  192771. }
  192772. else
  192773. #endif
  192774. {
  192775. sp = row;
  192776. dp = row;
  192777. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192778. {
  192779. png_byte a = *(sp + 3);
  192780. if (a == 0xff)
  192781. {
  192782. *dp = *sp;
  192783. *(dp + 1) = *(sp + 1);
  192784. *(dp + 2) = *(sp + 2);
  192785. }
  192786. else if (a == 0)
  192787. {
  192788. *dp = (png_byte)background->red;
  192789. *(dp + 1) = (png_byte)background->green;
  192790. *(dp + 2) = (png_byte)background->blue;
  192791. }
  192792. else
  192793. {
  192794. png_composite(*dp, *sp, a, background->red);
  192795. png_composite(*(dp + 1), *(sp + 1), a,
  192796. background->green);
  192797. png_composite(*(dp + 2), *(sp + 2), a,
  192798. background->blue);
  192799. }
  192800. }
  192801. }
  192802. }
  192803. else /* if (row_info->bit_depth == 16) */
  192804. {
  192805. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192806. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192807. gamma_16_to_1 != NULL)
  192808. {
  192809. sp = row;
  192810. dp = row;
  192811. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192812. {
  192813. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192814. << 8) + (png_uint_16)(*(sp + 7)));
  192815. if (a == (png_uint_16)0xffff)
  192816. {
  192817. png_uint_16 v;
  192818. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192819. *dp = (png_byte)((v >> 8) & 0xff);
  192820. *(dp + 1) = (png_byte)(v & 0xff);
  192821. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192822. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192823. *(dp + 3) = (png_byte)(v & 0xff);
  192824. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192825. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192826. *(dp + 5) = (png_byte)(v & 0xff);
  192827. }
  192828. else if (a == 0)
  192829. {
  192830. /* background is already in screen gamma */
  192831. *dp = (png_byte)((background->red >> 8) & 0xff);
  192832. *(dp + 1) = (png_byte)(background->red & 0xff);
  192833. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192834. *(dp + 3) = (png_byte)(background->green & 0xff);
  192835. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192836. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192837. }
  192838. else
  192839. {
  192840. png_uint_16 v, w, x;
  192841. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192842. png_composite_16(w, v, a, background_1->red);
  192843. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192844. *dp = (png_byte)((x >> 8) & 0xff);
  192845. *(dp + 1) = (png_byte)(x & 0xff);
  192846. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192847. png_composite_16(w, v, a, background_1->green);
  192848. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192849. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192850. *(dp + 3) = (png_byte)(x & 0xff);
  192851. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192852. png_composite_16(w, v, a, background_1->blue);
  192853. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192854. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192855. *(dp + 5) = (png_byte)(x & 0xff);
  192856. }
  192857. }
  192858. }
  192859. else
  192860. #endif
  192861. {
  192862. sp = row;
  192863. dp = row;
  192864. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192865. {
  192866. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192867. << 8) + (png_uint_16)(*(sp + 7)));
  192868. if (a == (png_uint_16)0xffff)
  192869. {
  192870. png_memcpy(dp, sp, 6);
  192871. }
  192872. else if (a == 0)
  192873. {
  192874. *dp = (png_byte)((background->red >> 8) & 0xff);
  192875. *(dp + 1) = (png_byte)(background->red & 0xff);
  192876. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192877. *(dp + 3) = (png_byte)(background->green & 0xff);
  192878. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192879. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192880. }
  192881. else
  192882. {
  192883. png_uint_16 v;
  192884. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192885. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192886. + *(sp + 3));
  192887. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192888. + *(sp + 5));
  192889. png_composite_16(v, r, a, background->red);
  192890. *dp = (png_byte)((v >> 8) & 0xff);
  192891. *(dp + 1) = (png_byte)(v & 0xff);
  192892. png_composite_16(v, g, a, background->green);
  192893. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192894. *(dp + 3) = (png_byte)(v & 0xff);
  192895. png_composite_16(v, b, a, background->blue);
  192896. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192897. *(dp + 5) = (png_byte)(v & 0xff);
  192898. }
  192899. }
  192900. }
  192901. }
  192902. break;
  192903. }
  192904. }
  192905. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192906. {
  192907. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192908. row_info->channels--;
  192909. row_info->pixel_depth = (png_byte)(row_info->channels *
  192910. row_info->bit_depth);
  192911. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192912. }
  192913. }
  192914. }
  192915. #endif
  192916. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192917. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192918. * you do this after you deal with the transparency issue on grayscale
  192919. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192920. * is 16, use gamma_16_table and gamma_shift. Build these with
  192921. * build_gamma_table().
  192922. */
  192923. void /* PRIVATE */
  192924. png_do_gamma(png_row_infop row_info, png_bytep row,
  192925. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192926. int gamma_shift)
  192927. {
  192928. png_bytep sp;
  192929. png_uint_32 i;
  192930. png_uint_32 row_width=row_info->width;
  192931. png_debug(1, "in png_do_gamma\n");
  192932. if (
  192933. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192934. row != NULL && row_info != NULL &&
  192935. #endif
  192936. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192937. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192938. {
  192939. switch (row_info->color_type)
  192940. {
  192941. case PNG_COLOR_TYPE_RGB:
  192942. {
  192943. if (row_info->bit_depth == 8)
  192944. {
  192945. sp = row;
  192946. for (i = 0; i < row_width; i++)
  192947. {
  192948. *sp = gamma_table[*sp];
  192949. sp++;
  192950. *sp = gamma_table[*sp];
  192951. sp++;
  192952. *sp = gamma_table[*sp];
  192953. sp++;
  192954. }
  192955. }
  192956. else /* if (row_info->bit_depth == 16) */
  192957. {
  192958. sp = row;
  192959. for (i = 0; i < row_width; i++)
  192960. {
  192961. png_uint_16 v;
  192962. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192963. *sp = (png_byte)((v >> 8) & 0xff);
  192964. *(sp + 1) = (png_byte)(v & 0xff);
  192965. sp += 2;
  192966. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192967. *sp = (png_byte)((v >> 8) & 0xff);
  192968. *(sp + 1) = (png_byte)(v & 0xff);
  192969. sp += 2;
  192970. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192971. *sp = (png_byte)((v >> 8) & 0xff);
  192972. *(sp + 1) = (png_byte)(v & 0xff);
  192973. sp += 2;
  192974. }
  192975. }
  192976. break;
  192977. }
  192978. case PNG_COLOR_TYPE_RGB_ALPHA:
  192979. {
  192980. if (row_info->bit_depth == 8)
  192981. {
  192982. sp = row;
  192983. for (i = 0; i < row_width; i++)
  192984. {
  192985. *sp = gamma_table[*sp];
  192986. sp++;
  192987. *sp = gamma_table[*sp];
  192988. sp++;
  192989. *sp = gamma_table[*sp];
  192990. sp++;
  192991. sp++;
  192992. }
  192993. }
  192994. else /* if (row_info->bit_depth == 16) */
  192995. {
  192996. sp = row;
  192997. for (i = 0; i < row_width; i++)
  192998. {
  192999. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193000. *sp = (png_byte)((v >> 8) & 0xff);
  193001. *(sp + 1) = (png_byte)(v & 0xff);
  193002. sp += 2;
  193003. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193004. *sp = (png_byte)((v >> 8) & 0xff);
  193005. *(sp + 1) = (png_byte)(v & 0xff);
  193006. sp += 2;
  193007. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193008. *sp = (png_byte)((v >> 8) & 0xff);
  193009. *(sp + 1) = (png_byte)(v & 0xff);
  193010. sp += 4;
  193011. }
  193012. }
  193013. break;
  193014. }
  193015. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193016. {
  193017. if (row_info->bit_depth == 8)
  193018. {
  193019. sp = row;
  193020. for (i = 0; i < row_width; i++)
  193021. {
  193022. *sp = gamma_table[*sp];
  193023. sp += 2;
  193024. }
  193025. }
  193026. else /* if (row_info->bit_depth == 16) */
  193027. {
  193028. sp = row;
  193029. for (i = 0; i < row_width; i++)
  193030. {
  193031. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193032. *sp = (png_byte)((v >> 8) & 0xff);
  193033. *(sp + 1) = (png_byte)(v & 0xff);
  193034. sp += 4;
  193035. }
  193036. }
  193037. break;
  193038. }
  193039. case PNG_COLOR_TYPE_GRAY:
  193040. {
  193041. if (row_info->bit_depth == 2)
  193042. {
  193043. sp = row;
  193044. for (i = 0; i < row_width; i += 4)
  193045. {
  193046. int a = *sp & 0xc0;
  193047. int b = *sp & 0x30;
  193048. int c = *sp & 0x0c;
  193049. int d = *sp & 0x03;
  193050. *sp = (png_byte)(
  193051. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193052. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193053. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193054. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193055. sp++;
  193056. }
  193057. }
  193058. if (row_info->bit_depth == 4)
  193059. {
  193060. sp = row;
  193061. for (i = 0; i < row_width; i += 2)
  193062. {
  193063. int msb = *sp & 0xf0;
  193064. int lsb = *sp & 0x0f;
  193065. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193066. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193067. sp++;
  193068. }
  193069. }
  193070. else if (row_info->bit_depth == 8)
  193071. {
  193072. sp = row;
  193073. for (i = 0; i < row_width; i++)
  193074. {
  193075. *sp = gamma_table[*sp];
  193076. sp++;
  193077. }
  193078. }
  193079. else if (row_info->bit_depth == 16)
  193080. {
  193081. sp = row;
  193082. for (i = 0; i < row_width; i++)
  193083. {
  193084. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193085. *sp = (png_byte)((v >> 8) & 0xff);
  193086. *(sp + 1) = (png_byte)(v & 0xff);
  193087. sp += 2;
  193088. }
  193089. }
  193090. break;
  193091. }
  193092. }
  193093. }
  193094. }
  193095. #endif
  193096. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193097. /* Expands a palette row to an RGB or RGBA row depending
  193098. * upon whether you supply trans and num_trans.
  193099. */
  193100. void /* PRIVATE */
  193101. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193102. png_colorp palette, png_bytep trans, int num_trans)
  193103. {
  193104. int shift, value;
  193105. png_bytep sp, dp;
  193106. png_uint_32 i;
  193107. png_uint_32 row_width=row_info->width;
  193108. png_debug(1, "in png_do_expand_palette\n");
  193109. if (
  193110. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193111. row != NULL && row_info != NULL &&
  193112. #endif
  193113. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193114. {
  193115. if (row_info->bit_depth < 8)
  193116. {
  193117. switch (row_info->bit_depth)
  193118. {
  193119. case 1:
  193120. {
  193121. sp = row + (png_size_t)((row_width - 1) >> 3);
  193122. dp = row + (png_size_t)row_width - 1;
  193123. shift = 7 - (int)((row_width + 7) & 0x07);
  193124. for (i = 0; i < row_width; i++)
  193125. {
  193126. if ((*sp >> shift) & 0x01)
  193127. *dp = 1;
  193128. else
  193129. *dp = 0;
  193130. if (shift == 7)
  193131. {
  193132. shift = 0;
  193133. sp--;
  193134. }
  193135. else
  193136. shift++;
  193137. dp--;
  193138. }
  193139. break;
  193140. }
  193141. case 2:
  193142. {
  193143. sp = row + (png_size_t)((row_width - 1) >> 2);
  193144. dp = row + (png_size_t)row_width - 1;
  193145. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193146. for (i = 0; i < row_width; i++)
  193147. {
  193148. value = (*sp >> shift) & 0x03;
  193149. *dp = (png_byte)value;
  193150. if (shift == 6)
  193151. {
  193152. shift = 0;
  193153. sp--;
  193154. }
  193155. else
  193156. shift += 2;
  193157. dp--;
  193158. }
  193159. break;
  193160. }
  193161. case 4:
  193162. {
  193163. sp = row + (png_size_t)((row_width - 1) >> 1);
  193164. dp = row + (png_size_t)row_width - 1;
  193165. shift = (int)((row_width & 0x01) << 2);
  193166. for (i = 0; i < row_width; i++)
  193167. {
  193168. value = (*sp >> shift) & 0x0f;
  193169. *dp = (png_byte)value;
  193170. if (shift == 4)
  193171. {
  193172. shift = 0;
  193173. sp--;
  193174. }
  193175. else
  193176. shift += 4;
  193177. dp--;
  193178. }
  193179. break;
  193180. }
  193181. }
  193182. row_info->bit_depth = 8;
  193183. row_info->pixel_depth = 8;
  193184. row_info->rowbytes = row_width;
  193185. }
  193186. switch (row_info->bit_depth)
  193187. {
  193188. case 8:
  193189. {
  193190. if (trans != NULL)
  193191. {
  193192. sp = row + (png_size_t)row_width - 1;
  193193. dp = row + (png_size_t)(row_width << 2) - 1;
  193194. for (i = 0; i < row_width; i++)
  193195. {
  193196. if ((int)(*sp) >= num_trans)
  193197. *dp-- = 0xff;
  193198. else
  193199. *dp-- = trans[*sp];
  193200. *dp-- = palette[*sp].blue;
  193201. *dp-- = palette[*sp].green;
  193202. *dp-- = palette[*sp].red;
  193203. sp--;
  193204. }
  193205. row_info->bit_depth = 8;
  193206. row_info->pixel_depth = 32;
  193207. row_info->rowbytes = row_width * 4;
  193208. row_info->color_type = 6;
  193209. row_info->channels = 4;
  193210. }
  193211. else
  193212. {
  193213. sp = row + (png_size_t)row_width - 1;
  193214. dp = row + (png_size_t)(row_width * 3) - 1;
  193215. for (i = 0; i < row_width; i++)
  193216. {
  193217. *dp-- = palette[*sp].blue;
  193218. *dp-- = palette[*sp].green;
  193219. *dp-- = palette[*sp].red;
  193220. sp--;
  193221. }
  193222. row_info->bit_depth = 8;
  193223. row_info->pixel_depth = 24;
  193224. row_info->rowbytes = row_width * 3;
  193225. row_info->color_type = 2;
  193226. row_info->channels = 3;
  193227. }
  193228. break;
  193229. }
  193230. }
  193231. }
  193232. }
  193233. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193234. * expanded transparency value is supplied, an alpha channel is built.
  193235. */
  193236. void /* PRIVATE */
  193237. png_do_expand(png_row_infop row_info, png_bytep row,
  193238. png_color_16p trans_value)
  193239. {
  193240. int shift, value;
  193241. png_bytep sp, dp;
  193242. png_uint_32 i;
  193243. png_uint_32 row_width=row_info->width;
  193244. png_debug(1, "in png_do_expand\n");
  193245. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193246. if (row != NULL && row_info != NULL)
  193247. #endif
  193248. {
  193249. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193250. {
  193251. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193252. if (row_info->bit_depth < 8)
  193253. {
  193254. switch (row_info->bit_depth)
  193255. {
  193256. case 1:
  193257. {
  193258. gray = (png_uint_16)((gray&0x01)*0xff);
  193259. sp = row + (png_size_t)((row_width - 1) >> 3);
  193260. dp = row + (png_size_t)row_width - 1;
  193261. shift = 7 - (int)((row_width + 7) & 0x07);
  193262. for (i = 0; i < row_width; i++)
  193263. {
  193264. if ((*sp >> shift) & 0x01)
  193265. *dp = 0xff;
  193266. else
  193267. *dp = 0;
  193268. if (shift == 7)
  193269. {
  193270. shift = 0;
  193271. sp--;
  193272. }
  193273. else
  193274. shift++;
  193275. dp--;
  193276. }
  193277. break;
  193278. }
  193279. case 2:
  193280. {
  193281. gray = (png_uint_16)((gray&0x03)*0x55);
  193282. sp = row + (png_size_t)((row_width - 1) >> 2);
  193283. dp = row + (png_size_t)row_width - 1;
  193284. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193285. for (i = 0; i < row_width; i++)
  193286. {
  193287. value = (*sp >> shift) & 0x03;
  193288. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193289. (value << 6));
  193290. if (shift == 6)
  193291. {
  193292. shift = 0;
  193293. sp--;
  193294. }
  193295. else
  193296. shift += 2;
  193297. dp--;
  193298. }
  193299. break;
  193300. }
  193301. case 4:
  193302. {
  193303. gray = (png_uint_16)((gray&0x0f)*0x11);
  193304. sp = row + (png_size_t)((row_width - 1) >> 1);
  193305. dp = row + (png_size_t)row_width - 1;
  193306. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193307. for (i = 0; i < row_width; i++)
  193308. {
  193309. value = (*sp >> shift) & 0x0f;
  193310. *dp = (png_byte)(value | (value << 4));
  193311. if (shift == 4)
  193312. {
  193313. shift = 0;
  193314. sp--;
  193315. }
  193316. else
  193317. shift = 4;
  193318. dp--;
  193319. }
  193320. break;
  193321. }
  193322. }
  193323. row_info->bit_depth = 8;
  193324. row_info->pixel_depth = 8;
  193325. row_info->rowbytes = row_width;
  193326. }
  193327. if (trans_value != NULL)
  193328. {
  193329. if (row_info->bit_depth == 8)
  193330. {
  193331. gray = gray & 0xff;
  193332. sp = row + (png_size_t)row_width - 1;
  193333. dp = row + (png_size_t)(row_width << 1) - 1;
  193334. for (i = 0; i < row_width; i++)
  193335. {
  193336. if (*sp == gray)
  193337. *dp-- = 0;
  193338. else
  193339. *dp-- = 0xff;
  193340. *dp-- = *sp--;
  193341. }
  193342. }
  193343. else if (row_info->bit_depth == 16)
  193344. {
  193345. png_byte gray_high = (gray >> 8) & 0xff;
  193346. png_byte gray_low = gray & 0xff;
  193347. sp = row + row_info->rowbytes - 1;
  193348. dp = row + (row_info->rowbytes << 1) - 1;
  193349. for (i = 0; i < row_width; i++)
  193350. {
  193351. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193352. {
  193353. *dp-- = 0;
  193354. *dp-- = 0;
  193355. }
  193356. else
  193357. {
  193358. *dp-- = 0xff;
  193359. *dp-- = 0xff;
  193360. }
  193361. *dp-- = *sp--;
  193362. *dp-- = *sp--;
  193363. }
  193364. }
  193365. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193366. row_info->channels = 2;
  193367. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193368. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193369. row_width);
  193370. }
  193371. }
  193372. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193373. {
  193374. if (row_info->bit_depth == 8)
  193375. {
  193376. png_byte red = trans_value->red & 0xff;
  193377. png_byte green = trans_value->green & 0xff;
  193378. png_byte blue = trans_value->blue & 0xff;
  193379. sp = row + (png_size_t)row_info->rowbytes - 1;
  193380. dp = row + (png_size_t)(row_width << 2) - 1;
  193381. for (i = 0; i < row_width; i++)
  193382. {
  193383. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193384. *dp-- = 0;
  193385. else
  193386. *dp-- = 0xff;
  193387. *dp-- = *sp--;
  193388. *dp-- = *sp--;
  193389. *dp-- = *sp--;
  193390. }
  193391. }
  193392. else if (row_info->bit_depth == 16)
  193393. {
  193394. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193395. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193396. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193397. png_byte red_low = trans_value->red & 0xff;
  193398. png_byte green_low = trans_value->green & 0xff;
  193399. png_byte blue_low = trans_value->blue & 0xff;
  193400. sp = row + row_info->rowbytes - 1;
  193401. dp = row + (png_size_t)(row_width << 3) - 1;
  193402. for (i = 0; i < row_width; i++)
  193403. {
  193404. if (*(sp - 5) == red_high &&
  193405. *(sp - 4) == red_low &&
  193406. *(sp - 3) == green_high &&
  193407. *(sp - 2) == green_low &&
  193408. *(sp - 1) == blue_high &&
  193409. *(sp ) == blue_low)
  193410. {
  193411. *dp-- = 0;
  193412. *dp-- = 0;
  193413. }
  193414. else
  193415. {
  193416. *dp-- = 0xff;
  193417. *dp-- = 0xff;
  193418. }
  193419. *dp-- = *sp--;
  193420. *dp-- = *sp--;
  193421. *dp-- = *sp--;
  193422. *dp-- = *sp--;
  193423. *dp-- = *sp--;
  193424. *dp-- = *sp--;
  193425. }
  193426. }
  193427. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193428. row_info->channels = 4;
  193429. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193430. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193431. }
  193432. }
  193433. }
  193434. #endif
  193435. #if defined(PNG_READ_DITHER_SUPPORTED)
  193436. void /* PRIVATE */
  193437. png_do_dither(png_row_infop row_info, png_bytep row,
  193438. png_bytep palette_lookup, png_bytep dither_lookup)
  193439. {
  193440. png_bytep sp, dp;
  193441. png_uint_32 i;
  193442. png_uint_32 row_width=row_info->width;
  193443. png_debug(1, "in png_do_dither\n");
  193444. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193445. if (row != NULL && row_info != NULL)
  193446. #endif
  193447. {
  193448. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193449. palette_lookup && row_info->bit_depth == 8)
  193450. {
  193451. int r, g, b, p;
  193452. sp = row;
  193453. dp = row;
  193454. for (i = 0; i < row_width; i++)
  193455. {
  193456. r = *sp++;
  193457. g = *sp++;
  193458. b = *sp++;
  193459. /* this looks real messy, but the compiler will reduce
  193460. it down to a reasonable formula. For example, with
  193461. 5 bits per color, we get:
  193462. p = (((r >> 3) & 0x1f) << 10) |
  193463. (((g >> 3) & 0x1f) << 5) |
  193464. ((b >> 3) & 0x1f);
  193465. */
  193466. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193467. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193468. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193469. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193470. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193471. (PNG_DITHER_BLUE_BITS)) |
  193472. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193473. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193474. *dp++ = palette_lookup[p];
  193475. }
  193476. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193477. row_info->channels = 1;
  193478. row_info->pixel_depth = row_info->bit_depth;
  193479. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193480. }
  193481. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193482. palette_lookup != NULL && row_info->bit_depth == 8)
  193483. {
  193484. int r, g, b, p;
  193485. sp = row;
  193486. dp = row;
  193487. for (i = 0; i < row_width; i++)
  193488. {
  193489. r = *sp++;
  193490. g = *sp++;
  193491. b = *sp++;
  193492. sp++;
  193493. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193494. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193495. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193496. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193497. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193498. (PNG_DITHER_BLUE_BITS)) |
  193499. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193500. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193501. *dp++ = palette_lookup[p];
  193502. }
  193503. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193504. row_info->channels = 1;
  193505. row_info->pixel_depth = row_info->bit_depth;
  193506. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193507. }
  193508. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193509. dither_lookup && row_info->bit_depth == 8)
  193510. {
  193511. sp = row;
  193512. for (i = 0; i < row_width; i++, sp++)
  193513. {
  193514. *sp = dither_lookup[*sp];
  193515. }
  193516. }
  193517. }
  193518. }
  193519. #endif
  193520. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193521. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193522. static PNG_CONST int png_gamma_shift[] =
  193523. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193524. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193525. * tables, we don't make a full table if we are reducing to 8-bit in
  193526. * the future. Note also how the gamma_16 tables are segmented so that
  193527. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193528. */
  193529. void /* PRIVATE */
  193530. png_build_gamma_table(png_structp png_ptr)
  193531. {
  193532. png_debug(1, "in png_build_gamma_table\n");
  193533. if (png_ptr->bit_depth <= 8)
  193534. {
  193535. int i;
  193536. double g;
  193537. if (png_ptr->screen_gamma > .000001)
  193538. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193539. else
  193540. g = 1.0;
  193541. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193542. (png_uint_32)256);
  193543. for (i = 0; i < 256; i++)
  193544. {
  193545. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193546. g) * 255.0 + .5);
  193547. }
  193548. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193549. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193550. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193551. {
  193552. g = 1.0 / (png_ptr->gamma);
  193553. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193554. (png_uint_32)256);
  193555. for (i = 0; i < 256; i++)
  193556. {
  193557. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193558. g) * 255.0 + .5);
  193559. }
  193560. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193561. (png_uint_32)256);
  193562. if(png_ptr->screen_gamma > 0.000001)
  193563. g = 1.0 / png_ptr->screen_gamma;
  193564. else
  193565. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193566. for (i = 0; i < 256; i++)
  193567. {
  193568. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193569. g) * 255.0 + .5);
  193570. }
  193571. }
  193572. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193573. }
  193574. else
  193575. {
  193576. double g;
  193577. int i, j, shift, num;
  193578. int sig_bit;
  193579. png_uint_32 ig;
  193580. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193581. {
  193582. sig_bit = (int)png_ptr->sig_bit.red;
  193583. if ((int)png_ptr->sig_bit.green > sig_bit)
  193584. sig_bit = png_ptr->sig_bit.green;
  193585. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193586. sig_bit = png_ptr->sig_bit.blue;
  193587. }
  193588. else
  193589. {
  193590. sig_bit = (int)png_ptr->sig_bit.gray;
  193591. }
  193592. if (sig_bit > 0)
  193593. shift = 16 - sig_bit;
  193594. else
  193595. shift = 0;
  193596. if (png_ptr->transformations & PNG_16_TO_8)
  193597. {
  193598. if (shift < (16 - PNG_MAX_GAMMA_8))
  193599. shift = (16 - PNG_MAX_GAMMA_8);
  193600. }
  193601. if (shift > 8)
  193602. shift = 8;
  193603. if (shift < 0)
  193604. shift = 0;
  193605. png_ptr->gamma_shift = (png_byte)shift;
  193606. num = (1 << (8 - shift));
  193607. if (png_ptr->screen_gamma > .000001)
  193608. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193609. else
  193610. g = 1.0;
  193611. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193612. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193613. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193614. {
  193615. double fin, fout;
  193616. png_uint_32 last, max;
  193617. for (i = 0; i < num; i++)
  193618. {
  193619. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193620. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193621. }
  193622. g = 1.0 / g;
  193623. last = 0;
  193624. for (i = 0; i < 256; i++)
  193625. {
  193626. fout = ((double)i + 0.5) / 256.0;
  193627. fin = pow(fout, g);
  193628. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193629. while (last <= max)
  193630. {
  193631. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193632. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193633. (png_uint_16)i | ((png_uint_16)i << 8));
  193634. last++;
  193635. }
  193636. }
  193637. while (last < ((png_uint_32)num << 8))
  193638. {
  193639. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193640. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193641. last++;
  193642. }
  193643. }
  193644. else
  193645. {
  193646. for (i = 0; i < num; i++)
  193647. {
  193648. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193649. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193650. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193651. for (j = 0; j < 256; j++)
  193652. {
  193653. png_ptr->gamma_16_table[i][j] =
  193654. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193655. 65535.0, g) * 65535.0 + .5);
  193656. }
  193657. }
  193658. }
  193659. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193660. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193661. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193662. {
  193663. g = 1.0 / (png_ptr->gamma);
  193664. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193665. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193666. for (i = 0; i < num; i++)
  193667. {
  193668. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193669. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193670. ig = (((png_uint_32)i *
  193671. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193672. for (j = 0; j < 256; j++)
  193673. {
  193674. png_ptr->gamma_16_to_1[i][j] =
  193675. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193676. 65535.0, g) * 65535.0 + .5);
  193677. }
  193678. }
  193679. if(png_ptr->screen_gamma > 0.000001)
  193680. g = 1.0 / png_ptr->screen_gamma;
  193681. else
  193682. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193683. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193684. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193685. for (i = 0; i < num; i++)
  193686. {
  193687. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193688. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193689. ig = (((png_uint_32)i *
  193690. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193691. for (j = 0; j < 256; j++)
  193692. {
  193693. png_ptr->gamma_16_from_1[i][j] =
  193694. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193695. 65535.0, g) * 65535.0 + .5);
  193696. }
  193697. }
  193698. }
  193699. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193700. }
  193701. }
  193702. #endif
  193703. /* To do: install integer version of png_build_gamma_table here */
  193704. #endif
  193705. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193706. /* undoes intrapixel differencing */
  193707. void /* PRIVATE */
  193708. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193709. {
  193710. png_debug(1, "in png_do_read_intrapixel\n");
  193711. if (
  193712. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193713. row != NULL && row_info != NULL &&
  193714. #endif
  193715. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193716. {
  193717. int bytes_per_pixel;
  193718. png_uint_32 row_width = row_info->width;
  193719. if (row_info->bit_depth == 8)
  193720. {
  193721. png_bytep rp;
  193722. png_uint_32 i;
  193723. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193724. bytes_per_pixel = 3;
  193725. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193726. bytes_per_pixel = 4;
  193727. else
  193728. return;
  193729. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193730. {
  193731. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193732. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193733. }
  193734. }
  193735. else if (row_info->bit_depth == 16)
  193736. {
  193737. png_bytep rp;
  193738. png_uint_32 i;
  193739. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193740. bytes_per_pixel = 6;
  193741. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193742. bytes_per_pixel = 8;
  193743. else
  193744. return;
  193745. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193746. {
  193747. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193748. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193749. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193750. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193751. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193752. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193753. *(rp+1) = (png_byte)(red & 0xff);
  193754. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193755. *(rp+5) = (png_byte)(blue & 0xff);
  193756. }
  193757. }
  193758. }
  193759. }
  193760. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193761. #endif /* PNG_READ_SUPPORTED */
  193762. /*** End of inlined file: pngrtran.c ***/
  193763. /*** Start of inlined file: pngrutil.c ***/
  193764. /* pngrutil.c - utilities to read a PNG file
  193765. *
  193766. * Last changed in libpng 1.2.21 [October 4, 2007]
  193767. * For conditions of distribution and use, see copyright notice in png.h
  193768. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193769. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193770. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193771. *
  193772. * This file contains routines that are only called from within
  193773. * libpng itself during the course of reading an image.
  193774. */
  193775. #define PNG_INTERNAL
  193776. #if defined(PNG_READ_SUPPORTED)
  193777. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193778. # define WIN32_WCE_OLD
  193779. #endif
  193780. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193781. # if defined(WIN32_WCE_OLD)
  193782. /* strtod() function is not supported on WindowsCE */
  193783. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193784. {
  193785. double result = 0;
  193786. int len;
  193787. wchar_t *str, *end;
  193788. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193789. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193790. if ( NULL != str )
  193791. {
  193792. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193793. result = wcstod(str, &end);
  193794. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193795. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193796. png_free(png_ptr, str);
  193797. }
  193798. return result;
  193799. }
  193800. # else
  193801. # define png_strtod(p,a,b) strtod(a,b)
  193802. # endif
  193803. #endif
  193804. png_uint_32 PNGAPI
  193805. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193806. {
  193807. png_uint_32 i = png_get_uint_32(buf);
  193808. if (i > PNG_UINT_31_MAX)
  193809. png_error(png_ptr, "PNG unsigned integer out of range.");
  193810. return (i);
  193811. }
  193812. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193813. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193814. png_uint_32 PNGAPI
  193815. png_get_uint_32(png_bytep buf)
  193816. {
  193817. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193818. ((png_uint_32)(*(buf + 1)) << 16) +
  193819. ((png_uint_32)(*(buf + 2)) << 8) +
  193820. (png_uint_32)(*(buf + 3));
  193821. return (i);
  193822. }
  193823. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193824. * data is stored in the PNG file in two's complement format, and it is
  193825. * assumed that the machine format for signed integers is the same. */
  193826. png_int_32 PNGAPI
  193827. png_get_int_32(png_bytep buf)
  193828. {
  193829. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193830. ((png_int_32)(*(buf + 1)) << 16) +
  193831. ((png_int_32)(*(buf + 2)) << 8) +
  193832. (png_int_32)(*(buf + 3));
  193833. return (i);
  193834. }
  193835. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193836. png_uint_16 PNGAPI
  193837. png_get_uint_16(png_bytep buf)
  193838. {
  193839. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193840. (png_uint_16)(*(buf + 1)));
  193841. return (i);
  193842. }
  193843. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193844. /* Read data, and (optionally) run it through the CRC. */
  193845. void /* PRIVATE */
  193846. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193847. {
  193848. if(png_ptr == NULL) return;
  193849. png_read_data(png_ptr, buf, length);
  193850. png_calculate_crc(png_ptr, buf, length);
  193851. }
  193852. /* Optionally skip data and then check the CRC. Depending on whether we
  193853. are reading a ancillary or critical chunk, and how the program has set
  193854. things up, we may calculate the CRC on the data and print a message.
  193855. Returns '1' if there was a CRC error, '0' otherwise. */
  193856. int /* PRIVATE */
  193857. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193858. {
  193859. png_size_t i;
  193860. png_size_t istop = png_ptr->zbuf_size;
  193861. for (i = (png_size_t)skip; i > istop; i -= istop)
  193862. {
  193863. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193864. }
  193865. if (i)
  193866. {
  193867. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193868. }
  193869. if (png_crc_error(png_ptr))
  193870. {
  193871. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193872. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193873. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193874. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193875. {
  193876. png_chunk_warning(png_ptr, "CRC error");
  193877. }
  193878. else
  193879. {
  193880. png_chunk_error(png_ptr, "CRC error");
  193881. }
  193882. return (1);
  193883. }
  193884. return (0);
  193885. }
  193886. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193887. the data it has read thus far. */
  193888. int /* PRIVATE */
  193889. png_crc_error(png_structp png_ptr)
  193890. {
  193891. png_byte crc_bytes[4];
  193892. png_uint_32 crc;
  193893. int need_crc = 1;
  193894. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193895. {
  193896. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193897. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193898. need_crc = 0;
  193899. }
  193900. else /* critical */
  193901. {
  193902. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193903. need_crc = 0;
  193904. }
  193905. png_read_data(png_ptr, crc_bytes, 4);
  193906. if (need_crc)
  193907. {
  193908. crc = png_get_uint_32(crc_bytes);
  193909. return ((int)(crc != png_ptr->crc));
  193910. }
  193911. else
  193912. return (0);
  193913. }
  193914. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193915. defined(PNG_READ_iCCP_SUPPORTED)
  193916. /*
  193917. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193918. * points at an allocated area holding the contents of a chunk with a
  193919. * trailing compressed part. What we get back is an allocated area
  193920. * holding the original prefix part and an uncompressed version of the
  193921. * trailing part (the malloc area passed in is freed).
  193922. */
  193923. png_charp /* PRIVATE */
  193924. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193925. png_charp chunkdata, png_size_t chunklength,
  193926. png_size_t prefix_size, png_size_t *newlength)
  193927. {
  193928. static PNG_CONST char msg[] = "Error decoding compressed text";
  193929. png_charp text;
  193930. png_size_t text_size;
  193931. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193932. {
  193933. int ret = Z_OK;
  193934. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193935. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193936. png_ptr->zstream.next_out = png_ptr->zbuf;
  193937. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193938. text_size = 0;
  193939. text = NULL;
  193940. while (png_ptr->zstream.avail_in)
  193941. {
  193942. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193943. if (ret != Z_OK && ret != Z_STREAM_END)
  193944. {
  193945. if (png_ptr->zstream.msg != NULL)
  193946. png_warning(png_ptr, png_ptr->zstream.msg);
  193947. else
  193948. png_warning(png_ptr, msg);
  193949. inflateReset(&png_ptr->zstream);
  193950. png_ptr->zstream.avail_in = 0;
  193951. if (text == NULL)
  193952. {
  193953. text_size = prefix_size + png_sizeof(msg) + 1;
  193954. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193955. if (text == NULL)
  193956. {
  193957. png_free(png_ptr,chunkdata);
  193958. png_error(png_ptr,"Not enough memory to decompress chunk");
  193959. }
  193960. png_memcpy(text, chunkdata, prefix_size);
  193961. }
  193962. text[text_size - 1] = 0x00;
  193963. /* Copy what we can of the error message into the text chunk */
  193964. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193965. text_size = png_sizeof(msg) > text_size ? text_size :
  193966. png_sizeof(msg);
  193967. png_memcpy(text + prefix_size, msg, text_size + 1);
  193968. break;
  193969. }
  193970. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193971. {
  193972. if (text == NULL)
  193973. {
  193974. text_size = prefix_size +
  193975. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193976. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193977. if (text == NULL)
  193978. {
  193979. png_free(png_ptr,chunkdata);
  193980. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193981. }
  193982. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193983. text_size - prefix_size);
  193984. png_memcpy(text, chunkdata, prefix_size);
  193985. *(text + text_size) = 0x00;
  193986. }
  193987. else
  193988. {
  193989. png_charp tmp;
  193990. tmp = text;
  193991. text = (png_charp)png_malloc_warn(png_ptr,
  193992. (png_uint_32)(text_size +
  193993. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193994. if (text == NULL)
  193995. {
  193996. png_free(png_ptr, tmp);
  193997. png_free(png_ptr, chunkdata);
  193998. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193999. }
  194000. png_memcpy(text, tmp, text_size);
  194001. png_free(png_ptr, tmp);
  194002. png_memcpy(text + text_size, png_ptr->zbuf,
  194003. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194004. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194005. *(text + text_size) = 0x00;
  194006. }
  194007. if (ret == Z_STREAM_END)
  194008. break;
  194009. else
  194010. {
  194011. png_ptr->zstream.next_out = png_ptr->zbuf;
  194012. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194013. }
  194014. }
  194015. }
  194016. if (ret != Z_STREAM_END)
  194017. {
  194018. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194019. char umsg[52];
  194020. if (ret == Z_BUF_ERROR)
  194021. png_snprintf(umsg, 52,
  194022. "Buffer error in compressed datastream in %s chunk",
  194023. png_ptr->chunk_name);
  194024. else if (ret == Z_DATA_ERROR)
  194025. png_snprintf(umsg, 52,
  194026. "Data error in compressed datastream in %s chunk",
  194027. png_ptr->chunk_name);
  194028. else
  194029. png_snprintf(umsg, 52,
  194030. "Incomplete compressed datastream in %s chunk",
  194031. png_ptr->chunk_name);
  194032. png_warning(png_ptr, umsg);
  194033. #else
  194034. png_warning(png_ptr,
  194035. "Incomplete compressed datastream in chunk other than IDAT");
  194036. #endif
  194037. text_size=prefix_size;
  194038. if (text == NULL)
  194039. {
  194040. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194041. if (text == NULL)
  194042. {
  194043. png_free(png_ptr, chunkdata);
  194044. png_error(png_ptr,"Not enough memory for text.");
  194045. }
  194046. png_memcpy(text, chunkdata, prefix_size);
  194047. }
  194048. *(text + text_size) = 0x00;
  194049. }
  194050. inflateReset(&png_ptr->zstream);
  194051. png_ptr->zstream.avail_in = 0;
  194052. png_free(png_ptr, chunkdata);
  194053. chunkdata = text;
  194054. *newlength=text_size;
  194055. }
  194056. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194057. {
  194058. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194059. char umsg[50];
  194060. png_snprintf(umsg, 50,
  194061. "Unknown zTXt compression type %d", comp_type);
  194062. png_warning(png_ptr, umsg);
  194063. #else
  194064. png_warning(png_ptr, "Unknown zTXt compression type");
  194065. #endif
  194066. *(chunkdata + prefix_size) = 0x00;
  194067. *newlength=prefix_size;
  194068. }
  194069. return chunkdata;
  194070. }
  194071. #endif
  194072. /* read and check the IDHR chunk */
  194073. void /* PRIVATE */
  194074. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194075. {
  194076. png_byte buf[13];
  194077. png_uint_32 width, height;
  194078. int bit_depth, color_type, compression_type, filter_type;
  194079. int interlace_type;
  194080. png_debug(1, "in png_handle_IHDR\n");
  194081. if (png_ptr->mode & PNG_HAVE_IHDR)
  194082. png_error(png_ptr, "Out of place IHDR");
  194083. /* check the length */
  194084. if (length != 13)
  194085. png_error(png_ptr, "Invalid IHDR chunk");
  194086. png_ptr->mode |= PNG_HAVE_IHDR;
  194087. png_crc_read(png_ptr, buf, 13);
  194088. png_crc_finish(png_ptr, 0);
  194089. width = png_get_uint_31(png_ptr, buf);
  194090. height = png_get_uint_31(png_ptr, buf + 4);
  194091. bit_depth = buf[8];
  194092. color_type = buf[9];
  194093. compression_type = buf[10];
  194094. filter_type = buf[11];
  194095. interlace_type = buf[12];
  194096. /* set internal variables */
  194097. png_ptr->width = width;
  194098. png_ptr->height = height;
  194099. png_ptr->bit_depth = (png_byte)bit_depth;
  194100. png_ptr->interlaced = (png_byte)interlace_type;
  194101. png_ptr->color_type = (png_byte)color_type;
  194102. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194103. png_ptr->filter_type = (png_byte)filter_type;
  194104. #endif
  194105. png_ptr->compression_type = (png_byte)compression_type;
  194106. /* find number of channels */
  194107. switch (png_ptr->color_type)
  194108. {
  194109. case PNG_COLOR_TYPE_GRAY:
  194110. case PNG_COLOR_TYPE_PALETTE:
  194111. png_ptr->channels = 1;
  194112. break;
  194113. case PNG_COLOR_TYPE_RGB:
  194114. png_ptr->channels = 3;
  194115. break;
  194116. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194117. png_ptr->channels = 2;
  194118. break;
  194119. case PNG_COLOR_TYPE_RGB_ALPHA:
  194120. png_ptr->channels = 4;
  194121. break;
  194122. }
  194123. /* set up other useful info */
  194124. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194125. png_ptr->channels);
  194126. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194127. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194128. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194129. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194130. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194131. color_type, interlace_type, compression_type, filter_type);
  194132. }
  194133. /* read and check the palette */
  194134. void /* PRIVATE */
  194135. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194136. {
  194137. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194138. int num, i;
  194139. #ifndef PNG_NO_POINTER_INDEXING
  194140. png_colorp pal_ptr;
  194141. #endif
  194142. png_debug(1, "in png_handle_PLTE\n");
  194143. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194144. png_error(png_ptr, "Missing IHDR before PLTE");
  194145. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194146. {
  194147. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194148. png_crc_finish(png_ptr, length);
  194149. return;
  194150. }
  194151. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194152. png_error(png_ptr, "Duplicate PLTE chunk");
  194153. png_ptr->mode |= PNG_HAVE_PLTE;
  194154. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194155. {
  194156. png_warning(png_ptr,
  194157. "Ignoring PLTE chunk in grayscale PNG");
  194158. png_crc_finish(png_ptr, length);
  194159. return;
  194160. }
  194161. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194162. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194163. {
  194164. png_crc_finish(png_ptr, length);
  194165. return;
  194166. }
  194167. #endif
  194168. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194169. {
  194170. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194171. {
  194172. png_warning(png_ptr, "Invalid palette chunk");
  194173. png_crc_finish(png_ptr, length);
  194174. return;
  194175. }
  194176. else
  194177. {
  194178. png_error(png_ptr, "Invalid palette chunk");
  194179. }
  194180. }
  194181. num = (int)length / 3;
  194182. #ifndef PNG_NO_POINTER_INDEXING
  194183. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194184. {
  194185. png_byte buf[3];
  194186. png_crc_read(png_ptr, buf, 3);
  194187. pal_ptr->red = buf[0];
  194188. pal_ptr->green = buf[1];
  194189. pal_ptr->blue = buf[2];
  194190. }
  194191. #else
  194192. for (i = 0; i < num; i++)
  194193. {
  194194. png_byte buf[3];
  194195. png_crc_read(png_ptr, buf, 3);
  194196. /* don't depend upon png_color being any order */
  194197. palette[i].red = buf[0];
  194198. palette[i].green = buf[1];
  194199. palette[i].blue = buf[2];
  194200. }
  194201. #endif
  194202. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194203. whatever the normal CRC configuration tells us. However, if we
  194204. have an RGB image, the PLTE can be considered ancillary, so
  194205. we will act as though it is. */
  194206. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194207. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194208. #endif
  194209. {
  194210. png_crc_finish(png_ptr, 0);
  194211. }
  194212. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194213. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194214. {
  194215. /* If we don't want to use the data from an ancillary chunk,
  194216. we have two options: an error abort, or a warning and we
  194217. ignore the data in this chunk (which should be OK, since
  194218. it's considered ancillary for a RGB or RGBA image). */
  194219. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194220. {
  194221. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194222. {
  194223. png_chunk_error(png_ptr, "CRC error");
  194224. }
  194225. else
  194226. {
  194227. png_chunk_warning(png_ptr, "CRC error");
  194228. return;
  194229. }
  194230. }
  194231. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194232. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194233. {
  194234. png_chunk_warning(png_ptr, "CRC error");
  194235. }
  194236. }
  194237. #endif
  194238. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194239. #if defined(PNG_READ_tRNS_SUPPORTED)
  194240. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194241. {
  194242. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194243. {
  194244. if (png_ptr->num_trans > (png_uint_16)num)
  194245. {
  194246. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194247. png_ptr->num_trans = (png_uint_16)num;
  194248. }
  194249. if (info_ptr->num_trans > (png_uint_16)num)
  194250. {
  194251. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194252. info_ptr->num_trans = (png_uint_16)num;
  194253. }
  194254. }
  194255. }
  194256. #endif
  194257. }
  194258. void /* PRIVATE */
  194259. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194260. {
  194261. png_debug(1, "in png_handle_IEND\n");
  194262. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194263. {
  194264. png_error(png_ptr, "No image in file");
  194265. }
  194266. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194267. if (length != 0)
  194268. {
  194269. png_warning(png_ptr, "Incorrect IEND chunk length");
  194270. }
  194271. png_crc_finish(png_ptr, length);
  194272. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194273. }
  194274. #if defined(PNG_READ_gAMA_SUPPORTED)
  194275. void /* PRIVATE */
  194276. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194277. {
  194278. png_fixed_point igamma;
  194279. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194280. float file_gamma;
  194281. #endif
  194282. png_byte buf[4];
  194283. png_debug(1, "in png_handle_gAMA\n");
  194284. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194285. png_error(png_ptr, "Missing IHDR before gAMA");
  194286. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194287. {
  194288. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194289. png_crc_finish(png_ptr, length);
  194290. return;
  194291. }
  194292. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194293. /* Should be an error, but we can cope with it */
  194294. png_warning(png_ptr, "Out of place gAMA chunk");
  194295. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194296. #if defined(PNG_READ_sRGB_SUPPORTED)
  194297. && !(info_ptr->valid & PNG_INFO_sRGB)
  194298. #endif
  194299. )
  194300. {
  194301. png_warning(png_ptr, "Duplicate gAMA chunk");
  194302. png_crc_finish(png_ptr, length);
  194303. return;
  194304. }
  194305. if (length != 4)
  194306. {
  194307. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194308. png_crc_finish(png_ptr, length);
  194309. return;
  194310. }
  194311. png_crc_read(png_ptr, buf, 4);
  194312. if (png_crc_finish(png_ptr, 0))
  194313. return;
  194314. igamma = (png_fixed_point)png_get_uint_32(buf);
  194315. /* check for zero gamma */
  194316. if (igamma == 0)
  194317. {
  194318. png_warning(png_ptr,
  194319. "Ignoring gAMA chunk with gamma=0");
  194320. return;
  194321. }
  194322. #if defined(PNG_READ_sRGB_SUPPORTED)
  194323. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194324. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194325. {
  194326. png_warning(png_ptr,
  194327. "Ignoring incorrect gAMA value when sRGB is also present");
  194328. #ifndef PNG_NO_CONSOLE_IO
  194329. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194330. #endif
  194331. return;
  194332. }
  194333. #endif /* PNG_READ_sRGB_SUPPORTED */
  194334. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194335. file_gamma = (float)igamma / (float)100000.0;
  194336. # ifdef PNG_READ_GAMMA_SUPPORTED
  194337. png_ptr->gamma = file_gamma;
  194338. # endif
  194339. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194340. #endif
  194341. #ifdef PNG_FIXED_POINT_SUPPORTED
  194342. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194343. #endif
  194344. }
  194345. #endif
  194346. #if defined(PNG_READ_sBIT_SUPPORTED)
  194347. void /* PRIVATE */
  194348. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194349. {
  194350. png_size_t truelen;
  194351. png_byte buf[4];
  194352. png_debug(1, "in png_handle_sBIT\n");
  194353. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194354. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194355. png_error(png_ptr, "Missing IHDR before sBIT");
  194356. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194357. {
  194358. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194359. png_crc_finish(png_ptr, length);
  194360. return;
  194361. }
  194362. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194363. {
  194364. /* Should be an error, but we can cope with it */
  194365. png_warning(png_ptr, "Out of place sBIT chunk");
  194366. }
  194367. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194368. {
  194369. png_warning(png_ptr, "Duplicate sBIT chunk");
  194370. png_crc_finish(png_ptr, length);
  194371. return;
  194372. }
  194373. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194374. truelen = 3;
  194375. else
  194376. truelen = (png_size_t)png_ptr->channels;
  194377. if (length != truelen || length > 4)
  194378. {
  194379. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194380. png_crc_finish(png_ptr, length);
  194381. return;
  194382. }
  194383. png_crc_read(png_ptr, buf, truelen);
  194384. if (png_crc_finish(png_ptr, 0))
  194385. return;
  194386. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194387. {
  194388. png_ptr->sig_bit.red = buf[0];
  194389. png_ptr->sig_bit.green = buf[1];
  194390. png_ptr->sig_bit.blue = buf[2];
  194391. png_ptr->sig_bit.alpha = buf[3];
  194392. }
  194393. else
  194394. {
  194395. png_ptr->sig_bit.gray = buf[0];
  194396. png_ptr->sig_bit.red = buf[0];
  194397. png_ptr->sig_bit.green = buf[0];
  194398. png_ptr->sig_bit.blue = buf[0];
  194399. png_ptr->sig_bit.alpha = buf[1];
  194400. }
  194401. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194402. }
  194403. #endif
  194404. #if defined(PNG_READ_cHRM_SUPPORTED)
  194405. void /* PRIVATE */
  194406. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194407. {
  194408. png_byte buf[4];
  194409. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194410. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194411. #endif
  194412. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194413. int_y_green, int_x_blue, int_y_blue;
  194414. png_uint_32 uint_x, uint_y;
  194415. png_debug(1, "in png_handle_cHRM\n");
  194416. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194417. png_error(png_ptr, "Missing IHDR before cHRM");
  194418. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194419. {
  194420. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194421. png_crc_finish(png_ptr, length);
  194422. return;
  194423. }
  194424. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194425. /* Should be an error, but we can cope with it */
  194426. png_warning(png_ptr, "Missing PLTE before cHRM");
  194427. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194428. #if defined(PNG_READ_sRGB_SUPPORTED)
  194429. && !(info_ptr->valid & PNG_INFO_sRGB)
  194430. #endif
  194431. )
  194432. {
  194433. png_warning(png_ptr, "Duplicate cHRM chunk");
  194434. png_crc_finish(png_ptr, length);
  194435. return;
  194436. }
  194437. if (length != 32)
  194438. {
  194439. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194440. png_crc_finish(png_ptr, length);
  194441. return;
  194442. }
  194443. png_crc_read(png_ptr, buf, 4);
  194444. uint_x = png_get_uint_32(buf);
  194445. png_crc_read(png_ptr, buf, 4);
  194446. uint_y = png_get_uint_32(buf);
  194447. if (uint_x > 80000L || uint_y > 80000L ||
  194448. uint_x + uint_y > 100000L)
  194449. {
  194450. png_warning(png_ptr, "Invalid cHRM white point");
  194451. png_crc_finish(png_ptr, 24);
  194452. return;
  194453. }
  194454. int_x_white = (png_fixed_point)uint_x;
  194455. int_y_white = (png_fixed_point)uint_y;
  194456. png_crc_read(png_ptr, buf, 4);
  194457. uint_x = png_get_uint_32(buf);
  194458. png_crc_read(png_ptr, buf, 4);
  194459. uint_y = png_get_uint_32(buf);
  194460. if (uint_x + uint_y > 100000L)
  194461. {
  194462. png_warning(png_ptr, "Invalid cHRM red point");
  194463. png_crc_finish(png_ptr, 16);
  194464. return;
  194465. }
  194466. int_x_red = (png_fixed_point)uint_x;
  194467. int_y_red = (png_fixed_point)uint_y;
  194468. png_crc_read(png_ptr, buf, 4);
  194469. uint_x = png_get_uint_32(buf);
  194470. png_crc_read(png_ptr, buf, 4);
  194471. uint_y = png_get_uint_32(buf);
  194472. if (uint_x + uint_y > 100000L)
  194473. {
  194474. png_warning(png_ptr, "Invalid cHRM green point");
  194475. png_crc_finish(png_ptr, 8);
  194476. return;
  194477. }
  194478. int_x_green = (png_fixed_point)uint_x;
  194479. int_y_green = (png_fixed_point)uint_y;
  194480. png_crc_read(png_ptr, buf, 4);
  194481. uint_x = png_get_uint_32(buf);
  194482. png_crc_read(png_ptr, buf, 4);
  194483. uint_y = png_get_uint_32(buf);
  194484. if (uint_x + uint_y > 100000L)
  194485. {
  194486. png_warning(png_ptr, "Invalid cHRM blue point");
  194487. png_crc_finish(png_ptr, 0);
  194488. return;
  194489. }
  194490. int_x_blue = (png_fixed_point)uint_x;
  194491. int_y_blue = (png_fixed_point)uint_y;
  194492. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194493. white_x = (float)int_x_white / (float)100000.0;
  194494. white_y = (float)int_y_white / (float)100000.0;
  194495. red_x = (float)int_x_red / (float)100000.0;
  194496. red_y = (float)int_y_red / (float)100000.0;
  194497. green_x = (float)int_x_green / (float)100000.0;
  194498. green_y = (float)int_y_green / (float)100000.0;
  194499. blue_x = (float)int_x_blue / (float)100000.0;
  194500. blue_y = (float)int_y_blue / (float)100000.0;
  194501. #endif
  194502. #if defined(PNG_READ_sRGB_SUPPORTED)
  194503. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194504. {
  194505. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194506. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194507. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194508. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194509. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194510. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194511. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194512. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194513. {
  194514. png_warning(png_ptr,
  194515. "Ignoring incorrect cHRM value when sRGB is also present");
  194516. #ifndef PNG_NO_CONSOLE_IO
  194517. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194518. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194519. white_x, white_y, red_x, red_y);
  194520. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194521. green_x, green_y, blue_x, blue_y);
  194522. #else
  194523. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194524. int_x_white, int_y_white, int_x_red, int_y_red);
  194525. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194526. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194527. #endif
  194528. #endif /* PNG_NO_CONSOLE_IO */
  194529. }
  194530. png_crc_finish(png_ptr, 0);
  194531. return;
  194532. }
  194533. #endif /* PNG_READ_sRGB_SUPPORTED */
  194534. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194535. png_set_cHRM(png_ptr, info_ptr,
  194536. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194537. #endif
  194538. #ifdef PNG_FIXED_POINT_SUPPORTED
  194539. png_set_cHRM_fixed(png_ptr, info_ptr,
  194540. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194541. int_y_green, int_x_blue, int_y_blue);
  194542. #endif
  194543. if (png_crc_finish(png_ptr, 0))
  194544. return;
  194545. }
  194546. #endif
  194547. #if defined(PNG_READ_sRGB_SUPPORTED)
  194548. void /* PRIVATE */
  194549. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194550. {
  194551. int intent;
  194552. png_byte buf[1];
  194553. png_debug(1, "in png_handle_sRGB\n");
  194554. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194555. png_error(png_ptr, "Missing IHDR before sRGB");
  194556. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194557. {
  194558. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194559. png_crc_finish(png_ptr, length);
  194560. return;
  194561. }
  194562. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194563. /* Should be an error, but we can cope with it */
  194564. png_warning(png_ptr, "Out of place sRGB chunk");
  194565. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194566. {
  194567. png_warning(png_ptr, "Duplicate sRGB chunk");
  194568. png_crc_finish(png_ptr, length);
  194569. return;
  194570. }
  194571. if (length != 1)
  194572. {
  194573. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194574. png_crc_finish(png_ptr, length);
  194575. return;
  194576. }
  194577. png_crc_read(png_ptr, buf, 1);
  194578. if (png_crc_finish(png_ptr, 0))
  194579. return;
  194580. intent = buf[0];
  194581. /* check for bad intent */
  194582. if (intent >= PNG_sRGB_INTENT_LAST)
  194583. {
  194584. png_warning(png_ptr, "Unknown sRGB intent");
  194585. return;
  194586. }
  194587. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194588. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194589. {
  194590. png_fixed_point igamma;
  194591. #ifdef PNG_FIXED_POINT_SUPPORTED
  194592. igamma=info_ptr->int_gamma;
  194593. #else
  194594. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194595. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194596. # endif
  194597. #endif
  194598. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194599. {
  194600. png_warning(png_ptr,
  194601. "Ignoring incorrect gAMA value when sRGB is also present");
  194602. #ifndef PNG_NO_CONSOLE_IO
  194603. # ifdef PNG_FIXED_POINT_SUPPORTED
  194604. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194605. # else
  194606. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194607. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194608. # endif
  194609. # endif
  194610. #endif
  194611. }
  194612. }
  194613. #endif /* PNG_READ_gAMA_SUPPORTED */
  194614. #ifdef PNG_READ_cHRM_SUPPORTED
  194615. #ifdef PNG_FIXED_POINT_SUPPORTED
  194616. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194617. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194618. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194619. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194620. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194621. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194622. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194623. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194624. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194625. {
  194626. png_warning(png_ptr,
  194627. "Ignoring incorrect cHRM value when sRGB is also present");
  194628. }
  194629. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194630. #endif /* PNG_READ_cHRM_SUPPORTED */
  194631. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194632. }
  194633. #endif /* PNG_READ_sRGB_SUPPORTED */
  194634. #if defined(PNG_READ_iCCP_SUPPORTED)
  194635. void /* PRIVATE */
  194636. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194637. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194638. {
  194639. png_charp chunkdata;
  194640. png_byte compression_type;
  194641. png_bytep pC;
  194642. png_charp profile;
  194643. png_uint_32 skip = 0;
  194644. png_uint_32 profile_size, profile_length;
  194645. png_size_t slength, prefix_length, data_length;
  194646. png_debug(1, "in png_handle_iCCP\n");
  194647. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194648. png_error(png_ptr, "Missing IHDR before iCCP");
  194649. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194650. {
  194651. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194652. png_crc_finish(png_ptr, length);
  194653. return;
  194654. }
  194655. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194656. /* Should be an error, but we can cope with it */
  194657. png_warning(png_ptr, "Out of place iCCP chunk");
  194658. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194659. {
  194660. png_warning(png_ptr, "Duplicate iCCP chunk");
  194661. png_crc_finish(png_ptr, length);
  194662. return;
  194663. }
  194664. #ifdef PNG_MAX_MALLOC_64K
  194665. if (length > (png_uint_32)65535L)
  194666. {
  194667. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194668. skip = length - (png_uint_32)65535L;
  194669. length = (png_uint_32)65535L;
  194670. }
  194671. #endif
  194672. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194673. slength = (png_size_t)length;
  194674. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194675. if (png_crc_finish(png_ptr, skip))
  194676. {
  194677. png_free(png_ptr, chunkdata);
  194678. return;
  194679. }
  194680. chunkdata[slength] = 0x00;
  194681. for (profile = chunkdata; *profile; profile++)
  194682. /* empty loop to find end of name */ ;
  194683. ++profile;
  194684. /* there should be at least one zero (the compression type byte)
  194685. following the separator, and we should be on it */
  194686. if ( profile >= chunkdata + slength - 1)
  194687. {
  194688. png_free(png_ptr, chunkdata);
  194689. png_warning(png_ptr, "Malformed iCCP chunk");
  194690. return;
  194691. }
  194692. /* compression_type should always be zero */
  194693. compression_type = *profile++;
  194694. if (compression_type)
  194695. {
  194696. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194697. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194698. wrote nonzero) */
  194699. }
  194700. prefix_length = profile - chunkdata;
  194701. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194702. slength, prefix_length, &data_length);
  194703. profile_length = data_length - prefix_length;
  194704. if ( prefix_length > data_length || profile_length < 4)
  194705. {
  194706. png_free(png_ptr, chunkdata);
  194707. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194708. return;
  194709. }
  194710. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194711. pC = (png_bytep)(chunkdata+prefix_length);
  194712. profile_size = ((*(pC ))<<24) |
  194713. ((*(pC+1))<<16) |
  194714. ((*(pC+2))<< 8) |
  194715. ((*(pC+3)) );
  194716. if(profile_size < profile_length)
  194717. profile_length = profile_size;
  194718. if(profile_size > profile_length)
  194719. {
  194720. png_free(png_ptr, chunkdata);
  194721. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194722. return;
  194723. }
  194724. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194725. chunkdata + prefix_length, profile_length);
  194726. png_free(png_ptr, chunkdata);
  194727. }
  194728. #endif /* PNG_READ_iCCP_SUPPORTED */
  194729. #if defined(PNG_READ_sPLT_SUPPORTED)
  194730. void /* PRIVATE */
  194731. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194732. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194733. {
  194734. png_bytep chunkdata;
  194735. png_bytep entry_start;
  194736. png_sPLT_t new_palette;
  194737. #ifdef PNG_NO_POINTER_INDEXING
  194738. png_sPLT_entryp pp;
  194739. #endif
  194740. int data_length, entry_size, i;
  194741. png_uint_32 skip = 0;
  194742. png_size_t slength;
  194743. png_debug(1, "in png_handle_sPLT\n");
  194744. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194745. png_error(png_ptr, "Missing IHDR before sPLT");
  194746. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194747. {
  194748. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194749. png_crc_finish(png_ptr, length);
  194750. return;
  194751. }
  194752. #ifdef PNG_MAX_MALLOC_64K
  194753. if (length > (png_uint_32)65535L)
  194754. {
  194755. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194756. skip = length - (png_uint_32)65535L;
  194757. length = (png_uint_32)65535L;
  194758. }
  194759. #endif
  194760. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194761. slength = (png_size_t)length;
  194762. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194763. if (png_crc_finish(png_ptr, skip))
  194764. {
  194765. png_free(png_ptr, chunkdata);
  194766. return;
  194767. }
  194768. chunkdata[slength] = 0x00;
  194769. for (entry_start = chunkdata; *entry_start; entry_start++)
  194770. /* empty loop to find end of name */ ;
  194771. ++entry_start;
  194772. /* a sample depth should follow the separator, and we should be on it */
  194773. if (entry_start > chunkdata + slength - 2)
  194774. {
  194775. png_free(png_ptr, chunkdata);
  194776. png_warning(png_ptr, "malformed sPLT chunk");
  194777. return;
  194778. }
  194779. new_palette.depth = *entry_start++;
  194780. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194781. data_length = (slength - (entry_start - chunkdata));
  194782. /* integrity-check the data length */
  194783. if (data_length % entry_size)
  194784. {
  194785. png_free(png_ptr, chunkdata);
  194786. png_warning(png_ptr, "sPLT chunk has bad length");
  194787. return;
  194788. }
  194789. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194790. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194791. png_sizeof(png_sPLT_entry)))
  194792. {
  194793. png_warning(png_ptr, "sPLT chunk too long");
  194794. return;
  194795. }
  194796. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194797. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194798. if (new_palette.entries == NULL)
  194799. {
  194800. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194801. return;
  194802. }
  194803. #ifndef PNG_NO_POINTER_INDEXING
  194804. for (i = 0; i < new_palette.nentries; i++)
  194805. {
  194806. png_sPLT_entryp pp = new_palette.entries + i;
  194807. if (new_palette.depth == 8)
  194808. {
  194809. pp->red = *entry_start++;
  194810. pp->green = *entry_start++;
  194811. pp->blue = *entry_start++;
  194812. pp->alpha = *entry_start++;
  194813. }
  194814. else
  194815. {
  194816. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194817. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194818. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194819. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194820. }
  194821. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194822. }
  194823. #else
  194824. pp = new_palette.entries;
  194825. for (i = 0; i < new_palette.nentries; i++)
  194826. {
  194827. if (new_palette.depth == 8)
  194828. {
  194829. pp[i].red = *entry_start++;
  194830. pp[i].green = *entry_start++;
  194831. pp[i].blue = *entry_start++;
  194832. pp[i].alpha = *entry_start++;
  194833. }
  194834. else
  194835. {
  194836. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194837. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194838. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194839. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194840. }
  194841. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194842. }
  194843. #endif
  194844. /* discard all chunk data except the name and stash that */
  194845. new_palette.name = (png_charp)chunkdata;
  194846. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194847. png_free(png_ptr, chunkdata);
  194848. png_free(png_ptr, new_palette.entries);
  194849. }
  194850. #endif /* PNG_READ_sPLT_SUPPORTED */
  194851. #if defined(PNG_READ_tRNS_SUPPORTED)
  194852. void /* PRIVATE */
  194853. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194854. {
  194855. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194856. int bit_mask;
  194857. png_debug(1, "in png_handle_tRNS\n");
  194858. /* For non-indexed color, mask off any bits in the tRNS value that
  194859. * exceed the bit depth. Some creators were writing extra bits there.
  194860. * This is not needed for indexed color. */
  194861. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194862. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194863. png_error(png_ptr, "Missing IHDR before tRNS");
  194864. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194865. {
  194866. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194867. png_crc_finish(png_ptr, length);
  194868. return;
  194869. }
  194870. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194871. {
  194872. png_warning(png_ptr, "Duplicate tRNS chunk");
  194873. png_crc_finish(png_ptr, length);
  194874. return;
  194875. }
  194876. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194877. {
  194878. png_byte buf[2];
  194879. if (length != 2)
  194880. {
  194881. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194882. png_crc_finish(png_ptr, length);
  194883. return;
  194884. }
  194885. png_crc_read(png_ptr, buf, 2);
  194886. png_ptr->num_trans = 1;
  194887. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194888. }
  194889. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194890. {
  194891. png_byte buf[6];
  194892. if (length != 6)
  194893. {
  194894. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194895. png_crc_finish(png_ptr, length);
  194896. return;
  194897. }
  194898. png_crc_read(png_ptr, buf, (png_size_t)length);
  194899. png_ptr->num_trans = 1;
  194900. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194901. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194902. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194903. }
  194904. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194905. {
  194906. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194907. {
  194908. /* Should be an error, but we can cope with it. */
  194909. png_warning(png_ptr, "Missing PLTE before tRNS");
  194910. }
  194911. if (length > (png_uint_32)png_ptr->num_palette ||
  194912. length > PNG_MAX_PALETTE_LENGTH)
  194913. {
  194914. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194915. png_crc_finish(png_ptr, length);
  194916. return;
  194917. }
  194918. if (length == 0)
  194919. {
  194920. png_warning(png_ptr, "Zero length tRNS chunk");
  194921. png_crc_finish(png_ptr, length);
  194922. return;
  194923. }
  194924. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194925. png_ptr->num_trans = (png_uint_16)length;
  194926. }
  194927. else
  194928. {
  194929. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194930. png_crc_finish(png_ptr, length);
  194931. return;
  194932. }
  194933. if (png_crc_finish(png_ptr, 0))
  194934. {
  194935. png_ptr->num_trans = 0;
  194936. return;
  194937. }
  194938. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194939. &(png_ptr->trans_values));
  194940. }
  194941. #endif
  194942. #if defined(PNG_READ_bKGD_SUPPORTED)
  194943. void /* PRIVATE */
  194944. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194945. {
  194946. png_size_t truelen;
  194947. png_byte buf[6];
  194948. png_debug(1, "in png_handle_bKGD\n");
  194949. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194950. png_error(png_ptr, "Missing IHDR before bKGD");
  194951. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194952. {
  194953. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194954. png_crc_finish(png_ptr, length);
  194955. return;
  194956. }
  194957. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194958. !(png_ptr->mode & PNG_HAVE_PLTE))
  194959. {
  194960. png_warning(png_ptr, "Missing PLTE before bKGD");
  194961. png_crc_finish(png_ptr, length);
  194962. return;
  194963. }
  194964. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194965. {
  194966. png_warning(png_ptr, "Duplicate bKGD chunk");
  194967. png_crc_finish(png_ptr, length);
  194968. return;
  194969. }
  194970. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194971. truelen = 1;
  194972. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194973. truelen = 6;
  194974. else
  194975. truelen = 2;
  194976. if (length != truelen)
  194977. {
  194978. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194979. png_crc_finish(png_ptr, length);
  194980. return;
  194981. }
  194982. png_crc_read(png_ptr, buf, truelen);
  194983. if (png_crc_finish(png_ptr, 0))
  194984. return;
  194985. /* We convert the index value into RGB components so that we can allow
  194986. * arbitrary RGB values for background when we have transparency, and
  194987. * so it is easy to determine the RGB values of the background color
  194988. * from the info_ptr struct. */
  194989. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194990. {
  194991. png_ptr->background.index = buf[0];
  194992. if(info_ptr->num_palette)
  194993. {
  194994. if(buf[0] > info_ptr->num_palette)
  194995. {
  194996. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194997. return;
  194998. }
  194999. png_ptr->background.red =
  195000. (png_uint_16)png_ptr->palette[buf[0]].red;
  195001. png_ptr->background.green =
  195002. (png_uint_16)png_ptr->palette[buf[0]].green;
  195003. png_ptr->background.blue =
  195004. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195005. }
  195006. }
  195007. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195008. {
  195009. png_ptr->background.red =
  195010. png_ptr->background.green =
  195011. png_ptr->background.blue =
  195012. png_ptr->background.gray = png_get_uint_16(buf);
  195013. }
  195014. else
  195015. {
  195016. png_ptr->background.red = png_get_uint_16(buf);
  195017. png_ptr->background.green = png_get_uint_16(buf + 2);
  195018. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195019. }
  195020. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195021. }
  195022. #endif
  195023. #if defined(PNG_READ_hIST_SUPPORTED)
  195024. void /* PRIVATE */
  195025. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195026. {
  195027. unsigned int num, i;
  195028. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195029. png_debug(1, "in png_handle_hIST\n");
  195030. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195031. png_error(png_ptr, "Missing IHDR before hIST");
  195032. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195033. {
  195034. png_warning(png_ptr, "Invalid hIST after IDAT");
  195035. png_crc_finish(png_ptr, length);
  195036. return;
  195037. }
  195038. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195039. {
  195040. png_warning(png_ptr, "Missing PLTE before hIST");
  195041. png_crc_finish(png_ptr, length);
  195042. return;
  195043. }
  195044. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195045. {
  195046. png_warning(png_ptr, "Duplicate hIST chunk");
  195047. png_crc_finish(png_ptr, length);
  195048. return;
  195049. }
  195050. num = length / 2 ;
  195051. if (num != (unsigned int) png_ptr->num_palette || num >
  195052. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195053. {
  195054. png_warning(png_ptr, "Incorrect hIST chunk length");
  195055. png_crc_finish(png_ptr, length);
  195056. return;
  195057. }
  195058. for (i = 0; i < num; i++)
  195059. {
  195060. png_byte buf[2];
  195061. png_crc_read(png_ptr, buf, 2);
  195062. readbuf[i] = png_get_uint_16(buf);
  195063. }
  195064. if (png_crc_finish(png_ptr, 0))
  195065. return;
  195066. png_set_hIST(png_ptr, info_ptr, readbuf);
  195067. }
  195068. #endif
  195069. #if defined(PNG_READ_pHYs_SUPPORTED)
  195070. void /* PRIVATE */
  195071. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195072. {
  195073. png_byte buf[9];
  195074. png_uint_32 res_x, res_y;
  195075. int unit_type;
  195076. png_debug(1, "in png_handle_pHYs\n");
  195077. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195078. png_error(png_ptr, "Missing IHDR before pHYs");
  195079. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195080. {
  195081. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195082. png_crc_finish(png_ptr, length);
  195083. return;
  195084. }
  195085. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195086. {
  195087. png_warning(png_ptr, "Duplicate pHYs chunk");
  195088. png_crc_finish(png_ptr, length);
  195089. return;
  195090. }
  195091. if (length != 9)
  195092. {
  195093. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195094. png_crc_finish(png_ptr, length);
  195095. return;
  195096. }
  195097. png_crc_read(png_ptr, buf, 9);
  195098. if (png_crc_finish(png_ptr, 0))
  195099. return;
  195100. res_x = png_get_uint_32(buf);
  195101. res_y = png_get_uint_32(buf + 4);
  195102. unit_type = buf[8];
  195103. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195104. }
  195105. #endif
  195106. #if defined(PNG_READ_oFFs_SUPPORTED)
  195107. void /* PRIVATE */
  195108. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195109. {
  195110. png_byte buf[9];
  195111. png_int_32 offset_x, offset_y;
  195112. int unit_type;
  195113. png_debug(1, "in png_handle_oFFs\n");
  195114. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195115. png_error(png_ptr, "Missing IHDR before oFFs");
  195116. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195117. {
  195118. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195119. png_crc_finish(png_ptr, length);
  195120. return;
  195121. }
  195122. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195123. {
  195124. png_warning(png_ptr, "Duplicate oFFs chunk");
  195125. png_crc_finish(png_ptr, length);
  195126. return;
  195127. }
  195128. if (length != 9)
  195129. {
  195130. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195131. png_crc_finish(png_ptr, length);
  195132. return;
  195133. }
  195134. png_crc_read(png_ptr, buf, 9);
  195135. if (png_crc_finish(png_ptr, 0))
  195136. return;
  195137. offset_x = png_get_int_32(buf);
  195138. offset_y = png_get_int_32(buf + 4);
  195139. unit_type = buf[8];
  195140. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195141. }
  195142. #endif
  195143. #if defined(PNG_READ_pCAL_SUPPORTED)
  195144. /* read the pCAL chunk (described in the PNG Extensions document) */
  195145. void /* PRIVATE */
  195146. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195147. {
  195148. png_charp purpose;
  195149. png_int_32 X0, X1;
  195150. png_byte type, nparams;
  195151. png_charp buf, units, endptr;
  195152. png_charpp params;
  195153. png_size_t slength;
  195154. int i;
  195155. png_debug(1, "in png_handle_pCAL\n");
  195156. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195157. png_error(png_ptr, "Missing IHDR before pCAL");
  195158. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195159. {
  195160. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195161. png_crc_finish(png_ptr, length);
  195162. return;
  195163. }
  195164. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195165. {
  195166. png_warning(png_ptr, "Duplicate pCAL chunk");
  195167. png_crc_finish(png_ptr, length);
  195168. return;
  195169. }
  195170. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195171. length + 1);
  195172. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195173. if (purpose == NULL)
  195174. {
  195175. png_warning(png_ptr, "No memory for pCAL purpose.");
  195176. return;
  195177. }
  195178. slength = (png_size_t)length;
  195179. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195180. if (png_crc_finish(png_ptr, 0))
  195181. {
  195182. png_free(png_ptr, purpose);
  195183. return;
  195184. }
  195185. purpose[slength] = 0x00; /* null terminate the last string */
  195186. png_debug(3, "Finding end of pCAL purpose string\n");
  195187. for (buf = purpose; *buf; buf++)
  195188. /* empty loop */ ;
  195189. endptr = purpose + slength;
  195190. /* We need to have at least 12 bytes after the purpose string
  195191. in order to get the parameter information. */
  195192. if (endptr <= buf + 12)
  195193. {
  195194. png_warning(png_ptr, "Invalid pCAL data");
  195195. png_free(png_ptr, purpose);
  195196. return;
  195197. }
  195198. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195199. X0 = png_get_int_32((png_bytep)buf+1);
  195200. X1 = png_get_int_32((png_bytep)buf+5);
  195201. type = buf[9];
  195202. nparams = buf[10];
  195203. units = buf + 11;
  195204. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195205. /* Check that we have the right number of parameters for known
  195206. equation types. */
  195207. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195208. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195209. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195210. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195211. {
  195212. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195213. png_free(png_ptr, purpose);
  195214. return;
  195215. }
  195216. else if (type >= PNG_EQUATION_LAST)
  195217. {
  195218. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195219. }
  195220. for (buf = units; *buf; buf++)
  195221. /* Empty loop to move past the units string. */ ;
  195222. png_debug(3, "Allocating pCAL parameters array\n");
  195223. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195224. *png_sizeof(png_charp))) ;
  195225. if (params == NULL)
  195226. {
  195227. png_free(png_ptr, purpose);
  195228. png_warning(png_ptr, "No memory for pCAL params.");
  195229. return;
  195230. }
  195231. /* Get pointers to the start of each parameter string. */
  195232. for (i = 0; i < (int)nparams; i++)
  195233. {
  195234. buf++; /* Skip the null string terminator from previous parameter. */
  195235. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195236. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195237. /* Empty loop to move past each parameter string */ ;
  195238. /* Make sure we haven't run out of data yet */
  195239. if (buf > endptr)
  195240. {
  195241. png_warning(png_ptr, "Invalid pCAL data");
  195242. png_free(png_ptr, purpose);
  195243. png_free(png_ptr, params);
  195244. return;
  195245. }
  195246. }
  195247. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195248. units, params);
  195249. png_free(png_ptr, purpose);
  195250. png_free(png_ptr, params);
  195251. }
  195252. #endif
  195253. #if defined(PNG_READ_sCAL_SUPPORTED)
  195254. /* read the sCAL chunk */
  195255. void /* PRIVATE */
  195256. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195257. {
  195258. png_charp buffer, ep;
  195259. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195260. double width, height;
  195261. png_charp vp;
  195262. #else
  195263. #ifdef PNG_FIXED_POINT_SUPPORTED
  195264. png_charp swidth, sheight;
  195265. #endif
  195266. #endif
  195267. png_size_t slength;
  195268. png_debug(1, "in png_handle_sCAL\n");
  195269. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195270. png_error(png_ptr, "Missing IHDR before sCAL");
  195271. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195272. {
  195273. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195274. png_crc_finish(png_ptr, length);
  195275. return;
  195276. }
  195277. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195278. {
  195279. png_warning(png_ptr, "Duplicate sCAL chunk");
  195280. png_crc_finish(png_ptr, length);
  195281. return;
  195282. }
  195283. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195284. length + 1);
  195285. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195286. if (buffer == NULL)
  195287. {
  195288. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195289. return;
  195290. }
  195291. slength = (png_size_t)length;
  195292. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195293. if (png_crc_finish(png_ptr, 0))
  195294. {
  195295. png_free(png_ptr, buffer);
  195296. return;
  195297. }
  195298. buffer[slength] = 0x00; /* null terminate the last string */
  195299. ep = buffer + 1; /* skip unit byte */
  195300. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195301. width = png_strtod(png_ptr, ep, &vp);
  195302. if (*vp)
  195303. {
  195304. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195305. return;
  195306. }
  195307. #else
  195308. #ifdef PNG_FIXED_POINT_SUPPORTED
  195309. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195310. if (swidth == NULL)
  195311. {
  195312. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195313. return;
  195314. }
  195315. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195316. #endif
  195317. #endif
  195318. for (ep = buffer; *ep; ep++)
  195319. /* empty loop */ ;
  195320. ep++;
  195321. if (buffer + slength < ep)
  195322. {
  195323. png_warning(png_ptr, "Truncated sCAL chunk");
  195324. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195325. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195326. png_free(png_ptr, swidth);
  195327. #endif
  195328. png_free(png_ptr, buffer);
  195329. return;
  195330. }
  195331. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195332. height = png_strtod(png_ptr, ep, &vp);
  195333. if (*vp)
  195334. {
  195335. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195336. return;
  195337. }
  195338. #else
  195339. #ifdef PNG_FIXED_POINT_SUPPORTED
  195340. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195341. if (swidth == NULL)
  195342. {
  195343. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195344. return;
  195345. }
  195346. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195347. #endif
  195348. #endif
  195349. if (buffer + slength < ep
  195350. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195351. || width <= 0. || height <= 0.
  195352. #endif
  195353. )
  195354. {
  195355. png_warning(png_ptr, "Invalid sCAL data");
  195356. png_free(png_ptr, buffer);
  195357. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195358. png_free(png_ptr, swidth);
  195359. png_free(png_ptr, sheight);
  195360. #endif
  195361. return;
  195362. }
  195363. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195364. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195365. #else
  195366. #ifdef PNG_FIXED_POINT_SUPPORTED
  195367. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195368. #endif
  195369. #endif
  195370. png_free(png_ptr, buffer);
  195371. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195372. png_free(png_ptr, swidth);
  195373. png_free(png_ptr, sheight);
  195374. #endif
  195375. }
  195376. #endif
  195377. #if defined(PNG_READ_tIME_SUPPORTED)
  195378. void /* PRIVATE */
  195379. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195380. {
  195381. png_byte buf[7];
  195382. png_time mod_time;
  195383. png_debug(1, "in png_handle_tIME\n");
  195384. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195385. png_error(png_ptr, "Out of place tIME chunk");
  195386. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195387. {
  195388. png_warning(png_ptr, "Duplicate tIME chunk");
  195389. png_crc_finish(png_ptr, length);
  195390. return;
  195391. }
  195392. if (png_ptr->mode & PNG_HAVE_IDAT)
  195393. png_ptr->mode |= PNG_AFTER_IDAT;
  195394. if (length != 7)
  195395. {
  195396. png_warning(png_ptr, "Incorrect tIME chunk length");
  195397. png_crc_finish(png_ptr, length);
  195398. return;
  195399. }
  195400. png_crc_read(png_ptr, buf, 7);
  195401. if (png_crc_finish(png_ptr, 0))
  195402. return;
  195403. mod_time.second = buf[6];
  195404. mod_time.minute = buf[5];
  195405. mod_time.hour = buf[4];
  195406. mod_time.day = buf[3];
  195407. mod_time.month = buf[2];
  195408. mod_time.year = png_get_uint_16(buf);
  195409. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195410. }
  195411. #endif
  195412. #if defined(PNG_READ_tEXt_SUPPORTED)
  195413. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195414. void /* PRIVATE */
  195415. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195416. {
  195417. png_textp text_ptr;
  195418. png_charp key;
  195419. png_charp text;
  195420. png_uint_32 skip = 0;
  195421. png_size_t slength;
  195422. int ret;
  195423. png_debug(1, "in png_handle_tEXt\n");
  195424. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195425. png_error(png_ptr, "Missing IHDR before tEXt");
  195426. if (png_ptr->mode & PNG_HAVE_IDAT)
  195427. png_ptr->mode |= PNG_AFTER_IDAT;
  195428. #ifdef PNG_MAX_MALLOC_64K
  195429. if (length > (png_uint_32)65535L)
  195430. {
  195431. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195432. skip = length - (png_uint_32)65535L;
  195433. length = (png_uint_32)65535L;
  195434. }
  195435. #endif
  195436. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195437. if (key == NULL)
  195438. {
  195439. png_warning(png_ptr, "No memory to process text chunk.");
  195440. return;
  195441. }
  195442. slength = (png_size_t)length;
  195443. png_crc_read(png_ptr, (png_bytep)key, slength);
  195444. if (png_crc_finish(png_ptr, skip))
  195445. {
  195446. png_free(png_ptr, key);
  195447. return;
  195448. }
  195449. key[slength] = 0x00;
  195450. for (text = key; *text; text++)
  195451. /* empty loop to find end of key */ ;
  195452. if (text != key + slength)
  195453. text++;
  195454. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195455. (png_uint_32)png_sizeof(png_text));
  195456. if (text_ptr == NULL)
  195457. {
  195458. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195459. png_free(png_ptr, key);
  195460. return;
  195461. }
  195462. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195463. text_ptr->key = key;
  195464. #ifdef PNG_iTXt_SUPPORTED
  195465. text_ptr->lang = NULL;
  195466. text_ptr->lang_key = NULL;
  195467. text_ptr->itxt_length = 0;
  195468. #endif
  195469. text_ptr->text = text;
  195470. text_ptr->text_length = png_strlen(text);
  195471. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195472. png_free(png_ptr, key);
  195473. png_free(png_ptr, text_ptr);
  195474. if (ret)
  195475. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195476. }
  195477. #endif
  195478. #if defined(PNG_READ_zTXt_SUPPORTED)
  195479. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195480. void /* PRIVATE */
  195481. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195482. {
  195483. png_textp text_ptr;
  195484. png_charp chunkdata;
  195485. png_charp text;
  195486. int comp_type;
  195487. int ret;
  195488. png_size_t slength, prefix_len, data_len;
  195489. png_debug(1, "in png_handle_zTXt\n");
  195490. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195491. png_error(png_ptr, "Missing IHDR before zTXt");
  195492. if (png_ptr->mode & PNG_HAVE_IDAT)
  195493. png_ptr->mode |= PNG_AFTER_IDAT;
  195494. #ifdef PNG_MAX_MALLOC_64K
  195495. /* We will no doubt have problems with chunks even half this size, but
  195496. there is no hard and fast rule to tell us where to stop. */
  195497. if (length > (png_uint_32)65535L)
  195498. {
  195499. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195500. png_crc_finish(png_ptr, length);
  195501. return;
  195502. }
  195503. #endif
  195504. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195505. if (chunkdata == NULL)
  195506. {
  195507. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195508. return;
  195509. }
  195510. slength = (png_size_t)length;
  195511. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195512. if (png_crc_finish(png_ptr, 0))
  195513. {
  195514. png_free(png_ptr, chunkdata);
  195515. return;
  195516. }
  195517. chunkdata[slength] = 0x00;
  195518. for (text = chunkdata; *text; text++)
  195519. /* empty loop */ ;
  195520. /* zTXt must have some text after the chunkdataword */
  195521. if (text >= chunkdata + slength - 2)
  195522. {
  195523. png_warning(png_ptr, "Truncated zTXt chunk");
  195524. png_free(png_ptr, chunkdata);
  195525. return;
  195526. }
  195527. else
  195528. {
  195529. comp_type = *(++text);
  195530. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195531. {
  195532. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195533. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195534. }
  195535. text++; /* skip the compression_method byte */
  195536. }
  195537. prefix_len = text - chunkdata;
  195538. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195539. (png_size_t)length, prefix_len, &data_len);
  195540. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195541. (png_uint_32)png_sizeof(png_text));
  195542. if (text_ptr == NULL)
  195543. {
  195544. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195545. png_free(png_ptr, chunkdata);
  195546. return;
  195547. }
  195548. text_ptr->compression = comp_type;
  195549. text_ptr->key = chunkdata;
  195550. #ifdef PNG_iTXt_SUPPORTED
  195551. text_ptr->lang = NULL;
  195552. text_ptr->lang_key = NULL;
  195553. text_ptr->itxt_length = 0;
  195554. #endif
  195555. text_ptr->text = chunkdata + prefix_len;
  195556. text_ptr->text_length = data_len;
  195557. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195558. png_free(png_ptr, text_ptr);
  195559. png_free(png_ptr, chunkdata);
  195560. if (ret)
  195561. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195562. }
  195563. #endif
  195564. #if defined(PNG_READ_iTXt_SUPPORTED)
  195565. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195566. void /* PRIVATE */
  195567. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195568. {
  195569. png_textp text_ptr;
  195570. png_charp chunkdata;
  195571. png_charp key, lang, text, lang_key;
  195572. int comp_flag;
  195573. int comp_type = 0;
  195574. int ret;
  195575. png_size_t slength, prefix_len, data_len;
  195576. png_debug(1, "in png_handle_iTXt\n");
  195577. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195578. png_error(png_ptr, "Missing IHDR before iTXt");
  195579. if (png_ptr->mode & PNG_HAVE_IDAT)
  195580. png_ptr->mode |= PNG_AFTER_IDAT;
  195581. #ifdef PNG_MAX_MALLOC_64K
  195582. /* We will no doubt have problems with chunks even half this size, but
  195583. there is no hard and fast rule to tell us where to stop. */
  195584. if (length > (png_uint_32)65535L)
  195585. {
  195586. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195587. png_crc_finish(png_ptr, length);
  195588. return;
  195589. }
  195590. #endif
  195591. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195592. if (chunkdata == NULL)
  195593. {
  195594. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195595. return;
  195596. }
  195597. slength = (png_size_t)length;
  195598. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195599. if (png_crc_finish(png_ptr, 0))
  195600. {
  195601. png_free(png_ptr, chunkdata);
  195602. return;
  195603. }
  195604. chunkdata[slength] = 0x00;
  195605. for (lang = chunkdata; *lang; lang++)
  195606. /* empty loop */ ;
  195607. lang++; /* skip NUL separator */
  195608. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195609. translated keyword (possibly empty), and possibly some text after the
  195610. keyword */
  195611. if (lang >= chunkdata + slength - 3)
  195612. {
  195613. png_warning(png_ptr, "Truncated iTXt chunk");
  195614. png_free(png_ptr, chunkdata);
  195615. return;
  195616. }
  195617. else
  195618. {
  195619. comp_flag = *lang++;
  195620. comp_type = *lang++;
  195621. }
  195622. for (lang_key = lang; *lang_key; lang_key++)
  195623. /* empty loop */ ;
  195624. lang_key++; /* skip NUL separator */
  195625. if (lang_key >= chunkdata + slength)
  195626. {
  195627. png_warning(png_ptr, "Truncated iTXt chunk");
  195628. png_free(png_ptr, chunkdata);
  195629. return;
  195630. }
  195631. for (text = lang_key; *text; text++)
  195632. /* empty loop */ ;
  195633. text++; /* skip NUL separator */
  195634. if (text >= chunkdata + slength)
  195635. {
  195636. png_warning(png_ptr, "Malformed iTXt chunk");
  195637. png_free(png_ptr, chunkdata);
  195638. return;
  195639. }
  195640. prefix_len = text - chunkdata;
  195641. key=chunkdata;
  195642. if (comp_flag)
  195643. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195644. (size_t)length, prefix_len, &data_len);
  195645. else
  195646. data_len=png_strlen(chunkdata + prefix_len);
  195647. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195648. (png_uint_32)png_sizeof(png_text));
  195649. if (text_ptr == NULL)
  195650. {
  195651. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195652. png_free(png_ptr, chunkdata);
  195653. return;
  195654. }
  195655. text_ptr->compression = (int)comp_flag + 1;
  195656. text_ptr->lang_key = chunkdata+(lang_key-key);
  195657. text_ptr->lang = chunkdata+(lang-key);
  195658. text_ptr->itxt_length = data_len;
  195659. text_ptr->text_length = 0;
  195660. text_ptr->key = chunkdata;
  195661. text_ptr->text = chunkdata + prefix_len;
  195662. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195663. png_free(png_ptr, text_ptr);
  195664. png_free(png_ptr, chunkdata);
  195665. if (ret)
  195666. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195667. }
  195668. #endif
  195669. /* This function is called when we haven't found a handler for a
  195670. chunk. If there isn't a problem with the chunk itself (ie bad
  195671. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195672. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195673. case it will be saved away to be written out later. */
  195674. void /* PRIVATE */
  195675. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195676. {
  195677. png_uint_32 skip = 0;
  195678. png_debug(1, "in png_handle_unknown\n");
  195679. if (png_ptr->mode & PNG_HAVE_IDAT)
  195680. {
  195681. #ifdef PNG_USE_LOCAL_ARRAYS
  195682. PNG_CONST PNG_IDAT;
  195683. #endif
  195684. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195685. png_ptr->mode |= PNG_AFTER_IDAT;
  195686. }
  195687. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195688. if (!(png_ptr->chunk_name[0] & 0x20))
  195689. {
  195690. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195691. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195692. PNG_HANDLE_CHUNK_ALWAYS
  195693. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195694. && png_ptr->read_user_chunk_fn == NULL
  195695. #endif
  195696. )
  195697. #endif
  195698. png_chunk_error(png_ptr, "unknown critical chunk");
  195699. }
  195700. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195701. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195702. (png_ptr->read_user_chunk_fn != NULL))
  195703. {
  195704. #ifdef PNG_MAX_MALLOC_64K
  195705. if (length > (png_uint_32)65535L)
  195706. {
  195707. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195708. skip = length - (png_uint_32)65535L;
  195709. length = (png_uint_32)65535L;
  195710. }
  195711. #endif
  195712. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195713. (png_charp)png_ptr->chunk_name, 5);
  195714. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195715. png_ptr->unknown_chunk.size = (png_size_t)length;
  195716. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195717. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195718. if(png_ptr->read_user_chunk_fn != NULL)
  195719. {
  195720. /* callback to user unknown chunk handler */
  195721. int ret;
  195722. ret = (*(png_ptr->read_user_chunk_fn))
  195723. (png_ptr, &png_ptr->unknown_chunk);
  195724. if (ret < 0)
  195725. png_chunk_error(png_ptr, "error in user chunk");
  195726. if (ret == 0)
  195727. {
  195728. if (!(png_ptr->chunk_name[0] & 0x20))
  195729. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195730. PNG_HANDLE_CHUNK_ALWAYS)
  195731. png_chunk_error(png_ptr, "unknown critical chunk");
  195732. png_set_unknown_chunks(png_ptr, info_ptr,
  195733. &png_ptr->unknown_chunk, 1);
  195734. }
  195735. }
  195736. #else
  195737. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195738. #endif
  195739. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195740. png_ptr->unknown_chunk.data = NULL;
  195741. }
  195742. else
  195743. #endif
  195744. skip = length;
  195745. png_crc_finish(png_ptr, skip);
  195746. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195747. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195748. #endif
  195749. }
  195750. /* This function is called to verify that a chunk name is valid.
  195751. This function can't have the "critical chunk check" incorporated
  195752. into it, since in the future we will need to be able to call user
  195753. functions to handle unknown critical chunks after we check that
  195754. the chunk name itself is valid. */
  195755. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195756. void /* PRIVATE */
  195757. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195758. {
  195759. png_debug(1, "in png_check_chunk_name\n");
  195760. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195761. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195762. {
  195763. png_chunk_error(png_ptr, "invalid chunk type");
  195764. }
  195765. }
  195766. /* Combines the row recently read in with the existing pixels in the
  195767. row. This routine takes care of alpha and transparency if requested.
  195768. This routine also handles the two methods of progressive display
  195769. of interlaced images, depending on the mask value.
  195770. The mask value describes which pixels are to be combined with
  195771. the row. The pattern always repeats every 8 pixels, so just 8
  195772. bits are needed. A one indicates the pixel is to be combined,
  195773. a zero indicates the pixel is to be skipped. This is in addition
  195774. to any alpha or transparency value associated with the pixel. If
  195775. you want all pixels to be combined, pass 0xff (255) in mask. */
  195776. void /* PRIVATE */
  195777. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195778. {
  195779. png_debug(1,"in png_combine_row\n");
  195780. if (mask == 0xff)
  195781. {
  195782. png_memcpy(row, png_ptr->row_buf + 1,
  195783. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195784. }
  195785. else
  195786. {
  195787. switch (png_ptr->row_info.pixel_depth)
  195788. {
  195789. case 1:
  195790. {
  195791. png_bytep sp = png_ptr->row_buf + 1;
  195792. png_bytep dp = row;
  195793. int s_inc, s_start, s_end;
  195794. int m = 0x80;
  195795. int shift;
  195796. png_uint_32 i;
  195797. png_uint_32 row_width = png_ptr->width;
  195798. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195799. if (png_ptr->transformations & PNG_PACKSWAP)
  195800. {
  195801. s_start = 0;
  195802. s_end = 7;
  195803. s_inc = 1;
  195804. }
  195805. else
  195806. #endif
  195807. {
  195808. s_start = 7;
  195809. s_end = 0;
  195810. s_inc = -1;
  195811. }
  195812. shift = s_start;
  195813. for (i = 0; i < row_width; i++)
  195814. {
  195815. if (m & mask)
  195816. {
  195817. int value;
  195818. value = (*sp >> shift) & 0x01;
  195819. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195820. *dp |= (png_byte)(value << shift);
  195821. }
  195822. if (shift == s_end)
  195823. {
  195824. shift = s_start;
  195825. sp++;
  195826. dp++;
  195827. }
  195828. else
  195829. shift += s_inc;
  195830. if (m == 1)
  195831. m = 0x80;
  195832. else
  195833. m >>= 1;
  195834. }
  195835. break;
  195836. }
  195837. case 2:
  195838. {
  195839. png_bytep sp = png_ptr->row_buf + 1;
  195840. png_bytep dp = row;
  195841. int s_start, s_end, s_inc;
  195842. int m = 0x80;
  195843. int shift;
  195844. png_uint_32 i;
  195845. png_uint_32 row_width = png_ptr->width;
  195846. int value;
  195847. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195848. if (png_ptr->transformations & PNG_PACKSWAP)
  195849. {
  195850. s_start = 0;
  195851. s_end = 6;
  195852. s_inc = 2;
  195853. }
  195854. else
  195855. #endif
  195856. {
  195857. s_start = 6;
  195858. s_end = 0;
  195859. s_inc = -2;
  195860. }
  195861. shift = s_start;
  195862. for (i = 0; i < row_width; i++)
  195863. {
  195864. if (m & mask)
  195865. {
  195866. value = (*sp >> shift) & 0x03;
  195867. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195868. *dp |= (png_byte)(value << shift);
  195869. }
  195870. if (shift == s_end)
  195871. {
  195872. shift = s_start;
  195873. sp++;
  195874. dp++;
  195875. }
  195876. else
  195877. shift += s_inc;
  195878. if (m == 1)
  195879. m = 0x80;
  195880. else
  195881. m >>= 1;
  195882. }
  195883. break;
  195884. }
  195885. case 4:
  195886. {
  195887. png_bytep sp = png_ptr->row_buf + 1;
  195888. png_bytep dp = row;
  195889. int s_start, s_end, s_inc;
  195890. int m = 0x80;
  195891. int shift;
  195892. png_uint_32 i;
  195893. png_uint_32 row_width = png_ptr->width;
  195894. int value;
  195895. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195896. if (png_ptr->transformations & PNG_PACKSWAP)
  195897. {
  195898. s_start = 0;
  195899. s_end = 4;
  195900. s_inc = 4;
  195901. }
  195902. else
  195903. #endif
  195904. {
  195905. s_start = 4;
  195906. s_end = 0;
  195907. s_inc = -4;
  195908. }
  195909. shift = s_start;
  195910. for (i = 0; i < row_width; i++)
  195911. {
  195912. if (m & mask)
  195913. {
  195914. value = (*sp >> shift) & 0xf;
  195915. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195916. *dp |= (png_byte)(value << shift);
  195917. }
  195918. if (shift == s_end)
  195919. {
  195920. shift = s_start;
  195921. sp++;
  195922. dp++;
  195923. }
  195924. else
  195925. shift += s_inc;
  195926. if (m == 1)
  195927. m = 0x80;
  195928. else
  195929. m >>= 1;
  195930. }
  195931. break;
  195932. }
  195933. default:
  195934. {
  195935. png_bytep sp = png_ptr->row_buf + 1;
  195936. png_bytep dp = row;
  195937. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195938. png_uint_32 i;
  195939. png_uint_32 row_width = png_ptr->width;
  195940. png_byte m = 0x80;
  195941. for (i = 0; i < row_width; i++)
  195942. {
  195943. if (m & mask)
  195944. {
  195945. png_memcpy(dp, sp, pixel_bytes);
  195946. }
  195947. sp += pixel_bytes;
  195948. dp += pixel_bytes;
  195949. if (m == 1)
  195950. m = 0x80;
  195951. else
  195952. m >>= 1;
  195953. }
  195954. break;
  195955. }
  195956. }
  195957. }
  195958. }
  195959. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195960. /* OLD pre-1.0.9 interface:
  195961. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195962. png_uint_32 transformations)
  195963. */
  195964. void /* PRIVATE */
  195965. png_do_read_interlace(png_structp png_ptr)
  195966. {
  195967. png_row_infop row_info = &(png_ptr->row_info);
  195968. png_bytep row = png_ptr->row_buf + 1;
  195969. int pass = png_ptr->pass;
  195970. png_uint_32 transformations = png_ptr->transformations;
  195971. #ifdef PNG_USE_LOCAL_ARRAYS
  195972. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195973. /* offset to next interlace block */
  195974. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195975. #endif
  195976. png_debug(1,"in png_do_read_interlace\n");
  195977. if (row != NULL && row_info != NULL)
  195978. {
  195979. png_uint_32 final_width;
  195980. final_width = row_info->width * png_pass_inc[pass];
  195981. switch (row_info->pixel_depth)
  195982. {
  195983. case 1:
  195984. {
  195985. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195986. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195987. int sshift, dshift;
  195988. int s_start, s_end, s_inc;
  195989. int jstop = png_pass_inc[pass];
  195990. png_byte v;
  195991. png_uint_32 i;
  195992. int j;
  195993. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195994. if (transformations & PNG_PACKSWAP)
  195995. {
  195996. sshift = (int)((row_info->width + 7) & 0x07);
  195997. dshift = (int)((final_width + 7) & 0x07);
  195998. s_start = 7;
  195999. s_end = 0;
  196000. s_inc = -1;
  196001. }
  196002. else
  196003. #endif
  196004. {
  196005. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196006. dshift = 7 - (int)((final_width + 7) & 0x07);
  196007. s_start = 0;
  196008. s_end = 7;
  196009. s_inc = 1;
  196010. }
  196011. for (i = 0; i < row_info->width; i++)
  196012. {
  196013. v = (png_byte)((*sp >> sshift) & 0x01);
  196014. for (j = 0; j < jstop; j++)
  196015. {
  196016. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196017. *dp |= (png_byte)(v << dshift);
  196018. if (dshift == s_end)
  196019. {
  196020. dshift = s_start;
  196021. dp--;
  196022. }
  196023. else
  196024. dshift += s_inc;
  196025. }
  196026. if (sshift == s_end)
  196027. {
  196028. sshift = s_start;
  196029. sp--;
  196030. }
  196031. else
  196032. sshift += s_inc;
  196033. }
  196034. break;
  196035. }
  196036. case 2:
  196037. {
  196038. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196039. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196040. int sshift, dshift;
  196041. int s_start, s_end, s_inc;
  196042. int jstop = png_pass_inc[pass];
  196043. png_uint_32 i;
  196044. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196045. if (transformations & PNG_PACKSWAP)
  196046. {
  196047. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196048. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196049. s_start = 6;
  196050. s_end = 0;
  196051. s_inc = -2;
  196052. }
  196053. else
  196054. #endif
  196055. {
  196056. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196057. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196058. s_start = 0;
  196059. s_end = 6;
  196060. s_inc = 2;
  196061. }
  196062. for (i = 0; i < row_info->width; i++)
  196063. {
  196064. png_byte v;
  196065. int j;
  196066. v = (png_byte)((*sp >> sshift) & 0x03);
  196067. for (j = 0; j < jstop; j++)
  196068. {
  196069. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196070. *dp |= (png_byte)(v << dshift);
  196071. if (dshift == s_end)
  196072. {
  196073. dshift = s_start;
  196074. dp--;
  196075. }
  196076. else
  196077. dshift += s_inc;
  196078. }
  196079. if (sshift == s_end)
  196080. {
  196081. sshift = s_start;
  196082. sp--;
  196083. }
  196084. else
  196085. sshift += s_inc;
  196086. }
  196087. break;
  196088. }
  196089. case 4:
  196090. {
  196091. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196092. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196093. int sshift, dshift;
  196094. int s_start, s_end, s_inc;
  196095. png_uint_32 i;
  196096. int jstop = png_pass_inc[pass];
  196097. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196098. if (transformations & PNG_PACKSWAP)
  196099. {
  196100. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196101. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196102. s_start = 4;
  196103. s_end = 0;
  196104. s_inc = -4;
  196105. }
  196106. else
  196107. #endif
  196108. {
  196109. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196110. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196111. s_start = 0;
  196112. s_end = 4;
  196113. s_inc = 4;
  196114. }
  196115. for (i = 0; i < row_info->width; i++)
  196116. {
  196117. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196118. int j;
  196119. for (j = 0; j < jstop; j++)
  196120. {
  196121. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196122. *dp |= (png_byte)(v << dshift);
  196123. if (dshift == s_end)
  196124. {
  196125. dshift = s_start;
  196126. dp--;
  196127. }
  196128. else
  196129. dshift += s_inc;
  196130. }
  196131. if (sshift == s_end)
  196132. {
  196133. sshift = s_start;
  196134. sp--;
  196135. }
  196136. else
  196137. sshift += s_inc;
  196138. }
  196139. break;
  196140. }
  196141. default:
  196142. {
  196143. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196144. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196145. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196146. int jstop = png_pass_inc[pass];
  196147. png_uint_32 i;
  196148. for (i = 0; i < row_info->width; i++)
  196149. {
  196150. png_byte v[8];
  196151. int j;
  196152. png_memcpy(v, sp, pixel_bytes);
  196153. for (j = 0; j < jstop; j++)
  196154. {
  196155. png_memcpy(dp, v, pixel_bytes);
  196156. dp -= pixel_bytes;
  196157. }
  196158. sp -= pixel_bytes;
  196159. }
  196160. break;
  196161. }
  196162. }
  196163. row_info->width = final_width;
  196164. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196165. }
  196166. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196167. transformations = transformations; /* silence compiler warning */
  196168. #endif
  196169. }
  196170. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196171. void /* PRIVATE */
  196172. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196173. png_bytep prev_row, int filter)
  196174. {
  196175. png_debug(1, "in png_read_filter_row\n");
  196176. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196177. switch (filter)
  196178. {
  196179. case PNG_FILTER_VALUE_NONE:
  196180. break;
  196181. case PNG_FILTER_VALUE_SUB:
  196182. {
  196183. png_uint_32 i;
  196184. png_uint_32 istop = row_info->rowbytes;
  196185. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196186. png_bytep rp = row + bpp;
  196187. png_bytep lp = row;
  196188. for (i = bpp; i < istop; i++)
  196189. {
  196190. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196191. rp++;
  196192. }
  196193. break;
  196194. }
  196195. case PNG_FILTER_VALUE_UP:
  196196. {
  196197. png_uint_32 i;
  196198. png_uint_32 istop = row_info->rowbytes;
  196199. png_bytep rp = row;
  196200. png_bytep pp = prev_row;
  196201. for (i = 0; i < istop; i++)
  196202. {
  196203. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196204. rp++;
  196205. }
  196206. break;
  196207. }
  196208. case PNG_FILTER_VALUE_AVG:
  196209. {
  196210. png_uint_32 i;
  196211. png_bytep rp = row;
  196212. png_bytep pp = prev_row;
  196213. png_bytep lp = row;
  196214. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196215. png_uint_32 istop = row_info->rowbytes - bpp;
  196216. for (i = 0; i < bpp; i++)
  196217. {
  196218. *rp = (png_byte)(((int)(*rp) +
  196219. ((int)(*pp++) / 2 )) & 0xff);
  196220. rp++;
  196221. }
  196222. for (i = 0; i < istop; i++)
  196223. {
  196224. *rp = (png_byte)(((int)(*rp) +
  196225. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196226. rp++;
  196227. }
  196228. break;
  196229. }
  196230. case PNG_FILTER_VALUE_PAETH:
  196231. {
  196232. png_uint_32 i;
  196233. png_bytep rp = row;
  196234. png_bytep pp = prev_row;
  196235. png_bytep lp = row;
  196236. png_bytep cp = prev_row;
  196237. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196238. png_uint_32 istop=row_info->rowbytes - bpp;
  196239. for (i = 0; i < bpp; i++)
  196240. {
  196241. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196242. rp++;
  196243. }
  196244. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196245. {
  196246. int a, b, c, pa, pb, pc, p;
  196247. a = *lp++;
  196248. b = *pp++;
  196249. c = *cp++;
  196250. p = b - c;
  196251. pc = a - c;
  196252. #ifdef PNG_USE_ABS
  196253. pa = abs(p);
  196254. pb = abs(pc);
  196255. pc = abs(p + pc);
  196256. #else
  196257. pa = p < 0 ? -p : p;
  196258. pb = pc < 0 ? -pc : pc;
  196259. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196260. #endif
  196261. /*
  196262. if (pa <= pb && pa <= pc)
  196263. p = a;
  196264. else if (pb <= pc)
  196265. p = b;
  196266. else
  196267. p = c;
  196268. */
  196269. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196270. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196271. rp++;
  196272. }
  196273. break;
  196274. }
  196275. default:
  196276. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196277. *row=0;
  196278. break;
  196279. }
  196280. }
  196281. void /* PRIVATE */
  196282. png_read_finish_row(png_structp png_ptr)
  196283. {
  196284. #ifdef PNG_USE_LOCAL_ARRAYS
  196285. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196286. /* start of interlace block */
  196287. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196288. /* offset to next interlace block */
  196289. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196290. /* start of interlace block in the y direction */
  196291. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196292. /* offset to next interlace block in the y direction */
  196293. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196294. #endif
  196295. png_debug(1, "in png_read_finish_row\n");
  196296. png_ptr->row_number++;
  196297. if (png_ptr->row_number < png_ptr->num_rows)
  196298. return;
  196299. if (png_ptr->interlaced)
  196300. {
  196301. png_ptr->row_number = 0;
  196302. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196303. png_ptr->rowbytes + 1);
  196304. do
  196305. {
  196306. png_ptr->pass++;
  196307. if (png_ptr->pass >= 7)
  196308. break;
  196309. png_ptr->iwidth = (png_ptr->width +
  196310. png_pass_inc[png_ptr->pass] - 1 -
  196311. png_pass_start[png_ptr->pass]) /
  196312. png_pass_inc[png_ptr->pass];
  196313. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196314. png_ptr->iwidth) + 1;
  196315. if (!(png_ptr->transformations & PNG_INTERLACE))
  196316. {
  196317. png_ptr->num_rows = (png_ptr->height +
  196318. png_pass_yinc[png_ptr->pass] - 1 -
  196319. png_pass_ystart[png_ptr->pass]) /
  196320. png_pass_yinc[png_ptr->pass];
  196321. if (!(png_ptr->num_rows))
  196322. continue;
  196323. }
  196324. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196325. break;
  196326. } while (png_ptr->iwidth == 0);
  196327. if (png_ptr->pass < 7)
  196328. return;
  196329. }
  196330. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196331. {
  196332. #ifdef PNG_USE_LOCAL_ARRAYS
  196333. PNG_CONST PNG_IDAT;
  196334. #endif
  196335. char extra;
  196336. int ret;
  196337. png_ptr->zstream.next_out = (Bytef *)&extra;
  196338. png_ptr->zstream.avail_out = (uInt)1;
  196339. for(;;)
  196340. {
  196341. if (!(png_ptr->zstream.avail_in))
  196342. {
  196343. while (!png_ptr->idat_size)
  196344. {
  196345. png_byte chunk_length[4];
  196346. png_crc_finish(png_ptr, 0);
  196347. png_read_data(png_ptr, chunk_length, 4);
  196348. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196349. png_reset_crc(png_ptr);
  196350. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196351. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196352. png_error(png_ptr, "Not enough image data");
  196353. }
  196354. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196355. png_ptr->zstream.next_in = png_ptr->zbuf;
  196356. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196357. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196358. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196359. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196360. }
  196361. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196362. if (ret == Z_STREAM_END)
  196363. {
  196364. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196365. png_ptr->idat_size)
  196366. png_warning(png_ptr, "Extra compressed data");
  196367. png_ptr->mode |= PNG_AFTER_IDAT;
  196368. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196369. break;
  196370. }
  196371. if (ret != Z_OK)
  196372. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196373. "Decompression Error");
  196374. if (!(png_ptr->zstream.avail_out))
  196375. {
  196376. png_warning(png_ptr, "Extra compressed data.");
  196377. png_ptr->mode |= PNG_AFTER_IDAT;
  196378. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196379. break;
  196380. }
  196381. }
  196382. png_ptr->zstream.avail_out = 0;
  196383. }
  196384. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196385. png_warning(png_ptr, "Extra compression data");
  196386. inflateReset(&png_ptr->zstream);
  196387. png_ptr->mode |= PNG_AFTER_IDAT;
  196388. }
  196389. void /* PRIVATE */
  196390. png_read_start_row(png_structp png_ptr)
  196391. {
  196392. #ifdef PNG_USE_LOCAL_ARRAYS
  196393. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196394. /* start of interlace block */
  196395. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196396. /* offset to next interlace block */
  196397. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196398. /* start of interlace block in the y direction */
  196399. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196400. /* offset to next interlace block in the y direction */
  196401. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196402. #endif
  196403. int max_pixel_depth;
  196404. png_uint_32 row_bytes;
  196405. png_debug(1, "in png_read_start_row\n");
  196406. png_ptr->zstream.avail_in = 0;
  196407. png_init_read_transformations(png_ptr);
  196408. if (png_ptr->interlaced)
  196409. {
  196410. if (!(png_ptr->transformations & PNG_INTERLACE))
  196411. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196412. png_pass_ystart[0]) / png_pass_yinc[0];
  196413. else
  196414. png_ptr->num_rows = png_ptr->height;
  196415. png_ptr->iwidth = (png_ptr->width +
  196416. png_pass_inc[png_ptr->pass] - 1 -
  196417. png_pass_start[png_ptr->pass]) /
  196418. png_pass_inc[png_ptr->pass];
  196419. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196420. png_ptr->irowbytes = (png_size_t)row_bytes;
  196421. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196422. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196423. }
  196424. else
  196425. {
  196426. png_ptr->num_rows = png_ptr->height;
  196427. png_ptr->iwidth = png_ptr->width;
  196428. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196429. }
  196430. max_pixel_depth = png_ptr->pixel_depth;
  196431. #if defined(PNG_READ_PACK_SUPPORTED)
  196432. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196433. max_pixel_depth = 8;
  196434. #endif
  196435. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196436. if (png_ptr->transformations & PNG_EXPAND)
  196437. {
  196438. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196439. {
  196440. if (png_ptr->num_trans)
  196441. max_pixel_depth = 32;
  196442. else
  196443. max_pixel_depth = 24;
  196444. }
  196445. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196446. {
  196447. if (max_pixel_depth < 8)
  196448. max_pixel_depth = 8;
  196449. if (png_ptr->num_trans)
  196450. max_pixel_depth *= 2;
  196451. }
  196452. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196453. {
  196454. if (png_ptr->num_trans)
  196455. {
  196456. max_pixel_depth *= 4;
  196457. max_pixel_depth /= 3;
  196458. }
  196459. }
  196460. }
  196461. #endif
  196462. #if defined(PNG_READ_FILLER_SUPPORTED)
  196463. if (png_ptr->transformations & (PNG_FILLER))
  196464. {
  196465. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196466. max_pixel_depth = 32;
  196467. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196468. {
  196469. if (max_pixel_depth <= 8)
  196470. max_pixel_depth = 16;
  196471. else
  196472. max_pixel_depth = 32;
  196473. }
  196474. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196475. {
  196476. if (max_pixel_depth <= 32)
  196477. max_pixel_depth = 32;
  196478. else
  196479. max_pixel_depth = 64;
  196480. }
  196481. }
  196482. #endif
  196483. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196484. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196485. {
  196486. if (
  196487. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196488. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196489. #endif
  196490. #if defined(PNG_READ_FILLER_SUPPORTED)
  196491. (png_ptr->transformations & (PNG_FILLER)) ||
  196492. #endif
  196493. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196494. {
  196495. if (max_pixel_depth <= 16)
  196496. max_pixel_depth = 32;
  196497. else
  196498. max_pixel_depth = 64;
  196499. }
  196500. else
  196501. {
  196502. if (max_pixel_depth <= 8)
  196503. {
  196504. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196505. max_pixel_depth = 32;
  196506. else
  196507. max_pixel_depth = 24;
  196508. }
  196509. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196510. max_pixel_depth = 64;
  196511. else
  196512. max_pixel_depth = 48;
  196513. }
  196514. }
  196515. #endif
  196516. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196517. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196518. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196519. {
  196520. int user_pixel_depth=png_ptr->user_transform_depth*
  196521. png_ptr->user_transform_channels;
  196522. if(user_pixel_depth > max_pixel_depth)
  196523. max_pixel_depth=user_pixel_depth;
  196524. }
  196525. #endif
  196526. /* align the width on the next larger 8 pixels. Mainly used
  196527. for interlacing */
  196528. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196529. /* calculate the maximum bytes needed, adding a byte and a pixel
  196530. for safety's sake */
  196531. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196532. 1 + ((max_pixel_depth + 7) >> 3);
  196533. #ifdef PNG_MAX_MALLOC_64K
  196534. if (row_bytes > (png_uint_32)65536L)
  196535. png_error(png_ptr, "This image requires a row greater than 64KB");
  196536. #endif
  196537. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196538. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196539. #ifdef PNG_MAX_MALLOC_64K
  196540. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196541. png_error(png_ptr, "This image requires a row greater than 64KB");
  196542. #endif
  196543. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196544. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196545. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196546. png_ptr->rowbytes + 1));
  196547. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196548. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196549. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196550. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196551. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196552. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196553. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196554. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196555. }
  196556. #endif /* PNG_READ_SUPPORTED */
  196557. /*** End of inlined file: pngrutil.c ***/
  196558. /*** Start of inlined file: pngset.c ***/
  196559. /* pngset.c - storage of image information into info struct
  196560. *
  196561. * Last changed in libpng 1.2.21 [October 4, 2007]
  196562. * For conditions of distribution and use, see copyright notice in png.h
  196563. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196564. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196565. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196566. *
  196567. * The functions here are used during reads to store data from the file
  196568. * into the info struct, and during writes to store application data
  196569. * into the info struct for writing into the file. This abstracts the
  196570. * info struct and allows us to change the structure in the future.
  196571. */
  196572. #define PNG_INTERNAL
  196573. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196574. #if defined(PNG_bKGD_SUPPORTED)
  196575. void PNGAPI
  196576. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196577. {
  196578. png_debug1(1, "in %s storage function\n", "bKGD");
  196579. if (png_ptr == NULL || info_ptr == NULL)
  196580. return;
  196581. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196582. info_ptr->valid |= PNG_INFO_bKGD;
  196583. }
  196584. #endif
  196585. #if defined(PNG_cHRM_SUPPORTED)
  196586. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196587. void PNGAPI
  196588. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196589. double white_x, double white_y, double red_x, double red_y,
  196590. double green_x, double green_y, double blue_x, double blue_y)
  196591. {
  196592. png_debug1(1, "in %s storage function\n", "cHRM");
  196593. if (png_ptr == NULL || info_ptr == NULL)
  196594. return;
  196595. if (white_x < 0.0 || white_y < 0.0 ||
  196596. red_x < 0.0 || red_y < 0.0 ||
  196597. green_x < 0.0 || green_y < 0.0 ||
  196598. blue_x < 0.0 || blue_y < 0.0)
  196599. {
  196600. png_warning(png_ptr,
  196601. "Ignoring attempt to set negative chromaticity value");
  196602. return;
  196603. }
  196604. if (white_x > 21474.83 || white_y > 21474.83 ||
  196605. red_x > 21474.83 || red_y > 21474.83 ||
  196606. green_x > 21474.83 || green_y > 21474.83 ||
  196607. blue_x > 21474.83 || blue_y > 21474.83)
  196608. {
  196609. png_warning(png_ptr,
  196610. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196611. return;
  196612. }
  196613. info_ptr->x_white = (float)white_x;
  196614. info_ptr->y_white = (float)white_y;
  196615. info_ptr->x_red = (float)red_x;
  196616. info_ptr->y_red = (float)red_y;
  196617. info_ptr->x_green = (float)green_x;
  196618. info_ptr->y_green = (float)green_y;
  196619. info_ptr->x_blue = (float)blue_x;
  196620. info_ptr->y_blue = (float)blue_y;
  196621. #ifdef PNG_FIXED_POINT_SUPPORTED
  196622. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196623. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196624. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196625. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196626. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196627. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196628. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196629. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196630. #endif
  196631. info_ptr->valid |= PNG_INFO_cHRM;
  196632. }
  196633. #endif
  196634. #ifdef PNG_FIXED_POINT_SUPPORTED
  196635. void PNGAPI
  196636. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196637. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196638. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196639. png_fixed_point blue_x, png_fixed_point blue_y)
  196640. {
  196641. png_debug1(1, "in %s storage function\n", "cHRM");
  196642. if (png_ptr == NULL || info_ptr == NULL)
  196643. return;
  196644. if (white_x < 0 || white_y < 0 ||
  196645. red_x < 0 || red_y < 0 ||
  196646. green_x < 0 || green_y < 0 ||
  196647. blue_x < 0 || blue_y < 0)
  196648. {
  196649. png_warning(png_ptr,
  196650. "Ignoring attempt to set negative chromaticity value");
  196651. return;
  196652. }
  196653. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196654. if (white_x > (double) PNG_UINT_31_MAX ||
  196655. white_y > (double) PNG_UINT_31_MAX ||
  196656. red_x > (double) PNG_UINT_31_MAX ||
  196657. red_y > (double) PNG_UINT_31_MAX ||
  196658. green_x > (double) PNG_UINT_31_MAX ||
  196659. green_y > (double) PNG_UINT_31_MAX ||
  196660. blue_x > (double) PNG_UINT_31_MAX ||
  196661. blue_y > (double) PNG_UINT_31_MAX)
  196662. #else
  196663. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196664. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196665. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196666. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196667. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196668. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196669. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196670. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196671. #endif
  196672. {
  196673. png_warning(png_ptr,
  196674. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196675. return;
  196676. }
  196677. info_ptr->int_x_white = white_x;
  196678. info_ptr->int_y_white = white_y;
  196679. info_ptr->int_x_red = red_x;
  196680. info_ptr->int_y_red = red_y;
  196681. info_ptr->int_x_green = green_x;
  196682. info_ptr->int_y_green = green_y;
  196683. info_ptr->int_x_blue = blue_x;
  196684. info_ptr->int_y_blue = blue_y;
  196685. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196686. info_ptr->x_white = (float)(white_x/100000.);
  196687. info_ptr->y_white = (float)(white_y/100000.);
  196688. info_ptr->x_red = (float)( red_x/100000.);
  196689. info_ptr->y_red = (float)( red_y/100000.);
  196690. info_ptr->x_green = (float)(green_x/100000.);
  196691. info_ptr->y_green = (float)(green_y/100000.);
  196692. info_ptr->x_blue = (float)( blue_x/100000.);
  196693. info_ptr->y_blue = (float)( blue_y/100000.);
  196694. #endif
  196695. info_ptr->valid |= PNG_INFO_cHRM;
  196696. }
  196697. #endif
  196698. #endif
  196699. #if defined(PNG_gAMA_SUPPORTED)
  196700. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196701. void PNGAPI
  196702. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196703. {
  196704. double gamma;
  196705. png_debug1(1, "in %s storage function\n", "gAMA");
  196706. if (png_ptr == NULL || info_ptr == NULL)
  196707. return;
  196708. /* Check for overflow */
  196709. if (file_gamma > 21474.83)
  196710. {
  196711. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196712. gamma=21474.83;
  196713. }
  196714. else
  196715. gamma=file_gamma;
  196716. info_ptr->gamma = (float)gamma;
  196717. #ifdef PNG_FIXED_POINT_SUPPORTED
  196718. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196719. #endif
  196720. info_ptr->valid |= PNG_INFO_gAMA;
  196721. if(gamma == 0.0)
  196722. png_warning(png_ptr, "Setting gamma=0");
  196723. }
  196724. #endif
  196725. void PNGAPI
  196726. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196727. int_gamma)
  196728. {
  196729. png_fixed_point gamma;
  196730. png_debug1(1, "in %s storage function\n", "gAMA");
  196731. if (png_ptr == NULL || info_ptr == NULL)
  196732. return;
  196733. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196734. {
  196735. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196736. gamma=PNG_UINT_31_MAX;
  196737. }
  196738. else
  196739. {
  196740. if (int_gamma < 0)
  196741. {
  196742. png_warning(png_ptr, "Setting negative gamma to zero");
  196743. gamma=0;
  196744. }
  196745. else
  196746. gamma=int_gamma;
  196747. }
  196748. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196749. info_ptr->gamma = (float)(gamma/100000.);
  196750. #endif
  196751. #ifdef PNG_FIXED_POINT_SUPPORTED
  196752. info_ptr->int_gamma = gamma;
  196753. #endif
  196754. info_ptr->valid |= PNG_INFO_gAMA;
  196755. if(gamma == 0)
  196756. png_warning(png_ptr, "Setting gamma=0");
  196757. }
  196758. #endif
  196759. #if defined(PNG_hIST_SUPPORTED)
  196760. void PNGAPI
  196761. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196762. {
  196763. int i;
  196764. png_debug1(1, "in %s storage function\n", "hIST");
  196765. if (png_ptr == NULL || info_ptr == NULL)
  196766. return;
  196767. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196768. > PNG_MAX_PALETTE_LENGTH)
  196769. {
  196770. png_warning(png_ptr,
  196771. "Invalid palette size, hIST allocation skipped.");
  196772. return;
  196773. }
  196774. #ifdef PNG_FREE_ME_SUPPORTED
  196775. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196776. #endif
  196777. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196778. 1.2.1 */
  196779. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196780. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196781. if (png_ptr->hist == NULL)
  196782. {
  196783. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196784. return;
  196785. }
  196786. for (i = 0; i < info_ptr->num_palette; i++)
  196787. png_ptr->hist[i] = hist[i];
  196788. info_ptr->hist = png_ptr->hist;
  196789. info_ptr->valid |= PNG_INFO_hIST;
  196790. #ifdef PNG_FREE_ME_SUPPORTED
  196791. info_ptr->free_me |= PNG_FREE_HIST;
  196792. #else
  196793. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196794. #endif
  196795. }
  196796. #endif
  196797. void PNGAPI
  196798. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196799. png_uint_32 width, png_uint_32 height, int bit_depth,
  196800. int color_type, int interlace_type, int compression_type,
  196801. int filter_type)
  196802. {
  196803. png_debug1(1, "in %s storage function\n", "IHDR");
  196804. if (png_ptr == NULL || info_ptr == NULL)
  196805. return;
  196806. /* check for width and height valid values */
  196807. if (width == 0 || height == 0)
  196808. png_error(png_ptr, "Image width or height is zero in IHDR");
  196809. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196810. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196811. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196812. #else
  196813. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196814. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196815. #endif
  196816. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196817. png_error(png_ptr, "Invalid image size in IHDR");
  196818. if ( width > (PNG_UINT_32_MAX
  196819. >> 3) /* 8-byte RGBA pixels */
  196820. - 64 /* bigrowbuf hack */
  196821. - 1 /* filter byte */
  196822. - 7*8 /* rounding of width to multiple of 8 pixels */
  196823. - 8) /* extra max_pixel_depth pad */
  196824. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196825. /* check other values */
  196826. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196827. bit_depth != 8 && bit_depth != 16)
  196828. png_error(png_ptr, "Invalid bit depth in IHDR");
  196829. if (color_type < 0 || color_type == 1 ||
  196830. color_type == 5 || color_type > 6)
  196831. png_error(png_ptr, "Invalid color type in IHDR");
  196832. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196833. ((color_type == PNG_COLOR_TYPE_RGB ||
  196834. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196835. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196836. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196837. if (interlace_type >= PNG_INTERLACE_LAST)
  196838. png_error(png_ptr, "Unknown interlace method in IHDR");
  196839. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196840. png_error(png_ptr, "Unknown compression method in IHDR");
  196841. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196842. /* Accept filter_method 64 (intrapixel differencing) only if
  196843. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196844. * 2. Libpng did not read a PNG signature (this filter_method is only
  196845. * used in PNG datastreams that are embedded in MNG datastreams) and
  196846. * 3. The application called png_permit_mng_features with a mask that
  196847. * included PNG_FLAG_MNG_FILTER_64 and
  196848. * 4. The filter_method is 64 and
  196849. * 5. The color_type is RGB or RGBA
  196850. */
  196851. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196852. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196853. if(filter_type != PNG_FILTER_TYPE_BASE)
  196854. {
  196855. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196856. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196857. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196858. (color_type == PNG_COLOR_TYPE_RGB ||
  196859. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196860. png_error(png_ptr, "Unknown filter method in IHDR");
  196861. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196862. png_warning(png_ptr, "Invalid filter method in IHDR");
  196863. }
  196864. #else
  196865. if(filter_type != PNG_FILTER_TYPE_BASE)
  196866. png_error(png_ptr, "Unknown filter method in IHDR");
  196867. #endif
  196868. info_ptr->width = width;
  196869. info_ptr->height = height;
  196870. info_ptr->bit_depth = (png_byte)bit_depth;
  196871. info_ptr->color_type =(png_byte) color_type;
  196872. info_ptr->compression_type = (png_byte)compression_type;
  196873. info_ptr->filter_type = (png_byte)filter_type;
  196874. info_ptr->interlace_type = (png_byte)interlace_type;
  196875. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196876. info_ptr->channels = 1;
  196877. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196878. info_ptr->channels = 3;
  196879. else
  196880. info_ptr->channels = 1;
  196881. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196882. info_ptr->channels++;
  196883. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196884. /* check for potential overflow */
  196885. if (width > (PNG_UINT_32_MAX
  196886. >> 3) /* 8-byte RGBA pixels */
  196887. - 64 /* bigrowbuf hack */
  196888. - 1 /* filter byte */
  196889. - 7*8 /* rounding of width to multiple of 8 pixels */
  196890. - 8) /* extra max_pixel_depth pad */
  196891. info_ptr->rowbytes = (png_size_t)0;
  196892. else
  196893. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196894. }
  196895. #if defined(PNG_oFFs_SUPPORTED)
  196896. void PNGAPI
  196897. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196898. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196899. {
  196900. png_debug1(1, "in %s storage function\n", "oFFs");
  196901. if (png_ptr == NULL || info_ptr == NULL)
  196902. return;
  196903. info_ptr->x_offset = offset_x;
  196904. info_ptr->y_offset = offset_y;
  196905. info_ptr->offset_unit_type = (png_byte)unit_type;
  196906. info_ptr->valid |= PNG_INFO_oFFs;
  196907. }
  196908. #endif
  196909. #if defined(PNG_pCAL_SUPPORTED)
  196910. void PNGAPI
  196911. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196912. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196913. png_charp units, png_charpp params)
  196914. {
  196915. png_uint_32 length;
  196916. int i;
  196917. png_debug1(1, "in %s storage function\n", "pCAL");
  196918. if (png_ptr == NULL || info_ptr == NULL)
  196919. return;
  196920. length = png_strlen(purpose) + 1;
  196921. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196922. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196923. if (info_ptr->pcal_purpose == NULL)
  196924. {
  196925. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196926. return;
  196927. }
  196928. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196929. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196930. info_ptr->pcal_X0 = X0;
  196931. info_ptr->pcal_X1 = X1;
  196932. info_ptr->pcal_type = (png_byte)type;
  196933. info_ptr->pcal_nparams = (png_byte)nparams;
  196934. length = png_strlen(units) + 1;
  196935. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196936. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196937. if (info_ptr->pcal_units == NULL)
  196938. {
  196939. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196940. return;
  196941. }
  196942. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196943. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196944. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196945. if (info_ptr->pcal_params == NULL)
  196946. {
  196947. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196948. return;
  196949. }
  196950. info_ptr->pcal_params[nparams] = NULL;
  196951. for (i = 0; i < nparams; i++)
  196952. {
  196953. length = png_strlen(params[i]) + 1;
  196954. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196955. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196956. if (info_ptr->pcal_params[i] == NULL)
  196957. {
  196958. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196959. return;
  196960. }
  196961. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196962. }
  196963. info_ptr->valid |= PNG_INFO_pCAL;
  196964. #ifdef PNG_FREE_ME_SUPPORTED
  196965. info_ptr->free_me |= PNG_FREE_PCAL;
  196966. #endif
  196967. }
  196968. #endif
  196969. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196970. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196971. void PNGAPI
  196972. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196973. int unit, double width, double height)
  196974. {
  196975. png_debug1(1, "in %s storage function\n", "sCAL");
  196976. if (png_ptr == NULL || info_ptr == NULL)
  196977. return;
  196978. info_ptr->scal_unit = (png_byte)unit;
  196979. info_ptr->scal_pixel_width = width;
  196980. info_ptr->scal_pixel_height = height;
  196981. info_ptr->valid |= PNG_INFO_sCAL;
  196982. }
  196983. #else
  196984. #ifdef PNG_FIXED_POINT_SUPPORTED
  196985. void PNGAPI
  196986. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196987. int unit, png_charp swidth, png_charp sheight)
  196988. {
  196989. png_uint_32 length;
  196990. png_debug1(1, "in %s storage function\n", "sCAL");
  196991. if (png_ptr == NULL || info_ptr == NULL)
  196992. return;
  196993. info_ptr->scal_unit = (png_byte)unit;
  196994. length = png_strlen(swidth) + 1;
  196995. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196996. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196997. if (info_ptr->scal_s_width == NULL)
  196998. {
  196999. png_warning(png_ptr,
  197000. "Memory allocation failed while processing sCAL.");
  197001. }
  197002. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197003. length = png_strlen(sheight) + 1;
  197004. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197005. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197006. if (info_ptr->scal_s_height == NULL)
  197007. {
  197008. png_free (png_ptr, info_ptr->scal_s_width);
  197009. png_warning(png_ptr,
  197010. "Memory allocation failed while processing sCAL.");
  197011. }
  197012. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197013. info_ptr->valid |= PNG_INFO_sCAL;
  197014. #ifdef PNG_FREE_ME_SUPPORTED
  197015. info_ptr->free_me |= PNG_FREE_SCAL;
  197016. #endif
  197017. }
  197018. #endif
  197019. #endif
  197020. #endif
  197021. #if defined(PNG_pHYs_SUPPORTED)
  197022. void PNGAPI
  197023. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197024. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197025. {
  197026. png_debug1(1, "in %s storage function\n", "pHYs");
  197027. if (png_ptr == NULL || info_ptr == NULL)
  197028. return;
  197029. info_ptr->x_pixels_per_unit = res_x;
  197030. info_ptr->y_pixels_per_unit = res_y;
  197031. info_ptr->phys_unit_type = (png_byte)unit_type;
  197032. info_ptr->valid |= PNG_INFO_pHYs;
  197033. }
  197034. #endif
  197035. void PNGAPI
  197036. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197037. png_colorp palette, int num_palette)
  197038. {
  197039. png_debug1(1, "in %s storage function\n", "PLTE");
  197040. if (png_ptr == NULL || info_ptr == NULL)
  197041. return;
  197042. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197043. {
  197044. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197045. png_error(png_ptr, "Invalid palette length");
  197046. else
  197047. {
  197048. png_warning(png_ptr, "Invalid palette length");
  197049. return;
  197050. }
  197051. }
  197052. /*
  197053. * It may not actually be necessary to set png_ptr->palette here;
  197054. * we do it for backward compatibility with the way the png_handle_tRNS
  197055. * function used to do the allocation.
  197056. */
  197057. #ifdef PNG_FREE_ME_SUPPORTED
  197058. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197059. #endif
  197060. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197061. of num_palette entries,
  197062. in case of an invalid PNG file that has too-large sample values. */
  197063. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197064. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197065. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197066. png_sizeof(png_color));
  197067. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197068. info_ptr->palette = png_ptr->palette;
  197069. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197070. #ifdef PNG_FREE_ME_SUPPORTED
  197071. info_ptr->free_me |= PNG_FREE_PLTE;
  197072. #else
  197073. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197074. #endif
  197075. info_ptr->valid |= PNG_INFO_PLTE;
  197076. }
  197077. #if defined(PNG_sBIT_SUPPORTED)
  197078. void PNGAPI
  197079. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197080. png_color_8p sig_bit)
  197081. {
  197082. png_debug1(1, "in %s storage function\n", "sBIT");
  197083. if (png_ptr == NULL || info_ptr == NULL)
  197084. return;
  197085. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197086. info_ptr->valid |= PNG_INFO_sBIT;
  197087. }
  197088. #endif
  197089. #if defined(PNG_sRGB_SUPPORTED)
  197090. void PNGAPI
  197091. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197092. {
  197093. png_debug1(1, "in %s storage function\n", "sRGB");
  197094. if (png_ptr == NULL || info_ptr == NULL)
  197095. return;
  197096. info_ptr->srgb_intent = (png_byte)intent;
  197097. info_ptr->valid |= PNG_INFO_sRGB;
  197098. }
  197099. void PNGAPI
  197100. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197101. int intent)
  197102. {
  197103. #if defined(PNG_gAMA_SUPPORTED)
  197104. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197105. float file_gamma;
  197106. #endif
  197107. #ifdef PNG_FIXED_POINT_SUPPORTED
  197108. png_fixed_point int_file_gamma;
  197109. #endif
  197110. #endif
  197111. #if defined(PNG_cHRM_SUPPORTED)
  197112. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197113. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197114. #endif
  197115. #ifdef PNG_FIXED_POINT_SUPPORTED
  197116. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197117. int_green_y, int_blue_x, int_blue_y;
  197118. #endif
  197119. #endif
  197120. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197121. if (png_ptr == NULL || info_ptr == NULL)
  197122. return;
  197123. png_set_sRGB(png_ptr, info_ptr, intent);
  197124. #if defined(PNG_gAMA_SUPPORTED)
  197125. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197126. file_gamma = (float).45455;
  197127. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197128. #endif
  197129. #ifdef PNG_FIXED_POINT_SUPPORTED
  197130. int_file_gamma = 45455L;
  197131. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197132. #endif
  197133. #endif
  197134. #if defined(PNG_cHRM_SUPPORTED)
  197135. #ifdef PNG_FIXED_POINT_SUPPORTED
  197136. int_white_x = 31270L;
  197137. int_white_y = 32900L;
  197138. int_red_x = 64000L;
  197139. int_red_y = 33000L;
  197140. int_green_x = 30000L;
  197141. int_green_y = 60000L;
  197142. int_blue_x = 15000L;
  197143. int_blue_y = 6000L;
  197144. png_set_cHRM_fixed(png_ptr, info_ptr,
  197145. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197146. int_blue_x, int_blue_y);
  197147. #endif
  197148. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197149. white_x = (float).3127;
  197150. white_y = (float).3290;
  197151. red_x = (float).64;
  197152. red_y = (float).33;
  197153. green_x = (float).30;
  197154. green_y = (float).60;
  197155. blue_x = (float).15;
  197156. blue_y = (float).06;
  197157. png_set_cHRM(png_ptr, info_ptr,
  197158. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197159. #endif
  197160. #endif
  197161. }
  197162. #endif
  197163. #if defined(PNG_iCCP_SUPPORTED)
  197164. void PNGAPI
  197165. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197166. png_charp name, int compression_type,
  197167. png_charp profile, png_uint_32 proflen)
  197168. {
  197169. png_charp new_iccp_name;
  197170. png_charp new_iccp_profile;
  197171. png_debug1(1, "in %s storage function\n", "iCCP");
  197172. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197173. return;
  197174. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197175. if (new_iccp_name == NULL)
  197176. {
  197177. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197178. return;
  197179. }
  197180. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197181. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197182. if (new_iccp_profile == NULL)
  197183. {
  197184. png_free (png_ptr, new_iccp_name);
  197185. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197186. return;
  197187. }
  197188. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197189. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197190. info_ptr->iccp_proflen = proflen;
  197191. info_ptr->iccp_name = new_iccp_name;
  197192. info_ptr->iccp_profile = new_iccp_profile;
  197193. /* Compression is always zero but is here so the API and info structure
  197194. * does not have to change if we introduce multiple compression types */
  197195. info_ptr->iccp_compression = (png_byte)compression_type;
  197196. #ifdef PNG_FREE_ME_SUPPORTED
  197197. info_ptr->free_me |= PNG_FREE_ICCP;
  197198. #endif
  197199. info_ptr->valid |= PNG_INFO_iCCP;
  197200. }
  197201. #endif
  197202. #if defined(PNG_TEXT_SUPPORTED)
  197203. void PNGAPI
  197204. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197205. int num_text)
  197206. {
  197207. int ret;
  197208. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197209. if (ret)
  197210. png_error(png_ptr, "Insufficient memory to store text");
  197211. }
  197212. int /* PRIVATE */
  197213. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197214. int num_text)
  197215. {
  197216. int i;
  197217. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197218. "text" : (png_const_charp)png_ptr->chunk_name));
  197219. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197220. return(0);
  197221. /* Make sure we have enough space in the "text" array in info_struct
  197222. * to hold all of the incoming text_ptr objects.
  197223. */
  197224. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197225. {
  197226. if (info_ptr->text != NULL)
  197227. {
  197228. png_textp old_text;
  197229. int old_max;
  197230. old_max = info_ptr->max_text;
  197231. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197232. old_text = info_ptr->text;
  197233. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197234. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197235. if (info_ptr->text == NULL)
  197236. {
  197237. png_free(png_ptr, old_text);
  197238. return(1);
  197239. }
  197240. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197241. png_sizeof(png_text)));
  197242. png_free(png_ptr, old_text);
  197243. }
  197244. else
  197245. {
  197246. info_ptr->max_text = num_text + 8;
  197247. info_ptr->num_text = 0;
  197248. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197249. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197250. if (info_ptr->text == NULL)
  197251. return(1);
  197252. #ifdef PNG_FREE_ME_SUPPORTED
  197253. info_ptr->free_me |= PNG_FREE_TEXT;
  197254. #endif
  197255. }
  197256. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197257. info_ptr->max_text);
  197258. }
  197259. for (i = 0; i < num_text; i++)
  197260. {
  197261. png_size_t text_length,key_len;
  197262. png_size_t lang_len,lang_key_len;
  197263. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197264. if (text_ptr[i].key == NULL)
  197265. continue;
  197266. key_len = png_strlen(text_ptr[i].key);
  197267. if(text_ptr[i].compression <= 0)
  197268. {
  197269. lang_len = 0;
  197270. lang_key_len = 0;
  197271. }
  197272. else
  197273. #ifdef PNG_iTXt_SUPPORTED
  197274. {
  197275. /* set iTXt data */
  197276. if (text_ptr[i].lang != NULL)
  197277. lang_len = png_strlen(text_ptr[i].lang);
  197278. else
  197279. lang_len = 0;
  197280. if (text_ptr[i].lang_key != NULL)
  197281. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197282. else
  197283. lang_key_len = 0;
  197284. }
  197285. #else
  197286. {
  197287. png_warning(png_ptr, "iTXt chunk not supported.");
  197288. continue;
  197289. }
  197290. #endif
  197291. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197292. {
  197293. text_length = 0;
  197294. #ifdef PNG_iTXt_SUPPORTED
  197295. if(text_ptr[i].compression > 0)
  197296. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197297. else
  197298. #endif
  197299. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197300. }
  197301. else
  197302. {
  197303. text_length = png_strlen(text_ptr[i].text);
  197304. textp->compression = text_ptr[i].compression;
  197305. }
  197306. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197307. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197308. if (textp->key == NULL)
  197309. return(1);
  197310. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197311. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197312. (int)textp->key);
  197313. png_memcpy(textp->key, text_ptr[i].key,
  197314. (png_size_t)(key_len));
  197315. *(textp->key+key_len) = '\0';
  197316. #ifdef PNG_iTXt_SUPPORTED
  197317. if (text_ptr[i].compression > 0)
  197318. {
  197319. textp->lang=textp->key + key_len + 1;
  197320. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197321. *(textp->lang+lang_len) = '\0';
  197322. textp->lang_key=textp->lang + lang_len + 1;
  197323. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197324. *(textp->lang_key+lang_key_len) = '\0';
  197325. textp->text=textp->lang_key + lang_key_len + 1;
  197326. }
  197327. else
  197328. #endif
  197329. {
  197330. #ifdef PNG_iTXt_SUPPORTED
  197331. textp->lang=NULL;
  197332. textp->lang_key=NULL;
  197333. #endif
  197334. textp->text=textp->key + key_len + 1;
  197335. }
  197336. if(text_length)
  197337. png_memcpy(textp->text, text_ptr[i].text,
  197338. (png_size_t)(text_length));
  197339. *(textp->text+text_length) = '\0';
  197340. #ifdef PNG_iTXt_SUPPORTED
  197341. if(textp->compression > 0)
  197342. {
  197343. textp->text_length = 0;
  197344. textp->itxt_length = text_length;
  197345. }
  197346. else
  197347. #endif
  197348. {
  197349. textp->text_length = text_length;
  197350. #ifdef PNG_iTXt_SUPPORTED
  197351. textp->itxt_length = 0;
  197352. #endif
  197353. }
  197354. info_ptr->num_text++;
  197355. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197356. }
  197357. return(0);
  197358. }
  197359. #endif
  197360. #if defined(PNG_tIME_SUPPORTED)
  197361. void PNGAPI
  197362. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197363. {
  197364. png_debug1(1, "in %s storage function\n", "tIME");
  197365. if (png_ptr == NULL || info_ptr == NULL ||
  197366. (png_ptr->mode & PNG_WROTE_tIME))
  197367. return;
  197368. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197369. info_ptr->valid |= PNG_INFO_tIME;
  197370. }
  197371. #endif
  197372. #if defined(PNG_tRNS_SUPPORTED)
  197373. void PNGAPI
  197374. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197375. png_bytep trans, int num_trans, png_color_16p trans_values)
  197376. {
  197377. png_debug1(1, "in %s storage function\n", "tRNS");
  197378. if (png_ptr == NULL || info_ptr == NULL)
  197379. return;
  197380. if (trans != NULL)
  197381. {
  197382. /*
  197383. * It may not actually be necessary to set png_ptr->trans here;
  197384. * we do it for backward compatibility with the way the png_handle_tRNS
  197385. * function used to do the allocation.
  197386. */
  197387. #ifdef PNG_FREE_ME_SUPPORTED
  197388. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197389. #endif
  197390. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197391. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197392. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197393. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197394. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197395. #ifdef PNG_FREE_ME_SUPPORTED
  197396. info_ptr->free_me |= PNG_FREE_TRNS;
  197397. #else
  197398. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197399. #endif
  197400. }
  197401. if (trans_values != NULL)
  197402. {
  197403. png_memcpy(&(info_ptr->trans_values), trans_values,
  197404. png_sizeof(png_color_16));
  197405. if (num_trans == 0)
  197406. num_trans = 1;
  197407. }
  197408. info_ptr->num_trans = (png_uint_16)num_trans;
  197409. info_ptr->valid |= PNG_INFO_tRNS;
  197410. }
  197411. #endif
  197412. #if defined(PNG_sPLT_SUPPORTED)
  197413. void PNGAPI
  197414. png_set_sPLT(png_structp png_ptr,
  197415. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197416. {
  197417. png_sPLT_tp np;
  197418. int i;
  197419. if (png_ptr == NULL || info_ptr == NULL)
  197420. return;
  197421. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197422. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197423. if (np == NULL)
  197424. {
  197425. png_warning(png_ptr, "No memory for sPLT palettes.");
  197426. return;
  197427. }
  197428. png_memcpy(np, info_ptr->splt_palettes,
  197429. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197430. png_free(png_ptr, info_ptr->splt_palettes);
  197431. info_ptr->splt_palettes=NULL;
  197432. for (i = 0; i < nentries; i++)
  197433. {
  197434. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197435. png_sPLT_tp from = entries + i;
  197436. to->name = (png_charp)png_malloc_warn(png_ptr,
  197437. png_strlen(from->name) + 1);
  197438. if (to->name == NULL)
  197439. {
  197440. png_warning(png_ptr,
  197441. "Out of memory while processing sPLT chunk");
  197442. }
  197443. /* TODO: use png_malloc_warn */
  197444. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197445. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197446. from->nentries * png_sizeof(png_sPLT_entry));
  197447. /* TODO: use png_malloc_warn */
  197448. png_memcpy(to->entries, from->entries,
  197449. from->nentries * png_sizeof(png_sPLT_entry));
  197450. if (to->entries == NULL)
  197451. {
  197452. png_warning(png_ptr,
  197453. "Out of memory while processing sPLT chunk");
  197454. png_free(png_ptr,to->name);
  197455. to->name = NULL;
  197456. }
  197457. to->nentries = from->nentries;
  197458. to->depth = from->depth;
  197459. }
  197460. info_ptr->splt_palettes = np;
  197461. info_ptr->splt_palettes_num += nentries;
  197462. info_ptr->valid |= PNG_INFO_sPLT;
  197463. #ifdef PNG_FREE_ME_SUPPORTED
  197464. info_ptr->free_me |= PNG_FREE_SPLT;
  197465. #endif
  197466. }
  197467. #endif /* PNG_sPLT_SUPPORTED */
  197468. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197469. void PNGAPI
  197470. png_set_unknown_chunks(png_structp png_ptr,
  197471. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197472. {
  197473. png_unknown_chunkp np;
  197474. int i;
  197475. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197476. return;
  197477. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197478. (info_ptr->unknown_chunks_num + num_unknowns) *
  197479. png_sizeof(png_unknown_chunk));
  197480. if (np == NULL)
  197481. {
  197482. png_warning(png_ptr,
  197483. "Out of memory while processing unknown chunk.");
  197484. return;
  197485. }
  197486. png_memcpy(np, info_ptr->unknown_chunks,
  197487. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197488. png_free(png_ptr, info_ptr->unknown_chunks);
  197489. info_ptr->unknown_chunks=NULL;
  197490. for (i = 0; i < num_unknowns; i++)
  197491. {
  197492. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197493. png_unknown_chunkp from = unknowns + i;
  197494. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197495. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197496. if (to->data == NULL)
  197497. {
  197498. png_warning(png_ptr,
  197499. "Out of memory while processing unknown chunk.");
  197500. }
  197501. else
  197502. {
  197503. png_memcpy(to->data, from->data, from->size);
  197504. to->size = from->size;
  197505. /* note our location in the read or write sequence */
  197506. to->location = (png_byte)(png_ptr->mode & 0xff);
  197507. }
  197508. }
  197509. info_ptr->unknown_chunks = np;
  197510. info_ptr->unknown_chunks_num += num_unknowns;
  197511. #ifdef PNG_FREE_ME_SUPPORTED
  197512. info_ptr->free_me |= PNG_FREE_UNKN;
  197513. #endif
  197514. }
  197515. void PNGAPI
  197516. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197517. int chunk, int location)
  197518. {
  197519. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197520. (int)info_ptr->unknown_chunks_num)
  197521. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197522. }
  197523. #endif
  197524. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197525. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197526. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197527. void PNGAPI
  197528. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197529. {
  197530. /* This function is deprecated in favor of png_permit_mng_features()
  197531. and will be removed from libpng-1.3.0 */
  197532. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197533. if (png_ptr == NULL)
  197534. return;
  197535. png_ptr->mng_features_permitted = (png_byte)
  197536. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197537. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197538. }
  197539. #endif
  197540. #endif
  197541. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197542. png_uint_32 PNGAPI
  197543. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197544. {
  197545. png_debug(1, "in png_permit_mng_features\n");
  197546. if (png_ptr == NULL)
  197547. return (png_uint_32)0;
  197548. png_ptr->mng_features_permitted =
  197549. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197550. return (png_uint_32)png_ptr->mng_features_permitted;
  197551. }
  197552. #endif
  197553. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197554. void PNGAPI
  197555. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197556. chunk_list, int num_chunks)
  197557. {
  197558. png_bytep new_list, p;
  197559. int i, old_num_chunks;
  197560. if (png_ptr == NULL)
  197561. return;
  197562. if (num_chunks == 0)
  197563. {
  197564. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197565. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197566. else
  197567. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197568. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197569. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197570. else
  197571. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197572. return;
  197573. }
  197574. if (chunk_list == NULL)
  197575. return;
  197576. old_num_chunks=png_ptr->num_chunk_list;
  197577. new_list=(png_bytep)png_malloc(png_ptr,
  197578. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197579. if(png_ptr->chunk_list != NULL)
  197580. {
  197581. png_memcpy(new_list, png_ptr->chunk_list,
  197582. (png_size_t)(5*old_num_chunks));
  197583. png_free(png_ptr, png_ptr->chunk_list);
  197584. png_ptr->chunk_list=NULL;
  197585. }
  197586. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197587. (png_size_t)(5*num_chunks));
  197588. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197589. *p=(png_byte)keep;
  197590. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197591. png_ptr->chunk_list=new_list;
  197592. #ifdef PNG_FREE_ME_SUPPORTED
  197593. png_ptr->free_me |= PNG_FREE_LIST;
  197594. #endif
  197595. }
  197596. #endif
  197597. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197598. void PNGAPI
  197599. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197600. png_user_chunk_ptr read_user_chunk_fn)
  197601. {
  197602. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197603. if (png_ptr == NULL)
  197604. return;
  197605. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197606. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197607. }
  197608. #endif
  197609. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197610. void PNGAPI
  197611. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197612. {
  197613. png_debug1(1, "in %s storage function\n", "rows");
  197614. if (png_ptr == NULL || info_ptr == NULL)
  197615. return;
  197616. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197617. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197618. info_ptr->row_pointers = row_pointers;
  197619. if(row_pointers)
  197620. info_ptr->valid |= PNG_INFO_IDAT;
  197621. }
  197622. #endif
  197623. #ifdef PNG_WRITE_SUPPORTED
  197624. void PNGAPI
  197625. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197626. {
  197627. if (png_ptr == NULL)
  197628. return;
  197629. if(png_ptr->zbuf)
  197630. png_free(png_ptr, png_ptr->zbuf);
  197631. png_ptr->zbuf_size = (png_size_t)size;
  197632. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197633. png_ptr->zstream.next_out = png_ptr->zbuf;
  197634. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197635. }
  197636. #endif
  197637. void PNGAPI
  197638. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197639. {
  197640. if (png_ptr && info_ptr)
  197641. info_ptr->valid &= ~(mask);
  197642. }
  197643. #ifndef PNG_1_0_X
  197644. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197645. /* function was added to libpng 1.2.0 and should always exist by default */
  197646. void PNGAPI
  197647. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197648. {
  197649. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197650. if (png_ptr != NULL)
  197651. png_ptr->asm_flags = 0;
  197652. }
  197653. /* this function was added to libpng 1.2.0 */
  197654. void PNGAPI
  197655. png_set_mmx_thresholds (png_structp png_ptr,
  197656. png_byte,
  197657. png_uint_32)
  197658. {
  197659. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197660. if (png_ptr == NULL)
  197661. return;
  197662. }
  197663. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197664. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197665. /* this function was added to libpng 1.2.6 */
  197666. void PNGAPI
  197667. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197668. png_uint_32 user_height_max)
  197669. {
  197670. /* Images with dimensions larger than these limits will be
  197671. * rejected by png_set_IHDR(). To accept any PNG datastream
  197672. * regardless of dimensions, set both limits to 0x7ffffffL.
  197673. */
  197674. if(png_ptr == NULL) return;
  197675. png_ptr->user_width_max = user_width_max;
  197676. png_ptr->user_height_max = user_height_max;
  197677. }
  197678. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197679. #endif /* ?PNG_1_0_X */
  197680. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197681. /*** End of inlined file: pngset.c ***/
  197682. /*** Start of inlined file: pngtrans.c ***/
  197683. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197684. *
  197685. * Last changed in libpng 1.2.17 May 15, 2007
  197686. * For conditions of distribution and use, see copyright notice in png.h
  197687. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197688. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197689. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197690. */
  197691. #define PNG_INTERNAL
  197692. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197693. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197694. /* turn on BGR-to-RGB mapping */
  197695. void PNGAPI
  197696. png_set_bgr(png_structp png_ptr)
  197697. {
  197698. png_debug(1, "in png_set_bgr\n");
  197699. if(png_ptr == NULL) return;
  197700. png_ptr->transformations |= PNG_BGR;
  197701. }
  197702. #endif
  197703. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197704. /* turn on 16 bit byte swapping */
  197705. void PNGAPI
  197706. png_set_swap(png_structp png_ptr)
  197707. {
  197708. png_debug(1, "in png_set_swap\n");
  197709. if(png_ptr == NULL) return;
  197710. if (png_ptr->bit_depth == 16)
  197711. png_ptr->transformations |= PNG_SWAP_BYTES;
  197712. }
  197713. #endif
  197714. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197715. /* turn on pixel packing */
  197716. void PNGAPI
  197717. png_set_packing(png_structp png_ptr)
  197718. {
  197719. png_debug(1, "in png_set_packing\n");
  197720. if(png_ptr == NULL) return;
  197721. if (png_ptr->bit_depth < 8)
  197722. {
  197723. png_ptr->transformations |= PNG_PACK;
  197724. png_ptr->usr_bit_depth = 8;
  197725. }
  197726. }
  197727. #endif
  197728. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197729. /* turn on packed pixel swapping */
  197730. void PNGAPI
  197731. png_set_packswap(png_structp png_ptr)
  197732. {
  197733. png_debug(1, "in png_set_packswap\n");
  197734. if(png_ptr == NULL) return;
  197735. if (png_ptr->bit_depth < 8)
  197736. png_ptr->transformations |= PNG_PACKSWAP;
  197737. }
  197738. #endif
  197739. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197740. void PNGAPI
  197741. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197742. {
  197743. png_debug(1, "in png_set_shift\n");
  197744. if(png_ptr == NULL) return;
  197745. png_ptr->transformations |= PNG_SHIFT;
  197746. png_ptr->shift = *true_bits;
  197747. }
  197748. #endif
  197749. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197750. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197751. int PNGAPI
  197752. png_set_interlace_handling(png_structp png_ptr)
  197753. {
  197754. png_debug(1, "in png_set_interlace handling\n");
  197755. if (png_ptr && png_ptr->interlaced)
  197756. {
  197757. png_ptr->transformations |= PNG_INTERLACE;
  197758. return (7);
  197759. }
  197760. return (1);
  197761. }
  197762. #endif
  197763. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197764. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197765. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197766. * for 48-bit input data, as well as to avoid problems with some compilers
  197767. * that don't like bytes as parameters.
  197768. */
  197769. void PNGAPI
  197770. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197771. {
  197772. png_debug(1, "in png_set_filler\n");
  197773. if(png_ptr == NULL) return;
  197774. png_ptr->transformations |= PNG_FILLER;
  197775. png_ptr->filler = (png_byte)filler;
  197776. if (filler_loc == PNG_FILLER_AFTER)
  197777. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197778. else
  197779. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197780. /* This should probably go in the "do_read_filler" routine.
  197781. * I attempted to do that in libpng-1.0.1a but that caused problems
  197782. * so I restored it in libpng-1.0.2a
  197783. */
  197784. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197785. {
  197786. png_ptr->usr_channels = 4;
  197787. }
  197788. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197789. * a less-than-8-bit grayscale to GA? */
  197790. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197791. {
  197792. png_ptr->usr_channels = 2;
  197793. }
  197794. }
  197795. #if !defined(PNG_1_0_X)
  197796. /* Added to libpng-1.2.7 */
  197797. void PNGAPI
  197798. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197799. {
  197800. png_debug(1, "in png_set_add_alpha\n");
  197801. if(png_ptr == NULL) return;
  197802. png_set_filler(png_ptr, filler, filler_loc);
  197803. png_ptr->transformations |= PNG_ADD_ALPHA;
  197804. }
  197805. #endif
  197806. #endif
  197807. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197808. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197809. void PNGAPI
  197810. png_set_swap_alpha(png_structp png_ptr)
  197811. {
  197812. png_debug(1, "in png_set_swap_alpha\n");
  197813. if(png_ptr == NULL) return;
  197814. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197815. }
  197816. #endif
  197817. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197818. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197819. void PNGAPI
  197820. png_set_invert_alpha(png_structp png_ptr)
  197821. {
  197822. png_debug(1, "in png_set_invert_alpha\n");
  197823. if(png_ptr == NULL) return;
  197824. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197825. }
  197826. #endif
  197827. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197828. void PNGAPI
  197829. png_set_invert_mono(png_structp png_ptr)
  197830. {
  197831. png_debug(1, "in png_set_invert_mono\n");
  197832. if(png_ptr == NULL) return;
  197833. png_ptr->transformations |= PNG_INVERT_MONO;
  197834. }
  197835. /* invert monochrome grayscale data */
  197836. void /* PRIVATE */
  197837. png_do_invert(png_row_infop row_info, png_bytep row)
  197838. {
  197839. png_debug(1, "in png_do_invert\n");
  197840. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197841. * if (row_info->bit_depth == 1 &&
  197842. */
  197843. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197844. if (row == NULL || row_info == NULL)
  197845. return;
  197846. #endif
  197847. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197848. {
  197849. png_bytep rp = row;
  197850. png_uint_32 i;
  197851. png_uint_32 istop = row_info->rowbytes;
  197852. for (i = 0; i < istop; i++)
  197853. {
  197854. *rp = (png_byte)(~(*rp));
  197855. rp++;
  197856. }
  197857. }
  197858. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197859. row_info->bit_depth == 8)
  197860. {
  197861. png_bytep rp = row;
  197862. png_uint_32 i;
  197863. png_uint_32 istop = row_info->rowbytes;
  197864. for (i = 0; i < istop; i+=2)
  197865. {
  197866. *rp = (png_byte)(~(*rp));
  197867. rp+=2;
  197868. }
  197869. }
  197870. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197871. row_info->bit_depth == 16)
  197872. {
  197873. png_bytep rp = row;
  197874. png_uint_32 i;
  197875. png_uint_32 istop = row_info->rowbytes;
  197876. for (i = 0; i < istop; i+=4)
  197877. {
  197878. *rp = (png_byte)(~(*rp));
  197879. *(rp+1) = (png_byte)(~(*(rp+1)));
  197880. rp+=4;
  197881. }
  197882. }
  197883. }
  197884. #endif
  197885. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197886. /* swaps byte order on 16 bit depth images */
  197887. void /* PRIVATE */
  197888. png_do_swap(png_row_infop row_info, png_bytep row)
  197889. {
  197890. png_debug(1, "in png_do_swap\n");
  197891. if (
  197892. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197893. row != NULL && row_info != NULL &&
  197894. #endif
  197895. row_info->bit_depth == 16)
  197896. {
  197897. png_bytep rp = row;
  197898. png_uint_32 i;
  197899. png_uint_32 istop= row_info->width * row_info->channels;
  197900. for (i = 0; i < istop; i++, rp += 2)
  197901. {
  197902. png_byte t = *rp;
  197903. *rp = *(rp + 1);
  197904. *(rp + 1) = t;
  197905. }
  197906. }
  197907. }
  197908. #endif
  197909. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197910. static PNG_CONST png_byte onebppswaptable[256] = {
  197911. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197912. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197913. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197914. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197915. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197916. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197917. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197918. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197919. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197920. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197921. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197922. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197923. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197924. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197925. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197926. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197927. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197928. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197929. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197930. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197931. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197932. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197933. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197934. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197935. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197936. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197937. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197938. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197939. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197940. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197941. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197942. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197943. };
  197944. static PNG_CONST png_byte twobppswaptable[256] = {
  197945. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197946. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197947. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197948. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197949. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197950. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197951. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197952. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197953. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197954. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197955. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197956. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197957. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197958. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197959. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197960. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197961. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197962. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197963. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197964. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197965. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197966. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197967. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197968. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197969. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197970. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197971. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197972. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197973. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197974. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197975. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197976. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197977. };
  197978. static PNG_CONST png_byte fourbppswaptable[256] = {
  197979. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197980. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197981. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197982. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197983. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197984. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197985. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197986. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197987. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197988. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197989. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197990. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197991. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197992. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197993. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197994. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197995. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197996. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197997. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197998. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197999. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198000. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198001. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198002. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198003. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198004. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198005. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198006. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198007. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198008. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198009. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198010. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198011. };
  198012. /* swaps pixel packing order within bytes */
  198013. void /* PRIVATE */
  198014. png_do_packswap(png_row_infop row_info, png_bytep row)
  198015. {
  198016. png_debug(1, "in png_do_packswap\n");
  198017. if (
  198018. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198019. row != NULL && row_info != NULL &&
  198020. #endif
  198021. row_info->bit_depth < 8)
  198022. {
  198023. png_bytep rp, end, table;
  198024. end = row + row_info->rowbytes;
  198025. if (row_info->bit_depth == 1)
  198026. table = (png_bytep)onebppswaptable;
  198027. else if (row_info->bit_depth == 2)
  198028. table = (png_bytep)twobppswaptable;
  198029. else if (row_info->bit_depth == 4)
  198030. table = (png_bytep)fourbppswaptable;
  198031. else
  198032. return;
  198033. for (rp = row; rp < end; rp++)
  198034. *rp = table[*rp];
  198035. }
  198036. }
  198037. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198038. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198039. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198040. /* remove filler or alpha byte(s) */
  198041. void /* PRIVATE */
  198042. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198043. {
  198044. png_debug(1, "in png_do_strip_filler\n");
  198045. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198046. if (row != NULL && row_info != NULL)
  198047. #endif
  198048. {
  198049. png_bytep sp=row;
  198050. png_bytep dp=row;
  198051. png_uint_32 row_width=row_info->width;
  198052. png_uint_32 i;
  198053. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198054. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198055. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198056. row_info->channels == 4)
  198057. {
  198058. if (row_info->bit_depth == 8)
  198059. {
  198060. /* This converts from RGBX or RGBA to RGB */
  198061. if (flags & PNG_FLAG_FILLER_AFTER)
  198062. {
  198063. dp+=3; sp+=4;
  198064. for (i = 1; i < row_width; i++)
  198065. {
  198066. *dp++ = *sp++;
  198067. *dp++ = *sp++;
  198068. *dp++ = *sp++;
  198069. sp++;
  198070. }
  198071. }
  198072. /* This converts from XRGB or ARGB to RGB */
  198073. else
  198074. {
  198075. for (i = 0; i < row_width; i++)
  198076. {
  198077. sp++;
  198078. *dp++ = *sp++;
  198079. *dp++ = *sp++;
  198080. *dp++ = *sp++;
  198081. }
  198082. }
  198083. row_info->pixel_depth = 24;
  198084. row_info->rowbytes = row_width * 3;
  198085. }
  198086. else /* if (row_info->bit_depth == 16) */
  198087. {
  198088. if (flags & PNG_FLAG_FILLER_AFTER)
  198089. {
  198090. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198091. sp += 8; dp += 6;
  198092. for (i = 1; i < row_width; i++)
  198093. {
  198094. /* This could be (although png_memcpy is probably slower):
  198095. png_memcpy(dp, sp, 6);
  198096. sp += 8;
  198097. dp += 6;
  198098. */
  198099. *dp++ = *sp++;
  198100. *dp++ = *sp++;
  198101. *dp++ = *sp++;
  198102. *dp++ = *sp++;
  198103. *dp++ = *sp++;
  198104. *dp++ = *sp++;
  198105. sp += 2;
  198106. }
  198107. }
  198108. else
  198109. {
  198110. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198111. for (i = 0; i < row_width; i++)
  198112. {
  198113. /* This could be (although png_memcpy is probably slower):
  198114. png_memcpy(dp, sp, 6);
  198115. sp += 8;
  198116. dp += 6;
  198117. */
  198118. sp+=2;
  198119. *dp++ = *sp++;
  198120. *dp++ = *sp++;
  198121. *dp++ = *sp++;
  198122. *dp++ = *sp++;
  198123. *dp++ = *sp++;
  198124. *dp++ = *sp++;
  198125. }
  198126. }
  198127. row_info->pixel_depth = 48;
  198128. row_info->rowbytes = row_width * 6;
  198129. }
  198130. row_info->channels = 3;
  198131. }
  198132. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198133. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198134. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198135. row_info->channels == 2)
  198136. {
  198137. if (row_info->bit_depth == 8)
  198138. {
  198139. /* This converts from GX or GA to G */
  198140. if (flags & PNG_FLAG_FILLER_AFTER)
  198141. {
  198142. for (i = 0; i < row_width; i++)
  198143. {
  198144. *dp++ = *sp++;
  198145. sp++;
  198146. }
  198147. }
  198148. /* This converts from XG or AG to G */
  198149. else
  198150. {
  198151. for (i = 0; i < row_width; i++)
  198152. {
  198153. sp++;
  198154. *dp++ = *sp++;
  198155. }
  198156. }
  198157. row_info->pixel_depth = 8;
  198158. row_info->rowbytes = row_width;
  198159. }
  198160. else /* if (row_info->bit_depth == 16) */
  198161. {
  198162. if (flags & PNG_FLAG_FILLER_AFTER)
  198163. {
  198164. /* This converts from GGXX or GGAA to GG */
  198165. sp += 4; dp += 2;
  198166. for (i = 1; i < row_width; i++)
  198167. {
  198168. *dp++ = *sp++;
  198169. *dp++ = *sp++;
  198170. sp += 2;
  198171. }
  198172. }
  198173. else
  198174. {
  198175. /* This converts from XXGG or AAGG to GG */
  198176. for (i = 0; i < row_width; i++)
  198177. {
  198178. sp += 2;
  198179. *dp++ = *sp++;
  198180. *dp++ = *sp++;
  198181. }
  198182. }
  198183. row_info->pixel_depth = 16;
  198184. row_info->rowbytes = row_width * 2;
  198185. }
  198186. row_info->channels = 1;
  198187. }
  198188. if (flags & PNG_FLAG_STRIP_ALPHA)
  198189. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198190. }
  198191. }
  198192. #endif
  198193. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198194. /* swaps red and blue bytes within a pixel */
  198195. void /* PRIVATE */
  198196. png_do_bgr(png_row_infop row_info, png_bytep row)
  198197. {
  198198. png_debug(1, "in png_do_bgr\n");
  198199. if (
  198200. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198201. row != NULL && row_info != NULL &&
  198202. #endif
  198203. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198204. {
  198205. png_uint_32 row_width = row_info->width;
  198206. if (row_info->bit_depth == 8)
  198207. {
  198208. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198209. {
  198210. png_bytep rp;
  198211. png_uint_32 i;
  198212. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198213. {
  198214. png_byte save = *rp;
  198215. *rp = *(rp + 2);
  198216. *(rp + 2) = save;
  198217. }
  198218. }
  198219. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198220. {
  198221. png_bytep rp;
  198222. png_uint_32 i;
  198223. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198224. {
  198225. png_byte save = *rp;
  198226. *rp = *(rp + 2);
  198227. *(rp + 2) = save;
  198228. }
  198229. }
  198230. }
  198231. else if (row_info->bit_depth == 16)
  198232. {
  198233. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198234. {
  198235. png_bytep rp;
  198236. png_uint_32 i;
  198237. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198238. {
  198239. png_byte save = *rp;
  198240. *rp = *(rp + 4);
  198241. *(rp + 4) = save;
  198242. save = *(rp + 1);
  198243. *(rp + 1) = *(rp + 5);
  198244. *(rp + 5) = save;
  198245. }
  198246. }
  198247. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198248. {
  198249. png_bytep rp;
  198250. png_uint_32 i;
  198251. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198252. {
  198253. png_byte save = *rp;
  198254. *rp = *(rp + 4);
  198255. *(rp + 4) = save;
  198256. save = *(rp + 1);
  198257. *(rp + 1) = *(rp + 5);
  198258. *(rp + 5) = save;
  198259. }
  198260. }
  198261. }
  198262. }
  198263. }
  198264. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198265. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198266. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198267. defined(PNG_LEGACY_SUPPORTED)
  198268. void PNGAPI
  198269. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198270. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198271. {
  198272. png_debug(1, "in png_set_user_transform_info\n");
  198273. if(png_ptr == NULL) return;
  198274. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198275. png_ptr->user_transform_ptr = user_transform_ptr;
  198276. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198277. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198278. #else
  198279. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198280. png_warning(png_ptr,
  198281. "This version of libpng does not support user transform info");
  198282. #endif
  198283. }
  198284. #endif
  198285. /* This function returns a pointer to the user_transform_ptr associated with
  198286. * the user transform functions. The application should free any memory
  198287. * associated with this pointer before png_write_destroy and png_read_destroy
  198288. * are called.
  198289. */
  198290. png_voidp PNGAPI
  198291. png_get_user_transform_ptr(png_structp png_ptr)
  198292. {
  198293. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198294. if (png_ptr == NULL) return (NULL);
  198295. return ((png_voidp)png_ptr->user_transform_ptr);
  198296. #else
  198297. return (NULL);
  198298. #endif
  198299. }
  198300. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198301. /*** End of inlined file: pngtrans.c ***/
  198302. /*** Start of inlined file: pngwio.c ***/
  198303. /* pngwio.c - functions for data output
  198304. *
  198305. * Last changed in libpng 1.2.13 November 13, 2006
  198306. * For conditions of distribution and use, see copyright notice in png.h
  198307. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198308. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198309. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198310. *
  198311. * This file provides a location for all output. Users who need
  198312. * special handling are expected to write functions that have the same
  198313. * arguments as these and perform similar functions, but that possibly
  198314. * use different output methods. Note that you shouldn't change these
  198315. * functions, but rather write replacement functions and then change
  198316. * them at run time with png_set_write_fn(...).
  198317. */
  198318. #define PNG_INTERNAL
  198319. #ifdef PNG_WRITE_SUPPORTED
  198320. /* Write the data to whatever output you are using. The default routine
  198321. writes to a file pointer. Note that this routine sometimes gets called
  198322. with very small lengths, so you should implement some kind of simple
  198323. buffering if you are using unbuffered writes. This should never be asked
  198324. to write more than 64K on a 16 bit machine. */
  198325. void /* PRIVATE */
  198326. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198327. {
  198328. if (png_ptr->write_data_fn != NULL )
  198329. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198330. else
  198331. png_error(png_ptr, "Call to NULL write function");
  198332. }
  198333. #if !defined(PNG_NO_STDIO)
  198334. /* This is the function that does the actual writing of data. If you are
  198335. not writing to a standard C stream, you should create a replacement
  198336. write_data function and use it at run time with png_set_write_fn(), rather
  198337. than changing the library. */
  198338. #ifndef USE_FAR_KEYWORD
  198339. void PNGAPI
  198340. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198341. {
  198342. png_uint_32 check;
  198343. if(png_ptr == NULL) return;
  198344. #if defined(_WIN32_WCE)
  198345. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198346. check = 0;
  198347. #else
  198348. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198349. #endif
  198350. if (check != length)
  198351. png_error(png_ptr, "Write Error");
  198352. }
  198353. #else
  198354. /* this is the model-independent version. Since the standard I/O library
  198355. can't handle far buffers in the medium and small models, we have to copy
  198356. the data.
  198357. */
  198358. #define NEAR_BUF_SIZE 1024
  198359. #define MIN(a,b) (a <= b ? a : b)
  198360. void PNGAPI
  198361. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198362. {
  198363. png_uint_32 check;
  198364. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198365. png_FILE_p io_ptr;
  198366. if(png_ptr == NULL) return;
  198367. /* Check if data really is near. If so, use usual code. */
  198368. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198369. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198370. if ((png_bytep)near_data == data)
  198371. {
  198372. #if defined(_WIN32_WCE)
  198373. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198374. check = 0;
  198375. #else
  198376. check = fwrite(near_data, 1, length, io_ptr);
  198377. #endif
  198378. }
  198379. else
  198380. {
  198381. png_byte buf[NEAR_BUF_SIZE];
  198382. png_size_t written, remaining, err;
  198383. check = 0;
  198384. remaining = length;
  198385. do
  198386. {
  198387. written = MIN(NEAR_BUF_SIZE, remaining);
  198388. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198389. #if defined(_WIN32_WCE)
  198390. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198391. err = 0;
  198392. #else
  198393. err = fwrite(buf, 1, written, io_ptr);
  198394. #endif
  198395. if (err != written)
  198396. break;
  198397. else
  198398. check += err;
  198399. data += written;
  198400. remaining -= written;
  198401. }
  198402. while (remaining != 0);
  198403. }
  198404. if (check != length)
  198405. png_error(png_ptr, "Write Error");
  198406. }
  198407. #endif
  198408. #endif
  198409. /* This function is called to output any data pending writing (normally
  198410. to disk). After png_flush is called, there should be no data pending
  198411. writing in any buffers. */
  198412. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198413. void /* PRIVATE */
  198414. png_flush(png_structp png_ptr)
  198415. {
  198416. if (png_ptr->output_flush_fn != NULL)
  198417. (*(png_ptr->output_flush_fn))(png_ptr);
  198418. }
  198419. #if !defined(PNG_NO_STDIO)
  198420. void PNGAPI
  198421. png_default_flush(png_structp png_ptr)
  198422. {
  198423. #if !defined(_WIN32_WCE)
  198424. png_FILE_p io_ptr;
  198425. #endif
  198426. if(png_ptr == NULL) return;
  198427. #if !defined(_WIN32_WCE)
  198428. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198429. if (io_ptr != NULL)
  198430. fflush(io_ptr);
  198431. #endif
  198432. }
  198433. #endif
  198434. #endif
  198435. /* This function allows the application to supply new output functions for
  198436. libpng if standard C streams aren't being used.
  198437. This function takes as its arguments:
  198438. png_ptr - pointer to a png output data structure
  198439. io_ptr - pointer to user supplied structure containing info about
  198440. the output functions. May be NULL.
  198441. write_data_fn - pointer to a new output function that takes as its
  198442. arguments a pointer to a png_struct, a pointer to
  198443. data to be written, and a 32-bit unsigned int that is
  198444. the number of bytes to be written. The new write
  198445. function should call png_error(png_ptr, "Error msg")
  198446. to exit and output any fatal error messages.
  198447. flush_data_fn - pointer to a new flush function that takes as its
  198448. arguments a pointer to a png_struct. After a call to
  198449. the flush function, there should be no data in any buffers
  198450. or pending transmission. If the output method doesn't do
  198451. any buffering of ouput, a function prototype must still be
  198452. supplied although it doesn't have to do anything. If
  198453. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198454. time, output_flush_fn will be ignored, although it must be
  198455. supplied for compatibility. */
  198456. void PNGAPI
  198457. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198458. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198459. {
  198460. if(png_ptr == NULL) return;
  198461. png_ptr->io_ptr = io_ptr;
  198462. #if !defined(PNG_NO_STDIO)
  198463. if (write_data_fn != NULL)
  198464. png_ptr->write_data_fn = write_data_fn;
  198465. else
  198466. png_ptr->write_data_fn = png_default_write_data;
  198467. #else
  198468. png_ptr->write_data_fn = write_data_fn;
  198469. #endif
  198470. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198471. #if !defined(PNG_NO_STDIO)
  198472. if (output_flush_fn != NULL)
  198473. png_ptr->output_flush_fn = output_flush_fn;
  198474. else
  198475. png_ptr->output_flush_fn = png_default_flush;
  198476. #else
  198477. png_ptr->output_flush_fn = output_flush_fn;
  198478. #endif
  198479. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198480. /* It is an error to read while writing a png file */
  198481. if (png_ptr->read_data_fn != NULL)
  198482. {
  198483. png_ptr->read_data_fn = NULL;
  198484. png_warning(png_ptr,
  198485. "Attempted to set both read_data_fn and write_data_fn in");
  198486. png_warning(png_ptr,
  198487. "the same structure. Resetting read_data_fn to NULL.");
  198488. }
  198489. }
  198490. #if defined(USE_FAR_KEYWORD)
  198491. #if defined(_MSC_VER)
  198492. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198493. {
  198494. void *near_ptr;
  198495. void FAR *far_ptr;
  198496. FP_OFF(near_ptr) = FP_OFF(ptr);
  198497. far_ptr = (void FAR *)near_ptr;
  198498. if(check != 0)
  198499. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198500. png_error(png_ptr,"segment lost in conversion");
  198501. return(near_ptr);
  198502. }
  198503. # else
  198504. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198505. {
  198506. void *near_ptr;
  198507. void FAR *far_ptr;
  198508. near_ptr = (void FAR *)ptr;
  198509. far_ptr = (void FAR *)near_ptr;
  198510. if(check != 0)
  198511. if(far_ptr != ptr)
  198512. png_error(png_ptr,"segment lost in conversion");
  198513. return(near_ptr);
  198514. }
  198515. # endif
  198516. # endif
  198517. #endif /* PNG_WRITE_SUPPORTED */
  198518. /*** End of inlined file: pngwio.c ***/
  198519. /*** Start of inlined file: pngwrite.c ***/
  198520. /* pngwrite.c - general routines to write a PNG file
  198521. *
  198522. * Last changed in libpng 1.2.15 January 5, 2007
  198523. * For conditions of distribution and use, see copyright notice in png.h
  198524. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198525. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198526. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198527. */
  198528. /* get internal access to png.h */
  198529. #define PNG_INTERNAL
  198530. #ifdef PNG_WRITE_SUPPORTED
  198531. /* Writes all the PNG information. This is the suggested way to use the
  198532. * library. If you have a new chunk to add, make a function to write it,
  198533. * and put it in the correct location here. If you want the chunk written
  198534. * after the image data, put it in png_write_end(). I strongly encourage
  198535. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198536. * the chunk, as that will keep the code from breaking if you want to just
  198537. * write a plain PNG file. If you have long comments, I suggest writing
  198538. * them in png_write_end(), and compressing them.
  198539. */
  198540. void PNGAPI
  198541. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198542. {
  198543. png_debug(1, "in png_write_info_before_PLTE\n");
  198544. if (png_ptr == NULL || info_ptr == NULL)
  198545. return;
  198546. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198547. {
  198548. png_write_sig(png_ptr); /* write PNG signature */
  198549. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198550. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198551. {
  198552. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198553. png_ptr->mng_features_permitted=0;
  198554. }
  198555. #endif
  198556. /* write IHDR information. */
  198557. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198558. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198559. info_ptr->filter_type,
  198560. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198561. info_ptr->interlace_type);
  198562. #else
  198563. 0);
  198564. #endif
  198565. /* the rest of these check to see if the valid field has the appropriate
  198566. flag set, and if it does, writes the chunk. */
  198567. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198568. if (info_ptr->valid & PNG_INFO_gAMA)
  198569. {
  198570. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198571. png_write_gAMA(png_ptr, info_ptr->gamma);
  198572. #else
  198573. #ifdef PNG_FIXED_POINT_SUPPORTED
  198574. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198575. # endif
  198576. #endif
  198577. }
  198578. #endif
  198579. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198580. if (info_ptr->valid & PNG_INFO_sRGB)
  198581. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198582. #endif
  198583. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198584. if (info_ptr->valid & PNG_INFO_iCCP)
  198585. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198586. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198587. #endif
  198588. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198589. if (info_ptr->valid & PNG_INFO_sBIT)
  198590. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198591. #endif
  198592. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198593. if (info_ptr->valid & PNG_INFO_cHRM)
  198594. {
  198595. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198596. png_write_cHRM(png_ptr,
  198597. info_ptr->x_white, info_ptr->y_white,
  198598. info_ptr->x_red, info_ptr->y_red,
  198599. info_ptr->x_green, info_ptr->y_green,
  198600. info_ptr->x_blue, info_ptr->y_blue);
  198601. #else
  198602. # ifdef PNG_FIXED_POINT_SUPPORTED
  198603. png_write_cHRM_fixed(png_ptr,
  198604. info_ptr->int_x_white, info_ptr->int_y_white,
  198605. info_ptr->int_x_red, info_ptr->int_y_red,
  198606. info_ptr->int_x_green, info_ptr->int_y_green,
  198607. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198608. # endif
  198609. #endif
  198610. }
  198611. #endif
  198612. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198613. if (info_ptr->unknown_chunks_num)
  198614. {
  198615. png_unknown_chunk *up;
  198616. png_debug(5, "writing extra chunks\n");
  198617. for (up = info_ptr->unknown_chunks;
  198618. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198619. up++)
  198620. {
  198621. int keep=png_handle_as_unknown(png_ptr, up->name);
  198622. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198623. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198624. !(up->location & PNG_HAVE_IDAT) &&
  198625. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198626. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198627. {
  198628. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198629. }
  198630. }
  198631. }
  198632. #endif
  198633. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198634. }
  198635. }
  198636. void PNGAPI
  198637. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198638. {
  198639. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198640. int i;
  198641. #endif
  198642. png_debug(1, "in png_write_info\n");
  198643. if (png_ptr == NULL || info_ptr == NULL)
  198644. return;
  198645. png_write_info_before_PLTE(png_ptr, info_ptr);
  198646. if (info_ptr->valid & PNG_INFO_PLTE)
  198647. png_write_PLTE(png_ptr, info_ptr->palette,
  198648. (png_uint_32)info_ptr->num_palette);
  198649. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198650. png_error(png_ptr, "Valid palette required for paletted images");
  198651. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198652. if (info_ptr->valid & PNG_INFO_tRNS)
  198653. {
  198654. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198655. /* invert the alpha channel (in tRNS) */
  198656. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198657. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198658. {
  198659. int j;
  198660. for (j=0; j<(int)info_ptr->num_trans; j++)
  198661. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198662. }
  198663. #endif
  198664. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198665. info_ptr->num_trans, info_ptr->color_type);
  198666. }
  198667. #endif
  198668. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198669. if (info_ptr->valid & PNG_INFO_bKGD)
  198670. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198671. #endif
  198672. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198673. if (info_ptr->valid & PNG_INFO_hIST)
  198674. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198675. #endif
  198676. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198677. if (info_ptr->valid & PNG_INFO_oFFs)
  198678. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198679. info_ptr->offset_unit_type);
  198680. #endif
  198681. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198682. if (info_ptr->valid & PNG_INFO_pCAL)
  198683. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198684. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198685. info_ptr->pcal_units, info_ptr->pcal_params);
  198686. #endif
  198687. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198688. if (info_ptr->valid & PNG_INFO_sCAL)
  198689. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198690. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198691. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198692. #else
  198693. #ifdef PNG_FIXED_POINT_SUPPORTED
  198694. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198695. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198696. #else
  198697. png_warning(png_ptr,
  198698. "png_write_sCAL not supported; sCAL chunk not written.");
  198699. #endif
  198700. #endif
  198701. #endif
  198702. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198703. if (info_ptr->valid & PNG_INFO_pHYs)
  198704. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198705. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198706. #endif
  198707. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198708. if (info_ptr->valid & PNG_INFO_tIME)
  198709. {
  198710. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198711. png_ptr->mode |= PNG_WROTE_tIME;
  198712. }
  198713. #endif
  198714. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198715. if (info_ptr->valid & PNG_INFO_sPLT)
  198716. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198717. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198718. #endif
  198719. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198720. /* Check to see if we need to write text chunks */
  198721. for (i = 0; i < info_ptr->num_text; i++)
  198722. {
  198723. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198724. info_ptr->text[i].compression);
  198725. /* an internationalized chunk? */
  198726. if (info_ptr->text[i].compression > 0)
  198727. {
  198728. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198729. /* write international chunk */
  198730. png_write_iTXt(png_ptr,
  198731. info_ptr->text[i].compression,
  198732. info_ptr->text[i].key,
  198733. info_ptr->text[i].lang,
  198734. info_ptr->text[i].lang_key,
  198735. info_ptr->text[i].text);
  198736. #else
  198737. png_warning(png_ptr, "Unable to write international text");
  198738. #endif
  198739. /* Mark this chunk as written */
  198740. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198741. }
  198742. /* If we want a compressed text chunk */
  198743. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198744. {
  198745. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198746. /* write compressed chunk */
  198747. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198748. info_ptr->text[i].text, 0,
  198749. info_ptr->text[i].compression);
  198750. #else
  198751. png_warning(png_ptr, "Unable to write compressed text");
  198752. #endif
  198753. /* Mark this chunk as written */
  198754. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198755. }
  198756. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198757. {
  198758. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198759. /* write uncompressed chunk */
  198760. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198761. info_ptr->text[i].text,
  198762. 0);
  198763. #else
  198764. png_warning(png_ptr, "Unable to write uncompressed text");
  198765. #endif
  198766. /* Mark this chunk as written */
  198767. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198768. }
  198769. }
  198770. #endif
  198771. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198772. if (info_ptr->unknown_chunks_num)
  198773. {
  198774. png_unknown_chunk *up;
  198775. png_debug(5, "writing extra chunks\n");
  198776. for (up = info_ptr->unknown_chunks;
  198777. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198778. up++)
  198779. {
  198780. int keep=png_handle_as_unknown(png_ptr, up->name);
  198781. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198782. up->location && (up->location & PNG_HAVE_PLTE) &&
  198783. !(up->location & PNG_HAVE_IDAT) &&
  198784. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198785. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198786. {
  198787. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198788. }
  198789. }
  198790. }
  198791. #endif
  198792. }
  198793. /* Writes the end of the PNG file. If you don't want to write comments or
  198794. * time information, you can pass NULL for info. If you already wrote these
  198795. * in png_write_info(), do not write them again here. If you have long
  198796. * comments, I suggest writing them here, and compressing them.
  198797. */
  198798. void PNGAPI
  198799. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198800. {
  198801. png_debug(1, "in png_write_end\n");
  198802. if (png_ptr == NULL)
  198803. return;
  198804. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198805. png_error(png_ptr, "No IDATs written into file");
  198806. /* see if user wants us to write information chunks */
  198807. if (info_ptr != NULL)
  198808. {
  198809. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198810. int i; /* local index variable */
  198811. #endif
  198812. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198813. /* check to see if user has supplied a time chunk */
  198814. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198815. !(png_ptr->mode & PNG_WROTE_tIME))
  198816. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198817. #endif
  198818. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198819. /* loop through comment chunks */
  198820. for (i = 0; i < info_ptr->num_text; i++)
  198821. {
  198822. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198823. info_ptr->text[i].compression);
  198824. /* an internationalized chunk? */
  198825. if (info_ptr->text[i].compression > 0)
  198826. {
  198827. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198828. /* write international chunk */
  198829. png_write_iTXt(png_ptr,
  198830. info_ptr->text[i].compression,
  198831. info_ptr->text[i].key,
  198832. info_ptr->text[i].lang,
  198833. info_ptr->text[i].lang_key,
  198834. info_ptr->text[i].text);
  198835. #else
  198836. png_warning(png_ptr, "Unable to write international text");
  198837. #endif
  198838. /* Mark this chunk as written */
  198839. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198840. }
  198841. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198842. {
  198843. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198844. /* write compressed chunk */
  198845. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198846. info_ptr->text[i].text, 0,
  198847. info_ptr->text[i].compression);
  198848. #else
  198849. png_warning(png_ptr, "Unable to write compressed text");
  198850. #endif
  198851. /* Mark this chunk as written */
  198852. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198853. }
  198854. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198855. {
  198856. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198857. /* write uncompressed chunk */
  198858. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198859. info_ptr->text[i].text, 0);
  198860. #else
  198861. png_warning(png_ptr, "Unable to write uncompressed text");
  198862. #endif
  198863. /* Mark this chunk as written */
  198864. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198865. }
  198866. }
  198867. #endif
  198868. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198869. if (info_ptr->unknown_chunks_num)
  198870. {
  198871. png_unknown_chunk *up;
  198872. png_debug(5, "writing extra chunks\n");
  198873. for (up = info_ptr->unknown_chunks;
  198874. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198875. up++)
  198876. {
  198877. int keep=png_handle_as_unknown(png_ptr, up->name);
  198878. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198879. up->location && (up->location & PNG_AFTER_IDAT) &&
  198880. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198881. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198882. {
  198883. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198884. }
  198885. }
  198886. }
  198887. #endif
  198888. }
  198889. png_ptr->mode |= PNG_AFTER_IDAT;
  198890. /* write end of PNG file */
  198891. png_write_IEND(png_ptr);
  198892. }
  198893. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198894. #if !defined(_WIN32_WCE)
  198895. /* "time.h" functions are not supported on WindowsCE */
  198896. void PNGAPI
  198897. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198898. {
  198899. png_debug(1, "in png_convert_from_struct_tm\n");
  198900. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198901. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198902. ptime->day = (png_byte)ttime->tm_mday;
  198903. ptime->hour = (png_byte)ttime->tm_hour;
  198904. ptime->minute = (png_byte)ttime->tm_min;
  198905. ptime->second = (png_byte)ttime->tm_sec;
  198906. }
  198907. void PNGAPI
  198908. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198909. {
  198910. struct tm *tbuf;
  198911. png_debug(1, "in png_convert_from_time_t\n");
  198912. tbuf = gmtime(&ttime);
  198913. png_convert_from_struct_tm(ptime, tbuf);
  198914. }
  198915. #endif
  198916. #endif
  198917. /* Initialize png_ptr structure, and allocate any memory needed */
  198918. png_structp PNGAPI
  198919. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198920. png_error_ptr error_fn, png_error_ptr warn_fn)
  198921. {
  198922. #ifdef PNG_USER_MEM_SUPPORTED
  198923. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198924. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198925. }
  198926. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198927. png_structp PNGAPI
  198928. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198929. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198930. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198931. {
  198932. #endif /* PNG_USER_MEM_SUPPORTED */
  198933. png_structp png_ptr;
  198934. #ifdef PNG_SETJMP_SUPPORTED
  198935. #ifdef USE_FAR_KEYWORD
  198936. jmp_buf jmpbuf;
  198937. #endif
  198938. #endif
  198939. int i;
  198940. png_debug(1, "in png_create_write_struct\n");
  198941. #ifdef PNG_USER_MEM_SUPPORTED
  198942. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198943. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198944. #else
  198945. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198946. #endif /* PNG_USER_MEM_SUPPORTED */
  198947. if (png_ptr == NULL)
  198948. return (NULL);
  198949. /* added at libpng-1.2.6 */
  198950. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198951. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198952. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198953. #endif
  198954. #ifdef PNG_SETJMP_SUPPORTED
  198955. #ifdef USE_FAR_KEYWORD
  198956. if (setjmp(jmpbuf))
  198957. #else
  198958. if (setjmp(png_ptr->jmpbuf))
  198959. #endif
  198960. {
  198961. png_free(png_ptr, png_ptr->zbuf);
  198962. png_ptr->zbuf=NULL;
  198963. png_destroy_struct(png_ptr);
  198964. return (NULL);
  198965. }
  198966. #ifdef USE_FAR_KEYWORD
  198967. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198968. #endif
  198969. #endif
  198970. #ifdef PNG_USER_MEM_SUPPORTED
  198971. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198972. #endif /* PNG_USER_MEM_SUPPORTED */
  198973. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198974. i=0;
  198975. do
  198976. {
  198977. if(user_png_ver[i] != png_libpng_ver[i])
  198978. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198979. } while (png_libpng_ver[i++]);
  198980. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198981. {
  198982. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198983. * we must recompile any applications that use any older library version.
  198984. * For versions after libpng 1.0, we will be compatible, so we need
  198985. * only check the first digit.
  198986. */
  198987. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198988. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198989. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198990. {
  198991. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198992. char msg[80];
  198993. if (user_png_ver)
  198994. {
  198995. png_snprintf(msg, 80,
  198996. "Application was compiled with png.h from libpng-%.20s",
  198997. user_png_ver);
  198998. png_warning(png_ptr, msg);
  198999. }
  199000. png_snprintf(msg, 80,
  199001. "Application is running with png.c from libpng-%.20s",
  199002. png_libpng_ver);
  199003. png_warning(png_ptr, msg);
  199004. #endif
  199005. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199006. png_ptr->flags=0;
  199007. #endif
  199008. png_error(png_ptr,
  199009. "Incompatible libpng version in application and library");
  199010. }
  199011. }
  199012. /* initialize zbuf - compression buffer */
  199013. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199014. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199015. (png_uint_32)png_ptr->zbuf_size);
  199016. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199017. png_flush_ptr_NULL);
  199018. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199019. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199020. 1, png_doublep_NULL, png_doublep_NULL);
  199021. #endif
  199022. #ifdef PNG_SETJMP_SUPPORTED
  199023. /* Applications that neglect to set up their own setjmp() and then encounter
  199024. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199025. abort instead of returning. */
  199026. #ifdef USE_FAR_KEYWORD
  199027. if (setjmp(jmpbuf))
  199028. PNG_ABORT();
  199029. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199030. #else
  199031. if (setjmp(png_ptr->jmpbuf))
  199032. PNG_ABORT();
  199033. #endif
  199034. #endif
  199035. return (png_ptr);
  199036. }
  199037. /* Initialize png_ptr structure, and allocate any memory needed */
  199038. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199039. /* Deprecated. */
  199040. #undef png_write_init
  199041. void PNGAPI
  199042. png_write_init(png_structp png_ptr)
  199043. {
  199044. /* We only come here via pre-1.0.7-compiled applications */
  199045. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199046. }
  199047. void PNGAPI
  199048. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199049. png_size_t png_struct_size, png_size_t png_info_size)
  199050. {
  199051. /* We only come here via pre-1.0.12-compiled applications */
  199052. if(png_ptr == NULL) return;
  199053. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199054. if(png_sizeof(png_struct) > png_struct_size ||
  199055. png_sizeof(png_info) > png_info_size)
  199056. {
  199057. char msg[80];
  199058. png_ptr->warning_fn=NULL;
  199059. if (user_png_ver)
  199060. {
  199061. png_snprintf(msg, 80,
  199062. "Application was compiled with png.h from libpng-%.20s",
  199063. user_png_ver);
  199064. png_warning(png_ptr, msg);
  199065. }
  199066. png_snprintf(msg, 80,
  199067. "Application is running with png.c from libpng-%.20s",
  199068. png_libpng_ver);
  199069. png_warning(png_ptr, msg);
  199070. }
  199071. #endif
  199072. if(png_sizeof(png_struct) > png_struct_size)
  199073. {
  199074. png_ptr->error_fn=NULL;
  199075. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199076. png_ptr->flags=0;
  199077. #endif
  199078. png_error(png_ptr,
  199079. "The png struct allocated by the application for writing is too small.");
  199080. }
  199081. if(png_sizeof(png_info) > png_info_size)
  199082. {
  199083. png_ptr->error_fn=NULL;
  199084. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199085. png_ptr->flags=0;
  199086. #endif
  199087. png_error(png_ptr,
  199088. "The info struct allocated by the application for writing is too small.");
  199089. }
  199090. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199091. }
  199092. #endif /* PNG_1_0_X || PNG_1_2_X */
  199093. void PNGAPI
  199094. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199095. png_size_t png_struct_size)
  199096. {
  199097. png_structp png_ptr=*ptr_ptr;
  199098. #ifdef PNG_SETJMP_SUPPORTED
  199099. jmp_buf tmp_jmp; /* to save current jump buffer */
  199100. #endif
  199101. int i = 0;
  199102. if (png_ptr == NULL)
  199103. return;
  199104. do
  199105. {
  199106. if (user_png_ver[i] != png_libpng_ver[i])
  199107. {
  199108. #ifdef PNG_LEGACY_SUPPORTED
  199109. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199110. #else
  199111. png_ptr->warning_fn=NULL;
  199112. png_warning(png_ptr,
  199113. "Application uses deprecated png_write_init() and should be recompiled.");
  199114. break;
  199115. #endif
  199116. }
  199117. } while (png_libpng_ver[i++]);
  199118. png_debug(1, "in png_write_init_3\n");
  199119. #ifdef PNG_SETJMP_SUPPORTED
  199120. /* save jump buffer and error functions */
  199121. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199122. #endif
  199123. if (png_sizeof(png_struct) > png_struct_size)
  199124. {
  199125. png_destroy_struct(png_ptr);
  199126. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199127. *ptr_ptr = png_ptr;
  199128. }
  199129. /* reset all variables to 0 */
  199130. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199131. /* added at libpng-1.2.6 */
  199132. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199133. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199134. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199135. #endif
  199136. #ifdef PNG_SETJMP_SUPPORTED
  199137. /* restore jump buffer */
  199138. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199139. #endif
  199140. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199141. png_flush_ptr_NULL);
  199142. /* initialize zbuf - compression buffer */
  199143. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199144. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199145. (png_uint_32)png_ptr->zbuf_size);
  199146. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199147. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199148. 1, png_doublep_NULL, png_doublep_NULL);
  199149. #endif
  199150. }
  199151. /* Write a few rows of image data. If the image is interlaced,
  199152. * either you will have to write the 7 sub images, or, if you
  199153. * have called png_set_interlace_handling(), you will have to
  199154. * "write" the image seven times.
  199155. */
  199156. void PNGAPI
  199157. png_write_rows(png_structp png_ptr, png_bytepp row,
  199158. png_uint_32 num_rows)
  199159. {
  199160. png_uint_32 i; /* row counter */
  199161. png_bytepp rp; /* row pointer */
  199162. png_debug(1, "in png_write_rows\n");
  199163. if (png_ptr == NULL)
  199164. return;
  199165. /* loop through the rows */
  199166. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199167. {
  199168. png_write_row(png_ptr, *rp);
  199169. }
  199170. }
  199171. /* Write the image. You only need to call this function once, even
  199172. * if you are writing an interlaced image.
  199173. */
  199174. void PNGAPI
  199175. png_write_image(png_structp png_ptr, png_bytepp image)
  199176. {
  199177. png_uint_32 i; /* row index */
  199178. int pass, num_pass; /* pass variables */
  199179. png_bytepp rp; /* points to current row */
  199180. if (png_ptr == NULL)
  199181. return;
  199182. png_debug(1, "in png_write_image\n");
  199183. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199184. /* intialize interlace handling. If image is not interlaced,
  199185. this will set pass to 1 */
  199186. num_pass = png_set_interlace_handling(png_ptr);
  199187. #else
  199188. num_pass = 1;
  199189. #endif
  199190. /* loop through passes */
  199191. for (pass = 0; pass < num_pass; pass++)
  199192. {
  199193. /* loop through image */
  199194. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199195. {
  199196. png_write_row(png_ptr, *rp);
  199197. }
  199198. }
  199199. }
  199200. /* called by user to write a row of image data */
  199201. void PNGAPI
  199202. png_write_row(png_structp png_ptr, png_bytep row)
  199203. {
  199204. if (png_ptr == NULL)
  199205. return;
  199206. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199207. png_ptr->row_number, png_ptr->pass);
  199208. /* initialize transformations and other stuff if first time */
  199209. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199210. {
  199211. /* make sure we wrote the header info */
  199212. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199213. png_error(png_ptr,
  199214. "png_write_info was never called before png_write_row.");
  199215. /* check for transforms that have been set but were defined out */
  199216. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199217. if (png_ptr->transformations & PNG_INVERT_MONO)
  199218. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199219. #endif
  199220. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199221. if (png_ptr->transformations & PNG_FILLER)
  199222. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199223. #endif
  199224. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199225. if (png_ptr->transformations & PNG_PACKSWAP)
  199226. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199227. #endif
  199228. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199229. if (png_ptr->transformations & PNG_PACK)
  199230. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199231. #endif
  199232. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199233. if (png_ptr->transformations & PNG_SHIFT)
  199234. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199235. #endif
  199236. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199237. if (png_ptr->transformations & PNG_BGR)
  199238. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199239. #endif
  199240. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199241. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199242. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199243. #endif
  199244. png_write_start_row(png_ptr);
  199245. }
  199246. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199247. /* if interlaced and not interested in row, return */
  199248. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199249. {
  199250. switch (png_ptr->pass)
  199251. {
  199252. case 0:
  199253. if (png_ptr->row_number & 0x07)
  199254. {
  199255. png_write_finish_row(png_ptr);
  199256. return;
  199257. }
  199258. break;
  199259. case 1:
  199260. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199261. {
  199262. png_write_finish_row(png_ptr);
  199263. return;
  199264. }
  199265. break;
  199266. case 2:
  199267. if ((png_ptr->row_number & 0x07) != 4)
  199268. {
  199269. png_write_finish_row(png_ptr);
  199270. return;
  199271. }
  199272. break;
  199273. case 3:
  199274. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199275. {
  199276. png_write_finish_row(png_ptr);
  199277. return;
  199278. }
  199279. break;
  199280. case 4:
  199281. if ((png_ptr->row_number & 0x03) != 2)
  199282. {
  199283. png_write_finish_row(png_ptr);
  199284. return;
  199285. }
  199286. break;
  199287. case 5:
  199288. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199289. {
  199290. png_write_finish_row(png_ptr);
  199291. return;
  199292. }
  199293. break;
  199294. case 6:
  199295. if (!(png_ptr->row_number & 0x01))
  199296. {
  199297. png_write_finish_row(png_ptr);
  199298. return;
  199299. }
  199300. break;
  199301. }
  199302. }
  199303. #endif
  199304. /* set up row info for transformations */
  199305. png_ptr->row_info.color_type = png_ptr->color_type;
  199306. png_ptr->row_info.width = png_ptr->usr_width;
  199307. png_ptr->row_info.channels = png_ptr->usr_channels;
  199308. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199309. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199310. png_ptr->row_info.channels);
  199311. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199312. png_ptr->row_info.width);
  199313. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199314. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199315. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199316. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199317. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199318. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199319. /* Copy user's row into buffer, leaving room for filter byte. */
  199320. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199321. png_ptr->row_info.rowbytes);
  199322. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199323. /* handle interlacing */
  199324. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199325. (png_ptr->transformations & PNG_INTERLACE))
  199326. {
  199327. png_do_write_interlace(&(png_ptr->row_info),
  199328. png_ptr->row_buf + 1, png_ptr->pass);
  199329. /* this should always get caught above, but still ... */
  199330. if (!(png_ptr->row_info.width))
  199331. {
  199332. png_write_finish_row(png_ptr);
  199333. return;
  199334. }
  199335. }
  199336. #endif
  199337. /* handle other transformations */
  199338. if (png_ptr->transformations)
  199339. png_do_write_transformations(png_ptr);
  199340. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199341. /* Write filter_method 64 (intrapixel differencing) only if
  199342. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199343. * 2. Libpng did not write a PNG signature (this filter_method is only
  199344. * used in PNG datastreams that are embedded in MNG datastreams) and
  199345. * 3. The application called png_permit_mng_features with a mask that
  199346. * included PNG_FLAG_MNG_FILTER_64 and
  199347. * 4. The filter_method is 64 and
  199348. * 5. The color_type is RGB or RGBA
  199349. */
  199350. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199351. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199352. {
  199353. /* Intrapixel differencing */
  199354. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199355. }
  199356. #endif
  199357. /* Find a filter if necessary, filter the row and write it out. */
  199358. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199359. if (png_ptr->write_row_fn != NULL)
  199360. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199361. }
  199362. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199363. /* Set the automatic flush interval or 0 to turn flushing off */
  199364. void PNGAPI
  199365. png_set_flush(png_structp png_ptr, int nrows)
  199366. {
  199367. png_debug(1, "in png_set_flush\n");
  199368. if (png_ptr == NULL)
  199369. return;
  199370. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199371. }
  199372. /* flush the current output buffers now */
  199373. void PNGAPI
  199374. png_write_flush(png_structp png_ptr)
  199375. {
  199376. int wrote_IDAT;
  199377. png_debug(1, "in png_write_flush\n");
  199378. if (png_ptr == NULL)
  199379. return;
  199380. /* We have already written out all of the data */
  199381. if (png_ptr->row_number >= png_ptr->num_rows)
  199382. return;
  199383. do
  199384. {
  199385. int ret;
  199386. /* compress the data */
  199387. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199388. wrote_IDAT = 0;
  199389. /* check for compression errors */
  199390. if (ret != Z_OK)
  199391. {
  199392. if (png_ptr->zstream.msg != NULL)
  199393. png_error(png_ptr, png_ptr->zstream.msg);
  199394. else
  199395. png_error(png_ptr, "zlib error");
  199396. }
  199397. if (!(png_ptr->zstream.avail_out))
  199398. {
  199399. /* write the IDAT and reset the zlib output buffer */
  199400. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199401. png_ptr->zbuf_size);
  199402. png_ptr->zstream.next_out = png_ptr->zbuf;
  199403. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199404. wrote_IDAT = 1;
  199405. }
  199406. } while(wrote_IDAT == 1);
  199407. /* If there is any data left to be output, write it into a new IDAT */
  199408. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199409. {
  199410. /* write the IDAT and reset the zlib output buffer */
  199411. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199412. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199413. png_ptr->zstream.next_out = png_ptr->zbuf;
  199414. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199415. }
  199416. png_ptr->flush_rows = 0;
  199417. png_flush(png_ptr);
  199418. }
  199419. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199420. /* free all memory used by the write */
  199421. void PNGAPI
  199422. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199423. {
  199424. png_structp png_ptr = NULL;
  199425. png_infop info_ptr = NULL;
  199426. #ifdef PNG_USER_MEM_SUPPORTED
  199427. png_free_ptr free_fn = NULL;
  199428. png_voidp mem_ptr = NULL;
  199429. #endif
  199430. png_debug(1, "in png_destroy_write_struct\n");
  199431. if (png_ptr_ptr != NULL)
  199432. {
  199433. png_ptr = *png_ptr_ptr;
  199434. #ifdef PNG_USER_MEM_SUPPORTED
  199435. free_fn = png_ptr->free_fn;
  199436. mem_ptr = png_ptr->mem_ptr;
  199437. #endif
  199438. }
  199439. if (info_ptr_ptr != NULL)
  199440. info_ptr = *info_ptr_ptr;
  199441. if (info_ptr != NULL)
  199442. {
  199443. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199444. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199445. if (png_ptr->num_chunk_list)
  199446. {
  199447. png_free(png_ptr, png_ptr->chunk_list);
  199448. png_ptr->chunk_list=NULL;
  199449. png_ptr->num_chunk_list=0;
  199450. }
  199451. #endif
  199452. #ifdef PNG_USER_MEM_SUPPORTED
  199453. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199454. (png_voidp)mem_ptr);
  199455. #else
  199456. png_destroy_struct((png_voidp)info_ptr);
  199457. #endif
  199458. *info_ptr_ptr = NULL;
  199459. }
  199460. if (png_ptr != NULL)
  199461. {
  199462. png_write_destroy(png_ptr);
  199463. #ifdef PNG_USER_MEM_SUPPORTED
  199464. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199465. (png_voidp)mem_ptr);
  199466. #else
  199467. png_destroy_struct((png_voidp)png_ptr);
  199468. #endif
  199469. *png_ptr_ptr = NULL;
  199470. }
  199471. }
  199472. /* Free any memory used in png_ptr struct (old method) */
  199473. void /* PRIVATE */
  199474. png_write_destroy(png_structp png_ptr)
  199475. {
  199476. #ifdef PNG_SETJMP_SUPPORTED
  199477. jmp_buf tmp_jmp; /* save jump buffer */
  199478. #endif
  199479. png_error_ptr error_fn;
  199480. png_error_ptr warning_fn;
  199481. png_voidp error_ptr;
  199482. #ifdef PNG_USER_MEM_SUPPORTED
  199483. png_free_ptr free_fn;
  199484. #endif
  199485. png_debug(1, "in png_write_destroy\n");
  199486. /* free any memory zlib uses */
  199487. deflateEnd(&png_ptr->zstream);
  199488. /* free our memory. png_free checks NULL for us. */
  199489. png_free(png_ptr, png_ptr->zbuf);
  199490. png_free(png_ptr, png_ptr->row_buf);
  199491. png_free(png_ptr, png_ptr->prev_row);
  199492. png_free(png_ptr, png_ptr->sub_row);
  199493. png_free(png_ptr, png_ptr->up_row);
  199494. png_free(png_ptr, png_ptr->avg_row);
  199495. png_free(png_ptr, png_ptr->paeth_row);
  199496. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199497. png_free(png_ptr, png_ptr->time_buffer);
  199498. #endif
  199499. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199500. png_free(png_ptr, png_ptr->prev_filters);
  199501. png_free(png_ptr, png_ptr->filter_weights);
  199502. png_free(png_ptr, png_ptr->inv_filter_weights);
  199503. png_free(png_ptr, png_ptr->filter_costs);
  199504. png_free(png_ptr, png_ptr->inv_filter_costs);
  199505. #endif
  199506. #ifdef PNG_SETJMP_SUPPORTED
  199507. /* reset structure */
  199508. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199509. #endif
  199510. error_fn = png_ptr->error_fn;
  199511. warning_fn = png_ptr->warning_fn;
  199512. error_ptr = png_ptr->error_ptr;
  199513. #ifdef PNG_USER_MEM_SUPPORTED
  199514. free_fn = png_ptr->free_fn;
  199515. #endif
  199516. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199517. png_ptr->error_fn = error_fn;
  199518. png_ptr->warning_fn = warning_fn;
  199519. png_ptr->error_ptr = error_ptr;
  199520. #ifdef PNG_USER_MEM_SUPPORTED
  199521. png_ptr->free_fn = free_fn;
  199522. #endif
  199523. #ifdef PNG_SETJMP_SUPPORTED
  199524. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199525. #endif
  199526. }
  199527. /* Allow the application to select one or more row filters to use. */
  199528. void PNGAPI
  199529. png_set_filter(png_structp png_ptr, int method, int filters)
  199530. {
  199531. png_debug(1, "in png_set_filter\n");
  199532. if (png_ptr == NULL)
  199533. return;
  199534. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199535. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199536. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199537. method = PNG_FILTER_TYPE_BASE;
  199538. #endif
  199539. if (method == PNG_FILTER_TYPE_BASE)
  199540. {
  199541. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199542. {
  199543. #ifndef PNG_NO_WRITE_FILTER
  199544. case 5:
  199545. case 6:
  199546. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199547. #endif /* PNG_NO_WRITE_FILTER */
  199548. case PNG_FILTER_VALUE_NONE:
  199549. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199550. #ifndef PNG_NO_WRITE_FILTER
  199551. case PNG_FILTER_VALUE_SUB:
  199552. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199553. case PNG_FILTER_VALUE_UP:
  199554. png_ptr->do_filter=PNG_FILTER_UP; break;
  199555. case PNG_FILTER_VALUE_AVG:
  199556. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199557. case PNG_FILTER_VALUE_PAETH:
  199558. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199559. default: png_ptr->do_filter = (png_byte)filters; break;
  199560. #else
  199561. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199562. #endif /* PNG_NO_WRITE_FILTER */
  199563. }
  199564. /* If we have allocated the row_buf, this means we have already started
  199565. * with the image and we should have allocated all of the filter buffers
  199566. * that have been selected. If prev_row isn't already allocated, then
  199567. * it is too late to start using the filters that need it, since we
  199568. * will be missing the data in the previous row. If an application
  199569. * wants to start and stop using particular filters during compression,
  199570. * it should start out with all of the filters, and then add and
  199571. * remove them after the start of compression.
  199572. */
  199573. if (png_ptr->row_buf != NULL)
  199574. {
  199575. #ifndef PNG_NO_WRITE_FILTER
  199576. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199577. {
  199578. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199579. (png_ptr->rowbytes + 1));
  199580. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199581. }
  199582. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199583. {
  199584. if (png_ptr->prev_row == NULL)
  199585. {
  199586. png_warning(png_ptr, "Can't add Up filter after starting");
  199587. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199588. }
  199589. else
  199590. {
  199591. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199592. (png_ptr->rowbytes + 1));
  199593. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199594. }
  199595. }
  199596. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199597. {
  199598. if (png_ptr->prev_row == NULL)
  199599. {
  199600. png_warning(png_ptr, "Can't add Average filter after starting");
  199601. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199602. }
  199603. else
  199604. {
  199605. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199606. (png_ptr->rowbytes + 1));
  199607. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199608. }
  199609. }
  199610. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199611. png_ptr->paeth_row == NULL)
  199612. {
  199613. if (png_ptr->prev_row == NULL)
  199614. {
  199615. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199616. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199617. }
  199618. else
  199619. {
  199620. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199621. (png_ptr->rowbytes + 1));
  199622. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199623. }
  199624. }
  199625. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199626. #endif /* PNG_NO_WRITE_FILTER */
  199627. png_ptr->do_filter = PNG_FILTER_NONE;
  199628. }
  199629. }
  199630. else
  199631. png_error(png_ptr, "Unknown custom filter method");
  199632. }
  199633. /* This allows us to influence the way in which libpng chooses the "best"
  199634. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199635. * differences metric is relatively fast and effective, there is some
  199636. * question as to whether it can be improved upon by trying to keep the
  199637. * filtered data going to zlib more consistent, hopefully resulting in
  199638. * better compression.
  199639. */
  199640. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199641. void PNGAPI
  199642. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199643. int num_weights, png_doublep filter_weights,
  199644. png_doublep filter_costs)
  199645. {
  199646. int i;
  199647. png_debug(1, "in png_set_filter_heuristics\n");
  199648. if (png_ptr == NULL)
  199649. return;
  199650. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199651. {
  199652. png_warning(png_ptr, "Unknown filter heuristic method");
  199653. return;
  199654. }
  199655. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199656. {
  199657. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199658. }
  199659. if (num_weights < 0 || filter_weights == NULL ||
  199660. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199661. {
  199662. num_weights = 0;
  199663. }
  199664. png_ptr->num_prev_filters = (png_byte)num_weights;
  199665. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199666. if (num_weights > 0)
  199667. {
  199668. if (png_ptr->prev_filters == NULL)
  199669. {
  199670. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199671. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199672. /* To make sure that the weighting starts out fairly */
  199673. for (i = 0; i < num_weights; i++)
  199674. {
  199675. png_ptr->prev_filters[i] = 255;
  199676. }
  199677. }
  199678. if (png_ptr->filter_weights == NULL)
  199679. {
  199680. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199681. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199682. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199683. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199684. for (i = 0; i < num_weights; i++)
  199685. {
  199686. png_ptr->inv_filter_weights[i] =
  199687. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199688. }
  199689. }
  199690. for (i = 0; i < num_weights; i++)
  199691. {
  199692. if (filter_weights[i] < 0.0)
  199693. {
  199694. png_ptr->inv_filter_weights[i] =
  199695. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199696. }
  199697. else
  199698. {
  199699. png_ptr->inv_filter_weights[i] =
  199700. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199701. png_ptr->filter_weights[i] =
  199702. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199703. }
  199704. }
  199705. }
  199706. /* If, in the future, there are other filter methods, this would
  199707. * need to be based on png_ptr->filter.
  199708. */
  199709. if (png_ptr->filter_costs == NULL)
  199710. {
  199711. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199712. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199713. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199714. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199715. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199716. {
  199717. png_ptr->inv_filter_costs[i] =
  199718. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199719. }
  199720. }
  199721. /* Here is where we set the relative costs of the different filters. We
  199722. * should take the desired compression level into account when setting
  199723. * the costs, so that Paeth, for instance, has a high relative cost at low
  199724. * compression levels, while it has a lower relative cost at higher
  199725. * compression settings. The filter types are in order of increasing
  199726. * relative cost, so it would be possible to do this with an algorithm.
  199727. */
  199728. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199729. {
  199730. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199731. {
  199732. png_ptr->inv_filter_costs[i] =
  199733. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199734. }
  199735. else if (filter_costs[i] >= 1.0)
  199736. {
  199737. png_ptr->inv_filter_costs[i] =
  199738. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199739. png_ptr->filter_costs[i] =
  199740. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199741. }
  199742. }
  199743. }
  199744. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199745. void PNGAPI
  199746. png_set_compression_level(png_structp png_ptr, int level)
  199747. {
  199748. png_debug(1, "in png_set_compression_level\n");
  199749. if (png_ptr == NULL)
  199750. return;
  199751. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199752. png_ptr->zlib_level = level;
  199753. }
  199754. void PNGAPI
  199755. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199756. {
  199757. png_debug(1, "in png_set_compression_mem_level\n");
  199758. if (png_ptr == NULL)
  199759. return;
  199760. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199761. png_ptr->zlib_mem_level = mem_level;
  199762. }
  199763. void PNGAPI
  199764. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199765. {
  199766. png_debug(1, "in png_set_compression_strategy\n");
  199767. if (png_ptr == NULL)
  199768. return;
  199769. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199770. png_ptr->zlib_strategy = strategy;
  199771. }
  199772. void PNGAPI
  199773. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199774. {
  199775. if (png_ptr == NULL)
  199776. return;
  199777. if (window_bits > 15)
  199778. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199779. else if (window_bits < 8)
  199780. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199781. #ifndef WBITS_8_OK
  199782. /* avoid libpng bug with 256-byte windows */
  199783. if (window_bits == 8)
  199784. {
  199785. png_warning(png_ptr, "Compression window is being reset to 512");
  199786. window_bits=9;
  199787. }
  199788. #endif
  199789. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199790. png_ptr->zlib_window_bits = window_bits;
  199791. }
  199792. void PNGAPI
  199793. png_set_compression_method(png_structp png_ptr, int method)
  199794. {
  199795. png_debug(1, "in png_set_compression_method\n");
  199796. if (png_ptr == NULL)
  199797. return;
  199798. if (method != 8)
  199799. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199800. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199801. png_ptr->zlib_method = method;
  199802. }
  199803. void PNGAPI
  199804. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199805. {
  199806. if (png_ptr == NULL)
  199807. return;
  199808. png_ptr->write_row_fn = write_row_fn;
  199809. }
  199810. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199811. void PNGAPI
  199812. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199813. write_user_transform_fn)
  199814. {
  199815. png_debug(1, "in png_set_write_user_transform_fn\n");
  199816. if (png_ptr == NULL)
  199817. return;
  199818. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199819. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199820. }
  199821. #endif
  199822. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199823. void PNGAPI
  199824. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199825. int transforms, voidp params)
  199826. {
  199827. if (png_ptr == NULL || info_ptr == NULL)
  199828. return;
  199829. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199830. /* invert the alpha channel from opacity to transparency */
  199831. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199832. png_set_invert_alpha(png_ptr);
  199833. #endif
  199834. /* Write the file header information. */
  199835. png_write_info(png_ptr, info_ptr);
  199836. /* ------ these transformations don't touch the info structure ------- */
  199837. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199838. /* invert monochrome pixels */
  199839. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199840. png_set_invert_mono(png_ptr);
  199841. #endif
  199842. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199843. /* Shift the pixels up to a legal bit depth and fill in
  199844. * as appropriate to correctly scale the image.
  199845. */
  199846. if ((transforms & PNG_TRANSFORM_SHIFT)
  199847. && (info_ptr->valid & PNG_INFO_sBIT))
  199848. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199849. #endif
  199850. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199851. /* pack pixels into bytes */
  199852. if (transforms & PNG_TRANSFORM_PACKING)
  199853. png_set_packing(png_ptr);
  199854. #endif
  199855. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199856. /* swap location of alpha bytes from ARGB to RGBA */
  199857. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199858. png_set_swap_alpha(png_ptr);
  199859. #endif
  199860. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199861. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199862. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199863. */
  199864. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199865. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199866. #endif
  199867. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199868. /* flip BGR pixels to RGB */
  199869. if (transforms & PNG_TRANSFORM_BGR)
  199870. png_set_bgr(png_ptr);
  199871. #endif
  199872. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199873. /* swap bytes of 16-bit files to most significant byte first */
  199874. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199875. png_set_swap(png_ptr);
  199876. #endif
  199877. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199878. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199879. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199880. png_set_packswap(png_ptr);
  199881. #endif
  199882. /* ----------------------- end of transformations ------------------- */
  199883. /* write the bits */
  199884. if (info_ptr->valid & PNG_INFO_IDAT)
  199885. png_write_image(png_ptr, info_ptr->row_pointers);
  199886. /* It is REQUIRED to call this to finish writing the rest of the file */
  199887. png_write_end(png_ptr, info_ptr);
  199888. transforms = transforms; /* quiet compiler warnings */
  199889. params = params;
  199890. }
  199891. #endif
  199892. #endif /* PNG_WRITE_SUPPORTED */
  199893. /*** End of inlined file: pngwrite.c ***/
  199894. /*** Start of inlined file: pngwtran.c ***/
  199895. /* pngwtran.c - transforms the data in a row for PNG writers
  199896. *
  199897. * Last changed in libpng 1.2.9 April 14, 2006
  199898. * For conditions of distribution and use, see copyright notice in png.h
  199899. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199900. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199901. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199902. */
  199903. #define PNG_INTERNAL
  199904. #ifdef PNG_WRITE_SUPPORTED
  199905. /* Transform the data according to the user's wishes. The order of
  199906. * transformations is significant.
  199907. */
  199908. void /* PRIVATE */
  199909. png_do_write_transformations(png_structp png_ptr)
  199910. {
  199911. png_debug(1, "in png_do_write_transformations\n");
  199912. if (png_ptr == NULL)
  199913. return;
  199914. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199915. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199916. if(png_ptr->write_user_transform_fn != NULL)
  199917. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199918. (png_ptr, /* png_ptr */
  199919. &(png_ptr->row_info), /* row_info: */
  199920. /* png_uint_32 width; width of row */
  199921. /* png_uint_32 rowbytes; number of bytes in row */
  199922. /* png_byte color_type; color type of pixels */
  199923. /* png_byte bit_depth; bit depth of samples */
  199924. /* png_byte channels; number of channels (1-4) */
  199925. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199926. png_ptr->row_buf + 1); /* start of pixel data for row */
  199927. #endif
  199928. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199929. if (png_ptr->transformations & PNG_FILLER)
  199930. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199931. png_ptr->flags);
  199932. #endif
  199933. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199934. if (png_ptr->transformations & PNG_PACKSWAP)
  199935. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199936. #endif
  199937. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199938. if (png_ptr->transformations & PNG_PACK)
  199939. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199940. (png_uint_32)png_ptr->bit_depth);
  199941. #endif
  199942. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199943. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199944. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199945. #endif
  199946. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199947. if (png_ptr->transformations & PNG_SHIFT)
  199948. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199949. &(png_ptr->shift));
  199950. #endif
  199951. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199952. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199953. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199954. #endif
  199955. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199956. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199957. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199958. #endif
  199959. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199960. if (png_ptr->transformations & PNG_BGR)
  199961. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199962. #endif
  199963. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199964. if (png_ptr->transformations & PNG_INVERT_MONO)
  199965. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199966. #endif
  199967. }
  199968. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199969. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199970. * row_info bit depth should be 8 (one pixel per byte). The channels
  199971. * should be 1 (this only happens on grayscale and paletted images).
  199972. */
  199973. void /* PRIVATE */
  199974. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199975. {
  199976. png_debug(1, "in png_do_pack\n");
  199977. if (row_info->bit_depth == 8 &&
  199978. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199979. row != NULL && row_info != NULL &&
  199980. #endif
  199981. row_info->channels == 1)
  199982. {
  199983. switch ((int)bit_depth)
  199984. {
  199985. case 1:
  199986. {
  199987. png_bytep sp, dp;
  199988. int mask, v;
  199989. png_uint_32 i;
  199990. png_uint_32 row_width = row_info->width;
  199991. sp = row;
  199992. dp = row;
  199993. mask = 0x80;
  199994. v = 0;
  199995. for (i = 0; i < row_width; i++)
  199996. {
  199997. if (*sp != 0)
  199998. v |= mask;
  199999. sp++;
  200000. if (mask > 1)
  200001. mask >>= 1;
  200002. else
  200003. {
  200004. mask = 0x80;
  200005. *dp = (png_byte)v;
  200006. dp++;
  200007. v = 0;
  200008. }
  200009. }
  200010. if (mask != 0x80)
  200011. *dp = (png_byte)v;
  200012. break;
  200013. }
  200014. case 2:
  200015. {
  200016. png_bytep sp, dp;
  200017. int shift, v;
  200018. png_uint_32 i;
  200019. png_uint_32 row_width = row_info->width;
  200020. sp = row;
  200021. dp = row;
  200022. shift = 6;
  200023. v = 0;
  200024. for (i = 0; i < row_width; i++)
  200025. {
  200026. png_byte value;
  200027. value = (png_byte)(*sp & 0x03);
  200028. v |= (value << shift);
  200029. if (shift == 0)
  200030. {
  200031. shift = 6;
  200032. *dp = (png_byte)v;
  200033. dp++;
  200034. v = 0;
  200035. }
  200036. else
  200037. shift -= 2;
  200038. sp++;
  200039. }
  200040. if (shift != 6)
  200041. *dp = (png_byte)v;
  200042. break;
  200043. }
  200044. case 4:
  200045. {
  200046. png_bytep sp, dp;
  200047. int shift, v;
  200048. png_uint_32 i;
  200049. png_uint_32 row_width = row_info->width;
  200050. sp = row;
  200051. dp = row;
  200052. shift = 4;
  200053. v = 0;
  200054. for (i = 0; i < row_width; i++)
  200055. {
  200056. png_byte value;
  200057. value = (png_byte)(*sp & 0x0f);
  200058. v |= (value << shift);
  200059. if (shift == 0)
  200060. {
  200061. shift = 4;
  200062. *dp = (png_byte)v;
  200063. dp++;
  200064. v = 0;
  200065. }
  200066. else
  200067. shift -= 4;
  200068. sp++;
  200069. }
  200070. if (shift != 4)
  200071. *dp = (png_byte)v;
  200072. break;
  200073. }
  200074. }
  200075. row_info->bit_depth = (png_byte)bit_depth;
  200076. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200077. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200078. row_info->width);
  200079. }
  200080. }
  200081. #endif
  200082. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200083. /* Shift pixel values to take advantage of whole range. Pass the
  200084. * true number of bits in bit_depth. The row should be packed
  200085. * according to row_info->bit_depth. Thus, if you had a row of
  200086. * bit depth 4, but the pixels only had values from 0 to 7, you
  200087. * would pass 3 as bit_depth, and this routine would translate the
  200088. * data to 0 to 15.
  200089. */
  200090. void /* PRIVATE */
  200091. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200092. {
  200093. png_debug(1, "in png_do_shift\n");
  200094. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200095. if (row != NULL && row_info != NULL &&
  200096. #else
  200097. if (
  200098. #endif
  200099. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200100. {
  200101. int shift_start[4], shift_dec[4];
  200102. int channels = 0;
  200103. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200104. {
  200105. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200106. shift_dec[channels] = bit_depth->red;
  200107. channels++;
  200108. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200109. shift_dec[channels] = bit_depth->green;
  200110. channels++;
  200111. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200112. shift_dec[channels] = bit_depth->blue;
  200113. channels++;
  200114. }
  200115. else
  200116. {
  200117. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200118. shift_dec[channels] = bit_depth->gray;
  200119. channels++;
  200120. }
  200121. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200122. {
  200123. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200124. shift_dec[channels] = bit_depth->alpha;
  200125. channels++;
  200126. }
  200127. /* with low row depths, could only be grayscale, so one channel */
  200128. if (row_info->bit_depth < 8)
  200129. {
  200130. png_bytep bp = row;
  200131. png_uint_32 i;
  200132. png_byte mask;
  200133. png_uint_32 row_bytes = row_info->rowbytes;
  200134. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200135. mask = 0x55;
  200136. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200137. mask = 0x11;
  200138. else
  200139. mask = 0xff;
  200140. for (i = 0; i < row_bytes; i++, bp++)
  200141. {
  200142. png_uint_16 v;
  200143. int j;
  200144. v = *bp;
  200145. *bp = 0;
  200146. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200147. {
  200148. if (j > 0)
  200149. *bp |= (png_byte)((v << j) & 0xff);
  200150. else
  200151. *bp |= (png_byte)((v >> (-j)) & mask);
  200152. }
  200153. }
  200154. }
  200155. else if (row_info->bit_depth == 8)
  200156. {
  200157. png_bytep bp = row;
  200158. png_uint_32 i;
  200159. png_uint_32 istop = channels * row_info->width;
  200160. for (i = 0; i < istop; i++, bp++)
  200161. {
  200162. png_uint_16 v;
  200163. int j;
  200164. int c = (int)(i%channels);
  200165. v = *bp;
  200166. *bp = 0;
  200167. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200168. {
  200169. if (j > 0)
  200170. *bp |= (png_byte)((v << j) & 0xff);
  200171. else
  200172. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200173. }
  200174. }
  200175. }
  200176. else
  200177. {
  200178. png_bytep bp;
  200179. png_uint_32 i;
  200180. png_uint_32 istop = channels * row_info->width;
  200181. for (bp = row, i = 0; i < istop; i++)
  200182. {
  200183. int c = (int)(i%channels);
  200184. png_uint_16 value, v;
  200185. int j;
  200186. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200187. value = 0;
  200188. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200189. {
  200190. if (j > 0)
  200191. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200192. else
  200193. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200194. }
  200195. *bp++ = (png_byte)(value >> 8);
  200196. *bp++ = (png_byte)(value & 0xff);
  200197. }
  200198. }
  200199. }
  200200. }
  200201. #endif
  200202. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200203. void /* PRIVATE */
  200204. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200205. {
  200206. png_debug(1, "in png_do_write_swap_alpha\n");
  200207. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200208. if (row != NULL && row_info != NULL)
  200209. #endif
  200210. {
  200211. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200212. {
  200213. /* This converts from ARGB to RGBA */
  200214. if (row_info->bit_depth == 8)
  200215. {
  200216. png_bytep sp, dp;
  200217. png_uint_32 i;
  200218. png_uint_32 row_width = row_info->width;
  200219. for (i = 0, sp = dp = row; i < row_width; i++)
  200220. {
  200221. png_byte save = *(sp++);
  200222. *(dp++) = *(sp++);
  200223. *(dp++) = *(sp++);
  200224. *(dp++) = *(sp++);
  200225. *(dp++) = save;
  200226. }
  200227. }
  200228. /* This converts from AARRGGBB to RRGGBBAA */
  200229. else
  200230. {
  200231. png_bytep sp, dp;
  200232. png_uint_32 i;
  200233. png_uint_32 row_width = row_info->width;
  200234. for (i = 0, sp = dp = row; i < row_width; i++)
  200235. {
  200236. png_byte save[2];
  200237. save[0] = *(sp++);
  200238. save[1] = *(sp++);
  200239. *(dp++) = *(sp++);
  200240. *(dp++) = *(sp++);
  200241. *(dp++) = *(sp++);
  200242. *(dp++) = *(sp++);
  200243. *(dp++) = *(sp++);
  200244. *(dp++) = *(sp++);
  200245. *(dp++) = save[0];
  200246. *(dp++) = save[1];
  200247. }
  200248. }
  200249. }
  200250. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200251. {
  200252. /* This converts from AG to GA */
  200253. if (row_info->bit_depth == 8)
  200254. {
  200255. png_bytep sp, dp;
  200256. png_uint_32 i;
  200257. png_uint_32 row_width = row_info->width;
  200258. for (i = 0, sp = dp = row; i < row_width; i++)
  200259. {
  200260. png_byte save = *(sp++);
  200261. *(dp++) = *(sp++);
  200262. *(dp++) = save;
  200263. }
  200264. }
  200265. /* This converts from AAGG to GGAA */
  200266. else
  200267. {
  200268. png_bytep sp, dp;
  200269. png_uint_32 i;
  200270. png_uint_32 row_width = row_info->width;
  200271. for (i = 0, sp = dp = row; i < row_width; i++)
  200272. {
  200273. png_byte save[2];
  200274. save[0] = *(sp++);
  200275. save[1] = *(sp++);
  200276. *(dp++) = *(sp++);
  200277. *(dp++) = *(sp++);
  200278. *(dp++) = save[0];
  200279. *(dp++) = save[1];
  200280. }
  200281. }
  200282. }
  200283. }
  200284. }
  200285. #endif
  200286. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200287. void /* PRIVATE */
  200288. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200289. {
  200290. png_debug(1, "in png_do_write_invert_alpha\n");
  200291. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200292. if (row != NULL && row_info != NULL)
  200293. #endif
  200294. {
  200295. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200296. {
  200297. /* This inverts the alpha channel in RGBA */
  200298. if (row_info->bit_depth == 8)
  200299. {
  200300. png_bytep sp, dp;
  200301. png_uint_32 i;
  200302. png_uint_32 row_width = row_info->width;
  200303. for (i = 0, sp = dp = row; i < row_width; i++)
  200304. {
  200305. /* does nothing
  200306. *(dp++) = *(sp++);
  200307. *(dp++) = *(sp++);
  200308. *(dp++) = *(sp++);
  200309. */
  200310. sp+=3; dp = sp;
  200311. *(dp++) = (png_byte)(255 - *(sp++));
  200312. }
  200313. }
  200314. /* This inverts the alpha channel in RRGGBBAA */
  200315. else
  200316. {
  200317. png_bytep sp, dp;
  200318. png_uint_32 i;
  200319. png_uint_32 row_width = row_info->width;
  200320. for (i = 0, sp = dp = row; i < row_width; i++)
  200321. {
  200322. /* does nothing
  200323. *(dp++) = *(sp++);
  200324. *(dp++) = *(sp++);
  200325. *(dp++) = *(sp++);
  200326. *(dp++) = *(sp++);
  200327. *(dp++) = *(sp++);
  200328. *(dp++) = *(sp++);
  200329. */
  200330. sp+=6; dp = sp;
  200331. *(dp++) = (png_byte)(255 - *(sp++));
  200332. *(dp++) = (png_byte)(255 - *(sp++));
  200333. }
  200334. }
  200335. }
  200336. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200337. {
  200338. /* This inverts the alpha channel in GA */
  200339. if (row_info->bit_depth == 8)
  200340. {
  200341. png_bytep sp, dp;
  200342. png_uint_32 i;
  200343. png_uint_32 row_width = row_info->width;
  200344. for (i = 0, sp = dp = row; i < row_width; i++)
  200345. {
  200346. *(dp++) = *(sp++);
  200347. *(dp++) = (png_byte)(255 - *(sp++));
  200348. }
  200349. }
  200350. /* This inverts the alpha channel in GGAA */
  200351. else
  200352. {
  200353. png_bytep sp, dp;
  200354. png_uint_32 i;
  200355. png_uint_32 row_width = row_info->width;
  200356. for (i = 0, sp = dp = row; i < row_width; i++)
  200357. {
  200358. /* does nothing
  200359. *(dp++) = *(sp++);
  200360. *(dp++) = *(sp++);
  200361. */
  200362. sp+=2; dp = sp;
  200363. *(dp++) = (png_byte)(255 - *(sp++));
  200364. *(dp++) = (png_byte)(255 - *(sp++));
  200365. }
  200366. }
  200367. }
  200368. }
  200369. }
  200370. #endif
  200371. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200372. /* undoes intrapixel differencing */
  200373. void /* PRIVATE */
  200374. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200375. {
  200376. png_debug(1, "in png_do_write_intrapixel\n");
  200377. if (
  200378. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200379. row != NULL && row_info != NULL &&
  200380. #endif
  200381. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200382. {
  200383. int bytes_per_pixel;
  200384. png_uint_32 row_width = row_info->width;
  200385. if (row_info->bit_depth == 8)
  200386. {
  200387. png_bytep rp;
  200388. png_uint_32 i;
  200389. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200390. bytes_per_pixel = 3;
  200391. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200392. bytes_per_pixel = 4;
  200393. else
  200394. return;
  200395. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200396. {
  200397. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200398. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200399. }
  200400. }
  200401. else if (row_info->bit_depth == 16)
  200402. {
  200403. png_bytep rp;
  200404. png_uint_32 i;
  200405. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200406. bytes_per_pixel = 6;
  200407. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200408. bytes_per_pixel = 8;
  200409. else
  200410. return;
  200411. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200412. {
  200413. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200414. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200415. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200416. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200417. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200418. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200419. *(rp+1) = (png_byte)(red & 0xff);
  200420. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200421. *(rp+5) = (png_byte)(blue & 0xff);
  200422. }
  200423. }
  200424. }
  200425. }
  200426. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200427. #endif /* PNG_WRITE_SUPPORTED */
  200428. /*** End of inlined file: pngwtran.c ***/
  200429. /*** Start of inlined file: pngwutil.c ***/
  200430. /* pngwutil.c - utilities to write a PNG file
  200431. *
  200432. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200433. * For conditions of distribution and use, see copyright notice in png.h
  200434. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200435. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200436. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200437. */
  200438. #define PNG_INTERNAL
  200439. #ifdef PNG_WRITE_SUPPORTED
  200440. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200441. * with unsigned numbers for convenience, although one supported
  200442. * ancillary chunk uses signed (two's complement) numbers.
  200443. */
  200444. void PNGAPI
  200445. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200446. {
  200447. buf[0] = (png_byte)((i >> 24) & 0xff);
  200448. buf[1] = (png_byte)((i >> 16) & 0xff);
  200449. buf[2] = (png_byte)((i >> 8) & 0xff);
  200450. buf[3] = (png_byte)(i & 0xff);
  200451. }
  200452. /* The png_save_int_32 function assumes integers are stored in two's
  200453. * complement format. If this isn't the case, then this routine needs to
  200454. * be modified to write data in two's complement format.
  200455. */
  200456. void PNGAPI
  200457. png_save_int_32(png_bytep buf, png_int_32 i)
  200458. {
  200459. buf[0] = (png_byte)((i >> 24) & 0xff);
  200460. buf[1] = (png_byte)((i >> 16) & 0xff);
  200461. buf[2] = (png_byte)((i >> 8) & 0xff);
  200462. buf[3] = (png_byte)(i & 0xff);
  200463. }
  200464. /* Place a 16-bit number into a buffer in PNG byte order.
  200465. * The parameter is declared unsigned int, not png_uint_16,
  200466. * just to avoid potential problems on pre-ANSI C compilers.
  200467. */
  200468. void PNGAPI
  200469. png_save_uint_16(png_bytep buf, unsigned int i)
  200470. {
  200471. buf[0] = (png_byte)((i >> 8) & 0xff);
  200472. buf[1] = (png_byte)(i & 0xff);
  200473. }
  200474. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200475. * representing the chunk name. The array must be at least 4 bytes in
  200476. * length, and does not need to be null terminated. To be safe, pass the
  200477. * pre-defined chunk names here, and if you need a new one, define it
  200478. * where the others are defined. The length is the length of the data.
  200479. * All the data must be present. If that is not possible, use the
  200480. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200481. * functions instead.
  200482. */
  200483. void PNGAPI
  200484. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200485. png_bytep data, png_size_t length)
  200486. {
  200487. if(png_ptr == NULL) return;
  200488. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200489. png_write_chunk_data(png_ptr, data, length);
  200490. png_write_chunk_end(png_ptr);
  200491. }
  200492. /* Write the start of a PNG chunk. The type is the chunk type.
  200493. * The total_length is the sum of the lengths of all the data you will be
  200494. * passing in png_write_chunk_data().
  200495. */
  200496. void PNGAPI
  200497. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200498. png_uint_32 length)
  200499. {
  200500. png_byte buf[4];
  200501. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200502. if(png_ptr == NULL) return;
  200503. /* write the length */
  200504. png_save_uint_32(buf, length);
  200505. png_write_data(png_ptr, buf, (png_size_t)4);
  200506. /* write the chunk name */
  200507. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200508. /* reset the crc and run it over the chunk name */
  200509. png_reset_crc(png_ptr);
  200510. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200511. }
  200512. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200513. * Note that multiple calls to this function are allowed, and that the
  200514. * sum of the lengths from these calls *must* add up to the total_length
  200515. * given to png_write_chunk_start().
  200516. */
  200517. void PNGAPI
  200518. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200519. {
  200520. /* write the data, and run the CRC over it */
  200521. if(png_ptr == NULL) return;
  200522. if (data != NULL && length > 0)
  200523. {
  200524. png_calculate_crc(png_ptr, data, length);
  200525. png_write_data(png_ptr, data, length);
  200526. }
  200527. }
  200528. /* Finish a chunk started with png_write_chunk_start(). */
  200529. void PNGAPI
  200530. png_write_chunk_end(png_structp png_ptr)
  200531. {
  200532. png_byte buf[4];
  200533. if(png_ptr == NULL) return;
  200534. /* write the crc */
  200535. png_save_uint_32(buf, png_ptr->crc);
  200536. png_write_data(png_ptr, buf, (png_size_t)4);
  200537. }
  200538. /* Simple function to write the signature. If we have already written
  200539. * the magic bytes of the signature, or more likely, the PNG stream is
  200540. * being embedded into another stream and doesn't need its own signature,
  200541. * we should call png_set_sig_bytes() to tell libpng how many of the
  200542. * bytes have already been written.
  200543. */
  200544. void /* PRIVATE */
  200545. png_write_sig(png_structp png_ptr)
  200546. {
  200547. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200548. /* write the rest of the 8 byte signature */
  200549. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200550. (png_size_t)8 - png_ptr->sig_bytes);
  200551. if(png_ptr->sig_bytes < 3)
  200552. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200553. }
  200554. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200555. /*
  200556. * This pair of functions encapsulates the operation of (a) compressing a
  200557. * text string, and (b) issuing it later as a series of chunk data writes.
  200558. * The compression_state structure is shared context for these functions
  200559. * set up by the caller in order to make the whole mess thread-safe.
  200560. */
  200561. typedef struct
  200562. {
  200563. char *input; /* the uncompressed input data */
  200564. int input_len; /* its length */
  200565. int num_output_ptr; /* number of output pointers used */
  200566. int max_output_ptr; /* size of output_ptr */
  200567. png_charpp output_ptr; /* array of pointers to output */
  200568. } compression_state;
  200569. /* compress given text into storage in the png_ptr structure */
  200570. static int /* PRIVATE */
  200571. png_text_compress(png_structp png_ptr,
  200572. png_charp text, png_size_t text_len, int compression,
  200573. compression_state *comp)
  200574. {
  200575. int ret;
  200576. comp->num_output_ptr = 0;
  200577. comp->max_output_ptr = 0;
  200578. comp->output_ptr = NULL;
  200579. comp->input = NULL;
  200580. comp->input_len = 0;
  200581. /* we may just want to pass the text right through */
  200582. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200583. {
  200584. comp->input = text;
  200585. comp->input_len = text_len;
  200586. return((int)text_len);
  200587. }
  200588. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200589. {
  200590. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200591. char msg[50];
  200592. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200593. png_warning(png_ptr, msg);
  200594. #else
  200595. png_warning(png_ptr, "Unknown compression type");
  200596. #endif
  200597. }
  200598. /* We can't write the chunk until we find out how much data we have,
  200599. * which means we need to run the compressor first and save the
  200600. * output. This shouldn't be a problem, as the vast majority of
  200601. * comments should be reasonable, but we will set up an array of
  200602. * malloc'd pointers to be sure.
  200603. *
  200604. * If we knew the application was well behaved, we could simplify this
  200605. * greatly by assuming we can always malloc an output buffer large
  200606. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200607. * and malloc this directly. The only time this would be a bad idea is
  200608. * if we can't malloc more than 64K and we have 64K of random input
  200609. * data, or if the input string is incredibly large (although this
  200610. * wouldn't cause a failure, just a slowdown due to swapping).
  200611. */
  200612. /* set up the compression buffers */
  200613. png_ptr->zstream.avail_in = (uInt)text_len;
  200614. png_ptr->zstream.next_in = (Bytef *)text;
  200615. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200616. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200617. /* this is the same compression loop as in png_write_row() */
  200618. do
  200619. {
  200620. /* compress the data */
  200621. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200622. if (ret != Z_OK)
  200623. {
  200624. /* error */
  200625. if (png_ptr->zstream.msg != NULL)
  200626. png_error(png_ptr, png_ptr->zstream.msg);
  200627. else
  200628. png_error(png_ptr, "zlib error");
  200629. }
  200630. /* check to see if we need more room */
  200631. if (!(png_ptr->zstream.avail_out))
  200632. {
  200633. /* make sure the output array has room */
  200634. if (comp->num_output_ptr >= comp->max_output_ptr)
  200635. {
  200636. int old_max;
  200637. old_max = comp->max_output_ptr;
  200638. comp->max_output_ptr = comp->num_output_ptr + 4;
  200639. if (comp->output_ptr != NULL)
  200640. {
  200641. png_charpp old_ptr;
  200642. old_ptr = comp->output_ptr;
  200643. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200644. (png_uint_32)(comp->max_output_ptr *
  200645. png_sizeof (png_charpp)));
  200646. png_memcpy(comp->output_ptr, old_ptr, old_max
  200647. * png_sizeof (png_charp));
  200648. png_free(png_ptr, old_ptr);
  200649. }
  200650. else
  200651. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200652. (png_uint_32)(comp->max_output_ptr *
  200653. png_sizeof (png_charp)));
  200654. }
  200655. /* save the data */
  200656. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200657. (png_uint_32)png_ptr->zbuf_size);
  200658. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200659. png_ptr->zbuf_size);
  200660. comp->num_output_ptr++;
  200661. /* and reset the buffer */
  200662. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200663. png_ptr->zstream.next_out = png_ptr->zbuf;
  200664. }
  200665. /* continue until we don't have any more to compress */
  200666. } while (png_ptr->zstream.avail_in);
  200667. /* finish the compression */
  200668. do
  200669. {
  200670. /* tell zlib we are finished */
  200671. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200672. if (ret == Z_OK)
  200673. {
  200674. /* check to see if we need more room */
  200675. if (!(png_ptr->zstream.avail_out))
  200676. {
  200677. /* check to make sure our output array has room */
  200678. if (comp->num_output_ptr >= comp->max_output_ptr)
  200679. {
  200680. int old_max;
  200681. old_max = comp->max_output_ptr;
  200682. comp->max_output_ptr = comp->num_output_ptr + 4;
  200683. if (comp->output_ptr != NULL)
  200684. {
  200685. png_charpp old_ptr;
  200686. old_ptr = comp->output_ptr;
  200687. /* This could be optimized to realloc() */
  200688. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200689. (png_uint_32)(comp->max_output_ptr *
  200690. png_sizeof (png_charpp)));
  200691. png_memcpy(comp->output_ptr, old_ptr,
  200692. old_max * png_sizeof (png_charp));
  200693. png_free(png_ptr, old_ptr);
  200694. }
  200695. else
  200696. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200697. (png_uint_32)(comp->max_output_ptr *
  200698. png_sizeof (png_charp)));
  200699. }
  200700. /* save off the data */
  200701. comp->output_ptr[comp->num_output_ptr] =
  200702. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200703. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200704. png_ptr->zbuf_size);
  200705. comp->num_output_ptr++;
  200706. /* and reset the buffer pointers */
  200707. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200708. png_ptr->zstream.next_out = png_ptr->zbuf;
  200709. }
  200710. }
  200711. else if (ret != Z_STREAM_END)
  200712. {
  200713. /* we got an error */
  200714. if (png_ptr->zstream.msg != NULL)
  200715. png_error(png_ptr, png_ptr->zstream.msg);
  200716. else
  200717. png_error(png_ptr, "zlib error");
  200718. }
  200719. } while (ret != Z_STREAM_END);
  200720. /* text length is number of buffers plus last buffer */
  200721. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200722. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200723. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200724. return((int)text_len);
  200725. }
  200726. /* ship the compressed text out via chunk writes */
  200727. static void /* PRIVATE */
  200728. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200729. {
  200730. int i;
  200731. /* handle the no-compression case */
  200732. if (comp->input)
  200733. {
  200734. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200735. (png_size_t)comp->input_len);
  200736. return;
  200737. }
  200738. /* write saved output buffers, if any */
  200739. for (i = 0; i < comp->num_output_ptr; i++)
  200740. {
  200741. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200742. png_ptr->zbuf_size);
  200743. png_free(png_ptr, comp->output_ptr[i]);
  200744. comp->output_ptr[i]=NULL;
  200745. }
  200746. if (comp->max_output_ptr != 0)
  200747. png_free(png_ptr, comp->output_ptr);
  200748. comp->output_ptr=NULL;
  200749. /* write anything left in zbuf */
  200750. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200751. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200752. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200753. /* reset zlib for another zTXt/iTXt or image data */
  200754. deflateReset(&png_ptr->zstream);
  200755. png_ptr->zstream.data_type = Z_BINARY;
  200756. }
  200757. #endif
  200758. /* Write the IHDR chunk, and update the png_struct with the necessary
  200759. * information. Note that the rest of this code depends upon this
  200760. * information being correct.
  200761. */
  200762. void /* PRIVATE */
  200763. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200764. int bit_depth, int color_type, int compression_type, int filter_type,
  200765. int interlace_type)
  200766. {
  200767. #ifdef PNG_USE_LOCAL_ARRAYS
  200768. PNG_IHDR;
  200769. #endif
  200770. png_byte buf[13]; /* buffer to store the IHDR info */
  200771. png_debug(1, "in png_write_IHDR\n");
  200772. /* Check that we have valid input data from the application info */
  200773. switch (color_type)
  200774. {
  200775. case PNG_COLOR_TYPE_GRAY:
  200776. switch (bit_depth)
  200777. {
  200778. case 1:
  200779. case 2:
  200780. case 4:
  200781. case 8:
  200782. case 16: png_ptr->channels = 1; break;
  200783. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200784. }
  200785. break;
  200786. case PNG_COLOR_TYPE_RGB:
  200787. if (bit_depth != 8 && bit_depth != 16)
  200788. png_error(png_ptr, "Invalid bit depth for RGB image");
  200789. png_ptr->channels = 3;
  200790. break;
  200791. case PNG_COLOR_TYPE_PALETTE:
  200792. switch (bit_depth)
  200793. {
  200794. case 1:
  200795. case 2:
  200796. case 4:
  200797. case 8: png_ptr->channels = 1; break;
  200798. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200799. }
  200800. break;
  200801. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200802. if (bit_depth != 8 && bit_depth != 16)
  200803. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200804. png_ptr->channels = 2;
  200805. break;
  200806. case PNG_COLOR_TYPE_RGB_ALPHA:
  200807. if (bit_depth != 8 && bit_depth != 16)
  200808. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200809. png_ptr->channels = 4;
  200810. break;
  200811. default:
  200812. png_error(png_ptr, "Invalid image color type specified");
  200813. }
  200814. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200815. {
  200816. png_warning(png_ptr, "Invalid compression type specified");
  200817. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200818. }
  200819. /* Write filter_method 64 (intrapixel differencing) only if
  200820. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200821. * 2. Libpng did not write a PNG signature (this filter_method is only
  200822. * used in PNG datastreams that are embedded in MNG datastreams) and
  200823. * 3. The application called png_permit_mng_features with a mask that
  200824. * included PNG_FLAG_MNG_FILTER_64 and
  200825. * 4. The filter_method is 64 and
  200826. * 5. The color_type is RGB or RGBA
  200827. */
  200828. if (
  200829. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200830. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200831. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200832. (color_type == PNG_COLOR_TYPE_RGB ||
  200833. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200834. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200835. #endif
  200836. filter_type != PNG_FILTER_TYPE_BASE)
  200837. {
  200838. png_warning(png_ptr, "Invalid filter type specified");
  200839. filter_type = PNG_FILTER_TYPE_BASE;
  200840. }
  200841. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200842. if (interlace_type != PNG_INTERLACE_NONE &&
  200843. interlace_type != PNG_INTERLACE_ADAM7)
  200844. {
  200845. png_warning(png_ptr, "Invalid interlace type specified");
  200846. interlace_type = PNG_INTERLACE_ADAM7;
  200847. }
  200848. #else
  200849. interlace_type=PNG_INTERLACE_NONE;
  200850. #endif
  200851. /* save off the relevent information */
  200852. png_ptr->bit_depth = (png_byte)bit_depth;
  200853. png_ptr->color_type = (png_byte)color_type;
  200854. png_ptr->interlaced = (png_byte)interlace_type;
  200855. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200856. png_ptr->filter_type = (png_byte)filter_type;
  200857. #endif
  200858. png_ptr->compression_type = (png_byte)compression_type;
  200859. png_ptr->width = width;
  200860. png_ptr->height = height;
  200861. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200862. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200863. /* set the usr info, so any transformations can modify it */
  200864. png_ptr->usr_width = png_ptr->width;
  200865. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200866. png_ptr->usr_channels = png_ptr->channels;
  200867. /* pack the header information into the buffer */
  200868. png_save_uint_32(buf, width);
  200869. png_save_uint_32(buf + 4, height);
  200870. buf[8] = (png_byte)bit_depth;
  200871. buf[9] = (png_byte)color_type;
  200872. buf[10] = (png_byte)compression_type;
  200873. buf[11] = (png_byte)filter_type;
  200874. buf[12] = (png_byte)interlace_type;
  200875. /* write the chunk */
  200876. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200877. /* initialize zlib with PNG info */
  200878. png_ptr->zstream.zalloc = png_zalloc;
  200879. png_ptr->zstream.zfree = png_zfree;
  200880. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200881. if (!(png_ptr->do_filter))
  200882. {
  200883. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200884. png_ptr->bit_depth < 8)
  200885. png_ptr->do_filter = PNG_FILTER_NONE;
  200886. else
  200887. png_ptr->do_filter = PNG_ALL_FILTERS;
  200888. }
  200889. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200890. {
  200891. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200892. png_ptr->zlib_strategy = Z_FILTERED;
  200893. else
  200894. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200895. }
  200896. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200897. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200898. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200899. png_ptr->zlib_mem_level = 8;
  200900. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200901. png_ptr->zlib_window_bits = 15;
  200902. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200903. png_ptr->zlib_method = 8;
  200904. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200905. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200906. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200907. png_error(png_ptr, "zlib failed to initialize compressor");
  200908. png_ptr->zstream.next_out = png_ptr->zbuf;
  200909. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200910. /* libpng is not interested in zstream.data_type */
  200911. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200912. png_ptr->zstream.data_type = Z_BINARY;
  200913. png_ptr->mode = PNG_HAVE_IHDR;
  200914. }
  200915. /* write the palette. We are careful not to trust png_color to be in the
  200916. * correct order for PNG, so people can redefine it to any convenient
  200917. * structure.
  200918. */
  200919. void /* PRIVATE */
  200920. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200921. {
  200922. #ifdef PNG_USE_LOCAL_ARRAYS
  200923. PNG_PLTE;
  200924. #endif
  200925. png_uint_32 i;
  200926. png_colorp pal_ptr;
  200927. png_byte buf[3];
  200928. png_debug(1, "in png_write_PLTE\n");
  200929. if ((
  200930. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200931. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200932. #endif
  200933. num_pal == 0) || num_pal > 256)
  200934. {
  200935. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200936. {
  200937. png_error(png_ptr, "Invalid number of colors in palette");
  200938. }
  200939. else
  200940. {
  200941. png_warning(png_ptr, "Invalid number of colors in palette");
  200942. return;
  200943. }
  200944. }
  200945. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200946. {
  200947. png_warning(png_ptr,
  200948. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200949. return;
  200950. }
  200951. png_ptr->num_palette = (png_uint_16)num_pal;
  200952. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200953. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200954. #ifndef PNG_NO_POINTER_INDEXING
  200955. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200956. {
  200957. buf[0] = pal_ptr->red;
  200958. buf[1] = pal_ptr->green;
  200959. buf[2] = pal_ptr->blue;
  200960. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200961. }
  200962. #else
  200963. /* This is a little slower but some buggy compilers need to do this instead */
  200964. pal_ptr=palette;
  200965. for (i = 0; i < num_pal; i++)
  200966. {
  200967. buf[0] = pal_ptr[i].red;
  200968. buf[1] = pal_ptr[i].green;
  200969. buf[2] = pal_ptr[i].blue;
  200970. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200971. }
  200972. #endif
  200973. png_write_chunk_end(png_ptr);
  200974. png_ptr->mode |= PNG_HAVE_PLTE;
  200975. }
  200976. /* write an IDAT chunk */
  200977. void /* PRIVATE */
  200978. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200979. {
  200980. #ifdef PNG_USE_LOCAL_ARRAYS
  200981. PNG_IDAT;
  200982. #endif
  200983. png_debug(1, "in png_write_IDAT\n");
  200984. /* Optimize the CMF field in the zlib stream. */
  200985. /* This hack of the zlib stream is compliant to the stream specification. */
  200986. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200987. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200988. {
  200989. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200990. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200991. {
  200992. /* Avoid memory underflows and multiplication overflows. */
  200993. /* The conditions below are practically always satisfied;
  200994. however, they still must be checked. */
  200995. if (length >= 2 &&
  200996. png_ptr->height < 16384 && png_ptr->width < 16384)
  200997. {
  200998. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200999. ((png_ptr->width *
  201000. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201001. unsigned int z_cinfo = z_cmf >> 4;
  201002. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201003. while (uncompressed_idat_size <= half_z_window_size &&
  201004. half_z_window_size >= 256)
  201005. {
  201006. z_cinfo--;
  201007. half_z_window_size >>= 1;
  201008. }
  201009. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201010. if (data[0] != (png_byte)z_cmf)
  201011. {
  201012. data[0] = (png_byte)z_cmf;
  201013. data[1] &= 0xe0;
  201014. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201015. }
  201016. }
  201017. }
  201018. else
  201019. png_error(png_ptr,
  201020. "Invalid zlib compression method or flags in IDAT");
  201021. }
  201022. png_write_chunk(png_ptr, png_IDAT, data, length);
  201023. png_ptr->mode |= PNG_HAVE_IDAT;
  201024. }
  201025. /* write an IEND chunk */
  201026. void /* PRIVATE */
  201027. png_write_IEND(png_structp png_ptr)
  201028. {
  201029. #ifdef PNG_USE_LOCAL_ARRAYS
  201030. PNG_IEND;
  201031. #endif
  201032. png_debug(1, "in png_write_IEND\n");
  201033. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201034. (png_size_t)0);
  201035. png_ptr->mode |= PNG_HAVE_IEND;
  201036. }
  201037. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201038. /* write a gAMA chunk */
  201039. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201040. void /* PRIVATE */
  201041. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201042. {
  201043. #ifdef PNG_USE_LOCAL_ARRAYS
  201044. PNG_gAMA;
  201045. #endif
  201046. png_uint_32 igamma;
  201047. png_byte buf[4];
  201048. png_debug(1, "in png_write_gAMA\n");
  201049. /* file_gamma is saved in 1/100,000ths */
  201050. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201051. png_save_uint_32(buf, igamma);
  201052. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201053. }
  201054. #endif
  201055. #ifdef PNG_FIXED_POINT_SUPPORTED
  201056. void /* PRIVATE */
  201057. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201058. {
  201059. #ifdef PNG_USE_LOCAL_ARRAYS
  201060. PNG_gAMA;
  201061. #endif
  201062. png_byte buf[4];
  201063. png_debug(1, "in png_write_gAMA\n");
  201064. /* file_gamma is saved in 1/100,000ths */
  201065. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201066. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201067. }
  201068. #endif
  201069. #endif
  201070. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201071. /* write a sRGB chunk */
  201072. void /* PRIVATE */
  201073. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201074. {
  201075. #ifdef PNG_USE_LOCAL_ARRAYS
  201076. PNG_sRGB;
  201077. #endif
  201078. png_byte buf[1];
  201079. png_debug(1, "in png_write_sRGB\n");
  201080. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201081. png_warning(png_ptr,
  201082. "Invalid sRGB rendering intent specified");
  201083. buf[0]=(png_byte)srgb_intent;
  201084. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201085. }
  201086. #endif
  201087. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201088. /* write an iCCP chunk */
  201089. void /* PRIVATE */
  201090. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201091. png_charp profile, int profile_len)
  201092. {
  201093. #ifdef PNG_USE_LOCAL_ARRAYS
  201094. PNG_iCCP;
  201095. #endif
  201096. png_size_t name_len;
  201097. png_charp new_name;
  201098. compression_state comp;
  201099. int embedded_profile_len = 0;
  201100. png_debug(1, "in png_write_iCCP\n");
  201101. comp.num_output_ptr = 0;
  201102. comp.max_output_ptr = 0;
  201103. comp.output_ptr = NULL;
  201104. comp.input = NULL;
  201105. comp.input_len = 0;
  201106. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201107. &new_name)) == 0)
  201108. {
  201109. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201110. return;
  201111. }
  201112. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201113. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201114. if (profile == NULL)
  201115. profile_len = 0;
  201116. if (profile_len > 3)
  201117. embedded_profile_len =
  201118. ((*( (png_bytep)profile ))<<24) |
  201119. ((*( (png_bytep)profile+1))<<16) |
  201120. ((*( (png_bytep)profile+2))<< 8) |
  201121. ((*( (png_bytep)profile+3)) );
  201122. if (profile_len < embedded_profile_len)
  201123. {
  201124. png_warning(png_ptr,
  201125. "Embedded profile length too large in iCCP chunk");
  201126. return;
  201127. }
  201128. if (profile_len > embedded_profile_len)
  201129. {
  201130. png_warning(png_ptr,
  201131. "Truncating profile to actual length in iCCP chunk");
  201132. profile_len = embedded_profile_len;
  201133. }
  201134. if (profile_len)
  201135. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201136. PNG_COMPRESSION_TYPE_BASE, &comp);
  201137. /* make sure we include the NULL after the name and the compression type */
  201138. png_write_chunk_start(png_ptr, png_iCCP,
  201139. (png_uint_32)name_len+profile_len+2);
  201140. new_name[name_len+1]=0x00;
  201141. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201142. if (profile_len)
  201143. png_write_compressed_data_out(png_ptr, &comp);
  201144. png_write_chunk_end(png_ptr);
  201145. png_free(png_ptr, new_name);
  201146. }
  201147. #endif
  201148. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201149. /* write a sPLT chunk */
  201150. void /* PRIVATE */
  201151. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201152. {
  201153. #ifdef PNG_USE_LOCAL_ARRAYS
  201154. PNG_sPLT;
  201155. #endif
  201156. png_size_t name_len;
  201157. png_charp new_name;
  201158. png_byte entrybuf[10];
  201159. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201160. int palette_size = entry_size * spalette->nentries;
  201161. png_sPLT_entryp ep;
  201162. #ifdef PNG_NO_POINTER_INDEXING
  201163. int i;
  201164. #endif
  201165. png_debug(1, "in png_write_sPLT\n");
  201166. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201167. spalette->name, &new_name))==0)
  201168. {
  201169. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201170. return;
  201171. }
  201172. /* make sure we include the NULL after the name */
  201173. png_write_chunk_start(png_ptr, png_sPLT,
  201174. (png_uint_32)(name_len + 2 + palette_size));
  201175. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201176. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201177. /* loop through each palette entry, writing appropriately */
  201178. #ifndef PNG_NO_POINTER_INDEXING
  201179. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201180. {
  201181. if (spalette->depth == 8)
  201182. {
  201183. entrybuf[0] = (png_byte)ep->red;
  201184. entrybuf[1] = (png_byte)ep->green;
  201185. entrybuf[2] = (png_byte)ep->blue;
  201186. entrybuf[3] = (png_byte)ep->alpha;
  201187. png_save_uint_16(entrybuf + 4, ep->frequency);
  201188. }
  201189. else
  201190. {
  201191. png_save_uint_16(entrybuf + 0, ep->red);
  201192. png_save_uint_16(entrybuf + 2, ep->green);
  201193. png_save_uint_16(entrybuf + 4, ep->blue);
  201194. png_save_uint_16(entrybuf + 6, ep->alpha);
  201195. png_save_uint_16(entrybuf + 8, ep->frequency);
  201196. }
  201197. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201198. }
  201199. #else
  201200. ep=spalette->entries;
  201201. for (i=0; i>spalette->nentries; i++)
  201202. {
  201203. if (spalette->depth == 8)
  201204. {
  201205. entrybuf[0] = (png_byte)ep[i].red;
  201206. entrybuf[1] = (png_byte)ep[i].green;
  201207. entrybuf[2] = (png_byte)ep[i].blue;
  201208. entrybuf[3] = (png_byte)ep[i].alpha;
  201209. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201210. }
  201211. else
  201212. {
  201213. png_save_uint_16(entrybuf + 0, ep[i].red);
  201214. png_save_uint_16(entrybuf + 2, ep[i].green);
  201215. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201216. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201217. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201218. }
  201219. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201220. }
  201221. #endif
  201222. png_write_chunk_end(png_ptr);
  201223. png_free(png_ptr, new_name);
  201224. }
  201225. #endif
  201226. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201227. /* write the sBIT chunk */
  201228. void /* PRIVATE */
  201229. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201230. {
  201231. #ifdef PNG_USE_LOCAL_ARRAYS
  201232. PNG_sBIT;
  201233. #endif
  201234. png_byte buf[4];
  201235. png_size_t size;
  201236. png_debug(1, "in png_write_sBIT\n");
  201237. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201238. if (color_type & PNG_COLOR_MASK_COLOR)
  201239. {
  201240. png_byte maxbits;
  201241. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201242. png_ptr->usr_bit_depth);
  201243. if (sbit->red == 0 || sbit->red > maxbits ||
  201244. sbit->green == 0 || sbit->green > maxbits ||
  201245. sbit->blue == 0 || sbit->blue > maxbits)
  201246. {
  201247. png_warning(png_ptr, "Invalid sBIT depth specified");
  201248. return;
  201249. }
  201250. buf[0] = sbit->red;
  201251. buf[1] = sbit->green;
  201252. buf[2] = sbit->blue;
  201253. size = 3;
  201254. }
  201255. else
  201256. {
  201257. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201258. {
  201259. png_warning(png_ptr, "Invalid sBIT depth specified");
  201260. return;
  201261. }
  201262. buf[0] = sbit->gray;
  201263. size = 1;
  201264. }
  201265. if (color_type & PNG_COLOR_MASK_ALPHA)
  201266. {
  201267. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201268. {
  201269. png_warning(png_ptr, "Invalid sBIT depth specified");
  201270. return;
  201271. }
  201272. buf[size++] = sbit->alpha;
  201273. }
  201274. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201275. }
  201276. #endif
  201277. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201278. /* write the cHRM chunk */
  201279. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201280. void /* PRIVATE */
  201281. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201282. double red_x, double red_y, double green_x, double green_y,
  201283. double blue_x, double blue_y)
  201284. {
  201285. #ifdef PNG_USE_LOCAL_ARRAYS
  201286. PNG_cHRM;
  201287. #endif
  201288. png_byte buf[32];
  201289. png_uint_32 itemp;
  201290. png_debug(1, "in png_write_cHRM\n");
  201291. /* each value is saved in 1/100,000ths */
  201292. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201293. white_x + white_y > 1.0)
  201294. {
  201295. png_warning(png_ptr, "Invalid cHRM white point specified");
  201296. #if !defined(PNG_NO_CONSOLE_IO)
  201297. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201298. #endif
  201299. return;
  201300. }
  201301. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201302. png_save_uint_32(buf, itemp);
  201303. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201304. png_save_uint_32(buf + 4, itemp);
  201305. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201306. {
  201307. png_warning(png_ptr, "Invalid cHRM red point specified");
  201308. return;
  201309. }
  201310. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201311. png_save_uint_32(buf + 8, itemp);
  201312. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201313. png_save_uint_32(buf + 12, itemp);
  201314. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201315. {
  201316. png_warning(png_ptr, "Invalid cHRM green point specified");
  201317. return;
  201318. }
  201319. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201320. png_save_uint_32(buf + 16, itemp);
  201321. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201322. png_save_uint_32(buf + 20, itemp);
  201323. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201324. {
  201325. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201326. return;
  201327. }
  201328. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201329. png_save_uint_32(buf + 24, itemp);
  201330. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201331. png_save_uint_32(buf + 28, itemp);
  201332. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201333. }
  201334. #endif
  201335. #ifdef PNG_FIXED_POINT_SUPPORTED
  201336. void /* PRIVATE */
  201337. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201338. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201339. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201340. png_fixed_point blue_y)
  201341. {
  201342. #ifdef PNG_USE_LOCAL_ARRAYS
  201343. PNG_cHRM;
  201344. #endif
  201345. png_byte buf[32];
  201346. png_debug(1, "in png_write_cHRM\n");
  201347. /* each value is saved in 1/100,000ths */
  201348. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201349. {
  201350. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201351. #if !defined(PNG_NO_CONSOLE_IO)
  201352. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201353. #endif
  201354. return;
  201355. }
  201356. png_save_uint_32(buf, (png_uint_32)white_x);
  201357. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201358. if (red_x + red_y > 100000L)
  201359. {
  201360. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201361. return;
  201362. }
  201363. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201364. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201365. if (green_x + green_y > 100000L)
  201366. {
  201367. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201368. return;
  201369. }
  201370. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201371. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201372. if (blue_x + blue_y > 100000L)
  201373. {
  201374. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201375. return;
  201376. }
  201377. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201378. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201379. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201380. }
  201381. #endif
  201382. #endif
  201383. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201384. /* write the tRNS chunk */
  201385. void /* PRIVATE */
  201386. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201387. int num_trans, int color_type)
  201388. {
  201389. #ifdef PNG_USE_LOCAL_ARRAYS
  201390. PNG_tRNS;
  201391. #endif
  201392. png_byte buf[6];
  201393. png_debug(1, "in png_write_tRNS\n");
  201394. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201395. {
  201396. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201397. {
  201398. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201399. return;
  201400. }
  201401. /* write the chunk out as it is */
  201402. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201403. }
  201404. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201405. {
  201406. /* one 16 bit value */
  201407. if(tran->gray >= (1 << png_ptr->bit_depth))
  201408. {
  201409. png_warning(png_ptr,
  201410. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201411. return;
  201412. }
  201413. png_save_uint_16(buf, tran->gray);
  201414. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201415. }
  201416. else if (color_type == PNG_COLOR_TYPE_RGB)
  201417. {
  201418. /* three 16 bit values */
  201419. png_save_uint_16(buf, tran->red);
  201420. png_save_uint_16(buf + 2, tran->green);
  201421. png_save_uint_16(buf + 4, tran->blue);
  201422. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201423. {
  201424. png_warning(png_ptr,
  201425. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201426. return;
  201427. }
  201428. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201429. }
  201430. else
  201431. {
  201432. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201433. }
  201434. }
  201435. #endif
  201436. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201437. /* write the background chunk */
  201438. void /* PRIVATE */
  201439. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201440. {
  201441. #ifdef PNG_USE_LOCAL_ARRAYS
  201442. PNG_bKGD;
  201443. #endif
  201444. png_byte buf[6];
  201445. png_debug(1, "in png_write_bKGD\n");
  201446. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201447. {
  201448. if (
  201449. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201450. (png_ptr->num_palette ||
  201451. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201452. #endif
  201453. back->index > png_ptr->num_palette)
  201454. {
  201455. png_warning(png_ptr, "Invalid background palette index");
  201456. return;
  201457. }
  201458. buf[0] = back->index;
  201459. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201460. }
  201461. else if (color_type & PNG_COLOR_MASK_COLOR)
  201462. {
  201463. png_save_uint_16(buf, back->red);
  201464. png_save_uint_16(buf + 2, back->green);
  201465. png_save_uint_16(buf + 4, back->blue);
  201466. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201467. {
  201468. png_warning(png_ptr,
  201469. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201470. return;
  201471. }
  201472. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201473. }
  201474. else
  201475. {
  201476. if(back->gray >= (1 << png_ptr->bit_depth))
  201477. {
  201478. png_warning(png_ptr,
  201479. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201480. return;
  201481. }
  201482. png_save_uint_16(buf, back->gray);
  201483. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201484. }
  201485. }
  201486. #endif
  201487. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201488. /* write the histogram */
  201489. void /* PRIVATE */
  201490. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201491. {
  201492. #ifdef PNG_USE_LOCAL_ARRAYS
  201493. PNG_hIST;
  201494. #endif
  201495. int i;
  201496. png_byte buf[3];
  201497. png_debug(1, "in png_write_hIST\n");
  201498. if (num_hist > (int)png_ptr->num_palette)
  201499. {
  201500. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201501. png_ptr->num_palette);
  201502. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201503. return;
  201504. }
  201505. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201506. for (i = 0; i < num_hist; i++)
  201507. {
  201508. png_save_uint_16(buf, hist[i]);
  201509. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201510. }
  201511. png_write_chunk_end(png_ptr);
  201512. }
  201513. #endif
  201514. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201515. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201516. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201517. * and if invalid, correct the keyword rather than discarding the entire
  201518. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201519. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201520. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201521. *
  201522. * The new_key is allocated to hold the corrected keyword and must be freed
  201523. * by the calling routine. This avoids problems with trying to write to
  201524. * static keywords without having to have duplicate copies of the strings.
  201525. */
  201526. png_size_t /* PRIVATE */
  201527. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201528. {
  201529. png_size_t key_len;
  201530. png_charp kp, dp;
  201531. int kflag;
  201532. int kwarn=0;
  201533. png_debug(1, "in png_check_keyword\n");
  201534. *new_key = NULL;
  201535. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201536. {
  201537. png_warning(png_ptr, "zero length keyword");
  201538. return ((png_size_t)0);
  201539. }
  201540. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201541. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201542. if (*new_key == NULL)
  201543. {
  201544. png_warning(png_ptr, "Out of memory while procesing keyword");
  201545. return ((png_size_t)0);
  201546. }
  201547. /* Replace non-printing characters with a blank and print a warning */
  201548. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201549. {
  201550. if ((png_byte)*kp < 0x20 ||
  201551. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201552. {
  201553. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201554. char msg[40];
  201555. png_snprintf(msg, 40,
  201556. "invalid keyword character 0x%02X", (png_byte)*kp);
  201557. png_warning(png_ptr, msg);
  201558. #else
  201559. png_warning(png_ptr, "invalid character in keyword");
  201560. #endif
  201561. *dp = ' ';
  201562. }
  201563. else
  201564. {
  201565. *dp = *kp;
  201566. }
  201567. }
  201568. *dp = '\0';
  201569. /* Remove any trailing white space. */
  201570. kp = *new_key + key_len - 1;
  201571. if (*kp == ' ')
  201572. {
  201573. png_warning(png_ptr, "trailing spaces removed from keyword");
  201574. while (*kp == ' ')
  201575. {
  201576. *(kp--) = '\0';
  201577. key_len--;
  201578. }
  201579. }
  201580. /* Remove any leading white space. */
  201581. kp = *new_key;
  201582. if (*kp == ' ')
  201583. {
  201584. png_warning(png_ptr, "leading spaces removed from keyword");
  201585. while (*kp == ' ')
  201586. {
  201587. kp++;
  201588. key_len--;
  201589. }
  201590. }
  201591. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201592. /* Remove multiple internal spaces. */
  201593. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201594. {
  201595. if (*kp == ' ' && kflag == 0)
  201596. {
  201597. *(dp++) = *kp;
  201598. kflag = 1;
  201599. }
  201600. else if (*kp == ' ')
  201601. {
  201602. key_len--;
  201603. kwarn=1;
  201604. }
  201605. else
  201606. {
  201607. *(dp++) = *kp;
  201608. kflag = 0;
  201609. }
  201610. }
  201611. *dp = '\0';
  201612. if(kwarn)
  201613. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201614. if (key_len == 0)
  201615. {
  201616. png_free(png_ptr, *new_key);
  201617. *new_key=NULL;
  201618. png_warning(png_ptr, "Zero length keyword");
  201619. }
  201620. if (key_len > 79)
  201621. {
  201622. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201623. new_key[79] = '\0';
  201624. key_len = 79;
  201625. }
  201626. return (key_len);
  201627. }
  201628. #endif
  201629. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201630. /* write a tEXt chunk */
  201631. void /* PRIVATE */
  201632. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201633. png_size_t text_len)
  201634. {
  201635. #ifdef PNG_USE_LOCAL_ARRAYS
  201636. PNG_tEXt;
  201637. #endif
  201638. png_size_t key_len;
  201639. png_charp new_key;
  201640. png_debug(1, "in png_write_tEXt\n");
  201641. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201642. {
  201643. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201644. return;
  201645. }
  201646. if (text == NULL || *text == '\0')
  201647. text_len = 0;
  201648. else
  201649. text_len = png_strlen(text);
  201650. /* make sure we include the 0 after the key */
  201651. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201652. /*
  201653. * We leave it to the application to meet PNG-1.0 requirements on the
  201654. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201655. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201656. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201657. */
  201658. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201659. if (text_len)
  201660. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201661. png_write_chunk_end(png_ptr);
  201662. png_free(png_ptr, new_key);
  201663. }
  201664. #endif
  201665. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201666. /* write a compressed text chunk */
  201667. void /* PRIVATE */
  201668. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201669. png_size_t text_len, int compression)
  201670. {
  201671. #ifdef PNG_USE_LOCAL_ARRAYS
  201672. PNG_zTXt;
  201673. #endif
  201674. png_size_t key_len;
  201675. char buf[1];
  201676. png_charp new_key;
  201677. compression_state comp;
  201678. png_debug(1, "in png_write_zTXt\n");
  201679. comp.num_output_ptr = 0;
  201680. comp.max_output_ptr = 0;
  201681. comp.output_ptr = NULL;
  201682. comp.input = NULL;
  201683. comp.input_len = 0;
  201684. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201685. {
  201686. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201687. return;
  201688. }
  201689. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201690. {
  201691. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201692. png_free(png_ptr, new_key);
  201693. return;
  201694. }
  201695. text_len = png_strlen(text);
  201696. /* compute the compressed data; do it now for the length */
  201697. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201698. &comp);
  201699. /* write start of chunk */
  201700. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201701. (key_len+text_len+2));
  201702. /* write key */
  201703. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201704. png_free(png_ptr, new_key);
  201705. buf[0] = (png_byte)compression;
  201706. /* write compression */
  201707. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201708. /* write the compressed data */
  201709. png_write_compressed_data_out(png_ptr, &comp);
  201710. /* close the chunk */
  201711. png_write_chunk_end(png_ptr);
  201712. }
  201713. #endif
  201714. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201715. /* write an iTXt chunk */
  201716. void /* PRIVATE */
  201717. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201718. png_charp lang, png_charp lang_key, png_charp text)
  201719. {
  201720. #ifdef PNG_USE_LOCAL_ARRAYS
  201721. PNG_iTXt;
  201722. #endif
  201723. png_size_t lang_len, key_len, lang_key_len, text_len;
  201724. png_charp new_lang, new_key;
  201725. png_byte cbuf[2];
  201726. compression_state comp;
  201727. png_debug(1, "in png_write_iTXt\n");
  201728. comp.num_output_ptr = 0;
  201729. comp.max_output_ptr = 0;
  201730. comp.output_ptr = NULL;
  201731. comp.input = NULL;
  201732. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201733. {
  201734. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201735. return;
  201736. }
  201737. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201738. {
  201739. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201740. new_lang = NULL;
  201741. lang_len = 0;
  201742. }
  201743. if (lang_key == NULL)
  201744. lang_key_len = 0;
  201745. else
  201746. lang_key_len = png_strlen(lang_key);
  201747. if (text == NULL)
  201748. text_len = 0;
  201749. else
  201750. text_len = png_strlen(text);
  201751. /* compute the compressed data; do it now for the length */
  201752. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201753. &comp);
  201754. /* make sure we include the compression flag, the compression byte,
  201755. * and the NULs after the key, lang, and lang_key parts */
  201756. png_write_chunk_start(png_ptr, png_iTXt,
  201757. (png_uint_32)(
  201758. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201759. + key_len
  201760. + lang_len
  201761. + lang_key_len
  201762. + text_len));
  201763. /*
  201764. * We leave it to the application to meet PNG-1.0 requirements on the
  201765. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201766. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201767. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201768. */
  201769. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201770. /* set the compression flag */
  201771. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201772. compression == PNG_TEXT_COMPRESSION_NONE)
  201773. cbuf[0] = 0;
  201774. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201775. cbuf[0] = 1;
  201776. /* set the compression method */
  201777. cbuf[1] = 0;
  201778. png_write_chunk_data(png_ptr, cbuf, 2);
  201779. cbuf[0] = 0;
  201780. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201781. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201782. png_write_compressed_data_out(png_ptr, &comp);
  201783. png_write_chunk_end(png_ptr);
  201784. png_free(png_ptr, new_key);
  201785. if (new_lang)
  201786. png_free(png_ptr, new_lang);
  201787. }
  201788. #endif
  201789. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201790. /* write the oFFs chunk */
  201791. void /* PRIVATE */
  201792. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201793. int unit_type)
  201794. {
  201795. #ifdef PNG_USE_LOCAL_ARRAYS
  201796. PNG_oFFs;
  201797. #endif
  201798. png_byte buf[9];
  201799. png_debug(1, "in png_write_oFFs\n");
  201800. if (unit_type >= PNG_OFFSET_LAST)
  201801. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201802. png_save_int_32(buf, x_offset);
  201803. png_save_int_32(buf + 4, y_offset);
  201804. buf[8] = (png_byte)unit_type;
  201805. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201806. }
  201807. #endif
  201808. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201809. /* write the pCAL chunk (described in the PNG extensions document) */
  201810. void /* PRIVATE */
  201811. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201812. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201813. {
  201814. #ifdef PNG_USE_LOCAL_ARRAYS
  201815. PNG_pCAL;
  201816. #endif
  201817. png_size_t purpose_len, units_len, total_len;
  201818. png_uint_32p params_len;
  201819. png_byte buf[10];
  201820. png_charp new_purpose;
  201821. int i;
  201822. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201823. if (type >= PNG_EQUATION_LAST)
  201824. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201825. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201826. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201827. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201828. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201829. total_len = purpose_len + units_len + 10;
  201830. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201831. *png_sizeof(png_uint_32)));
  201832. /* Find the length of each parameter, making sure we don't count the
  201833. null terminator for the last parameter. */
  201834. for (i = 0; i < nparams; i++)
  201835. {
  201836. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201837. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201838. total_len += (png_size_t)params_len[i];
  201839. }
  201840. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201841. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201842. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201843. png_save_int_32(buf, X0);
  201844. png_save_int_32(buf + 4, X1);
  201845. buf[8] = (png_byte)type;
  201846. buf[9] = (png_byte)nparams;
  201847. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201848. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201849. png_free(png_ptr, new_purpose);
  201850. for (i = 0; i < nparams; i++)
  201851. {
  201852. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201853. (png_size_t)params_len[i]);
  201854. }
  201855. png_free(png_ptr, params_len);
  201856. png_write_chunk_end(png_ptr);
  201857. }
  201858. #endif
  201859. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201860. /* write the sCAL chunk */
  201861. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201862. void /* PRIVATE */
  201863. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201864. {
  201865. #ifdef PNG_USE_LOCAL_ARRAYS
  201866. PNG_sCAL;
  201867. #endif
  201868. char buf[64];
  201869. png_size_t total_len;
  201870. png_debug(1, "in png_write_sCAL\n");
  201871. buf[0] = (char)unit;
  201872. #if defined(_WIN32_WCE)
  201873. /* sprintf() function is not supported on WindowsCE */
  201874. {
  201875. wchar_t wc_buf[32];
  201876. size_t wc_len;
  201877. swprintf(wc_buf, TEXT("%12.12e"), width);
  201878. wc_len = wcslen(wc_buf);
  201879. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201880. total_len = wc_len + 2;
  201881. swprintf(wc_buf, TEXT("%12.12e"), height);
  201882. wc_len = wcslen(wc_buf);
  201883. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201884. NULL, NULL);
  201885. total_len += wc_len;
  201886. }
  201887. #else
  201888. png_snprintf(buf + 1, 63, "%12.12e", width);
  201889. total_len = 1 + png_strlen(buf + 1) + 1;
  201890. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201891. total_len += png_strlen(buf + total_len);
  201892. #endif
  201893. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201894. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201895. }
  201896. #else
  201897. #ifdef PNG_FIXED_POINT_SUPPORTED
  201898. void /* PRIVATE */
  201899. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201900. png_charp height)
  201901. {
  201902. #ifdef PNG_USE_LOCAL_ARRAYS
  201903. PNG_sCAL;
  201904. #endif
  201905. png_byte buf[64];
  201906. png_size_t wlen, hlen, total_len;
  201907. png_debug(1, "in png_write_sCAL_s\n");
  201908. wlen = png_strlen(width);
  201909. hlen = png_strlen(height);
  201910. total_len = wlen + hlen + 2;
  201911. if (total_len > 64)
  201912. {
  201913. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201914. return;
  201915. }
  201916. buf[0] = (png_byte)unit;
  201917. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201918. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201919. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201920. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201921. }
  201922. #endif
  201923. #endif
  201924. #endif
  201925. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201926. /* write the pHYs chunk */
  201927. void /* PRIVATE */
  201928. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201929. png_uint_32 y_pixels_per_unit,
  201930. int unit_type)
  201931. {
  201932. #ifdef PNG_USE_LOCAL_ARRAYS
  201933. PNG_pHYs;
  201934. #endif
  201935. png_byte buf[9];
  201936. png_debug(1, "in png_write_pHYs\n");
  201937. if (unit_type >= PNG_RESOLUTION_LAST)
  201938. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201939. png_save_uint_32(buf, x_pixels_per_unit);
  201940. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201941. buf[8] = (png_byte)unit_type;
  201942. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201943. }
  201944. #endif
  201945. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201946. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201947. * or png_convert_from_time_t(), or fill in the structure yourself.
  201948. */
  201949. void /* PRIVATE */
  201950. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201951. {
  201952. #ifdef PNG_USE_LOCAL_ARRAYS
  201953. PNG_tIME;
  201954. #endif
  201955. png_byte buf[7];
  201956. png_debug(1, "in png_write_tIME\n");
  201957. if (mod_time->month > 12 || mod_time->month < 1 ||
  201958. mod_time->day > 31 || mod_time->day < 1 ||
  201959. mod_time->hour > 23 || mod_time->second > 60)
  201960. {
  201961. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201962. return;
  201963. }
  201964. png_save_uint_16(buf, mod_time->year);
  201965. buf[2] = mod_time->month;
  201966. buf[3] = mod_time->day;
  201967. buf[4] = mod_time->hour;
  201968. buf[5] = mod_time->minute;
  201969. buf[6] = mod_time->second;
  201970. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201971. }
  201972. #endif
  201973. /* initializes the row writing capability of libpng */
  201974. void /* PRIVATE */
  201975. png_write_start_row(png_structp png_ptr)
  201976. {
  201977. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201978. #ifdef PNG_USE_LOCAL_ARRAYS
  201979. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201980. /* start of interlace block */
  201981. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201982. /* offset to next interlace block */
  201983. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201984. /* start of interlace block in the y direction */
  201985. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201986. /* offset to next interlace block in the y direction */
  201987. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201988. #endif
  201989. #endif
  201990. png_size_t buf_size;
  201991. png_debug(1, "in png_write_start_row\n");
  201992. buf_size = (png_size_t)(PNG_ROWBYTES(
  201993. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201994. /* set up row buffer */
  201995. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201996. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201997. #ifndef PNG_NO_WRITE_FILTERING
  201998. /* set up filtering buffer, if using this filter */
  201999. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202000. {
  202001. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202002. (png_ptr->rowbytes + 1));
  202003. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202004. }
  202005. /* We only need to keep the previous row if we are using one of these. */
  202006. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202007. {
  202008. /* set up previous row buffer */
  202009. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202010. png_memset(png_ptr->prev_row, 0, buf_size);
  202011. if (png_ptr->do_filter & PNG_FILTER_UP)
  202012. {
  202013. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202014. (png_ptr->rowbytes + 1));
  202015. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202016. }
  202017. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202018. {
  202019. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202020. (png_ptr->rowbytes + 1));
  202021. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202022. }
  202023. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202024. {
  202025. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202026. (png_ptr->rowbytes + 1));
  202027. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202028. }
  202029. #endif /* PNG_NO_WRITE_FILTERING */
  202030. }
  202031. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202032. /* if interlaced, we need to set up width and height of pass */
  202033. if (png_ptr->interlaced)
  202034. {
  202035. if (!(png_ptr->transformations & PNG_INTERLACE))
  202036. {
  202037. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202038. png_pass_ystart[0]) / png_pass_yinc[0];
  202039. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202040. png_pass_start[0]) / png_pass_inc[0];
  202041. }
  202042. else
  202043. {
  202044. png_ptr->num_rows = png_ptr->height;
  202045. png_ptr->usr_width = png_ptr->width;
  202046. }
  202047. }
  202048. else
  202049. #endif
  202050. {
  202051. png_ptr->num_rows = png_ptr->height;
  202052. png_ptr->usr_width = png_ptr->width;
  202053. }
  202054. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202055. png_ptr->zstream.next_out = png_ptr->zbuf;
  202056. }
  202057. /* Internal use only. Called when finished processing a row of data. */
  202058. void /* PRIVATE */
  202059. png_write_finish_row(png_structp png_ptr)
  202060. {
  202061. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202062. #ifdef PNG_USE_LOCAL_ARRAYS
  202063. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202064. /* start of interlace block */
  202065. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202066. /* offset to next interlace block */
  202067. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202068. /* start of interlace block in the y direction */
  202069. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202070. /* offset to next interlace block in the y direction */
  202071. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202072. #endif
  202073. #endif
  202074. int ret;
  202075. png_debug(1, "in png_write_finish_row\n");
  202076. /* next row */
  202077. png_ptr->row_number++;
  202078. /* see if we are done */
  202079. if (png_ptr->row_number < png_ptr->num_rows)
  202080. return;
  202081. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202082. /* if interlaced, go to next pass */
  202083. if (png_ptr->interlaced)
  202084. {
  202085. png_ptr->row_number = 0;
  202086. if (png_ptr->transformations & PNG_INTERLACE)
  202087. {
  202088. png_ptr->pass++;
  202089. }
  202090. else
  202091. {
  202092. /* loop until we find a non-zero width or height pass */
  202093. do
  202094. {
  202095. png_ptr->pass++;
  202096. if (png_ptr->pass >= 7)
  202097. break;
  202098. png_ptr->usr_width = (png_ptr->width +
  202099. png_pass_inc[png_ptr->pass] - 1 -
  202100. png_pass_start[png_ptr->pass]) /
  202101. png_pass_inc[png_ptr->pass];
  202102. png_ptr->num_rows = (png_ptr->height +
  202103. png_pass_yinc[png_ptr->pass] - 1 -
  202104. png_pass_ystart[png_ptr->pass]) /
  202105. png_pass_yinc[png_ptr->pass];
  202106. if (png_ptr->transformations & PNG_INTERLACE)
  202107. break;
  202108. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202109. }
  202110. /* reset the row above the image for the next pass */
  202111. if (png_ptr->pass < 7)
  202112. {
  202113. if (png_ptr->prev_row != NULL)
  202114. png_memset(png_ptr->prev_row, 0,
  202115. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202116. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202117. return;
  202118. }
  202119. }
  202120. #endif
  202121. /* if we get here, we've just written the last row, so we need
  202122. to flush the compressor */
  202123. do
  202124. {
  202125. /* tell the compressor we are done */
  202126. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202127. /* check for an error */
  202128. if (ret == Z_OK)
  202129. {
  202130. /* check to see if we need more room */
  202131. if (!(png_ptr->zstream.avail_out))
  202132. {
  202133. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202134. png_ptr->zstream.next_out = png_ptr->zbuf;
  202135. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202136. }
  202137. }
  202138. else if (ret != Z_STREAM_END)
  202139. {
  202140. if (png_ptr->zstream.msg != NULL)
  202141. png_error(png_ptr, png_ptr->zstream.msg);
  202142. else
  202143. png_error(png_ptr, "zlib error");
  202144. }
  202145. } while (ret != Z_STREAM_END);
  202146. /* write any extra space */
  202147. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202148. {
  202149. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202150. png_ptr->zstream.avail_out);
  202151. }
  202152. deflateReset(&png_ptr->zstream);
  202153. png_ptr->zstream.data_type = Z_BINARY;
  202154. }
  202155. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202156. /* Pick out the correct pixels for the interlace pass.
  202157. * The basic idea here is to go through the row with a source
  202158. * pointer and a destination pointer (sp and dp), and copy the
  202159. * correct pixels for the pass. As the row gets compacted,
  202160. * sp will always be >= dp, so we should never overwrite anything.
  202161. * See the default: case for the easiest code to understand.
  202162. */
  202163. void /* PRIVATE */
  202164. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202165. {
  202166. #ifdef PNG_USE_LOCAL_ARRAYS
  202167. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202168. /* start of interlace block */
  202169. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202170. /* offset to next interlace block */
  202171. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202172. #endif
  202173. png_debug(1, "in png_do_write_interlace\n");
  202174. /* we don't have to do anything on the last pass (6) */
  202175. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202176. if (row != NULL && row_info != NULL && pass < 6)
  202177. #else
  202178. if (pass < 6)
  202179. #endif
  202180. {
  202181. /* each pixel depth is handled separately */
  202182. switch (row_info->pixel_depth)
  202183. {
  202184. case 1:
  202185. {
  202186. png_bytep sp;
  202187. png_bytep dp;
  202188. int shift;
  202189. int d;
  202190. int value;
  202191. png_uint_32 i;
  202192. png_uint_32 row_width = row_info->width;
  202193. dp = row;
  202194. d = 0;
  202195. shift = 7;
  202196. for (i = png_pass_start[pass]; i < row_width;
  202197. i += png_pass_inc[pass])
  202198. {
  202199. sp = row + (png_size_t)(i >> 3);
  202200. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202201. d |= (value << shift);
  202202. if (shift == 0)
  202203. {
  202204. shift = 7;
  202205. *dp++ = (png_byte)d;
  202206. d = 0;
  202207. }
  202208. else
  202209. shift--;
  202210. }
  202211. if (shift != 7)
  202212. *dp = (png_byte)d;
  202213. break;
  202214. }
  202215. case 2:
  202216. {
  202217. png_bytep sp;
  202218. png_bytep dp;
  202219. int shift;
  202220. int d;
  202221. int value;
  202222. png_uint_32 i;
  202223. png_uint_32 row_width = row_info->width;
  202224. dp = row;
  202225. shift = 6;
  202226. d = 0;
  202227. for (i = png_pass_start[pass]; i < row_width;
  202228. i += png_pass_inc[pass])
  202229. {
  202230. sp = row + (png_size_t)(i >> 2);
  202231. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202232. d |= (value << shift);
  202233. if (shift == 0)
  202234. {
  202235. shift = 6;
  202236. *dp++ = (png_byte)d;
  202237. d = 0;
  202238. }
  202239. else
  202240. shift -= 2;
  202241. }
  202242. if (shift != 6)
  202243. *dp = (png_byte)d;
  202244. break;
  202245. }
  202246. case 4:
  202247. {
  202248. png_bytep sp;
  202249. png_bytep dp;
  202250. int shift;
  202251. int d;
  202252. int value;
  202253. png_uint_32 i;
  202254. png_uint_32 row_width = row_info->width;
  202255. dp = row;
  202256. shift = 4;
  202257. d = 0;
  202258. for (i = png_pass_start[pass]; i < row_width;
  202259. i += png_pass_inc[pass])
  202260. {
  202261. sp = row + (png_size_t)(i >> 1);
  202262. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202263. d |= (value << shift);
  202264. if (shift == 0)
  202265. {
  202266. shift = 4;
  202267. *dp++ = (png_byte)d;
  202268. d = 0;
  202269. }
  202270. else
  202271. shift -= 4;
  202272. }
  202273. if (shift != 4)
  202274. *dp = (png_byte)d;
  202275. break;
  202276. }
  202277. default:
  202278. {
  202279. png_bytep sp;
  202280. png_bytep dp;
  202281. png_uint_32 i;
  202282. png_uint_32 row_width = row_info->width;
  202283. png_size_t pixel_bytes;
  202284. /* start at the beginning */
  202285. dp = row;
  202286. /* find out how many bytes each pixel takes up */
  202287. pixel_bytes = (row_info->pixel_depth >> 3);
  202288. /* loop through the row, only looking at the pixels that
  202289. matter */
  202290. for (i = png_pass_start[pass]; i < row_width;
  202291. i += png_pass_inc[pass])
  202292. {
  202293. /* find out where the original pixel is */
  202294. sp = row + (png_size_t)i * pixel_bytes;
  202295. /* move the pixel */
  202296. if (dp != sp)
  202297. png_memcpy(dp, sp, pixel_bytes);
  202298. /* next pixel */
  202299. dp += pixel_bytes;
  202300. }
  202301. break;
  202302. }
  202303. }
  202304. /* set new row width */
  202305. row_info->width = (row_info->width +
  202306. png_pass_inc[pass] - 1 -
  202307. png_pass_start[pass]) /
  202308. png_pass_inc[pass];
  202309. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202310. row_info->width);
  202311. }
  202312. }
  202313. #endif
  202314. /* This filters the row, chooses which filter to use, if it has not already
  202315. * been specified by the application, and then writes the row out with the
  202316. * chosen filter.
  202317. */
  202318. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202319. #define PNG_HISHIFT 10
  202320. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202321. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202322. void /* PRIVATE */
  202323. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202324. {
  202325. png_bytep best_row;
  202326. #ifndef PNG_NO_WRITE_FILTER
  202327. png_bytep prev_row, row_buf;
  202328. png_uint_32 mins, bpp;
  202329. png_byte filter_to_do = png_ptr->do_filter;
  202330. png_uint_32 row_bytes = row_info->rowbytes;
  202331. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202332. int num_p_filters = (int)png_ptr->num_prev_filters;
  202333. #endif
  202334. png_debug(1, "in png_write_find_filter\n");
  202335. /* find out how many bytes offset each pixel is */
  202336. bpp = (row_info->pixel_depth + 7) >> 3;
  202337. prev_row = png_ptr->prev_row;
  202338. #endif
  202339. best_row = png_ptr->row_buf;
  202340. #ifndef PNG_NO_WRITE_FILTER
  202341. row_buf = best_row;
  202342. mins = PNG_MAXSUM;
  202343. /* The prediction method we use is to find which method provides the
  202344. * smallest value when summing the absolute values of the distances
  202345. * from zero, using anything >= 128 as negative numbers. This is known
  202346. * as the "minimum sum of absolute differences" heuristic. Other
  202347. * heuristics are the "weighted minimum sum of absolute differences"
  202348. * (experimental and can in theory improve compression), and the "zlib
  202349. * predictive" method (not implemented yet), which does test compressions
  202350. * of lines using different filter methods, and then chooses the
  202351. * (series of) filter(s) that give minimum compressed data size (VERY
  202352. * computationally expensive).
  202353. *
  202354. * GRR 980525: consider also
  202355. * (1) minimum sum of absolute differences from running average (i.e.,
  202356. * keep running sum of non-absolute differences & count of bytes)
  202357. * [track dispersion, too? restart average if dispersion too large?]
  202358. * (1b) minimum sum of absolute differences from sliding average, probably
  202359. * with window size <= deflate window (usually 32K)
  202360. * (2) minimum sum of squared differences from zero or running average
  202361. * (i.e., ~ root-mean-square approach)
  202362. */
  202363. /* We don't need to test the 'no filter' case if this is the only filter
  202364. * that has been chosen, as it doesn't actually do anything to the data.
  202365. */
  202366. if ((filter_to_do & PNG_FILTER_NONE) &&
  202367. filter_to_do != PNG_FILTER_NONE)
  202368. {
  202369. png_bytep rp;
  202370. png_uint_32 sum = 0;
  202371. png_uint_32 i;
  202372. int v;
  202373. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202374. {
  202375. v = *rp;
  202376. sum += (v < 128) ? v : 256 - v;
  202377. }
  202378. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202379. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202380. {
  202381. png_uint_32 sumhi, sumlo;
  202382. int j;
  202383. sumlo = sum & PNG_LOMASK;
  202384. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202385. /* Reduce the sum if we match any of the previous rows */
  202386. for (j = 0; j < num_p_filters; j++)
  202387. {
  202388. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202389. {
  202390. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202391. PNG_WEIGHT_SHIFT;
  202392. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202393. PNG_WEIGHT_SHIFT;
  202394. }
  202395. }
  202396. /* Factor in the cost of this filter (this is here for completeness,
  202397. * but it makes no sense to have a "cost" for the NONE filter, as
  202398. * it has the minimum possible computational cost - none).
  202399. */
  202400. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202401. PNG_COST_SHIFT;
  202402. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202403. PNG_COST_SHIFT;
  202404. if (sumhi > PNG_HIMASK)
  202405. sum = PNG_MAXSUM;
  202406. else
  202407. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202408. }
  202409. #endif
  202410. mins = sum;
  202411. }
  202412. /* sub filter */
  202413. if (filter_to_do == PNG_FILTER_SUB)
  202414. /* it's the only filter so no testing is needed */
  202415. {
  202416. png_bytep rp, lp, dp;
  202417. png_uint_32 i;
  202418. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202419. i++, rp++, dp++)
  202420. {
  202421. *dp = *rp;
  202422. }
  202423. for (lp = row_buf + 1; i < row_bytes;
  202424. i++, rp++, lp++, dp++)
  202425. {
  202426. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202427. }
  202428. best_row = png_ptr->sub_row;
  202429. }
  202430. else if (filter_to_do & PNG_FILTER_SUB)
  202431. {
  202432. png_bytep rp, dp, lp;
  202433. png_uint_32 sum = 0, lmins = mins;
  202434. png_uint_32 i;
  202435. int v;
  202436. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202437. /* We temporarily increase the "minimum sum" by the factor we
  202438. * would reduce the sum of this filter, so that we can do the
  202439. * early exit comparison without scaling the sum each time.
  202440. */
  202441. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202442. {
  202443. int j;
  202444. png_uint_32 lmhi, lmlo;
  202445. lmlo = lmins & PNG_LOMASK;
  202446. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202447. for (j = 0; j < num_p_filters; j++)
  202448. {
  202449. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202450. {
  202451. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202452. PNG_WEIGHT_SHIFT;
  202453. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202454. PNG_WEIGHT_SHIFT;
  202455. }
  202456. }
  202457. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202458. PNG_COST_SHIFT;
  202459. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202460. PNG_COST_SHIFT;
  202461. if (lmhi > PNG_HIMASK)
  202462. lmins = PNG_MAXSUM;
  202463. else
  202464. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202465. }
  202466. #endif
  202467. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202468. i++, rp++, dp++)
  202469. {
  202470. v = *dp = *rp;
  202471. sum += (v < 128) ? v : 256 - v;
  202472. }
  202473. for (lp = row_buf + 1; i < row_bytes;
  202474. i++, rp++, lp++, dp++)
  202475. {
  202476. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202477. sum += (v < 128) ? v : 256 - v;
  202478. if (sum > lmins) /* We are already worse, don't continue. */
  202479. break;
  202480. }
  202481. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202482. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202483. {
  202484. int j;
  202485. png_uint_32 sumhi, sumlo;
  202486. sumlo = sum & PNG_LOMASK;
  202487. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202488. for (j = 0; j < num_p_filters; j++)
  202489. {
  202490. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202491. {
  202492. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202493. PNG_WEIGHT_SHIFT;
  202494. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202495. PNG_WEIGHT_SHIFT;
  202496. }
  202497. }
  202498. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202499. PNG_COST_SHIFT;
  202500. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202501. PNG_COST_SHIFT;
  202502. if (sumhi > PNG_HIMASK)
  202503. sum = PNG_MAXSUM;
  202504. else
  202505. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202506. }
  202507. #endif
  202508. if (sum < mins)
  202509. {
  202510. mins = sum;
  202511. best_row = png_ptr->sub_row;
  202512. }
  202513. }
  202514. /* up filter */
  202515. if (filter_to_do == PNG_FILTER_UP)
  202516. {
  202517. png_bytep rp, dp, pp;
  202518. png_uint_32 i;
  202519. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202520. pp = prev_row + 1; i < row_bytes;
  202521. i++, rp++, pp++, dp++)
  202522. {
  202523. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202524. }
  202525. best_row = png_ptr->up_row;
  202526. }
  202527. else if (filter_to_do & PNG_FILTER_UP)
  202528. {
  202529. png_bytep rp, dp, pp;
  202530. png_uint_32 sum = 0, lmins = mins;
  202531. png_uint_32 i;
  202532. int v;
  202533. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202534. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202535. {
  202536. int j;
  202537. png_uint_32 lmhi, lmlo;
  202538. lmlo = lmins & PNG_LOMASK;
  202539. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202540. for (j = 0; j < num_p_filters; j++)
  202541. {
  202542. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202543. {
  202544. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202545. PNG_WEIGHT_SHIFT;
  202546. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202547. PNG_WEIGHT_SHIFT;
  202548. }
  202549. }
  202550. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202551. PNG_COST_SHIFT;
  202552. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202553. PNG_COST_SHIFT;
  202554. if (lmhi > PNG_HIMASK)
  202555. lmins = PNG_MAXSUM;
  202556. else
  202557. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202558. }
  202559. #endif
  202560. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202561. pp = prev_row + 1; i < row_bytes; i++)
  202562. {
  202563. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202564. sum += (v < 128) ? v : 256 - v;
  202565. if (sum > lmins) /* We are already worse, don't continue. */
  202566. break;
  202567. }
  202568. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202569. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202570. {
  202571. int j;
  202572. png_uint_32 sumhi, sumlo;
  202573. sumlo = sum & PNG_LOMASK;
  202574. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202575. for (j = 0; j < num_p_filters; j++)
  202576. {
  202577. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202578. {
  202579. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202580. PNG_WEIGHT_SHIFT;
  202581. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202582. PNG_WEIGHT_SHIFT;
  202583. }
  202584. }
  202585. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202586. PNG_COST_SHIFT;
  202587. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202588. PNG_COST_SHIFT;
  202589. if (sumhi > PNG_HIMASK)
  202590. sum = PNG_MAXSUM;
  202591. else
  202592. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202593. }
  202594. #endif
  202595. if (sum < mins)
  202596. {
  202597. mins = sum;
  202598. best_row = png_ptr->up_row;
  202599. }
  202600. }
  202601. /* avg filter */
  202602. if (filter_to_do == PNG_FILTER_AVG)
  202603. {
  202604. png_bytep rp, dp, pp, lp;
  202605. png_uint_32 i;
  202606. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202607. pp = prev_row + 1; i < bpp; i++)
  202608. {
  202609. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202610. }
  202611. for (lp = row_buf + 1; i < row_bytes; i++)
  202612. {
  202613. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202614. & 0xff);
  202615. }
  202616. best_row = png_ptr->avg_row;
  202617. }
  202618. else if (filter_to_do & PNG_FILTER_AVG)
  202619. {
  202620. png_bytep rp, dp, pp, lp;
  202621. png_uint_32 sum = 0, lmins = mins;
  202622. png_uint_32 i;
  202623. int v;
  202624. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202625. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202626. {
  202627. int j;
  202628. png_uint_32 lmhi, lmlo;
  202629. lmlo = lmins & PNG_LOMASK;
  202630. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202631. for (j = 0; j < num_p_filters; j++)
  202632. {
  202633. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202634. {
  202635. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202636. PNG_WEIGHT_SHIFT;
  202637. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202638. PNG_WEIGHT_SHIFT;
  202639. }
  202640. }
  202641. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202642. PNG_COST_SHIFT;
  202643. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202644. PNG_COST_SHIFT;
  202645. if (lmhi > PNG_HIMASK)
  202646. lmins = PNG_MAXSUM;
  202647. else
  202648. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202649. }
  202650. #endif
  202651. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202652. pp = prev_row + 1; i < bpp; i++)
  202653. {
  202654. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202655. sum += (v < 128) ? v : 256 - v;
  202656. }
  202657. for (lp = row_buf + 1; i < row_bytes; i++)
  202658. {
  202659. v = *dp++ =
  202660. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202661. sum += (v < 128) ? v : 256 - v;
  202662. if (sum > lmins) /* We are already worse, don't continue. */
  202663. break;
  202664. }
  202665. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202666. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202667. {
  202668. int j;
  202669. png_uint_32 sumhi, sumlo;
  202670. sumlo = sum & PNG_LOMASK;
  202671. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202672. for (j = 0; j < num_p_filters; j++)
  202673. {
  202674. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202675. {
  202676. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202677. PNG_WEIGHT_SHIFT;
  202678. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202679. PNG_WEIGHT_SHIFT;
  202680. }
  202681. }
  202682. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202683. PNG_COST_SHIFT;
  202684. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202685. PNG_COST_SHIFT;
  202686. if (sumhi > PNG_HIMASK)
  202687. sum = PNG_MAXSUM;
  202688. else
  202689. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202690. }
  202691. #endif
  202692. if (sum < mins)
  202693. {
  202694. mins = sum;
  202695. best_row = png_ptr->avg_row;
  202696. }
  202697. }
  202698. /* Paeth filter */
  202699. if (filter_to_do == PNG_FILTER_PAETH)
  202700. {
  202701. png_bytep rp, dp, pp, cp, lp;
  202702. png_uint_32 i;
  202703. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202704. pp = prev_row + 1; i < bpp; i++)
  202705. {
  202706. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202707. }
  202708. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202709. {
  202710. int a, b, c, pa, pb, pc, p;
  202711. b = *pp++;
  202712. c = *cp++;
  202713. a = *lp++;
  202714. p = b - c;
  202715. pc = a - c;
  202716. #ifdef PNG_USE_ABS
  202717. pa = abs(p);
  202718. pb = abs(pc);
  202719. pc = abs(p + pc);
  202720. #else
  202721. pa = p < 0 ? -p : p;
  202722. pb = pc < 0 ? -pc : pc;
  202723. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202724. #endif
  202725. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202726. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202727. }
  202728. best_row = png_ptr->paeth_row;
  202729. }
  202730. else if (filter_to_do & PNG_FILTER_PAETH)
  202731. {
  202732. png_bytep rp, dp, pp, cp, lp;
  202733. png_uint_32 sum = 0, lmins = mins;
  202734. png_uint_32 i;
  202735. int v;
  202736. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202737. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202738. {
  202739. int j;
  202740. png_uint_32 lmhi, lmlo;
  202741. lmlo = lmins & PNG_LOMASK;
  202742. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202743. for (j = 0; j < num_p_filters; j++)
  202744. {
  202745. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202746. {
  202747. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202748. PNG_WEIGHT_SHIFT;
  202749. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202750. PNG_WEIGHT_SHIFT;
  202751. }
  202752. }
  202753. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202754. PNG_COST_SHIFT;
  202755. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202756. PNG_COST_SHIFT;
  202757. if (lmhi > PNG_HIMASK)
  202758. lmins = PNG_MAXSUM;
  202759. else
  202760. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202761. }
  202762. #endif
  202763. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202764. pp = prev_row + 1; i < bpp; i++)
  202765. {
  202766. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202767. sum += (v < 128) ? v : 256 - v;
  202768. }
  202769. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202770. {
  202771. int a, b, c, pa, pb, pc, p;
  202772. b = *pp++;
  202773. c = *cp++;
  202774. a = *lp++;
  202775. #ifndef PNG_SLOW_PAETH
  202776. p = b - c;
  202777. pc = a - c;
  202778. #ifdef PNG_USE_ABS
  202779. pa = abs(p);
  202780. pb = abs(pc);
  202781. pc = abs(p + pc);
  202782. #else
  202783. pa = p < 0 ? -p : p;
  202784. pb = pc < 0 ? -pc : pc;
  202785. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202786. #endif
  202787. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202788. #else /* PNG_SLOW_PAETH */
  202789. p = a + b - c;
  202790. pa = abs(p - a);
  202791. pb = abs(p - b);
  202792. pc = abs(p - c);
  202793. if (pa <= pb && pa <= pc)
  202794. p = a;
  202795. else if (pb <= pc)
  202796. p = b;
  202797. else
  202798. p = c;
  202799. #endif /* PNG_SLOW_PAETH */
  202800. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202801. sum += (v < 128) ? v : 256 - v;
  202802. if (sum > lmins) /* We are already worse, don't continue. */
  202803. break;
  202804. }
  202805. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202806. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202807. {
  202808. int j;
  202809. png_uint_32 sumhi, sumlo;
  202810. sumlo = sum & PNG_LOMASK;
  202811. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202812. for (j = 0; j < num_p_filters; j++)
  202813. {
  202814. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202815. {
  202816. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202817. PNG_WEIGHT_SHIFT;
  202818. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202819. PNG_WEIGHT_SHIFT;
  202820. }
  202821. }
  202822. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202823. PNG_COST_SHIFT;
  202824. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202825. PNG_COST_SHIFT;
  202826. if (sumhi > PNG_HIMASK)
  202827. sum = PNG_MAXSUM;
  202828. else
  202829. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202830. }
  202831. #endif
  202832. if (sum < mins)
  202833. {
  202834. best_row = png_ptr->paeth_row;
  202835. }
  202836. }
  202837. #endif /* PNG_NO_WRITE_FILTER */
  202838. /* Do the actual writing of the filtered row data from the chosen filter. */
  202839. png_write_filtered_row(png_ptr, best_row);
  202840. #ifndef PNG_NO_WRITE_FILTER
  202841. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202842. /* Save the type of filter we picked this time for future calculations */
  202843. if (png_ptr->num_prev_filters > 0)
  202844. {
  202845. int j;
  202846. for (j = 1; j < num_p_filters; j++)
  202847. {
  202848. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202849. }
  202850. png_ptr->prev_filters[j] = best_row[0];
  202851. }
  202852. #endif
  202853. #endif /* PNG_NO_WRITE_FILTER */
  202854. }
  202855. /* Do the actual writing of a previously filtered row. */
  202856. void /* PRIVATE */
  202857. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202858. {
  202859. png_debug(1, "in png_write_filtered_row\n");
  202860. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202861. /* set up the zlib input buffer */
  202862. png_ptr->zstream.next_in = filtered_row;
  202863. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202864. /* repeat until we have compressed all the data */
  202865. do
  202866. {
  202867. int ret; /* return of zlib */
  202868. /* compress the data */
  202869. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202870. /* check for compression errors */
  202871. if (ret != Z_OK)
  202872. {
  202873. if (png_ptr->zstream.msg != NULL)
  202874. png_error(png_ptr, png_ptr->zstream.msg);
  202875. else
  202876. png_error(png_ptr, "zlib error");
  202877. }
  202878. /* see if it is time to write another IDAT */
  202879. if (!(png_ptr->zstream.avail_out))
  202880. {
  202881. /* write the IDAT and reset the zlib output buffer */
  202882. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202883. png_ptr->zstream.next_out = png_ptr->zbuf;
  202884. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202885. }
  202886. /* repeat until all data has been compressed */
  202887. } while (png_ptr->zstream.avail_in);
  202888. /* swap the current and previous rows */
  202889. if (png_ptr->prev_row != NULL)
  202890. {
  202891. png_bytep tptr;
  202892. tptr = png_ptr->prev_row;
  202893. png_ptr->prev_row = png_ptr->row_buf;
  202894. png_ptr->row_buf = tptr;
  202895. }
  202896. /* finish row - updates counters and flushes zlib if last row */
  202897. png_write_finish_row(png_ptr);
  202898. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202899. png_ptr->flush_rows++;
  202900. if (png_ptr->flush_dist > 0 &&
  202901. png_ptr->flush_rows >= png_ptr->flush_dist)
  202902. {
  202903. png_write_flush(png_ptr);
  202904. }
  202905. #endif
  202906. }
  202907. #endif /* PNG_WRITE_SUPPORTED */
  202908. /*** End of inlined file: pngwutil.c ***/
  202909. #else
  202910. extern "C"
  202911. {
  202912. #include <png.h>
  202913. #include <pngconf.h>
  202914. }
  202915. #endif
  202916. }
  202917. #undef max
  202918. #undef min
  202919. #if JUCE_MSVC
  202920. #pragma warning (pop)
  202921. #endif
  202922. BEGIN_JUCE_NAMESPACE
  202923. using ::calloc;
  202924. using ::malloc;
  202925. using ::free;
  202926. namespace PNGHelpers
  202927. {
  202928. using namespace pnglibNamespace;
  202929. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  202930. {
  202931. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202932. }
  202933. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202934. {
  202935. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202936. }
  202937. struct PNGErrorStruct {};
  202938. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  202939. {
  202940. throw PNGErrorStruct();
  202941. }
  202942. }
  202943. PNGImageFormat::PNGImageFormat() {}
  202944. PNGImageFormat::~PNGImageFormat() {}
  202945. const String PNGImageFormat::getFormatName()
  202946. {
  202947. return "PNG";
  202948. }
  202949. bool PNGImageFormat::canUnderstand (InputStream& in)
  202950. {
  202951. const int bytesNeeded = 4;
  202952. char header [bytesNeeded];
  202953. return in.read (header, bytesNeeded) == bytesNeeded
  202954. && header[1] == 'P'
  202955. && header[2] == 'N'
  202956. && header[3] == 'G';
  202957. }
  202958. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  202959. const Image juce_loadWithCoreImage (InputStream& input);
  202960. #endif
  202961. const Image PNGImageFormat::decodeImage (InputStream& in)
  202962. {
  202963. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  202964. return juce_loadWithCoreImage (in);
  202965. #else
  202966. using namespace pnglibNamespace;
  202967. Image image;
  202968. png_structp pngReadStruct;
  202969. png_infop pngInfoStruct;
  202970. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202971. if (pngReadStruct != 0)
  202972. {
  202973. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202974. if (pngInfoStruct == 0)
  202975. {
  202976. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202977. return Image::null;
  202978. }
  202979. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202980. // read the header..
  202981. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202982. png_uint_32 width, height;
  202983. int bitDepth, colorType, interlaceType;
  202984. png_read_info (pngReadStruct, pngInfoStruct);
  202985. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202986. &width, &height,
  202987. &bitDepth, &colorType,
  202988. &interlaceType, 0, 0);
  202989. if (bitDepth == 16)
  202990. png_set_strip_16 (pngReadStruct);
  202991. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202992. png_set_expand (pngReadStruct);
  202993. if (bitDepth < 8)
  202994. png_set_expand (pngReadStruct);
  202995. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202996. png_set_expand (pngReadStruct);
  202997. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202998. png_set_gray_to_rgb (pngReadStruct);
  202999. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203000. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203001. || pngInfoStruct->num_trans > 0;
  203002. // Load the image into a temp buffer in the pnglib format..
  203003. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203004. {
  203005. HeapBlock <png_bytep> rows (height);
  203006. for (int y = (int) height; --y >= 0;)
  203007. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203008. png_read_image (pngReadStruct, rows);
  203009. png_read_end (pngReadStruct, pngInfoStruct);
  203010. }
  203011. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203012. // now convert the data to a juce image format..
  203013. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203014. (int) width, (int) height, hasAlphaChan);
  203015. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203016. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203017. const Image::BitmapData destData (image, true);
  203018. uint8* srcRow = tempBuffer;
  203019. uint8* destRow = destData.data;
  203020. for (int y = 0; y < (int) height; ++y)
  203021. {
  203022. const uint8* src = srcRow;
  203023. srcRow += (width << 2);
  203024. uint8* dest = destRow;
  203025. destRow += destData.lineStride;
  203026. if (hasAlphaChan)
  203027. {
  203028. for (int i = (int) width; --i >= 0;)
  203029. {
  203030. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203031. ((PixelARGB*) dest)->premultiply();
  203032. dest += destData.pixelStride;
  203033. src += 4;
  203034. }
  203035. }
  203036. else
  203037. {
  203038. for (int i = (int) width; --i >= 0;)
  203039. {
  203040. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203041. dest += destData.pixelStride;
  203042. src += 4;
  203043. }
  203044. }
  203045. }
  203046. }
  203047. return image;
  203048. #endif
  203049. }
  203050. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203051. {
  203052. using namespace pnglibNamespace;
  203053. const int width = image.getWidth();
  203054. const int height = image.getHeight();
  203055. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203056. if (pngWriteStruct == 0)
  203057. return false;
  203058. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203059. if (pngInfoStruct == 0)
  203060. {
  203061. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203062. return false;
  203063. }
  203064. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203065. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203066. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203067. : PNG_COLOR_TYPE_RGB,
  203068. PNG_INTERLACE_NONE,
  203069. PNG_COMPRESSION_TYPE_BASE,
  203070. PNG_FILTER_TYPE_BASE);
  203071. HeapBlock <uint8> rowData (width * 4);
  203072. png_color_8 sig_bit;
  203073. sig_bit.red = 8;
  203074. sig_bit.green = 8;
  203075. sig_bit.blue = 8;
  203076. sig_bit.alpha = 8;
  203077. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203078. png_write_info (pngWriteStruct, pngInfoStruct);
  203079. png_set_shift (pngWriteStruct, &sig_bit);
  203080. png_set_packing (pngWriteStruct);
  203081. const Image::BitmapData srcData (image, false);
  203082. for (int y = 0; y < height; ++y)
  203083. {
  203084. uint8* dst = rowData;
  203085. const uint8* src = srcData.getLinePointer (y);
  203086. if (image.hasAlphaChannel())
  203087. {
  203088. for (int i = width; --i >= 0;)
  203089. {
  203090. PixelARGB p (*(const PixelARGB*) src);
  203091. p.unpremultiply();
  203092. *dst++ = p.getRed();
  203093. *dst++ = p.getGreen();
  203094. *dst++ = p.getBlue();
  203095. *dst++ = p.getAlpha();
  203096. src += srcData.pixelStride;
  203097. }
  203098. }
  203099. else
  203100. {
  203101. for (int i = width; --i >= 0;)
  203102. {
  203103. *dst++ = ((const PixelRGB*) src)->getRed();
  203104. *dst++ = ((const PixelRGB*) src)->getGreen();
  203105. *dst++ = ((const PixelRGB*) src)->getBlue();
  203106. src += srcData.pixelStride;
  203107. }
  203108. }
  203109. png_bytep rowPtr = rowData;
  203110. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203111. }
  203112. png_write_end (pngWriteStruct, pngInfoStruct);
  203113. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203114. out.flush();
  203115. return true;
  203116. }
  203117. END_JUCE_NAMESPACE
  203118. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203119. #endif
  203120. //==============================================================================
  203121. #if JUCE_BUILD_NATIVE
  203122. // Non-public headers that are needed by more than one platform must be included
  203123. // before the platform-specific sections..
  203124. BEGIN_JUCE_NAMESPACE
  203125. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203126. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203127. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203128. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203129. /**
  203130. Helper class that takes chunks of incoming midi bytes, packages them into
  203131. messages, and dispatches them to a midi callback.
  203132. */
  203133. class MidiDataConcatenator
  203134. {
  203135. public:
  203136. MidiDataConcatenator (const int initialBufferSize)
  203137. : pendingData (initialBufferSize),
  203138. pendingBytes (0), pendingDataTime (0)
  203139. {
  203140. }
  203141. void reset()
  203142. {
  203143. pendingBytes = 0;
  203144. pendingDataTime = 0;
  203145. }
  203146. void pushMidiData (const void* data, int numBytes, double time,
  203147. MidiInput* input, MidiInputCallback& callback)
  203148. {
  203149. const uint8* d = static_cast <const uint8*> (data);
  203150. while (numBytes > 0)
  203151. {
  203152. if (pendingBytes > 0 || d[0] == 0xf0)
  203153. {
  203154. processSysex (d, numBytes, time, input, callback);
  203155. }
  203156. else
  203157. {
  203158. int used = 0;
  203159. const MidiMessage m (d, numBytes, used, 0, time);
  203160. if (used <= 0)
  203161. break; // malformed message..
  203162. callback.handleIncomingMidiMessage (input, m);
  203163. numBytes -= used;
  203164. d += used;
  203165. }
  203166. }
  203167. }
  203168. private:
  203169. void processSysex (const uint8*& d, int& numBytes, double time,
  203170. MidiInput* input, MidiInputCallback& callback)
  203171. {
  203172. if (*d == 0xf0)
  203173. {
  203174. pendingBytes = 0;
  203175. pendingDataTime = time;
  203176. }
  203177. pendingData.ensureSize (pendingBytes + numBytes, false);
  203178. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203179. uint8* dest = totalMessage + pendingBytes;
  203180. do
  203181. {
  203182. if (pendingBytes > 0 && *d >= 0x80)
  203183. {
  203184. if (*d >= 0xfa || *d == 0xf8)
  203185. {
  203186. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203187. ++d;
  203188. --numBytes;
  203189. }
  203190. else
  203191. {
  203192. if (*d == 0xf7)
  203193. {
  203194. *dest++ = *d++;
  203195. pendingBytes++;
  203196. --numBytes;
  203197. }
  203198. break;
  203199. }
  203200. }
  203201. else
  203202. {
  203203. *dest++ = *d++;
  203204. pendingBytes++;
  203205. --numBytes;
  203206. }
  203207. }
  203208. while (numBytes > 0);
  203209. if (pendingBytes > 0)
  203210. {
  203211. if (totalMessage [pendingBytes - 1] == 0xf7)
  203212. {
  203213. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203214. pendingBytes = 0;
  203215. }
  203216. else
  203217. {
  203218. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203219. }
  203220. }
  203221. }
  203222. MemoryBlock pendingData;
  203223. int pendingBytes;
  203224. double pendingDataTime;
  203225. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203226. };
  203227. #endif
  203228. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203229. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203230. END_JUCE_NAMESPACE
  203231. #if JUCE_WINDOWS
  203232. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203233. /*
  203234. This file wraps together all the win32-specific code, so that
  203235. we can include all the native headers just once, and compile all our
  203236. platform-specific stuff in one big lump, keeping it out of the way of
  203237. the rest of the codebase.
  203238. */
  203239. #if JUCE_WINDOWS
  203240. #undef JUCE_BUILD_NATIVE
  203241. #define JUCE_BUILD_NATIVE 1
  203242. BEGIN_JUCE_NAMESPACE
  203243. #define JUCE_INCLUDED_FILE 1
  203244. // Now include the actual code files..
  203245. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203246. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203247. // compiled on its own).
  203248. #if JUCE_INCLUDED_FILE
  203249. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203250. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203251. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203252. #ifndef DOXYGEN
  203253. // use with DynamicLibraryLoader to simplify importing functions
  203254. //
  203255. // functionName: function to import
  203256. // localFunctionName: name you want to use to actually call it (must be different)
  203257. // returnType: the return type
  203258. // object: the DynamicLibraryLoader to use
  203259. // params: list of params (bracketed)
  203260. //
  203261. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203262. typedef returnType (WINAPI *type##localFunctionName) params; \
  203263. type##localFunctionName localFunctionName \
  203264. = (type##localFunctionName)object.findProcAddress (#functionName);
  203265. // loads and unloads a DLL automatically
  203266. class JUCE_API DynamicLibraryLoader
  203267. {
  203268. public:
  203269. DynamicLibraryLoader (const String& name = String::empty);
  203270. ~DynamicLibraryLoader();
  203271. bool load (const String& libraryName);
  203272. void* findProcAddress (const String& functionName);
  203273. private:
  203274. void* libHandle;
  203275. };
  203276. #endif
  203277. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203278. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203279. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203280. : libHandle (0)
  203281. {
  203282. load (name);
  203283. }
  203284. DynamicLibraryLoader::~DynamicLibraryLoader()
  203285. {
  203286. load (String::empty);
  203287. }
  203288. bool DynamicLibraryLoader::load (const String& name)
  203289. {
  203290. FreeLibrary ((HMODULE) libHandle);
  203291. libHandle = name.isNotEmpty() ? LoadLibrary (name) : 0;
  203292. return libHandle != 0;
  203293. }
  203294. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203295. {
  203296. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203297. }
  203298. #endif
  203299. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203300. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203301. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203302. // compiled on its own).
  203303. #if JUCE_INCLUDED_FILE
  203304. void Logger::outputDebugString (const String& text)
  203305. {
  203306. OutputDebugString (text + "\n");
  203307. }
  203308. static int64 hiResTicksPerSecond;
  203309. static double hiResTicksScaleFactor;
  203310. #if JUCE_USE_INTRINSICS
  203311. // CPU info functions using intrinsics...
  203312. #pragma intrinsic (__cpuid)
  203313. #pragma intrinsic (__rdtsc)
  203314. const String SystemStats::getCpuVendor()
  203315. {
  203316. int info [4];
  203317. __cpuid (info, 0);
  203318. char v [12];
  203319. memcpy (v, info + 1, 4);
  203320. memcpy (v + 4, info + 3, 4);
  203321. memcpy (v + 8, info + 2, 4);
  203322. return String (v, 12);
  203323. }
  203324. #else
  203325. // CPU info functions using old fashioned inline asm...
  203326. static void juce_getCpuVendor (char* const v)
  203327. {
  203328. int vendor[4];
  203329. zeromem (vendor, 16);
  203330. #ifdef JUCE_64BIT
  203331. #else
  203332. #ifndef __MINGW32__
  203333. __try
  203334. #endif
  203335. {
  203336. #if JUCE_GCC
  203337. unsigned int dummy = 0;
  203338. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203339. #else
  203340. __asm
  203341. {
  203342. mov eax, 0
  203343. cpuid
  203344. mov [vendor], ebx
  203345. mov [vendor + 4], edx
  203346. mov [vendor + 8], ecx
  203347. }
  203348. #endif
  203349. }
  203350. #ifndef __MINGW32__
  203351. __except (EXCEPTION_EXECUTE_HANDLER)
  203352. {
  203353. *v = 0;
  203354. }
  203355. #endif
  203356. #endif
  203357. memcpy (v, vendor, 16);
  203358. }
  203359. const String SystemStats::getCpuVendor()
  203360. {
  203361. char v [16];
  203362. juce_getCpuVendor (v);
  203363. return String (v, 16);
  203364. }
  203365. #endif
  203366. void SystemStats::initialiseStats()
  203367. {
  203368. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203369. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203370. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203371. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203372. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203373. #else
  203374. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203375. #endif
  203376. {
  203377. SYSTEM_INFO systemInfo;
  203378. GetSystemInfo (&systemInfo);
  203379. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203380. }
  203381. LARGE_INTEGER f;
  203382. QueryPerformanceFrequency (&f);
  203383. hiResTicksPerSecond = f.QuadPart;
  203384. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203385. String s (SystemStats::getJUCEVersion());
  203386. const MMRESULT res = timeBeginPeriod (1);
  203387. (void) res;
  203388. jassert (res == TIMERR_NOERROR);
  203389. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203390. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203391. #endif
  203392. }
  203393. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203394. {
  203395. OSVERSIONINFO info;
  203396. info.dwOSVersionInfoSize = sizeof (info);
  203397. GetVersionEx (&info);
  203398. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203399. {
  203400. switch (info.dwMajorVersion)
  203401. {
  203402. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203403. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203404. default: jassertfalse; break; // !! not a supported OS!
  203405. }
  203406. }
  203407. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203408. {
  203409. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203410. return Win98;
  203411. }
  203412. return UnknownOS;
  203413. }
  203414. const String SystemStats::getOperatingSystemName()
  203415. {
  203416. const char* name = "Unknown OS";
  203417. switch (getOperatingSystemType())
  203418. {
  203419. case Windows7: name = "Windows 7"; break;
  203420. case WinVista: name = "Windows Vista"; break;
  203421. case WinXP: name = "Windows XP"; break;
  203422. case Win2000: name = "Windows 2000"; break;
  203423. case Win98: name = "Windows 98"; break;
  203424. default: jassertfalse; break; // !! new type of OS?
  203425. }
  203426. return name;
  203427. }
  203428. bool SystemStats::isOperatingSystem64Bit()
  203429. {
  203430. #ifdef _WIN64
  203431. return true;
  203432. #else
  203433. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203434. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203435. BOOL isWow64 = FALSE;
  203436. return (fnIsWow64Process != 0)
  203437. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203438. && (isWow64 != FALSE);
  203439. #endif
  203440. }
  203441. int SystemStats::getMemorySizeInMegabytes()
  203442. {
  203443. MEMORYSTATUSEX mem;
  203444. mem.dwLength = sizeof (mem);
  203445. GlobalMemoryStatusEx (&mem);
  203446. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203447. }
  203448. uint32 juce_millisecondsSinceStartup() throw()
  203449. {
  203450. return (uint32) timeGetTime();
  203451. }
  203452. int64 Time::getHighResolutionTicks() throw()
  203453. {
  203454. LARGE_INTEGER ticks;
  203455. QueryPerformanceCounter (&ticks);
  203456. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203457. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203458. // fix for a very obscure PCI hardware bug that can make the counter
  203459. // sometimes jump forwards by a few seconds..
  203460. static int64 hiResTicksOffset = 0;
  203461. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203462. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203463. hiResTicksOffset = newOffset;
  203464. return ticks.QuadPart + hiResTicksOffset;
  203465. }
  203466. double Time::getMillisecondCounterHiRes() throw()
  203467. {
  203468. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203469. }
  203470. int64 Time::getHighResolutionTicksPerSecond() throw()
  203471. {
  203472. return hiResTicksPerSecond;
  203473. }
  203474. static int64 juce_getClockCycleCounter() throw()
  203475. {
  203476. #if JUCE_USE_INTRINSICS
  203477. // MS intrinsics version...
  203478. return __rdtsc();
  203479. #elif JUCE_GCC
  203480. // GNU inline asm version...
  203481. unsigned int hi = 0, lo = 0;
  203482. __asm__ __volatile__ (
  203483. "xor %%eax, %%eax \n\
  203484. xor %%edx, %%edx \n\
  203485. rdtsc \n\
  203486. movl %%eax, %[lo] \n\
  203487. movl %%edx, %[hi]"
  203488. :
  203489. : [hi] "m" (hi),
  203490. [lo] "m" (lo)
  203491. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203492. return (int64) ((((uint64) hi) << 32) | lo);
  203493. #else
  203494. // MSVC inline asm version...
  203495. unsigned int hi = 0, lo = 0;
  203496. __asm
  203497. {
  203498. xor eax, eax
  203499. xor edx, edx
  203500. rdtsc
  203501. mov lo, eax
  203502. mov hi, edx
  203503. }
  203504. return (int64) ((((uint64) hi) << 32) | lo);
  203505. #endif
  203506. }
  203507. int SystemStats::getCpuSpeedInMegaherz()
  203508. {
  203509. const int64 cycles = juce_getClockCycleCounter();
  203510. const uint32 millis = Time::getMillisecondCounter();
  203511. int lastResult = 0;
  203512. for (;;)
  203513. {
  203514. int n = 1000000;
  203515. while (--n > 0) {}
  203516. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203517. const int64 cyclesNow = juce_getClockCycleCounter();
  203518. if (millisElapsed > 80)
  203519. {
  203520. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203521. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203522. return newResult;
  203523. lastResult = newResult;
  203524. }
  203525. }
  203526. }
  203527. bool Time::setSystemTimeToThisTime() const
  203528. {
  203529. SYSTEMTIME st;
  203530. st.wDayOfWeek = 0;
  203531. st.wYear = (WORD) getYear();
  203532. st.wMonth = (WORD) (getMonth() + 1);
  203533. st.wDay = (WORD) getDayOfMonth();
  203534. st.wHour = (WORD) getHours();
  203535. st.wMinute = (WORD) getMinutes();
  203536. st.wSecond = (WORD) getSeconds();
  203537. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203538. // do this twice because of daylight saving conversion problems - the
  203539. // first one sets it up, the second one kicks it in.
  203540. return SetLocalTime (&st) != 0
  203541. && SetLocalTime (&st) != 0;
  203542. }
  203543. int SystemStats::getPageSize()
  203544. {
  203545. SYSTEM_INFO systemInfo;
  203546. GetSystemInfo (&systemInfo);
  203547. return systemInfo.dwPageSize;
  203548. }
  203549. const String SystemStats::getLogonName()
  203550. {
  203551. TCHAR text [256];
  203552. DWORD len = numElementsInArray (text) - 2;
  203553. zerostruct (text);
  203554. GetUserName (text, &len);
  203555. return String (text, len);
  203556. }
  203557. const String SystemStats::getFullUserName()
  203558. {
  203559. return getLogonName();
  203560. }
  203561. #endif
  203562. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203563. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203564. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203565. // compiled on its own).
  203566. #if JUCE_INCLUDED_FILE
  203567. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203568. extern HWND juce_messageWindowHandle;
  203569. #endif
  203570. #if ! JUCE_USE_INTRINSICS
  203571. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203572. // older ones we have to actually call the ops as win32 functions..
  203573. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203574. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203575. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203576. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203577. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203578. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203579. {
  203580. jassertfalse; // This operation isn't available in old MS compiler versions!
  203581. __int64 oldValue = *value;
  203582. if (oldValue == valueToCompare)
  203583. *value = newValue;
  203584. return oldValue;
  203585. }
  203586. #endif
  203587. CriticalSection::CriticalSection() throw()
  203588. {
  203589. // (just to check the MS haven't changed this structure and broken things...)
  203590. #if JUCE_VC7_OR_EARLIER
  203591. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203592. #else
  203593. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203594. #endif
  203595. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203596. }
  203597. CriticalSection::~CriticalSection() throw()
  203598. {
  203599. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203600. }
  203601. void CriticalSection::enter() const throw()
  203602. {
  203603. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203604. }
  203605. bool CriticalSection::tryEnter() const throw()
  203606. {
  203607. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203608. }
  203609. void CriticalSection::exit() const throw()
  203610. {
  203611. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203612. }
  203613. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203614. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203615. {
  203616. }
  203617. WaitableEvent::~WaitableEvent() throw()
  203618. {
  203619. CloseHandle (internal);
  203620. }
  203621. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203622. {
  203623. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203624. }
  203625. void WaitableEvent::signal() const throw()
  203626. {
  203627. SetEvent (internal);
  203628. }
  203629. void WaitableEvent::reset() const throw()
  203630. {
  203631. ResetEvent (internal);
  203632. }
  203633. void JUCE_API juce_threadEntryPoint (void*);
  203634. static unsigned int __stdcall threadEntryProc (void* userData)
  203635. {
  203636. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203637. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203638. GetCurrentThreadId(), TRUE);
  203639. #endif
  203640. juce_threadEntryPoint (userData);
  203641. _endthreadex (0);
  203642. return 0;
  203643. }
  203644. void Thread::launchThread()
  203645. {
  203646. unsigned int newThreadId;
  203647. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  203648. threadId_ = (ThreadID) newThreadId;
  203649. }
  203650. void Thread::closeThreadHandle()
  203651. {
  203652. CloseHandle ((HANDLE) threadHandle_);
  203653. threadId_ = 0;
  203654. threadHandle_ = 0;
  203655. }
  203656. void Thread::killThread()
  203657. {
  203658. if (threadHandle_ != 0)
  203659. {
  203660. #if JUCE_DEBUG
  203661. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203662. #endif
  203663. TerminateThread (threadHandle_, 0);
  203664. }
  203665. }
  203666. void Thread::setCurrentThreadName (const String& name)
  203667. {
  203668. #if JUCE_DEBUG && JUCE_MSVC
  203669. struct
  203670. {
  203671. DWORD dwType;
  203672. LPCSTR szName;
  203673. DWORD dwThreadID;
  203674. DWORD dwFlags;
  203675. } info;
  203676. info.dwType = 0x1000;
  203677. info.szName = name.toCString();
  203678. info.dwThreadID = GetCurrentThreadId();
  203679. info.dwFlags = 0;
  203680. __try
  203681. {
  203682. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203683. }
  203684. __except (EXCEPTION_CONTINUE_EXECUTION)
  203685. {}
  203686. #else
  203687. (void) name;
  203688. #endif
  203689. }
  203690. Thread::ThreadID Thread::getCurrentThreadId()
  203691. {
  203692. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203693. }
  203694. bool Thread::setThreadPriority (void* handle, int priority)
  203695. {
  203696. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203697. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203698. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203699. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203700. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203701. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203702. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203703. if (handle == 0)
  203704. handle = GetCurrentThread();
  203705. return SetThreadPriority (handle, pri) != FALSE;
  203706. }
  203707. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203708. {
  203709. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203710. }
  203711. struct SleepEvent
  203712. {
  203713. SleepEvent()
  203714. : handle (CreateEvent (0, 0, 0,
  203715. #if JUCE_DEBUG
  203716. _T("Juce Sleep Event")))
  203717. #else
  203718. 0))
  203719. #endif
  203720. {
  203721. }
  203722. HANDLE handle;
  203723. };
  203724. static SleepEvent sleepEvent;
  203725. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203726. {
  203727. if (millisecs >= 10)
  203728. {
  203729. Sleep (millisecs);
  203730. }
  203731. else
  203732. {
  203733. // unlike Sleep() this is guaranteed to return to the current thread after
  203734. // the time expires, so we'll use this for short waits, which are more likely
  203735. // to need to be accurate
  203736. WaitForSingleObject (sleepEvent.handle, millisecs);
  203737. }
  203738. }
  203739. void Thread::yield()
  203740. {
  203741. Sleep (0);
  203742. }
  203743. static int lastProcessPriority = -1;
  203744. // called by WindowDriver because Windows does wierd things to process priority
  203745. // when you swap apps, and this forces an update when the app is brought to the front.
  203746. void juce_repeatLastProcessPriority()
  203747. {
  203748. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203749. {
  203750. DWORD p;
  203751. switch (lastProcessPriority)
  203752. {
  203753. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203754. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203755. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203756. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203757. default: jassertfalse; return; // bad priority value
  203758. }
  203759. SetPriorityClass (GetCurrentProcess(), p);
  203760. }
  203761. }
  203762. void Process::setPriority (ProcessPriority prior)
  203763. {
  203764. if (lastProcessPriority != (int) prior)
  203765. {
  203766. lastProcessPriority = (int) prior;
  203767. juce_repeatLastProcessPriority();
  203768. }
  203769. }
  203770. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  203771. {
  203772. return IsDebuggerPresent() != FALSE;
  203773. }
  203774. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203775. {
  203776. return juce_isRunningUnderDebugger();
  203777. }
  203778. void Process::raisePrivilege()
  203779. {
  203780. jassertfalse; // xxx not implemented
  203781. }
  203782. void Process::lowerPrivilege()
  203783. {
  203784. jassertfalse; // xxx not implemented
  203785. }
  203786. void Process::terminate()
  203787. {
  203788. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203789. _CrtDumpMemoryLeaks();
  203790. #endif
  203791. // bullet in the head in case there's a problem shutting down..
  203792. ExitProcess (0);
  203793. }
  203794. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203795. {
  203796. void* result = 0;
  203797. JUCE_TRY
  203798. {
  203799. result = LoadLibrary (name);
  203800. }
  203801. JUCE_CATCH_ALL
  203802. return result;
  203803. }
  203804. void PlatformUtilities::freeDynamicLibrary (void* h)
  203805. {
  203806. JUCE_TRY
  203807. {
  203808. if (h != 0)
  203809. FreeLibrary ((HMODULE) h);
  203810. }
  203811. JUCE_CATCH_ALL
  203812. }
  203813. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203814. {
  203815. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  203816. }
  203817. class InterProcessLock::Pimpl
  203818. {
  203819. public:
  203820. Pimpl (const String& name, const int timeOutMillisecs)
  203821. : handle (0), refCount (1)
  203822. {
  203823. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203824. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203825. {
  203826. if (timeOutMillisecs == 0)
  203827. {
  203828. close();
  203829. return;
  203830. }
  203831. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203832. {
  203833. case WAIT_OBJECT_0:
  203834. case WAIT_ABANDONED:
  203835. break;
  203836. case WAIT_TIMEOUT:
  203837. default:
  203838. close();
  203839. break;
  203840. }
  203841. }
  203842. }
  203843. ~Pimpl()
  203844. {
  203845. close();
  203846. }
  203847. void close()
  203848. {
  203849. if (handle != 0)
  203850. {
  203851. ReleaseMutex (handle);
  203852. CloseHandle (handle);
  203853. handle = 0;
  203854. }
  203855. }
  203856. HANDLE handle;
  203857. int refCount;
  203858. };
  203859. InterProcessLock::InterProcessLock (const String& name_)
  203860. : name (name_)
  203861. {
  203862. }
  203863. InterProcessLock::~InterProcessLock()
  203864. {
  203865. }
  203866. bool InterProcessLock::enter (const int timeOutMillisecs)
  203867. {
  203868. const ScopedLock sl (lock);
  203869. if (pimpl == 0)
  203870. {
  203871. pimpl = new Pimpl (name, timeOutMillisecs);
  203872. if (pimpl->handle == 0)
  203873. pimpl = 0;
  203874. }
  203875. else
  203876. {
  203877. pimpl->refCount++;
  203878. }
  203879. return pimpl != 0;
  203880. }
  203881. void InterProcessLock::exit()
  203882. {
  203883. const ScopedLock sl (lock);
  203884. // Trying to release the lock too many times!
  203885. jassert (pimpl != 0);
  203886. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203887. pimpl = 0;
  203888. }
  203889. #endif
  203890. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203891. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203892. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203893. // compiled on its own).
  203894. #if JUCE_INCLUDED_FILE
  203895. #ifndef CSIDL_MYMUSIC
  203896. #define CSIDL_MYMUSIC 0x000d
  203897. #endif
  203898. #ifndef CSIDL_MYVIDEO
  203899. #define CSIDL_MYVIDEO 0x000e
  203900. #endif
  203901. #ifndef INVALID_FILE_ATTRIBUTES
  203902. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203903. #endif
  203904. namespace WindowsFileHelpers
  203905. {
  203906. int64 fileTimeToTime (const FILETIME* const ft)
  203907. {
  203908. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203909. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203910. }
  203911. void timeToFileTime (const int64 time, FILETIME* const ft)
  203912. {
  203913. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203914. }
  203915. const String getDriveFromPath (const String& path)
  203916. {
  203917. if (path.isNotEmpty() && path[1] == ':')
  203918. return path.substring (0, 2) + '\\';
  203919. return path;
  203920. }
  203921. int64 getDiskSpaceInfo (const String& path, const bool total)
  203922. {
  203923. ULARGE_INTEGER spc, tot, totFree;
  203924. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  203925. return total ? (int64) tot.QuadPart
  203926. : (int64) spc.QuadPart;
  203927. return 0;
  203928. }
  203929. unsigned int getWindowsDriveType (const String& path)
  203930. {
  203931. return GetDriveType (getDriveFromPath (path));
  203932. }
  203933. const File getSpecialFolderPath (int type)
  203934. {
  203935. WCHAR path [MAX_PATH + 256];
  203936. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203937. return File (String (path));
  203938. return File::nonexistent;
  203939. }
  203940. }
  203941. const juce_wchar File::separator = '\\';
  203942. const String File::separatorString ("\\");
  203943. bool File::exists() const
  203944. {
  203945. return fullPath.isNotEmpty()
  203946. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  203947. }
  203948. bool File::existsAsFile() const
  203949. {
  203950. return fullPath.isNotEmpty()
  203951. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203952. }
  203953. bool File::isDirectory() const
  203954. {
  203955. const DWORD attr = GetFileAttributes (fullPath);
  203956. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203957. }
  203958. bool File::hasWriteAccess() const
  203959. {
  203960. if (exists())
  203961. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  203962. // on windows, it seems that even read-only directories can still be written into,
  203963. // so checking the parent directory's permissions would return the wrong result..
  203964. return true;
  203965. }
  203966. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203967. {
  203968. DWORD attr = GetFileAttributes (fullPath);
  203969. if (attr == INVALID_FILE_ATTRIBUTES)
  203970. return false;
  203971. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203972. return true;
  203973. if (shouldBeReadOnly)
  203974. attr |= FILE_ATTRIBUTE_READONLY;
  203975. else
  203976. attr &= ~FILE_ATTRIBUTE_READONLY;
  203977. return SetFileAttributes (fullPath, attr) != FALSE;
  203978. }
  203979. bool File::isHidden() const
  203980. {
  203981. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203982. }
  203983. bool File::deleteFile() const
  203984. {
  203985. if (! exists())
  203986. return true;
  203987. else if (isDirectory())
  203988. return RemoveDirectory (fullPath) != 0;
  203989. else
  203990. return DeleteFile (fullPath) != 0;
  203991. }
  203992. bool File::moveToTrash() const
  203993. {
  203994. if (! exists())
  203995. return true;
  203996. SHFILEOPSTRUCT fos;
  203997. zerostruct (fos);
  203998. // The string we pass in must be double null terminated..
  203999. String doubleNullTermPath (getFullPathName() + " ");
  204000. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204001. p [getFullPathName().length()] = 0;
  204002. fos.wFunc = FO_DELETE;
  204003. fos.pFrom = p;
  204004. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204005. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204006. return SHFileOperation (&fos) == 0;
  204007. }
  204008. bool File::copyInternal (const File& dest) const
  204009. {
  204010. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204011. }
  204012. bool File::moveInternal (const File& dest) const
  204013. {
  204014. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204015. }
  204016. void File::createDirectoryInternal (const String& fileName) const
  204017. {
  204018. CreateDirectory (fileName, 0);
  204019. }
  204020. int64 juce_fileSetPosition (void* handle, int64 pos)
  204021. {
  204022. LARGE_INTEGER li;
  204023. li.QuadPart = pos;
  204024. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204025. return li.QuadPart;
  204026. }
  204027. void FileInputStream::openHandle()
  204028. {
  204029. totalSize = file.getSize();
  204030. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204031. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204032. if (h != INVALID_HANDLE_VALUE)
  204033. fileHandle = (void*) h;
  204034. }
  204035. void FileInputStream::closeHandle()
  204036. {
  204037. CloseHandle ((HANDLE) fileHandle);
  204038. }
  204039. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204040. {
  204041. if (fileHandle != 0)
  204042. {
  204043. DWORD actualNum = 0;
  204044. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204045. return (size_t) actualNum;
  204046. }
  204047. return 0;
  204048. }
  204049. void FileOutputStream::openHandle()
  204050. {
  204051. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204052. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204053. if (h != INVALID_HANDLE_VALUE)
  204054. {
  204055. LARGE_INTEGER li;
  204056. li.QuadPart = 0;
  204057. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204058. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204059. {
  204060. fileHandle = (void*) h;
  204061. currentPosition = li.QuadPart;
  204062. }
  204063. }
  204064. }
  204065. void FileOutputStream::closeHandle()
  204066. {
  204067. CloseHandle ((HANDLE) fileHandle);
  204068. }
  204069. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204070. {
  204071. if (fileHandle != 0)
  204072. {
  204073. DWORD actualNum = 0;
  204074. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204075. return (int) actualNum;
  204076. }
  204077. return 0;
  204078. }
  204079. void FileOutputStream::flushInternal()
  204080. {
  204081. if (fileHandle != 0)
  204082. FlushFileBuffers ((HANDLE) fileHandle);
  204083. }
  204084. int64 File::getSize() const
  204085. {
  204086. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204087. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204088. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204089. return 0;
  204090. }
  204091. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204092. {
  204093. using namespace WindowsFileHelpers;
  204094. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204095. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204096. {
  204097. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204098. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204099. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204100. }
  204101. else
  204102. {
  204103. creationTime = accessTime = modificationTime = 0;
  204104. }
  204105. }
  204106. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204107. {
  204108. using namespace WindowsFileHelpers;
  204109. bool ok = false;
  204110. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204111. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204112. if (h != INVALID_HANDLE_VALUE)
  204113. {
  204114. FILETIME m, a, c;
  204115. timeToFileTime (modificationTime, &m);
  204116. timeToFileTime (accessTime, &a);
  204117. timeToFileTime (creationTime, &c);
  204118. ok = SetFileTime (h,
  204119. creationTime > 0 ? &c : 0,
  204120. accessTime > 0 ? &a : 0,
  204121. modificationTime > 0 ? &m : 0) != 0;
  204122. CloseHandle (h);
  204123. }
  204124. return ok;
  204125. }
  204126. void File::findFileSystemRoots (Array<File>& destArray)
  204127. {
  204128. TCHAR buffer [2048];
  204129. buffer[0] = 0;
  204130. buffer[1] = 0;
  204131. GetLogicalDriveStrings (2048, buffer);
  204132. const TCHAR* n = buffer;
  204133. StringArray roots;
  204134. while (*n != 0)
  204135. {
  204136. roots.add (String (n));
  204137. while (*n++ != 0)
  204138. {}
  204139. }
  204140. roots.sort (true);
  204141. for (int i = 0; i < roots.size(); ++i)
  204142. destArray.add (roots [i]);
  204143. }
  204144. const String File::getVolumeLabel() const
  204145. {
  204146. TCHAR dest[64];
  204147. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204148. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204149. dest[0] = 0;
  204150. return dest;
  204151. }
  204152. int File::getVolumeSerialNumber() const
  204153. {
  204154. TCHAR dest[64];
  204155. DWORD serialNum;
  204156. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204157. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204158. return 0;
  204159. return (int) serialNum;
  204160. }
  204161. int64 File::getBytesFreeOnVolume() const
  204162. {
  204163. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204164. }
  204165. int64 File::getVolumeTotalSize() const
  204166. {
  204167. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204168. }
  204169. bool File::isOnCDRomDrive() const
  204170. {
  204171. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204172. }
  204173. bool File::isOnHardDisk() const
  204174. {
  204175. if (fullPath.isEmpty())
  204176. return false;
  204177. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204178. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204179. return n != DRIVE_REMOVABLE;
  204180. else
  204181. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204182. }
  204183. bool File::isOnRemovableDrive() const
  204184. {
  204185. if (fullPath.isEmpty())
  204186. return false;
  204187. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204188. return n == DRIVE_CDROM
  204189. || n == DRIVE_REMOTE
  204190. || n == DRIVE_REMOVABLE
  204191. || n == DRIVE_RAMDISK;
  204192. }
  204193. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204194. {
  204195. int csidlType = 0;
  204196. switch (type)
  204197. {
  204198. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204199. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204200. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204201. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204202. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204203. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204204. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204205. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204206. case tempDirectory:
  204207. {
  204208. WCHAR dest [2048];
  204209. dest[0] = 0;
  204210. GetTempPath (numElementsInArray (dest), dest);
  204211. return File (String (dest));
  204212. }
  204213. case invokedExecutableFile:
  204214. case currentExecutableFile:
  204215. case currentApplicationFile:
  204216. {
  204217. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204218. WCHAR dest [MAX_PATH + 256];
  204219. dest[0] = 0;
  204220. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204221. return File (String (dest));
  204222. }
  204223. case hostApplicationPath:
  204224. {
  204225. WCHAR dest [MAX_PATH + 256];
  204226. dest[0] = 0;
  204227. GetModuleFileName (0, dest, numElementsInArray (dest));
  204228. return File (String (dest));
  204229. }
  204230. default:
  204231. jassertfalse; // unknown type?
  204232. return File::nonexistent;
  204233. }
  204234. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204235. }
  204236. const File File::getCurrentWorkingDirectory()
  204237. {
  204238. WCHAR dest [MAX_PATH + 256];
  204239. dest[0] = 0;
  204240. GetCurrentDirectory (numElementsInArray (dest), dest);
  204241. return File (String (dest));
  204242. }
  204243. bool File::setAsCurrentWorkingDirectory() const
  204244. {
  204245. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204246. }
  204247. const String File::getVersion() const
  204248. {
  204249. String result;
  204250. DWORD handle = 0;
  204251. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204252. HeapBlock<char> buffer;
  204253. buffer.calloc (bufferSize);
  204254. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204255. {
  204256. VS_FIXEDFILEINFO* vffi;
  204257. UINT len = 0;
  204258. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204259. {
  204260. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204261. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204262. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204263. << (int) LOWORD (vffi->dwFileVersionLS);
  204264. }
  204265. }
  204266. return result;
  204267. }
  204268. const File File::getLinkedTarget() const
  204269. {
  204270. File result (*this);
  204271. String p (getFullPathName());
  204272. if (! exists())
  204273. p += ".lnk";
  204274. else if (getFileExtension() != ".lnk")
  204275. return result;
  204276. ComSmartPtr <IShellLink> shellLink;
  204277. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204278. {
  204279. ComSmartPtr <IPersistFile> persistFile;
  204280. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204281. {
  204282. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204283. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204284. {
  204285. WIN32_FIND_DATA winFindData;
  204286. WCHAR resolvedPath [MAX_PATH];
  204287. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204288. result = File (resolvedPath);
  204289. }
  204290. }
  204291. }
  204292. return result;
  204293. }
  204294. class DirectoryIterator::NativeIterator::Pimpl
  204295. {
  204296. public:
  204297. Pimpl (const File& directory, const String& wildCard)
  204298. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204299. handle (INVALID_HANDLE_VALUE)
  204300. {
  204301. }
  204302. ~Pimpl()
  204303. {
  204304. if (handle != INVALID_HANDLE_VALUE)
  204305. FindClose (handle);
  204306. }
  204307. bool next (String& filenameFound,
  204308. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204309. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204310. {
  204311. using namespace WindowsFileHelpers;
  204312. WIN32_FIND_DATA findData;
  204313. if (handle == INVALID_HANDLE_VALUE)
  204314. {
  204315. handle = FindFirstFile (directoryWithWildCard, &findData);
  204316. if (handle == INVALID_HANDLE_VALUE)
  204317. return false;
  204318. }
  204319. else
  204320. {
  204321. if (FindNextFile (handle, &findData) == 0)
  204322. return false;
  204323. }
  204324. filenameFound = findData.cFileName;
  204325. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204326. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204327. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204328. if (modTime != 0) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  204329. if (creationTime != 0) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  204330. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204331. return true;
  204332. }
  204333. private:
  204334. const String directoryWithWildCard;
  204335. HANDLE handle;
  204336. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204337. };
  204338. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204339. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204340. {
  204341. }
  204342. DirectoryIterator::NativeIterator::~NativeIterator()
  204343. {
  204344. }
  204345. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204346. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204347. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204348. {
  204349. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204350. }
  204351. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204352. {
  204353. HINSTANCE hInstance = 0;
  204354. JUCE_TRY
  204355. {
  204356. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204357. }
  204358. JUCE_CATCH_ALL
  204359. return hInstance > (HINSTANCE) 32;
  204360. }
  204361. void File::revealToUser() const
  204362. {
  204363. if (isDirectory())
  204364. startAsProcess();
  204365. else if (getParentDirectory().exists())
  204366. getParentDirectory().startAsProcess();
  204367. }
  204368. class NamedPipeInternal
  204369. {
  204370. public:
  204371. NamedPipeInternal (const String& file, const bool isPipe_)
  204372. : pipeH (0),
  204373. cancelEvent (0),
  204374. connected (false),
  204375. isPipe (isPipe_)
  204376. {
  204377. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204378. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204379. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204380. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204381. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204382. }
  204383. ~NamedPipeInternal()
  204384. {
  204385. disconnectPipe();
  204386. if (pipeH != 0)
  204387. CloseHandle (pipeH);
  204388. CloseHandle (cancelEvent);
  204389. }
  204390. bool connect (const int timeOutMs)
  204391. {
  204392. if (! isPipe)
  204393. return true;
  204394. if (! connected)
  204395. {
  204396. OVERLAPPED over;
  204397. zerostruct (over);
  204398. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204399. if (ConnectNamedPipe (pipeH, &over))
  204400. {
  204401. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204402. }
  204403. else
  204404. {
  204405. const int err = GetLastError();
  204406. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204407. {
  204408. HANDLE handles[] = { over.hEvent, cancelEvent };
  204409. if (WaitForMultipleObjects (2, handles, FALSE,
  204410. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204411. connected = true;
  204412. }
  204413. else if (err == ERROR_PIPE_CONNECTED)
  204414. {
  204415. connected = true;
  204416. }
  204417. }
  204418. CloseHandle (over.hEvent);
  204419. }
  204420. return connected;
  204421. }
  204422. void disconnectPipe()
  204423. {
  204424. if (connected)
  204425. {
  204426. DisconnectNamedPipe (pipeH);
  204427. connected = false;
  204428. }
  204429. }
  204430. HANDLE pipeH;
  204431. HANDLE cancelEvent;
  204432. bool connected, isPipe;
  204433. };
  204434. void NamedPipe::close()
  204435. {
  204436. cancelPendingReads();
  204437. const ScopedLock sl (lock);
  204438. delete static_cast<NamedPipeInternal*> (internal);
  204439. internal = 0;
  204440. }
  204441. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204442. {
  204443. close();
  204444. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204445. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204446. {
  204447. internal = intern.release();
  204448. return true;
  204449. }
  204450. return false;
  204451. }
  204452. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204453. {
  204454. const ScopedLock sl (lock);
  204455. int bytesRead = -1;
  204456. bool waitAgain = true;
  204457. while (waitAgain && internal != 0)
  204458. {
  204459. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204460. waitAgain = false;
  204461. if (! intern->connect (timeOutMilliseconds))
  204462. break;
  204463. if (maxBytesToRead <= 0)
  204464. return 0;
  204465. OVERLAPPED over;
  204466. zerostruct (over);
  204467. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204468. unsigned long numRead;
  204469. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204470. {
  204471. bytesRead = (int) numRead;
  204472. }
  204473. else if (GetLastError() == ERROR_IO_PENDING)
  204474. {
  204475. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204476. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204477. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204478. : INFINITE);
  204479. if (waitResult != WAIT_OBJECT_0)
  204480. {
  204481. // if the operation timed out, let's cancel it...
  204482. CancelIo (intern->pipeH);
  204483. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204484. }
  204485. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204486. {
  204487. bytesRead = (int) numRead;
  204488. }
  204489. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204490. {
  204491. intern->disconnectPipe();
  204492. waitAgain = true;
  204493. }
  204494. }
  204495. else
  204496. {
  204497. waitAgain = internal != 0;
  204498. Sleep (5);
  204499. }
  204500. CloseHandle (over.hEvent);
  204501. }
  204502. return bytesRead;
  204503. }
  204504. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204505. {
  204506. int bytesWritten = -1;
  204507. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204508. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204509. {
  204510. if (numBytesToWrite <= 0)
  204511. return 0;
  204512. OVERLAPPED over;
  204513. zerostruct (over);
  204514. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204515. unsigned long numWritten;
  204516. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204517. {
  204518. bytesWritten = (int) numWritten;
  204519. }
  204520. else if (GetLastError() == ERROR_IO_PENDING)
  204521. {
  204522. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204523. DWORD waitResult;
  204524. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204525. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204526. : INFINITE);
  204527. if (waitResult != WAIT_OBJECT_0)
  204528. {
  204529. CancelIo (intern->pipeH);
  204530. WaitForSingleObject (over.hEvent, INFINITE);
  204531. }
  204532. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204533. {
  204534. bytesWritten = (int) numWritten;
  204535. }
  204536. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204537. {
  204538. intern->disconnectPipe();
  204539. }
  204540. }
  204541. CloseHandle (over.hEvent);
  204542. }
  204543. return bytesWritten;
  204544. }
  204545. void NamedPipe::cancelPendingReads()
  204546. {
  204547. if (internal != 0)
  204548. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204549. }
  204550. #endif
  204551. /*** End of inlined file: juce_win32_Files.cpp ***/
  204552. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204553. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204554. // compiled on its own).
  204555. #if JUCE_INCLUDED_FILE
  204556. #ifndef INTERNET_FLAG_NEED_FILE
  204557. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204558. #endif
  204559. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204560. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204561. #endif
  204562. static HINTERNET sessionHandle = 0;
  204563. #ifndef WORKAROUND_TIMEOUT_BUG
  204564. //#define WORKAROUND_TIMEOUT_BUG 1
  204565. #endif
  204566. #if WORKAROUND_TIMEOUT_BUG
  204567. // Required because of a Microsoft bug in setting a timeout
  204568. class InternetConnectThread : public Thread
  204569. {
  204570. public:
  204571. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204572. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204573. {
  204574. startThread();
  204575. }
  204576. ~InternetConnectThread()
  204577. {
  204578. stopThread (60000);
  204579. }
  204580. void run()
  204581. {
  204582. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204583. uc.nPort, _T(""), _T(""),
  204584. isFtp ? INTERNET_SERVICE_FTP
  204585. : INTERNET_SERVICE_HTTP,
  204586. 0, 0);
  204587. notify();
  204588. }
  204589. private:
  204590. URL_COMPONENTS& uc;
  204591. HINTERNET& connection;
  204592. const bool isFtp;
  204593. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  204594. };
  204595. #endif
  204596. class WebInputStream : public InputStream
  204597. {
  204598. public:
  204599. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  204600. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204601. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  204602. : connection (0), request (0),
  204603. address (address_), headers (headers_), postData (postData_), position (0),
  204604. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  204605. {
  204606. createConnection (progressCallback, progressCallbackContext);
  204607. if (responseHeaders != 0 && ! isError())
  204608. {
  204609. DWORD bufferSizeBytes = 4096;
  204610. for (;;)
  204611. {
  204612. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204613. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204614. {
  204615. StringArray headersArray;
  204616. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204617. for (int i = 0; i < headersArray.size(); ++i)
  204618. {
  204619. const String& header = headersArray[i];
  204620. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204621. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204622. const String previousValue ((*responseHeaders) [key]);
  204623. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204624. }
  204625. break;
  204626. }
  204627. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204628. break;
  204629. }
  204630. }
  204631. }
  204632. ~WebInputStream()
  204633. {
  204634. close();
  204635. }
  204636. bool isError() const { return request == 0; }
  204637. bool isExhausted() { return finished; }
  204638. int64 getPosition() { return position; }
  204639. int64 getTotalLength()
  204640. {
  204641. if (! isError())
  204642. {
  204643. DWORD index = 0, result = 0, size = sizeof (result);
  204644. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204645. return (int64) result;
  204646. }
  204647. return -1;
  204648. }
  204649. int read (void* buffer, int bytesToRead)
  204650. {
  204651. DWORD bytesRead = 0;
  204652. if (! (finished || isError()))
  204653. {
  204654. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  204655. position += bytesRead;
  204656. if (bytesRead == 0)
  204657. finished = true;
  204658. }
  204659. return (int) bytesRead;
  204660. }
  204661. bool setPosition (int64 wantedPos)
  204662. {
  204663. if (isError())
  204664. return false;
  204665. if (wantedPos != position)
  204666. {
  204667. finished = false;
  204668. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  204669. if (position == wantedPos)
  204670. return true;
  204671. if (wantedPos < position)
  204672. {
  204673. close();
  204674. position = 0;
  204675. createConnection (0, 0);
  204676. }
  204677. skipNextBytes (wantedPos - position);
  204678. }
  204679. return true;
  204680. }
  204681. private:
  204682. HINTERNET connection, request;
  204683. String address, headers;
  204684. MemoryBlock postData;
  204685. int64 position;
  204686. bool finished;
  204687. const bool isPost;
  204688. int timeOutMs;
  204689. void close()
  204690. {
  204691. if (request != 0)
  204692. {
  204693. InternetCloseHandle (request);
  204694. request = 0;
  204695. }
  204696. if (connection != 0)
  204697. {
  204698. InternetCloseHandle (connection);
  204699. connection = 0;
  204700. }
  204701. }
  204702. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  204703. void* progressCallbackContext)
  204704. {
  204705. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  204706. close();
  204707. if (sessionHandle != 0)
  204708. {
  204709. // break up the url..
  204710. TCHAR file[1024], server[1024];
  204711. URL_COMPONENTS uc;
  204712. zerostruct (uc);
  204713. uc.dwStructSize = sizeof (uc);
  204714. uc.dwUrlPathLength = sizeof (file);
  204715. uc.dwHostNameLength = sizeof (server);
  204716. uc.lpszUrlPath = file;
  204717. uc.lpszHostName = server;
  204718. if (InternetCrackUrl (address, 0, 0, &uc))
  204719. {
  204720. int disable = 1;
  204721. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204722. if (timeOutMs == 0)
  204723. timeOutMs = 30000;
  204724. else if (timeOutMs < 0)
  204725. timeOutMs = -1;
  204726. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204727. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  204728. #if WORKAROUND_TIMEOUT_BUG
  204729. connection = 0;
  204730. {
  204731. InternetConnectThread connectThread (uc, connection, isFtp);
  204732. connectThread.wait (timeOutMs);
  204733. if (connection == 0)
  204734. {
  204735. InternetCloseHandle (sessionHandle);
  204736. sessionHandle = 0;
  204737. }
  204738. }
  204739. #else
  204740. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  204741. _T(""), _T(""),
  204742. isFtp ? INTERNET_SERVICE_FTP
  204743. : INTERNET_SERVICE_HTTP,
  204744. 0, 0);
  204745. #endif
  204746. if (connection != 0)
  204747. {
  204748. if (isFtp)
  204749. {
  204750. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  204751. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  204752. }
  204753. else
  204754. {
  204755. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204756. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204757. if (address.startsWithIgnoreCase ("https:"))
  204758. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204759. // IE7 seems to automatically work out when it's https)
  204760. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  204761. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  204762. if (request != 0)
  204763. {
  204764. INTERNET_BUFFERS buffers;
  204765. zerostruct (buffers);
  204766. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204767. buffers.lpcszHeader = static_cast <LPCTSTR> (headers);
  204768. buffers.dwHeadersLength = headers.length();
  204769. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204770. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204771. {
  204772. int bytesSent = 0;
  204773. for (;;)
  204774. {
  204775. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204776. DWORD bytesDone = 0;
  204777. if (bytesToDo > 0
  204778. && ! InternetWriteFile (request,
  204779. static_cast <const char*> (postData.getData()) + bytesSent,
  204780. bytesToDo, &bytesDone))
  204781. {
  204782. break;
  204783. }
  204784. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204785. {
  204786. if (HttpEndRequest (request, 0, 0, 0))
  204787. return;
  204788. break;
  204789. }
  204790. bytesSent += bytesDone;
  204791. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  204792. break;
  204793. }
  204794. }
  204795. }
  204796. close();
  204797. }
  204798. }
  204799. }
  204800. }
  204801. }
  204802. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  204803. };
  204804. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  204805. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204806. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  204807. {
  204808. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  204809. progressCallback, progressCallbackContext,
  204810. headers, timeOutMs, responseHeaders));
  204811. return wi->isError() ? 0 : wi.release();
  204812. }
  204813. namespace MACAddressHelpers
  204814. {
  204815. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  204816. {
  204817. DynamicLibraryLoader dll ("iphlpapi.dll");
  204818. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204819. if (getAdaptersInfo != 0)
  204820. {
  204821. ULONG len = sizeof (IP_ADAPTER_INFO);
  204822. MemoryBlock mb;
  204823. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204824. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204825. {
  204826. mb.setSize (len);
  204827. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204828. }
  204829. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204830. {
  204831. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  204832. {
  204833. if (adapter->AddressLength >= 6)
  204834. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  204835. }
  204836. }
  204837. }
  204838. }
  204839. void getViaNetBios (Array<MACAddress>& result)
  204840. {
  204841. DynamicLibraryLoader dll ("netapi32.dll");
  204842. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204843. if (NetbiosCall != 0)
  204844. {
  204845. NCB ncb;
  204846. zerostruct (ncb);
  204847. struct ASTAT
  204848. {
  204849. ADAPTER_STATUS adapt;
  204850. NAME_BUFFER NameBuff [30];
  204851. };
  204852. ASTAT astat;
  204853. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204854. LANA_ENUM enums;
  204855. zerostruct (enums);
  204856. ncb.ncb_command = NCBENUM;
  204857. ncb.ncb_buffer = (unsigned char*) &enums;
  204858. ncb.ncb_length = sizeof (LANA_ENUM);
  204859. NetbiosCall (&ncb);
  204860. for (int i = 0; i < enums.length; ++i)
  204861. {
  204862. zerostruct (ncb);
  204863. ncb.ncb_command = NCBRESET;
  204864. ncb.ncb_lana_num = enums.lana[i];
  204865. if (NetbiosCall (&ncb) == 0)
  204866. {
  204867. zerostruct (ncb);
  204868. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204869. ncb.ncb_command = NCBASTAT;
  204870. ncb.ncb_lana_num = enums.lana[i];
  204871. ncb.ncb_buffer = (unsigned char*) &astat;
  204872. ncb.ncb_length = sizeof (ASTAT);
  204873. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  204874. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  204875. }
  204876. }
  204877. }
  204878. }
  204879. }
  204880. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  204881. {
  204882. MACAddressHelpers::getViaGetAdaptersInfo (result);
  204883. MACAddressHelpers::getViaNetBios (result);
  204884. }
  204885. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204886. const String& emailSubject,
  204887. const String& bodyText,
  204888. const StringArray& filesToAttach)
  204889. {
  204890. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204891. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204892. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204893. bool ok = false;
  204894. if (mapiSendMail != 0)
  204895. {
  204896. MapiMessage message;
  204897. zerostruct (message);
  204898. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204899. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204900. MapiRecipDesc recip;
  204901. zerostruct (recip);
  204902. recip.ulRecipClass = MAPI_TO;
  204903. String targetEmailAddress_ (targetEmailAddress);
  204904. if (targetEmailAddress_.isEmpty())
  204905. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204906. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204907. message.nRecipCount = 1;
  204908. message.lpRecips = &recip;
  204909. HeapBlock <MapiFileDesc> files;
  204910. files.calloc (filesToAttach.size());
  204911. message.nFileCount = filesToAttach.size();
  204912. message.lpFiles = files;
  204913. for (int i = 0; i < filesToAttach.size(); ++i)
  204914. {
  204915. files[i].nPosition = (ULONG) -1;
  204916. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204917. }
  204918. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204919. }
  204920. FreeLibrary (h);
  204921. return ok;
  204922. }
  204923. #endif
  204924. /*** End of inlined file: juce_win32_Network.cpp ***/
  204925. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204926. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204927. // compiled on its own).
  204928. #if JUCE_INCLUDED_FILE
  204929. namespace
  204930. {
  204931. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  204932. {
  204933. HKEY rootKey = 0;
  204934. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204935. rootKey = HKEY_CURRENT_USER;
  204936. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204937. rootKey = HKEY_LOCAL_MACHINE;
  204938. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204939. rootKey = HKEY_CLASSES_ROOT;
  204940. if (rootKey != 0)
  204941. {
  204942. name = name.substring (name.indexOfChar ('\\') + 1);
  204943. const int lastSlash = name.lastIndexOfChar ('\\');
  204944. valueName = name.substring (lastSlash + 1);
  204945. name = name.substring (0, lastSlash);
  204946. HKEY key;
  204947. DWORD result;
  204948. if (createForWriting)
  204949. {
  204950. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204951. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204952. return key;
  204953. }
  204954. else
  204955. {
  204956. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204957. return key;
  204958. }
  204959. }
  204960. return 0;
  204961. }
  204962. }
  204963. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204964. const String& defaultValue)
  204965. {
  204966. String valueName, result (defaultValue);
  204967. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204968. if (k != 0)
  204969. {
  204970. WCHAR buffer [2048];
  204971. unsigned long bufferSize = sizeof (buffer);
  204972. DWORD type = REG_SZ;
  204973. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204974. {
  204975. if (type == REG_SZ)
  204976. result = buffer;
  204977. else if (type == REG_DWORD)
  204978. result = String ((int) *(DWORD*) buffer);
  204979. }
  204980. RegCloseKey (k);
  204981. }
  204982. return result;
  204983. }
  204984. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204985. const String& value)
  204986. {
  204987. String valueName;
  204988. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204989. if (k != 0)
  204990. {
  204991. RegSetValueEx (k, valueName, 0, REG_SZ,
  204992. (const BYTE*) (const WCHAR*) value,
  204993. sizeof (WCHAR) * (value.length() + 1));
  204994. RegCloseKey (k);
  204995. }
  204996. }
  204997. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204998. {
  204999. bool exists = false;
  205000. String valueName;
  205001. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205002. if (k != 0)
  205003. {
  205004. unsigned char buffer [2048];
  205005. unsigned long bufferSize = sizeof (buffer);
  205006. DWORD type = 0;
  205007. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205008. exists = true;
  205009. RegCloseKey (k);
  205010. }
  205011. return exists;
  205012. }
  205013. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205014. {
  205015. String valueName;
  205016. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205017. if (k != 0)
  205018. {
  205019. RegDeleteValue (k, valueName);
  205020. RegCloseKey (k);
  205021. }
  205022. }
  205023. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205024. {
  205025. String valueName;
  205026. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205027. if (k != 0)
  205028. {
  205029. RegDeleteKey (k, valueName);
  205030. RegCloseKey (k);
  205031. }
  205032. }
  205033. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205034. const String& symbolicDescription,
  205035. const String& fullDescription,
  205036. const File& targetExecutable,
  205037. int iconResourceNumber)
  205038. {
  205039. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205040. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205041. if (iconResourceNumber != 0)
  205042. setRegistryValue (key + "\\DefaultIcon\\",
  205043. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205044. setRegistryValue (key + "\\", fullDescription);
  205045. setRegistryValue (key + "\\shell\\open\\command\\",
  205046. targetExecutable.getFullPathName() + " %1");
  205047. }
  205048. bool juce_IsRunningInWine()
  205049. {
  205050. HKEY key;
  205051. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205052. {
  205053. RegCloseKey (key);
  205054. return true;
  205055. }
  205056. return false;
  205057. }
  205058. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205059. {
  205060. String s (::GetCommandLineW());
  205061. StringArray tokens;
  205062. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205063. return tokens.joinIntoString (" ", 1);
  205064. }
  205065. static void* currentModuleHandle = 0;
  205066. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205067. {
  205068. if (currentModuleHandle == 0)
  205069. currentModuleHandle = GetModuleHandle (0);
  205070. return currentModuleHandle;
  205071. }
  205072. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205073. {
  205074. currentModuleHandle = newHandle;
  205075. }
  205076. void PlatformUtilities::fpuReset()
  205077. {
  205078. #if JUCE_MSVC
  205079. _clearfp();
  205080. #endif
  205081. }
  205082. void PlatformUtilities::beep()
  205083. {
  205084. MessageBeep (MB_OK);
  205085. }
  205086. #endif
  205087. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205088. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205089. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205090. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205091. // compiled on its own).
  205092. #if JUCE_INCLUDED_FILE
  205093. static const unsigned int specialId = WM_APP + 0x4400;
  205094. static const unsigned int broadcastId = WM_APP + 0x4403;
  205095. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205096. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205097. HWND juce_messageWindowHandle = 0;
  205098. extern long improbableWindowNumber; // defined in windowing.cpp
  205099. #ifndef WM_APPCOMMAND
  205100. #define WM_APPCOMMAND 0x0319
  205101. #endif
  205102. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205103. const UINT message,
  205104. const WPARAM wParam,
  205105. const LPARAM lParam) throw()
  205106. {
  205107. JUCE_TRY
  205108. {
  205109. if (h == juce_messageWindowHandle)
  205110. {
  205111. if (message == specialCallbackId)
  205112. {
  205113. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205114. return (LRESULT) (*func) ((void*) lParam);
  205115. }
  205116. else if (message == specialId)
  205117. {
  205118. // these are trapped early in the dispatch call, but must also be checked
  205119. // here in case there are windows modal dialog boxes doing their own
  205120. // dispatch loop and not calling our version
  205121. Message* const message = reinterpret_cast <Message*> (lParam);
  205122. MessageManager::getInstance()->deliverMessage (message);
  205123. message->decReferenceCount();
  205124. return 0;
  205125. }
  205126. else if (message == broadcastId)
  205127. {
  205128. const ScopedPointer <String> messageString ((String*) lParam);
  205129. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205130. return 0;
  205131. }
  205132. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205133. {
  205134. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205135. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205136. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205137. return 0;
  205138. }
  205139. }
  205140. }
  205141. JUCE_CATCH_EXCEPTION
  205142. return DefWindowProc (h, message, wParam, lParam);
  205143. }
  205144. static bool isEventBlockedByModalComps (MSG& m)
  205145. {
  205146. if (Component::getNumCurrentlyModalComponents() == 0
  205147. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205148. return false;
  205149. switch (m.message)
  205150. {
  205151. case WM_MOUSEMOVE:
  205152. case WM_NCMOUSEMOVE:
  205153. case 0x020A: /* WM_MOUSEWHEEL */
  205154. case 0x020E: /* WM_MOUSEHWHEEL */
  205155. case WM_KEYUP:
  205156. case WM_SYSKEYUP:
  205157. case WM_CHAR:
  205158. case WM_APPCOMMAND:
  205159. case WM_LBUTTONUP:
  205160. case WM_MBUTTONUP:
  205161. case WM_RBUTTONUP:
  205162. case WM_MOUSEACTIVATE:
  205163. case WM_NCMOUSEHOVER:
  205164. case WM_MOUSEHOVER:
  205165. return true;
  205166. case WM_NCLBUTTONDOWN:
  205167. case WM_NCLBUTTONDBLCLK:
  205168. case WM_NCRBUTTONDOWN:
  205169. case WM_NCRBUTTONDBLCLK:
  205170. case WM_NCMBUTTONDOWN:
  205171. case WM_NCMBUTTONDBLCLK:
  205172. case WM_LBUTTONDOWN:
  205173. case WM_LBUTTONDBLCLK:
  205174. case WM_MBUTTONDOWN:
  205175. case WM_MBUTTONDBLCLK:
  205176. case WM_RBUTTONDOWN:
  205177. case WM_RBUTTONDBLCLK:
  205178. case WM_KEYDOWN:
  205179. case WM_SYSKEYDOWN:
  205180. {
  205181. Component* const modal = Component::getCurrentlyModalComponent (0);
  205182. if (modal != 0)
  205183. modal->inputAttemptWhenModal();
  205184. return true;
  205185. }
  205186. default:
  205187. break;
  205188. }
  205189. return false;
  205190. }
  205191. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205192. {
  205193. MSG m;
  205194. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205195. return false;
  205196. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205197. {
  205198. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205199. {
  205200. Message* const message = reinterpret_cast <Message*> (m.lParam);
  205201. MessageManager::getInstance()->deliverMessage (message);
  205202. message->decReferenceCount();
  205203. }
  205204. else if (m.message == WM_QUIT)
  205205. {
  205206. if (JUCEApplication::getInstance() != 0)
  205207. JUCEApplication::getInstance()->systemRequestedQuit();
  205208. }
  205209. else if (! isEventBlockedByModalComps (m))
  205210. {
  205211. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205212. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205213. {
  205214. // if it's someone else's window being clicked on, and the focus is
  205215. // currently on a juce window, pass the kb focus over..
  205216. HWND currentFocus = GetFocus();
  205217. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205218. SetFocus (m.hwnd);
  205219. }
  205220. TranslateMessage (&m);
  205221. DispatchMessage (&m);
  205222. }
  205223. }
  205224. return true;
  205225. }
  205226. bool juce_postMessageToSystemQueue (Message* message)
  205227. {
  205228. message->incReferenceCount();
  205229. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205230. }
  205231. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205232. void* userData)
  205233. {
  205234. if (MessageManager::getInstance()->isThisTheMessageThread())
  205235. {
  205236. return (*callback) (userData);
  205237. }
  205238. else
  205239. {
  205240. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205241. // deadlock because the message manager is blocked from running, and can't
  205242. // call your function..
  205243. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205244. return (void*) SendMessage (juce_messageWindowHandle,
  205245. specialCallbackId,
  205246. (WPARAM) callback,
  205247. (LPARAM) userData);
  205248. }
  205249. }
  205250. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205251. {
  205252. if (hwnd != juce_messageWindowHandle)
  205253. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205254. return TRUE;
  205255. }
  205256. void MessageManager::broadcastMessage (const String& value)
  205257. {
  205258. Array<void*> windows;
  205259. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205260. const String localCopy (value);
  205261. COPYDATASTRUCT data;
  205262. data.dwData = broadcastId;
  205263. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205264. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205265. for (int i = windows.size(); --i >= 0;)
  205266. {
  205267. HWND hwnd = (HWND) windows.getUnchecked(i);
  205268. TCHAR windowName [64]; // no need to read longer strings than this
  205269. GetWindowText (hwnd, windowName, 64);
  205270. windowName [63] = 0;
  205271. if (String (windowName) == messageWindowName)
  205272. {
  205273. DWORD_PTR result;
  205274. SendMessageTimeout (hwnd, WM_COPYDATA,
  205275. (WPARAM) juce_messageWindowHandle,
  205276. (LPARAM) &data,
  205277. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205278. 8000,
  205279. &result);
  205280. }
  205281. }
  205282. }
  205283. static const String getMessageWindowClassName()
  205284. {
  205285. // this name has to be different for each app/dll instance because otherwise
  205286. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205287. // window class).
  205288. static int number = 0;
  205289. if (number == 0)
  205290. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205291. return "JUCEcs_" + String (number);
  205292. }
  205293. void MessageManager::doPlatformSpecificInitialisation()
  205294. {
  205295. OleInitialize (0);
  205296. const String className (getMessageWindowClassName());
  205297. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205298. WNDCLASSEX wc;
  205299. zerostruct (wc);
  205300. wc.cbSize = sizeof (wc);
  205301. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205302. wc.cbWndExtra = 4;
  205303. wc.hInstance = hmod;
  205304. wc.lpszClassName = className;
  205305. RegisterClassEx (&wc);
  205306. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205307. messageWindowName,
  205308. 0, 0, 0, 0, 0, 0, 0,
  205309. hmod, 0);
  205310. }
  205311. void MessageManager::doPlatformSpecificShutdown()
  205312. {
  205313. DestroyWindow (juce_messageWindowHandle);
  205314. UnregisterClass (getMessageWindowClassName(), 0);
  205315. OleUninitialize();
  205316. }
  205317. #endif
  205318. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205319. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205320. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205321. // compiled on its own).
  205322. #if JUCE_INCLUDED_FILE
  205323. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205324. NEWTEXTMETRICEXW*,
  205325. int type,
  205326. LPARAM lParam)
  205327. {
  205328. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205329. {
  205330. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205331. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205332. }
  205333. return 1;
  205334. }
  205335. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205336. NEWTEXTMETRICEXW*,
  205337. int type,
  205338. LPARAM lParam)
  205339. {
  205340. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205341. {
  205342. LOGFONTW lf;
  205343. zerostruct (lf);
  205344. lf.lfWeight = FW_DONTCARE;
  205345. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205346. lf.lfQuality = DEFAULT_QUALITY;
  205347. lf.lfCharSet = DEFAULT_CHARSET;
  205348. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205349. lf.lfPitchAndFamily = FF_DONTCARE;
  205350. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205351. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205352. HDC dc = CreateCompatibleDC (0);
  205353. EnumFontFamiliesEx (dc, &lf,
  205354. (FONTENUMPROCW) &wfontEnum2,
  205355. lParam, 0);
  205356. DeleteDC (dc);
  205357. }
  205358. return 1;
  205359. }
  205360. const StringArray Font::findAllTypefaceNames()
  205361. {
  205362. StringArray results;
  205363. HDC dc = CreateCompatibleDC (0);
  205364. {
  205365. LOGFONTW lf;
  205366. zerostruct (lf);
  205367. lf.lfWeight = FW_DONTCARE;
  205368. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205369. lf.lfQuality = DEFAULT_QUALITY;
  205370. lf.lfCharSet = DEFAULT_CHARSET;
  205371. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205372. lf.lfPitchAndFamily = FF_DONTCARE;
  205373. lf.lfFaceName[0] = 0;
  205374. EnumFontFamiliesEx (dc, &lf,
  205375. (FONTENUMPROCW) &wfontEnum1,
  205376. (LPARAM) &results, 0);
  205377. }
  205378. DeleteDC (dc);
  205379. results.sort (true);
  205380. return results;
  205381. }
  205382. extern bool juce_IsRunningInWine();
  205383. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205384. {
  205385. if (juce_IsRunningInWine())
  205386. {
  205387. // If we're running in Wine, then use fonts that might be available on Linux..
  205388. defaultSans = "Bitstream Vera Sans";
  205389. defaultSerif = "Bitstream Vera Serif";
  205390. defaultFixed = "Bitstream Vera Sans Mono";
  205391. }
  205392. else
  205393. {
  205394. defaultSans = "Verdana";
  205395. defaultSerif = "Times";
  205396. defaultFixed = "Lucida Console";
  205397. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205398. }
  205399. }
  205400. class FontDCHolder : private DeletedAtShutdown
  205401. {
  205402. public:
  205403. FontDCHolder()
  205404. : dc (0), fontH (0), previousFontH (0), numKPs (0), size (0),
  205405. bold (false), italic (false)
  205406. {
  205407. }
  205408. ~FontDCHolder()
  205409. {
  205410. deleteDCAndFont();
  205411. clearSingletonInstance();
  205412. }
  205413. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205414. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205415. {
  205416. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205417. {
  205418. fontName = fontName_;
  205419. bold = bold_;
  205420. italic = italic_;
  205421. size = size_;
  205422. deleteDCAndFont();
  205423. dc = CreateCompatibleDC (0);
  205424. SetMapperFlags (dc, 0);
  205425. SetMapMode (dc, MM_TEXT);
  205426. LOGFONTW lfw;
  205427. zerostruct (lfw);
  205428. lfw.lfCharSet = DEFAULT_CHARSET;
  205429. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205430. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205431. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205432. lfw.lfQuality = PROOF_QUALITY;
  205433. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205434. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205435. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205436. lfw.lfHeight = size > 0 ? size : -256;
  205437. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205438. if (standardSizedFont != 0)
  205439. {
  205440. if ((previousFontH = SelectObject (dc, standardSizedFont)) != 0)
  205441. {
  205442. fontH = standardSizedFont;
  205443. if (size == 0)
  205444. {
  205445. OUTLINETEXTMETRIC otm;
  205446. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205447. {
  205448. lfw.lfHeight = -(int) otm.otmEMSquare;
  205449. fontH = CreateFontIndirect (&lfw);
  205450. SelectObject (dc, fontH);
  205451. DeleteObject (standardSizedFont);
  205452. }
  205453. }
  205454. }
  205455. }
  205456. }
  205457. return dc;
  205458. }
  205459. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205460. {
  205461. if (kps == 0)
  205462. {
  205463. numKPs = GetKerningPairs (dc, 0, 0);
  205464. kps.calloc (numKPs);
  205465. GetKerningPairs (dc, numKPs, kps);
  205466. }
  205467. numKPs_ = numKPs;
  205468. return kps;
  205469. }
  205470. private:
  205471. HFONT fontH;
  205472. HGDIOBJ previousFontH;
  205473. HDC dc;
  205474. String fontName;
  205475. HeapBlock <KERNINGPAIR> kps;
  205476. int numKPs, size;
  205477. bool bold, italic;
  205478. void deleteDCAndFont()
  205479. {
  205480. if (dc != 0)
  205481. {
  205482. SelectObject (dc, previousFontH); // Replacing the previous font before deleting the DC avoids a warning in BoundsChecker
  205483. DeleteDC (dc);
  205484. dc = 0;
  205485. }
  205486. if (fontH != 0)
  205487. {
  205488. DeleteObject (fontH);
  205489. fontH = 0;
  205490. }
  205491. kps.free();
  205492. }
  205493. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205494. };
  205495. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205496. class WindowsTypeface : public CustomTypeface
  205497. {
  205498. public:
  205499. WindowsTypeface (const Font& font)
  205500. {
  205501. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205502. font.isBold(), font.isItalic(), 0);
  205503. TEXTMETRIC tm;
  205504. tm.tmAscent = tm.tmHeight = 1;
  205505. tm.tmDefaultChar = 0;
  205506. GetTextMetrics (dc, &tm);
  205507. setCharacteristics (font.getTypefaceName(),
  205508. tm.tmAscent / (float) tm.tmHeight,
  205509. font.isBold(), font.isItalic(),
  205510. tm.tmDefaultChar);
  205511. }
  205512. bool loadGlyphIfPossible (juce_wchar character)
  205513. {
  205514. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205515. GLYPHMETRICS gm;
  205516. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205517. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205518. // gets correctly created later on.
  205519. if (! isFallbackFont)
  205520. {
  205521. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205522. WORD index = 0;
  205523. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205524. && index == 0xffff)
  205525. {
  205526. return false;
  205527. }
  205528. }
  205529. Path glyphPath;
  205530. TEXTMETRIC tm;
  205531. if (! GetTextMetrics (dc, &tm))
  205532. {
  205533. addGlyph (character, glyphPath, 0);
  205534. return true;
  205535. }
  205536. const float height = (float) tm.tmHeight;
  205537. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205538. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205539. &gm, 0, 0, &identityMatrix);
  205540. if (bufSize > 0)
  205541. {
  205542. HeapBlock<char> data (bufSize);
  205543. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205544. bufSize, data, &identityMatrix);
  205545. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205546. const float scaleX = 1.0f / height;
  205547. const float scaleY = -1.0f / height;
  205548. while ((char*) pheader < data + bufSize)
  205549. {
  205550. float x = scaleX * pheader->pfxStart.x.value;
  205551. float y = scaleY * pheader->pfxStart.y.value;
  205552. glyphPath.startNewSubPath (x, y);
  205553. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205554. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205555. while ((const char*) curve < curveEnd)
  205556. {
  205557. if (curve->wType == TT_PRIM_LINE)
  205558. {
  205559. for (int i = 0; i < curve->cpfx; ++i)
  205560. {
  205561. x = scaleX * curve->apfx[i].x.value;
  205562. y = scaleY * curve->apfx[i].y.value;
  205563. glyphPath.lineTo (x, y);
  205564. }
  205565. }
  205566. else if (curve->wType == TT_PRIM_QSPLINE)
  205567. {
  205568. for (int i = 0; i < curve->cpfx - 1; ++i)
  205569. {
  205570. const float x2 = scaleX * curve->apfx[i].x.value;
  205571. const float y2 = scaleY * curve->apfx[i].y.value;
  205572. float x3, y3;
  205573. if (i < curve->cpfx - 2)
  205574. {
  205575. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205576. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205577. }
  205578. else
  205579. {
  205580. x3 = scaleX * curve->apfx[i + 1].x.value;
  205581. y3 = scaleY * curve->apfx[i + 1].y.value;
  205582. }
  205583. glyphPath.quadraticTo (x2, y2, x3, y3);
  205584. x = x3;
  205585. y = y3;
  205586. }
  205587. }
  205588. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205589. }
  205590. pheader = (const TTPOLYGONHEADER*) curve;
  205591. glyphPath.closeSubPath();
  205592. }
  205593. }
  205594. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205595. int numKPs;
  205596. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205597. for (int i = 0; i < numKPs; ++i)
  205598. {
  205599. if (kps[i].wFirst == character)
  205600. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205601. kps[i].iKernAmount / height);
  205602. }
  205603. return true;
  205604. }
  205605. private:
  205606. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  205607. };
  205608. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205609. {
  205610. return new WindowsTypeface (font);
  205611. }
  205612. #endif
  205613. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205614. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205615. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205616. // compiled on its own).
  205617. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205618. class SharedD2DFactory : public DeletedAtShutdown
  205619. {
  205620. public:
  205621. SharedD2DFactory()
  205622. {
  205623. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205624. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205625. if (directWriteFactory != 0)
  205626. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205627. }
  205628. ~SharedD2DFactory()
  205629. {
  205630. clearSingletonInstance();
  205631. }
  205632. juce_DeclareSingleton (SharedD2DFactory, false);
  205633. ComSmartPtr <ID2D1Factory> d2dFactory;
  205634. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205635. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205636. };
  205637. juce_ImplementSingleton (SharedD2DFactory)
  205638. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205639. {
  205640. public:
  205641. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205642. : hwnd (hwnd_),
  205643. currentState (0)
  205644. {
  205645. RECT windowRect;
  205646. GetClientRect (hwnd, &windowRect);
  205647. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205648. bounds.setSize (size.width, size.height);
  205649. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205650. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205651. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205652. // xxx check for error
  205653. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205654. }
  205655. ~Direct2DLowLevelGraphicsContext()
  205656. {
  205657. states.clear();
  205658. }
  205659. void resized()
  205660. {
  205661. RECT windowRect;
  205662. GetClientRect (hwnd, &windowRect);
  205663. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205664. renderingTarget->Resize (size);
  205665. bounds.setSize (size.width, size.height);
  205666. }
  205667. void clear()
  205668. {
  205669. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205670. }
  205671. void start()
  205672. {
  205673. renderingTarget->BeginDraw();
  205674. saveState();
  205675. }
  205676. void end()
  205677. {
  205678. states.clear();
  205679. currentState = 0;
  205680. renderingTarget->EndDraw();
  205681. renderingTarget->CheckWindowState();
  205682. }
  205683. bool isVectorDevice() const { return false; }
  205684. void setOrigin (int x, int y)
  205685. {
  205686. currentState->origin.addXY (x, y);
  205687. }
  205688. void addTransform (const AffineTransform& transform)
  205689. {
  205690. //xxx todo
  205691. jassertfalse;
  205692. }
  205693. float getScaleFactor()
  205694. {
  205695. jassertfalse; //xxx
  205696. return 1.0f;
  205697. }
  205698. bool clipToRectangle (const Rectangle<int>& r)
  205699. {
  205700. currentState->clipToRectangle (r);
  205701. return ! isClipEmpty();
  205702. }
  205703. bool clipToRectangleList (const RectangleList& clipRegion)
  205704. {
  205705. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205706. return ! isClipEmpty();
  205707. }
  205708. void excludeClipRectangle (const Rectangle<int>&)
  205709. {
  205710. //xxx
  205711. }
  205712. void clipToPath (const Path& path, const AffineTransform& transform)
  205713. {
  205714. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205715. }
  205716. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205717. {
  205718. currentState->clipToImage (sourceImage,transform);
  205719. }
  205720. bool clipRegionIntersects (const Rectangle<int>& r)
  205721. {
  205722. const Rectangle<int> r2 (r + currentState->origin);
  205723. return currentState->clipRect.intersects (r2);
  205724. }
  205725. const Rectangle<int> getClipBounds() const
  205726. {
  205727. // xxx could this take into account complex clip regions?
  205728. return currentState->clipRect - currentState->origin;
  205729. }
  205730. bool isClipEmpty() const
  205731. {
  205732. return currentState->clipRect.isEmpty();
  205733. }
  205734. void saveState()
  205735. {
  205736. states.add (new SavedState (*this));
  205737. currentState = states.getLast();
  205738. }
  205739. void restoreState()
  205740. {
  205741. jassert (states.size() > 1) //you should never pop the last state!
  205742. states.removeLast (1);
  205743. currentState = states.getLast();
  205744. }
  205745. void beginTransparencyLayer (float opacity)
  205746. {
  205747. jassertfalse; //xxx todo
  205748. }
  205749. void endTransparencyLayer()
  205750. {
  205751. jassertfalse; //xxx todo
  205752. }
  205753. void setFill (const FillType& fillType)
  205754. {
  205755. currentState->setFill (fillType);
  205756. }
  205757. void setOpacity (float newOpacity)
  205758. {
  205759. currentState->setOpacity (newOpacity);
  205760. }
  205761. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205762. {
  205763. }
  205764. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205765. {
  205766. currentState->createBrush();
  205767. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205768. }
  205769. void fillPath (const Path& p, const AffineTransform& transform)
  205770. {
  205771. currentState->createBrush();
  205772. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205773. if (renderingTarget != 0)
  205774. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205775. }
  205776. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205777. {
  205778. const int x = currentState->origin.getX();
  205779. const int y = currentState->origin.getY();
  205780. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205781. D2D1_SIZE_U size;
  205782. size.width = image.getWidth();
  205783. size.height = image.getHeight();
  205784. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205785. Image img (image.convertedToFormat (Image::ARGB));
  205786. Image::BitmapData bd (img, false);
  205787. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205788. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205789. {
  205790. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205791. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  205792. if (tempBitmap != 0)
  205793. renderingTarget->DrawBitmap (tempBitmap);
  205794. }
  205795. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205796. }
  205797. void drawLine (const Line <float>& line)
  205798. {
  205799. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205800. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205801. line.getEnd() + currentState->origin.toFloat());
  205802. currentState->createBrush();
  205803. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205804. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205805. currentState->currentBrush);
  205806. }
  205807. void drawVerticalLine (int x, float top, float bottom)
  205808. {
  205809. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205810. currentState->createBrush();
  205811. x += currentState->origin.getX();
  205812. const int y = currentState->origin.getY();
  205813. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205814. D2D1::Point2F (x, y + bottom),
  205815. currentState->currentBrush);
  205816. }
  205817. void drawHorizontalLine (int y, float left, float right)
  205818. {
  205819. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205820. currentState->createBrush();
  205821. y += currentState->origin.getY();
  205822. const int x = currentState->origin.getX();
  205823. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205824. D2D1::Point2F (x + right, y),
  205825. currentState->currentBrush);
  205826. }
  205827. void setFont (const Font& newFont)
  205828. {
  205829. currentState->setFont (newFont);
  205830. }
  205831. const Font getFont()
  205832. {
  205833. return currentState->font;
  205834. }
  205835. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205836. {
  205837. const float x = currentState->origin.getX();
  205838. const float y = currentState->origin.getY();
  205839. currentState->createBrush();
  205840. currentState->createFont();
  205841. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205842. float hScale = currentState->font.getHorizontalScale();
  205843. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205844. float dpiX = 0, dpiY = 0;
  205845. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  205846. UINT32 glyphNum = glyphNumber;
  205847. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  205848. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  205849. DWRITE_GLYPH_OFFSET offset;
  205850. offset.advanceOffset = 0;
  205851. offset.ascenderOffset = 0;
  205852. float glyphAdvances = 0;
  205853. DWRITE_GLYPH_RUN glyph;
  205854. glyph.fontFace = currentState->currentFontFace;
  205855. glyph.glyphCount = 1;
  205856. glyph.glyphIndices = &glyphNum1;
  205857. glyph.isSideways = FALSE;
  205858. glyph.glyphAdvances = &glyphAdvances;
  205859. glyph.glyphOffsets = &offset;
  205860. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  205861. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  205862. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205863. }
  205864. class SavedState
  205865. {
  205866. public:
  205867. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  205868. : owner (owner_), currentBrush (0),
  205869. fontScaling (1.0f), currentFontFace (0),
  205870. clipsRect (false), shouldClipRect (false),
  205871. clipsRectList (false), shouldClipRectList (false),
  205872. clipsComplex (false), shouldClipComplex (false),
  205873. clipsBitmap (false), shouldClipBitmap (false)
  205874. {
  205875. if (owner.currentState != 0)
  205876. {
  205877. // xxx seems like a very slow way to create one of these, and this is a performance
  205878. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  205879. setFill (owner.currentState->fillType);
  205880. currentBrush = owner.currentState->currentBrush;
  205881. origin = owner.currentState->origin;
  205882. clipRect = owner.currentState->clipRect;
  205883. font = owner.currentState->font;
  205884. currentFontFace = owner.currentState->currentFontFace;
  205885. }
  205886. else
  205887. {
  205888. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  205889. clipRect.setSize (size.width, size.height);
  205890. setFill (FillType (Colours::black));
  205891. }
  205892. }
  205893. ~SavedState()
  205894. {
  205895. clearClip();
  205896. clearFont();
  205897. clearFill();
  205898. clearPathClip();
  205899. clearImageClip();
  205900. complexClipLayer = 0;
  205901. bitmapMaskLayer = 0;
  205902. }
  205903. void clearClip()
  205904. {
  205905. popClips();
  205906. shouldClipRect = false;
  205907. }
  205908. void clipToRectangle (const Rectangle<int>& r)
  205909. {
  205910. clearClip();
  205911. clipRect = r + origin;
  205912. shouldClipRect = true;
  205913. pushClips();
  205914. }
  205915. void clearPathClip()
  205916. {
  205917. popClips();
  205918. if (shouldClipComplex)
  205919. {
  205920. complexClipGeometry = 0;
  205921. shouldClipComplex = false;
  205922. }
  205923. }
  205924. void clipToPath (ID2D1Geometry* geometry)
  205925. {
  205926. clearPathClip();
  205927. if (complexClipLayer == 0)
  205928. owner.renderingTarget->CreateLayer (&complexClipLayer);
  205929. complexClipGeometry = geometry;
  205930. shouldClipComplex = true;
  205931. pushClips();
  205932. }
  205933. void clearRectListClip()
  205934. {
  205935. popClips();
  205936. if (shouldClipRectList)
  205937. {
  205938. rectListGeometry = 0;
  205939. shouldClipRectList = false;
  205940. }
  205941. }
  205942. void clipToRectList (ID2D1Geometry* geometry)
  205943. {
  205944. clearRectListClip();
  205945. if (rectListLayer == 0)
  205946. owner.renderingTarget->CreateLayer (&rectListLayer);
  205947. rectListGeometry = geometry;
  205948. shouldClipRectList = true;
  205949. pushClips();
  205950. }
  205951. void clearImageClip()
  205952. {
  205953. popClips();
  205954. if (shouldClipBitmap)
  205955. {
  205956. maskBitmap = 0;
  205957. bitmapMaskBrush = 0;
  205958. shouldClipBitmap = false;
  205959. }
  205960. }
  205961. void clipToImage (const Image& image, const AffineTransform& transform)
  205962. {
  205963. clearImageClip();
  205964. if (bitmapMaskLayer == 0)
  205965. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  205966. D2D1_BRUSH_PROPERTIES brushProps;
  205967. brushProps.opacity = 1;
  205968. brushProps.transform = transfromToMatrix (transform);
  205969. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  205970. D2D1_SIZE_U size;
  205971. size.width = image.getWidth();
  205972. size.height = image.getHeight();
  205973. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205974. maskImage = image.convertedToFormat (Image::ARGB);
  205975. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  205976. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  205977. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205978. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  205979. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  205980. imageMaskLayerParams = D2D1::LayerParameters();
  205981. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  205982. shouldClipBitmap = true;
  205983. pushClips();
  205984. }
  205985. void popClips()
  205986. {
  205987. if (clipsBitmap)
  205988. {
  205989. owner.renderingTarget->PopLayer();
  205990. clipsBitmap = false;
  205991. }
  205992. if (clipsComplex)
  205993. {
  205994. owner.renderingTarget->PopLayer();
  205995. clipsComplex = false;
  205996. }
  205997. if (clipsRectList)
  205998. {
  205999. owner.renderingTarget->PopLayer();
  206000. clipsRectList = false;
  206001. }
  206002. if (clipsRect)
  206003. {
  206004. owner.renderingTarget->PopAxisAlignedClip();
  206005. clipsRect = false;
  206006. }
  206007. }
  206008. void pushClips()
  206009. {
  206010. if (shouldClipRect && ! clipsRect)
  206011. {
  206012. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206013. clipsRect = true;
  206014. }
  206015. if (shouldClipRectList && ! clipsRectList)
  206016. {
  206017. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206018. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206019. layerParams.geometricMask = rectListGeometry;
  206020. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206021. clipsRectList = true;
  206022. }
  206023. if (shouldClipComplex && ! clipsComplex)
  206024. {
  206025. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206026. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206027. layerParams.geometricMask = complexClipGeometry;
  206028. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206029. clipsComplex = true;
  206030. }
  206031. if (shouldClipBitmap && ! clipsBitmap)
  206032. {
  206033. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206034. clipsBitmap = true;
  206035. }
  206036. }
  206037. void setFill (const FillType& newFillType)
  206038. {
  206039. if (fillType != newFillType)
  206040. {
  206041. fillType = newFillType;
  206042. clearFill();
  206043. }
  206044. }
  206045. void clearFont()
  206046. {
  206047. currentFontFace = localFontFace = 0;
  206048. }
  206049. void setFont (const Font& newFont)
  206050. {
  206051. if (font != newFont)
  206052. {
  206053. font = newFont;
  206054. clearFont();
  206055. }
  206056. }
  206057. void createFont()
  206058. {
  206059. // xxx The font shouldn't be managed by the graphics context.
  206060. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206061. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206062. // WindowsTypeface class.
  206063. if (currentFontFace == 0)
  206064. {
  206065. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206066. fontScaling = systemType->getAscent();
  206067. BOOL fontFound;
  206068. uint32 fontIndex;
  206069. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206070. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206071. if (! fontFound)
  206072. fontIndex = 0;
  206073. ComSmartPtr <IDWriteFontFamily> fontFam;
  206074. fonts->GetFontFamily (fontIndex, &fontFam);
  206075. ComSmartPtr <IDWriteFont> font;
  206076. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206077. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206078. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206079. font->CreateFontFace (&localFontFace);
  206080. currentFontFace = localFontFace;
  206081. }
  206082. }
  206083. void setOpacity (float newOpacity)
  206084. {
  206085. fillType.setOpacity (newOpacity);
  206086. if (currentBrush != 0)
  206087. currentBrush->SetOpacity (newOpacity);
  206088. }
  206089. void clearFill()
  206090. {
  206091. gradientStops = 0;
  206092. linearGradient = 0;
  206093. radialGradient = 0;
  206094. bitmap = 0;
  206095. bitmapBrush = 0;
  206096. currentBrush = 0;
  206097. }
  206098. void createBrush()
  206099. {
  206100. if (currentBrush == 0)
  206101. {
  206102. const int x = origin.getX();
  206103. const int y = origin.getY();
  206104. if (fillType.isColour())
  206105. {
  206106. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206107. owner.colourBrush->SetColor (colour);
  206108. currentBrush = owner.colourBrush;
  206109. }
  206110. else if (fillType.isTiledImage())
  206111. {
  206112. D2D1_BRUSH_PROPERTIES brushProps;
  206113. brushProps.opacity = fillType.getOpacity();
  206114. brushProps.transform = transfromToMatrix (fillType.transform);
  206115. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206116. image = fillType.image;
  206117. D2D1_SIZE_U size;
  206118. size.width = image.getWidth();
  206119. size.height = image.getHeight();
  206120. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206121. this->image = image.convertedToFormat (Image::ARGB);
  206122. Image::BitmapData bd (this->image, false);
  206123. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206124. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206125. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206126. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206127. currentBrush = bitmapBrush;
  206128. }
  206129. else if (fillType.isGradient())
  206130. {
  206131. gradientStops = 0;
  206132. D2D1_BRUSH_PROPERTIES brushProps;
  206133. brushProps.opacity = fillType.getOpacity();
  206134. brushProps.transform = transfromToMatrix (fillType.transform);
  206135. const int numColors = fillType.gradient->getNumColours();
  206136. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206137. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206138. {
  206139. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206140. stops[i].position = fillType.gradient->getColourPosition(i);
  206141. }
  206142. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206143. if (fillType.gradient->isRadial)
  206144. {
  206145. radialGradient = 0;
  206146. const Point<float>& p1 = fillType.gradient->point1;
  206147. const Point<float>& p2 = fillType.gradient->point2;
  206148. float r = p1.getDistanceFrom (p2);
  206149. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206150. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206151. D2D1::Point2F (0, 0),
  206152. r, r);
  206153. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206154. currentBrush = radialGradient;
  206155. }
  206156. else
  206157. {
  206158. linearGradient = 0;
  206159. const Point<float>& p1 = fillType.gradient->point1;
  206160. const Point<float>& p2 = fillType.gradient->point2;
  206161. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206162. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206163. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206164. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206165. currentBrush = linearGradient;
  206166. }
  206167. }
  206168. }
  206169. }
  206170. //xxx most of these members should probably be private...
  206171. Direct2DLowLevelGraphicsContext& owner;
  206172. Point<int> origin;
  206173. Font font;
  206174. float fontScaling;
  206175. IDWriteFontFace* currentFontFace;
  206176. ComSmartPtr <IDWriteFontFace> localFontFace;
  206177. FillType fillType;
  206178. Image image;
  206179. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206180. Rectangle<int> clipRect;
  206181. bool clipsRect, shouldClipRect;
  206182. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206183. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206184. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206185. bool clipsComplex, shouldClipComplex;
  206186. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206187. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206188. ComSmartPtr <ID2D1Layer> rectListLayer;
  206189. bool clipsRectList, shouldClipRectList;
  206190. Image maskImage;
  206191. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206192. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206193. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206194. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206195. bool clipsBitmap, shouldClipBitmap;
  206196. ID2D1Brush* currentBrush;
  206197. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206198. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206199. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206200. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206201. private:
  206202. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206203. };
  206204. private:
  206205. HWND hwnd;
  206206. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206207. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206208. Rectangle<int> bounds;
  206209. SavedState* currentState;
  206210. OwnedArray<SavedState> states;
  206211. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206212. {
  206213. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206214. }
  206215. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206216. {
  206217. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206218. }
  206219. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206220. {
  206221. transform.transformPoint (x, y);
  206222. return D2D1::Point2F (x, y);
  206223. }
  206224. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206225. {
  206226. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206227. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206228. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206229. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206230. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206231. }
  206232. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206233. {
  206234. ID2D1PathGeometry* p = 0;
  206235. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206236. ComSmartPtr <ID2D1GeometrySink> sink;
  206237. HRESULT hr = p->Open (&sink); // xxx handle error
  206238. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206239. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206240. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206241. hr = sink->Close();
  206242. return p;
  206243. }
  206244. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206245. {
  206246. Path::Iterator it (path);
  206247. while (it.next())
  206248. {
  206249. switch (it.elementType)
  206250. {
  206251. case Path::Iterator::cubicTo:
  206252. {
  206253. D2D1_BEZIER_SEGMENT seg;
  206254. transform.transformPoint (it.x1, it.y1);
  206255. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206256. transform.transformPoint (it.x2, it.y2);
  206257. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206258. transform.transformPoint(it.x3, it.y3);
  206259. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206260. sink->AddBezier (seg);
  206261. break;
  206262. }
  206263. case Path::Iterator::lineTo:
  206264. {
  206265. transform.transformPoint (it.x1, it.y1);
  206266. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206267. break;
  206268. }
  206269. case Path::Iterator::quadraticTo:
  206270. {
  206271. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206272. transform.transformPoint (it.x1, it.y1);
  206273. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206274. transform.transformPoint (it.x2, it.y2);
  206275. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206276. sink->AddQuadraticBezier (seg);
  206277. break;
  206278. }
  206279. case Path::Iterator::closePath:
  206280. {
  206281. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206282. break;
  206283. }
  206284. case Path::Iterator::startNewSubPath:
  206285. {
  206286. transform.transformPoint (it.x1, it.y1);
  206287. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206288. break;
  206289. }
  206290. }
  206291. }
  206292. }
  206293. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206294. {
  206295. ID2D1PathGeometry* p = 0;
  206296. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206297. ComSmartPtr <ID2D1GeometrySink> sink;
  206298. HRESULT hr = p->Open (&sink);
  206299. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206300. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206301. hr = sink->Close();
  206302. return p;
  206303. }
  206304. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206305. {
  206306. D2D1::Matrix3x2F matrix;
  206307. matrix._11 = transform.mat00;
  206308. matrix._12 = transform.mat10;
  206309. matrix._21 = transform.mat01;
  206310. matrix._22 = transform.mat11;
  206311. matrix._31 = transform.mat02;
  206312. matrix._32 = transform.mat12;
  206313. return matrix;
  206314. }
  206315. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206316. };
  206317. #endif
  206318. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206319. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206320. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206321. // compiled on its own).
  206322. #if JUCE_INCLUDED_FILE
  206323. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206324. // these are in the windows SDK, but need to be repeated here for GCC..
  206325. #ifndef GET_APPCOMMAND_LPARAM
  206326. #define FAPPCOMMAND_MASK 0xF000
  206327. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206328. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206329. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206330. #define APPCOMMAND_MEDIA_STOP 13
  206331. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206332. #define WM_APPCOMMAND 0x0319
  206333. #endif
  206334. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206335. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206336. extern bool juce_IsRunningInWine();
  206337. #ifndef ULW_ALPHA
  206338. #define ULW_ALPHA 0x00000002
  206339. #endif
  206340. #ifndef AC_SRC_ALPHA
  206341. #define AC_SRC_ALPHA 0x01
  206342. #endif
  206343. static bool shouldDeactivateTitleBar = true;
  206344. #define WM_TRAYNOTIFY WM_USER + 100
  206345. using ::abs;
  206346. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206347. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206348. bool Desktop::canUseSemiTransparentWindows() throw()
  206349. {
  206350. if (updateLayeredWindow == 0)
  206351. {
  206352. if (! juce_IsRunningInWine())
  206353. {
  206354. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206355. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206356. }
  206357. }
  206358. return updateLayeredWindow != 0;
  206359. }
  206360. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206361. {
  206362. return upright;
  206363. }
  206364. const int extendedKeyModifier = 0x10000;
  206365. const int KeyPress::spaceKey = VK_SPACE;
  206366. const int KeyPress::returnKey = VK_RETURN;
  206367. const int KeyPress::escapeKey = VK_ESCAPE;
  206368. const int KeyPress::backspaceKey = VK_BACK;
  206369. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206370. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206371. const int KeyPress::tabKey = VK_TAB;
  206372. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206373. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206374. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206375. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206376. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206377. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206378. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206379. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206380. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206381. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206382. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206383. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206384. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206385. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206386. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206387. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206388. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206389. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206390. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206391. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206392. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206393. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206394. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206395. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206396. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206397. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206398. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206399. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206400. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206401. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206402. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206403. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206404. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206405. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206406. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206407. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206408. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206409. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206410. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206411. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206412. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206413. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206414. const int KeyPress::playKey = 0x30000;
  206415. const int KeyPress::stopKey = 0x30001;
  206416. const int KeyPress::fastForwardKey = 0x30002;
  206417. const int KeyPress::rewindKey = 0x30003;
  206418. class WindowsBitmapImage : public Image::SharedImage
  206419. {
  206420. public:
  206421. HBITMAP hBitmap;
  206422. HGDIOBJ previousBitmap;
  206423. BITMAPV4HEADER bitmapInfo;
  206424. HDC hdc;
  206425. unsigned char* bitmapData;
  206426. WindowsBitmapImage (const Image::PixelFormat format_,
  206427. const int w, const int h, const bool clearImage)
  206428. : Image::SharedImage (format_, w, h)
  206429. {
  206430. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206431. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206432. zerostruct (bitmapInfo);
  206433. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206434. bitmapInfo.bV4Width = w;
  206435. bitmapInfo.bV4Height = h;
  206436. bitmapInfo.bV4Planes = 1;
  206437. bitmapInfo.bV4CSType = 1;
  206438. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206439. if (format_ == Image::ARGB)
  206440. {
  206441. bitmapInfo.bV4AlphaMask = 0xff000000;
  206442. bitmapInfo.bV4RedMask = 0xff0000;
  206443. bitmapInfo.bV4GreenMask = 0xff00;
  206444. bitmapInfo.bV4BlueMask = 0xff;
  206445. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206446. }
  206447. else
  206448. {
  206449. bitmapInfo.bV4V4Compression = BI_RGB;
  206450. }
  206451. lineStride = -((w * pixelStride + 3) & ~3);
  206452. HDC dc = GetDC (0);
  206453. hdc = CreateCompatibleDC (dc);
  206454. ReleaseDC (0, dc);
  206455. SetMapMode (hdc, MM_TEXT);
  206456. hBitmap = CreateDIBSection (hdc,
  206457. (BITMAPINFO*) &(bitmapInfo),
  206458. DIB_RGB_COLORS,
  206459. (void**) &bitmapData,
  206460. 0, 0);
  206461. previousBitmap = SelectObject (hdc, hBitmap);
  206462. if (format_ == Image::ARGB && clearImage)
  206463. zeromem (bitmapData, abs (h * lineStride));
  206464. imageData = bitmapData - (lineStride * (h - 1));
  206465. }
  206466. ~WindowsBitmapImage()
  206467. {
  206468. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  206469. DeleteDC (hdc);
  206470. DeleteObject (hBitmap);
  206471. }
  206472. Image::ImageType getType() const { return Image::NativeImage; }
  206473. LowLevelGraphicsContext* createLowLevelContext()
  206474. {
  206475. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206476. }
  206477. Image::SharedImage* clone()
  206478. {
  206479. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206480. for (int i = 0; i < height; ++i)
  206481. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206482. return im;
  206483. }
  206484. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206485. const int x, const int y,
  206486. const RectangleList& maskedRegion,
  206487. const uint8 updateLayeredWindowAlpha) throw()
  206488. {
  206489. static HDRAWDIB hdd = 0;
  206490. static bool needToCreateDrawDib = true;
  206491. if (needToCreateDrawDib)
  206492. {
  206493. needToCreateDrawDib = false;
  206494. HDC dc = GetDC (0);
  206495. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206496. ReleaseDC (0, dc);
  206497. // only open if we're not palettised
  206498. if (n > 8)
  206499. hdd = DrawDibOpen();
  206500. }
  206501. SetMapMode (dc, MM_TEXT);
  206502. if (transparent)
  206503. {
  206504. POINT p, pos;
  206505. SIZE size;
  206506. RECT windowBounds;
  206507. GetWindowRect (hwnd, &windowBounds);
  206508. p.x = -x;
  206509. p.y = -y;
  206510. pos.x = windowBounds.left;
  206511. pos.y = windowBounds.top;
  206512. size.cx = windowBounds.right - windowBounds.left;
  206513. size.cy = windowBounds.bottom - windowBounds.top;
  206514. BLENDFUNCTION bf;
  206515. bf.AlphaFormat = AC_SRC_ALPHA;
  206516. bf.BlendFlags = 0;
  206517. bf.BlendOp = AC_SRC_OVER;
  206518. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206519. if (! maskedRegion.isEmpty())
  206520. {
  206521. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206522. {
  206523. const Rectangle<int>& r = *i.getRectangle();
  206524. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206525. }
  206526. }
  206527. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206528. }
  206529. else
  206530. {
  206531. int savedDC = 0;
  206532. if (! maskedRegion.isEmpty())
  206533. {
  206534. savedDC = SaveDC (dc);
  206535. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206536. {
  206537. const Rectangle<int>& r = *i.getRectangle();
  206538. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206539. }
  206540. }
  206541. if (hdd == 0)
  206542. {
  206543. StretchDIBits (dc,
  206544. x, y, width, height,
  206545. 0, 0, width, height,
  206546. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206547. DIB_RGB_COLORS, SRCCOPY);
  206548. }
  206549. else
  206550. {
  206551. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206552. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206553. 0, 0, width, height, 0);
  206554. }
  206555. if (! maskedRegion.isEmpty())
  206556. RestoreDC (dc, savedDC);
  206557. }
  206558. }
  206559. private:
  206560. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206561. };
  206562. namespace IconConverters
  206563. {
  206564. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206565. {
  206566. Image im;
  206567. if (bitmap != 0)
  206568. {
  206569. BITMAP bm;
  206570. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206571. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206572. {
  206573. HDC tempDC = GetDC (0);
  206574. HDC dc = CreateCompatibleDC (tempDC);
  206575. ReleaseDC (0, tempDC);
  206576. SelectObject (dc, bitmap);
  206577. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206578. Image::BitmapData imageData (im, true);
  206579. for (int y = bm.bmHeight; --y >= 0;)
  206580. {
  206581. for (int x = bm.bmWidth; --x >= 0;)
  206582. {
  206583. COLORREF col = GetPixel (dc, x, y);
  206584. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206585. (uint8) GetGValue (col),
  206586. (uint8) GetBValue (col)));
  206587. }
  206588. }
  206589. DeleteDC (dc);
  206590. }
  206591. }
  206592. return im;
  206593. }
  206594. const Image createImageFromHICON (HICON icon)
  206595. {
  206596. ICONINFO info;
  206597. if (GetIconInfo (icon, &info))
  206598. {
  206599. Image mask (createImageFromHBITMAP (info.hbmMask));
  206600. Image image (createImageFromHBITMAP (info.hbmColor));
  206601. if (mask.isValid() && image.isValid())
  206602. {
  206603. for (int y = image.getHeight(); --y >= 0;)
  206604. {
  206605. for (int x = image.getWidth(); --x >= 0;)
  206606. {
  206607. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206608. if (brightness > 0.0f)
  206609. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206610. }
  206611. }
  206612. return image;
  206613. }
  206614. }
  206615. return Image::null;
  206616. }
  206617. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206618. {
  206619. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206620. Image bitmap (nativeBitmap);
  206621. {
  206622. Graphics g (bitmap);
  206623. g.drawImageAt (image, 0, 0);
  206624. }
  206625. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206626. ICONINFO info;
  206627. info.fIcon = isIcon;
  206628. info.xHotspot = hotspotX;
  206629. info.yHotspot = hotspotY;
  206630. info.hbmMask = mask;
  206631. info.hbmColor = nativeBitmap->hBitmap;
  206632. HICON hi = CreateIconIndirect (&info);
  206633. DeleteObject (mask);
  206634. return hi;
  206635. }
  206636. }
  206637. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206638. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206639. {
  206640. SHORT k = (SHORT) keyCode;
  206641. if ((keyCode & extendedKeyModifier) == 0
  206642. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206643. k += (SHORT) 'A' - (SHORT) 'a';
  206644. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206645. (SHORT) '+', VK_OEM_PLUS,
  206646. (SHORT) '-', VK_OEM_MINUS,
  206647. (SHORT) '.', VK_OEM_PERIOD,
  206648. (SHORT) ';', VK_OEM_1,
  206649. (SHORT) ':', VK_OEM_1,
  206650. (SHORT) '/', VK_OEM_2,
  206651. (SHORT) '?', VK_OEM_2,
  206652. (SHORT) '[', VK_OEM_4,
  206653. (SHORT) ']', VK_OEM_6 };
  206654. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206655. if (k == translatedValues [i])
  206656. k = translatedValues [i + 1];
  206657. return (GetKeyState (k) & 0x8000) != 0;
  206658. }
  206659. class Win32ComponentPeer : public ComponentPeer
  206660. {
  206661. public:
  206662. enum RenderingEngineType
  206663. {
  206664. softwareRenderingEngine = 0,
  206665. direct2DRenderingEngine
  206666. };
  206667. Win32ComponentPeer (Component* const component,
  206668. const int windowStyleFlags,
  206669. HWND parentToAddTo_)
  206670. : ComponentPeer (component, windowStyleFlags),
  206671. dontRepaint (false),
  206672. #if JUCE_DIRECT2D
  206673. currentRenderingEngine (direct2DRenderingEngine),
  206674. #else
  206675. currentRenderingEngine (softwareRenderingEngine),
  206676. #endif
  206677. fullScreen (false),
  206678. isDragging (false),
  206679. isMouseOver (false),
  206680. hasCreatedCaret (false),
  206681. constrainerIsResizing (false),
  206682. currentWindowIcon (0),
  206683. dropTarget (0),
  206684. updateLayeredWindowAlpha (255),
  206685. parentToAddTo (parentToAddTo_)
  206686. {
  206687. callFunctionIfNotLocked (&createWindowCallback, this);
  206688. setTitle (component->getName());
  206689. if ((windowStyleFlags & windowHasDropShadow) != 0
  206690. && Desktop::canUseSemiTransparentWindows())
  206691. {
  206692. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206693. if (shadower != 0)
  206694. shadower->setOwner (component);
  206695. }
  206696. }
  206697. ~Win32ComponentPeer()
  206698. {
  206699. setTaskBarIcon (Image());
  206700. shadower = 0;
  206701. // do this before the next bit to avoid messages arriving for this window
  206702. // before it's destroyed
  206703. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206704. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206705. if (currentWindowIcon != 0)
  206706. DestroyIcon (currentWindowIcon);
  206707. if (dropTarget != 0)
  206708. {
  206709. dropTarget->Release();
  206710. dropTarget = 0;
  206711. }
  206712. #if JUCE_DIRECT2D
  206713. direct2DContext = 0;
  206714. #endif
  206715. }
  206716. void* getNativeHandle() const
  206717. {
  206718. return hwnd;
  206719. }
  206720. void setVisible (bool shouldBeVisible)
  206721. {
  206722. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206723. if (shouldBeVisible)
  206724. InvalidateRect (hwnd, 0, 0);
  206725. else
  206726. lastPaintTime = 0;
  206727. }
  206728. void setTitle (const String& title)
  206729. {
  206730. SetWindowText (hwnd, title);
  206731. }
  206732. void setPosition (int x, int y)
  206733. {
  206734. offsetWithinParent (x, y);
  206735. SetWindowPos (hwnd, 0,
  206736. x - windowBorder.getLeft(),
  206737. y - windowBorder.getTop(),
  206738. 0, 0,
  206739. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206740. }
  206741. void repaintNowIfTransparent()
  206742. {
  206743. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206744. handlePaintMessage();
  206745. }
  206746. void updateBorderSize()
  206747. {
  206748. WINDOWINFO info;
  206749. info.cbSize = sizeof (info);
  206750. if (GetWindowInfo (hwnd, &info))
  206751. {
  206752. windowBorder = BorderSize<int> (info.rcClient.top - info.rcWindow.top,
  206753. info.rcClient.left - info.rcWindow.left,
  206754. info.rcWindow.bottom - info.rcClient.bottom,
  206755. info.rcWindow.right - info.rcClient.right);
  206756. }
  206757. #if JUCE_DIRECT2D
  206758. if (direct2DContext != 0)
  206759. direct2DContext->resized();
  206760. #endif
  206761. }
  206762. void setSize (int w, int h)
  206763. {
  206764. SetWindowPos (hwnd, 0, 0, 0,
  206765. w + windowBorder.getLeftAndRight(),
  206766. h + windowBorder.getTopAndBottom(),
  206767. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206768. updateBorderSize();
  206769. repaintNowIfTransparent();
  206770. }
  206771. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206772. {
  206773. fullScreen = isNowFullScreen;
  206774. offsetWithinParent (x, y);
  206775. SetWindowPos (hwnd, 0,
  206776. x - windowBorder.getLeft(),
  206777. y - windowBorder.getTop(),
  206778. w + windowBorder.getLeftAndRight(),
  206779. h + windowBorder.getTopAndBottom(),
  206780. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206781. updateBorderSize();
  206782. repaintNowIfTransparent();
  206783. }
  206784. const Rectangle<int> getBounds() const
  206785. {
  206786. RECT r;
  206787. GetWindowRect (hwnd, &r);
  206788. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206789. HWND parentH = GetParent (hwnd);
  206790. if (parentH != 0)
  206791. {
  206792. GetWindowRect (parentH, &r);
  206793. bounds.translate (-r.left, -r.top);
  206794. }
  206795. return windowBorder.subtractedFrom (bounds);
  206796. }
  206797. const Point<int> getScreenPosition() const
  206798. {
  206799. RECT r;
  206800. GetWindowRect (hwnd, &r);
  206801. return Point<int> (r.left + windowBorder.getLeft(),
  206802. r.top + windowBorder.getTop());
  206803. }
  206804. const Point<int> localToGlobal (const Point<int>& relativePosition)
  206805. {
  206806. return relativePosition + getScreenPosition();
  206807. }
  206808. const Point<int> globalToLocal (const Point<int>& screenPosition)
  206809. {
  206810. return screenPosition - getScreenPosition();
  206811. }
  206812. void setAlpha (float newAlpha)
  206813. {
  206814. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  206815. if (component->isOpaque())
  206816. {
  206817. if (newAlpha < 1.0f)
  206818. {
  206819. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  206820. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  206821. }
  206822. else
  206823. {
  206824. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  206825. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  206826. }
  206827. }
  206828. else
  206829. {
  206830. updateLayeredWindowAlpha = intAlpha;
  206831. component->repaint();
  206832. }
  206833. }
  206834. void setMinimised (bool shouldBeMinimised)
  206835. {
  206836. if (shouldBeMinimised != isMinimised())
  206837. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206838. }
  206839. bool isMinimised() const
  206840. {
  206841. WINDOWPLACEMENT wp;
  206842. wp.length = sizeof (WINDOWPLACEMENT);
  206843. GetWindowPlacement (hwnd, &wp);
  206844. return wp.showCmd == SW_SHOWMINIMIZED;
  206845. }
  206846. void setFullScreen (bool shouldBeFullScreen)
  206847. {
  206848. setMinimised (false);
  206849. if (fullScreen != shouldBeFullScreen)
  206850. {
  206851. fullScreen = shouldBeFullScreen;
  206852. const WeakReference<Component> deletionChecker (component);
  206853. if (! fullScreen)
  206854. {
  206855. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206856. if (hasTitleBar())
  206857. ShowWindow (hwnd, SW_SHOWNORMAL);
  206858. if (! boundsCopy.isEmpty())
  206859. {
  206860. setBounds (boundsCopy.getX(),
  206861. boundsCopy.getY(),
  206862. boundsCopy.getWidth(),
  206863. boundsCopy.getHeight(),
  206864. false);
  206865. }
  206866. }
  206867. else
  206868. {
  206869. if (hasTitleBar())
  206870. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206871. else
  206872. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206873. }
  206874. if (deletionChecker != 0)
  206875. handleMovedOrResized();
  206876. }
  206877. }
  206878. bool isFullScreen() const
  206879. {
  206880. if (! hasTitleBar())
  206881. return fullScreen;
  206882. WINDOWPLACEMENT wp;
  206883. wp.length = sizeof (wp);
  206884. GetWindowPlacement (hwnd, &wp);
  206885. return wp.showCmd == SW_SHOWMAXIMIZED;
  206886. }
  206887. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206888. {
  206889. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  206890. && isPositiveAndBelow (position.getY(), component->getHeight())))
  206891. return false;
  206892. RECT r;
  206893. GetWindowRect (hwnd, &r);
  206894. POINT p;
  206895. p.x = position.getX() + r.left + windowBorder.getLeft();
  206896. p.y = position.getY() + r.top + windowBorder.getTop();
  206897. HWND w = WindowFromPoint (p);
  206898. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206899. }
  206900. const BorderSize<int> getFrameSize() const
  206901. {
  206902. return windowBorder;
  206903. }
  206904. bool setAlwaysOnTop (bool alwaysOnTop)
  206905. {
  206906. const bool oldDeactivate = shouldDeactivateTitleBar;
  206907. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206908. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206909. 0, 0, 0, 0,
  206910. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206911. shouldDeactivateTitleBar = oldDeactivate;
  206912. if (shadower != 0)
  206913. shadower->componentBroughtToFront (*component);
  206914. return true;
  206915. }
  206916. void toFront (bool makeActive)
  206917. {
  206918. setMinimised (false);
  206919. const bool oldDeactivate = shouldDeactivateTitleBar;
  206920. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206921. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  206922. shouldDeactivateTitleBar = oldDeactivate;
  206923. if (! makeActive)
  206924. {
  206925. // in this case a broughttofront call won't have occured, so do it now..
  206926. handleBroughtToFront();
  206927. }
  206928. }
  206929. void toBehind (ComponentPeer* other)
  206930. {
  206931. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206932. jassert (otherPeer != 0); // wrong type of window?
  206933. if (otherPeer != 0)
  206934. {
  206935. setMinimised (false);
  206936. // must be careful not to try to put a topmost window behind a normal one, or win32
  206937. // promotes the normal one to be topmost!
  206938. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  206939. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206940. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206941. else if (otherPeer->getComponent()->isAlwaysOnTop())
  206942. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  206943. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206944. }
  206945. }
  206946. bool isFocused() const
  206947. {
  206948. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  206949. }
  206950. void grabFocus()
  206951. {
  206952. const bool oldDeactivate = shouldDeactivateTitleBar;
  206953. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206954. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  206955. shouldDeactivateTitleBar = oldDeactivate;
  206956. }
  206957. void textInputRequired (const Point<int>&)
  206958. {
  206959. if (! hasCreatedCaret)
  206960. {
  206961. hasCreatedCaret = true;
  206962. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  206963. }
  206964. ShowCaret (hwnd);
  206965. SetCaretPos (0, 0);
  206966. }
  206967. void repaint (const Rectangle<int>& area)
  206968. {
  206969. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  206970. InvalidateRect (hwnd, &r, FALSE);
  206971. }
  206972. void performAnyPendingRepaintsNow()
  206973. {
  206974. MSG m;
  206975. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206976. DispatchMessage (&m);
  206977. }
  206978. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206979. {
  206980. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206981. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  206982. return 0;
  206983. }
  206984. void setTaskBarIcon (const Image& image)
  206985. {
  206986. if (image.isValid())
  206987. {
  206988. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  206989. if (taskBarIcon == 0)
  206990. {
  206991. taskBarIcon = new NOTIFYICONDATA();
  206992. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  206993. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206994. taskBarIcon->hWnd = (HWND) hwnd;
  206995. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206996. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206997. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206998. taskBarIcon->hIcon = hicon;
  206999. taskBarIcon->szTip[0] = 0;
  207000. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207001. }
  207002. else
  207003. {
  207004. HICON oldIcon = taskBarIcon->hIcon;
  207005. taskBarIcon->hIcon = hicon;
  207006. taskBarIcon->uFlags = NIF_ICON;
  207007. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207008. DestroyIcon (oldIcon);
  207009. }
  207010. }
  207011. else if (taskBarIcon != 0)
  207012. {
  207013. taskBarIcon->uFlags = 0;
  207014. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207015. DestroyIcon (taskBarIcon->hIcon);
  207016. taskBarIcon = 0;
  207017. }
  207018. }
  207019. void setTaskBarIconToolTip (const String& toolTip) const
  207020. {
  207021. if (taskBarIcon != 0)
  207022. {
  207023. taskBarIcon->uFlags = NIF_TIP;
  207024. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207025. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207026. }
  207027. }
  207028. void handleTaskBarEvent (const LPARAM lParam)
  207029. {
  207030. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207031. {
  207032. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207033. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207034. {
  207035. Component* const current = Component::getCurrentlyModalComponent();
  207036. if (current != 0)
  207037. current->inputAttemptWhenModal();
  207038. }
  207039. }
  207040. else
  207041. {
  207042. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207043. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207044. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207045. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207046. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207047. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207048. eventMods = eventMods.withoutMouseButtons();
  207049. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207050. Point<int>(), eventMods, component, component, Time (getMouseEventTime()),
  207051. Point<int>(), Time (getMouseEventTime()), 1, false);
  207052. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207053. {
  207054. SetFocus (hwnd);
  207055. SetForegroundWindow (hwnd);
  207056. component->mouseDown (e);
  207057. }
  207058. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207059. {
  207060. component->mouseUp (e);
  207061. }
  207062. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207063. {
  207064. component->mouseDoubleClick (e);
  207065. }
  207066. else if (lParam == WM_MOUSEMOVE)
  207067. {
  207068. component->mouseMove (e);
  207069. }
  207070. }
  207071. }
  207072. bool isInside (HWND h) const
  207073. {
  207074. return GetAncestor (hwnd, GA_ROOT) == h;
  207075. }
  207076. static void updateKeyModifiers() throw()
  207077. {
  207078. int keyMods = 0;
  207079. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207080. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207081. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207082. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207083. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207084. }
  207085. static void updateModifiersFromWParam (const WPARAM wParam)
  207086. {
  207087. int mouseMods = 0;
  207088. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207089. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207090. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207091. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207092. updateKeyModifiers();
  207093. }
  207094. static int64 getMouseEventTime()
  207095. {
  207096. static int64 eventTimeOffset = 0;
  207097. static DWORD lastMessageTime = 0;
  207098. const DWORD thisMessageTime = GetMessageTime();
  207099. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207100. {
  207101. lastMessageTime = thisMessageTime;
  207102. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207103. }
  207104. return eventTimeOffset + thisMessageTime;
  207105. }
  207106. bool dontRepaint;
  207107. static ModifierKeys currentModifiers;
  207108. static ModifierKeys modifiersAtLastCallback;
  207109. private:
  207110. HWND hwnd, parentToAddTo;
  207111. ScopedPointer<DropShadower> shadower;
  207112. RenderingEngineType currentRenderingEngine;
  207113. #if JUCE_DIRECT2D
  207114. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207115. #endif
  207116. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  207117. BorderSize<int> windowBorder;
  207118. HICON currentWindowIcon;
  207119. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207120. IDropTarget* dropTarget;
  207121. uint8 updateLayeredWindowAlpha;
  207122. class TemporaryImage : public Timer
  207123. {
  207124. public:
  207125. TemporaryImage() {}
  207126. ~TemporaryImage() {}
  207127. const Image& getImage (const bool transparent, const int w, const int h)
  207128. {
  207129. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207130. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207131. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207132. startTimer (3000);
  207133. return image;
  207134. }
  207135. void timerCallback()
  207136. {
  207137. stopTimer();
  207138. image = Image::null;
  207139. }
  207140. private:
  207141. Image image;
  207142. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207143. };
  207144. TemporaryImage offscreenImageGenerator;
  207145. class WindowClassHolder : public DeletedAtShutdown
  207146. {
  207147. public:
  207148. WindowClassHolder()
  207149. : windowClassName ("JUCE_")
  207150. {
  207151. // this name has to be different for each app/dll instance because otherwise
  207152. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207153. // window class).
  207154. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207155. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207156. TCHAR moduleFile [1024];
  207157. moduleFile[0] = 0;
  207158. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207159. WORD iconNum = 0;
  207160. WNDCLASSEX wcex;
  207161. wcex.cbSize = sizeof (wcex);
  207162. wcex.style = CS_OWNDC;
  207163. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207164. wcex.lpszClassName = windowClassName;
  207165. wcex.cbClsExtra = 0;
  207166. wcex.cbWndExtra = 32;
  207167. wcex.hInstance = moduleHandle;
  207168. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207169. iconNum = 1;
  207170. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207171. wcex.hCursor = 0;
  207172. wcex.hbrBackground = 0;
  207173. wcex.lpszMenuName = 0;
  207174. RegisterClassEx (&wcex);
  207175. }
  207176. ~WindowClassHolder()
  207177. {
  207178. if (ComponentPeer::getNumPeers() == 0)
  207179. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207180. clearSingletonInstance();
  207181. }
  207182. String windowClassName;
  207183. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207184. };
  207185. static void* createWindowCallback (void* userData)
  207186. {
  207187. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207188. return 0;
  207189. }
  207190. void createWindow()
  207191. {
  207192. DWORD exstyle = WS_EX_ACCEPTFILES;
  207193. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207194. if (hasTitleBar())
  207195. {
  207196. type |= WS_OVERLAPPED;
  207197. if ((styleFlags & windowHasCloseButton) != 0)
  207198. {
  207199. type |= WS_SYSMENU;
  207200. }
  207201. else
  207202. {
  207203. // annoyingly, windows won't let you have a min/max button without a close button
  207204. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207205. }
  207206. if ((styleFlags & windowIsResizable) != 0)
  207207. type |= WS_THICKFRAME;
  207208. }
  207209. else if (parentToAddTo != 0)
  207210. {
  207211. type |= WS_CHILD;
  207212. }
  207213. else
  207214. {
  207215. type |= WS_POPUP | WS_SYSMENU;
  207216. }
  207217. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207218. exstyle |= WS_EX_TOOLWINDOW;
  207219. else
  207220. exstyle |= WS_EX_APPWINDOW;
  207221. if ((styleFlags & windowHasMinimiseButton) != 0)
  207222. type |= WS_MINIMIZEBOX;
  207223. if ((styleFlags & windowHasMaximiseButton) != 0)
  207224. type |= WS_MAXIMIZEBOX;
  207225. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207226. exstyle |= WS_EX_TRANSPARENT;
  207227. if ((styleFlags & windowIsSemiTransparent) != 0
  207228. && Desktop::canUseSemiTransparentWindows())
  207229. exstyle |= WS_EX_LAYERED;
  207230. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207231. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207232. #if JUCE_DIRECT2D
  207233. updateDirect2DContext();
  207234. #endif
  207235. if (hwnd != 0)
  207236. {
  207237. SetWindowLongPtr (hwnd, 0, 0);
  207238. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207239. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207240. if (dropTarget == 0)
  207241. dropTarget = new JuceDropTarget (this);
  207242. RegisterDragDrop (hwnd, dropTarget);
  207243. updateBorderSize();
  207244. // Calling this function here is (for some reason) necessary to make Windows
  207245. // correctly enable the menu items that we specify in the wm_initmenu message.
  207246. GetSystemMenu (hwnd, false);
  207247. const float alpha = component->getAlpha();
  207248. if (alpha < 1.0f)
  207249. setAlpha (alpha);
  207250. }
  207251. else
  207252. {
  207253. jassertfalse;
  207254. }
  207255. }
  207256. static void* destroyWindowCallback (void* handle)
  207257. {
  207258. RevokeDragDrop ((HWND) handle);
  207259. DestroyWindow ((HWND) handle);
  207260. return 0;
  207261. }
  207262. static void* toFrontCallback1 (void* h)
  207263. {
  207264. SetForegroundWindow ((HWND) h);
  207265. return 0;
  207266. }
  207267. static void* toFrontCallback2 (void* h)
  207268. {
  207269. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207270. return 0;
  207271. }
  207272. static void* setFocusCallback (void* h)
  207273. {
  207274. SetFocus ((HWND) h);
  207275. return 0;
  207276. }
  207277. static void* getFocusCallback (void*)
  207278. {
  207279. return GetFocus();
  207280. }
  207281. void offsetWithinParent (int& x, int& y) const
  207282. {
  207283. if (isUsingUpdateLayeredWindow())
  207284. {
  207285. HWND parentHwnd = GetParent (hwnd);
  207286. if (parentHwnd != 0)
  207287. {
  207288. RECT parentRect;
  207289. GetWindowRect (parentHwnd, &parentRect);
  207290. x += parentRect.left;
  207291. y += parentRect.top;
  207292. }
  207293. }
  207294. }
  207295. bool isUsingUpdateLayeredWindow() const
  207296. {
  207297. return ! component->isOpaque();
  207298. }
  207299. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207300. void setIcon (const Image& newIcon)
  207301. {
  207302. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207303. if (hicon != 0)
  207304. {
  207305. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207306. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207307. if (currentWindowIcon != 0)
  207308. DestroyIcon (currentWindowIcon);
  207309. currentWindowIcon = hicon;
  207310. }
  207311. }
  207312. void handlePaintMessage()
  207313. {
  207314. #if JUCE_DIRECT2D
  207315. if (direct2DContext != 0)
  207316. {
  207317. RECT r;
  207318. if (GetUpdateRect (hwnd, &r, false))
  207319. {
  207320. direct2DContext->start();
  207321. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207322. handlePaint (*direct2DContext);
  207323. direct2DContext->end();
  207324. }
  207325. }
  207326. else
  207327. #endif
  207328. {
  207329. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207330. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207331. PAINTSTRUCT paintStruct;
  207332. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207333. // message and become re-entrant, but that's OK
  207334. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207335. // corrupt the image it's using to paint into, so do a check here.
  207336. static bool reentrant = false;
  207337. if (reentrant)
  207338. {
  207339. DeleteObject (rgn);
  207340. EndPaint (hwnd, &paintStruct);
  207341. return;
  207342. }
  207343. const ScopedValueSetter<bool> setter (reentrant, true, false);
  207344. // this is the rectangle to update..
  207345. int x = paintStruct.rcPaint.left;
  207346. int y = paintStruct.rcPaint.top;
  207347. int w = paintStruct.rcPaint.right - x;
  207348. int h = paintStruct.rcPaint.bottom - y;
  207349. const bool transparent = isUsingUpdateLayeredWindow();
  207350. if (transparent)
  207351. {
  207352. // it's not possible to have a transparent window with a title bar at the moment!
  207353. jassert (! hasTitleBar());
  207354. RECT r;
  207355. GetWindowRect (hwnd, &r);
  207356. x = y = 0;
  207357. w = r.right - r.left;
  207358. h = r.bottom - r.top;
  207359. }
  207360. if (w > 0 && h > 0)
  207361. {
  207362. clearMaskedRegion();
  207363. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207364. RectangleList contextClip;
  207365. const Rectangle<int> clipBounds (0, 0, w, h);
  207366. bool needToPaintAll = true;
  207367. if (regionType == COMPLEXREGION && ! transparent)
  207368. {
  207369. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207370. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207371. DeleteObject (clipRgn);
  207372. char rgnData [8192];
  207373. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207374. if (res > 0 && res <= sizeof (rgnData))
  207375. {
  207376. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207377. if (hdr->iType == RDH_RECTANGLES
  207378. && hdr->rcBound.right - hdr->rcBound.left >= w
  207379. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207380. {
  207381. needToPaintAll = false;
  207382. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207383. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207384. while (--num >= 0)
  207385. {
  207386. if (rects->right <= x + w && rects->bottom <= y + h)
  207387. {
  207388. const int cx = jmax (x, (int) rects->left);
  207389. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207390. .getIntersection (clipBounds));
  207391. }
  207392. else
  207393. {
  207394. needToPaintAll = true;
  207395. break;
  207396. }
  207397. ++rects;
  207398. }
  207399. }
  207400. }
  207401. }
  207402. if (needToPaintAll)
  207403. {
  207404. contextClip.clear();
  207405. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207406. }
  207407. if (transparent)
  207408. {
  207409. RectangleList::Iterator i (contextClip);
  207410. while (i.next())
  207411. offscreenImage.clear (*i.getRectangle());
  207412. }
  207413. // if the component's not opaque, this won't draw properly unless the platform can support this
  207414. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207415. updateCurrentModifiers();
  207416. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207417. handlePaint (context);
  207418. if (! dontRepaint)
  207419. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207420. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207421. }
  207422. DeleteObject (rgn);
  207423. EndPaint (hwnd, &paintStruct);
  207424. }
  207425. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207426. _fpreset(); // because some graphics cards can unmask FP exceptions
  207427. #endif
  207428. lastPaintTime = Time::getMillisecondCounter();
  207429. }
  207430. void doMouseEvent (const Point<int>& position)
  207431. {
  207432. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207433. }
  207434. const StringArray getAvailableRenderingEngines()
  207435. {
  207436. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207437. #if JUCE_DIRECT2D
  207438. // xxx is this correct? Seems to enable it on Vista too??
  207439. OSVERSIONINFO info;
  207440. zerostruct (info);
  207441. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207442. GetVersionEx (&info);
  207443. if (info.dwMajorVersion >= 6)
  207444. s.add ("Direct2D");
  207445. #endif
  207446. return s;
  207447. }
  207448. int getCurrentRenderingEngine() throw()
  207449. {
  207450. return currentRenderingEngine;
  207451. }
  207452. #if JUCE_DIRECT2D
  207453. void updateDirect2DContext()
  207454. {
  207455. if (currentRenderingEngine != direct2DRenderingEngine)
  207456. direct2DContext = 0;
  207457. else if (direct2DContext == 0)
  207458. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207459. }
  207460. #endif
  207461. void setCurrentRenderingEngine (int index)
  207462. {
  207463. (void) index;
  207464. #if JUCE_DIRECT2D
  207465. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207466. updateDirect2DContext();
  207467. repaint (component->getLocalBounds());
  207468. #endif
  207469. }
  207470. void doMouseMove (const Point<int>& position)
  207471. {
  207472. if (! isMouseOver)
  207473. {
  207474. isMouseOver = true;
  207475. updateKeyModifiers();
  207476. TRACKMOUSEEVENT tme;
  207477. tme.cbSize = sizeof (tme);
  207478. tme.dwFlags = TME_LEAVE;
  207479. tme.hwndTrack = hwnd;
  207480. tme.dwHoverTime = 0;
  207481. if (! TrackMouseEvent (&tme))
  207482. jassertfalse;
  207483. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207484. }
  207485. else if (! isDragging)
  207486. {
  207487. if (! contains (position, false))
  207488. return;
  207489. }
  207490. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207491. static uint32 lastMouseTime = 0;
  207492. const uint32 now = Time::getMillisecondCounter();
  207493. const int maxMouseMovesPerSecond = 60;
  207494. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207495. {
  207496. lastMouseTime = now;
  207497. doMouseEvent (position);
  207498. }
  207499. }
  207500. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207501. {
  207502. if (GetCapture() != hwnd)
  207503. SetCapture (hwnd);
  207504. doMouseMove (position);
  207505. updateModifiersFromWParam (wParam);
  207506. isDragging = true;
  207507. doMouseEvent (position);
  207508. }
  207509. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207510. {
  207511. updateModifiersFromWParam (wParam);
  207512. isDragging = false;
  207513. // release the mouse capture if the user has released all buttons
  207514. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207515. ReleaseCapture();
  207516. doMouseEvent (position);
  207517. }
  207518. void doCaptureChanged()
  207519. {
  207520. if (constrainerIsResizing)
  207521. {
  207522. if (constrainer != 0)
  207523. constrainer->resizeEnd();
  207524. constrainerIsResizing = false;
  207525. }
  207526. if (isDragging)
  207527. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207528. }
  207529. void doMouseExit()
  207530. {
  207531. isMouseOver = false;
  207532. doMouseEvent (getCurrentMousePos());
  207533. }
  207534. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207535. {
  207536. updateKeyModifiers();
  207537. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207538. handleMouseWheel (0, position, getMouseEventTime(),
  207539. isVertical ? 0.0f : amount,
  207540. isVertical ? amount : 0.0f);
  207541. }
  207542. void sendModifierKeyChangeIfNeeded()
  207543. {
  207544. if (modifiersAtLastCallback != currentModifiers)
  207545. {
  207546. modifiersAtLastCallback = currentModifiers;
  207547. handleModifierKeysChange();
  207548. }
  207549. }
  207550. bool doKeyUp (const WPARAM key)
  207551. {
  207552. updateKeyModifiers();
  207553. switch (key)
  207554. {
  207555. case VK_SHIFT:
  207556. case VK_CONTROL:
  207557. case VK_MENU:
  207558. case VK_CAPITAL:
  207559. case VK_LWIN:
  207560. case VK_RWIN:
  207561. case VK_APPS:
  207562. case VK_NUMLOCK:
  207563. case VK_SCROLL:
  207564. case VK_LSHIFT:
  207565. case VK_RSHIFT:
  207566. case VK_LCONTROL:
  207567. case VK_LMENU:
  207568. case VK_RCONTROL:
  207569. case VK_RMENU:
  207570. sendModifierKeyChangeIfNeeded();
  207571. }
  207572. return handleKeyUpOrDown (false)
  207573. || Component::getCurrentlyModalComponent() != 0;
  207574. }
  207575. bool doKeyDown (const WPARAM key)
  207576. {
  207577. updateKeyModifiers();
  207578. bool used = false;
  207579. switch (key)
  207580. {
  207581. case VK_SHIFT:
  207582. case VK_LSHIFT:
  207583. case VK_RSHIFT:
  207584. case VK_CONTROL:
  207585. case VK_LCONTROL:
  207586. case VK_RCONTROL:
  207587. case VK_MENU:
  207588. case VK_LMENU:
  207589. case VK_RMENU:
  207590. case VK_LWIN:
  207591. case VK_RWIN:
  207592. case VK_CAPITAL:
  207593. case VK_NUMLOCK:
  207594. case VK_SCROLL:
  207595. case VK_APPS:
  207596. sendModifierKeyChangeIfNeeded();
  207597. break;
  207598. case VK_LEFT:
  207599. case VK_RIGHT:
  207600. case VK_UP:
  207601. case VK_DOWN:
  207602. case VK_PRIOR:
  207603. case VK_NEXT:
  207604. case VK_HOME:
  207605. case VK_END:
  207606. case VK_DELETE:
  207607. case VK_INSERT:
  207608. case VK_F1:
  207609. case VK_F2:
  207610. case VK_F3:
  207611. case VK_F4:
  207612. case VK_F5:
  207613. case VK_F6:
  207614. case VK_F7:
  207615. case VK_F8:
  207616. case VK_F9:
  207617. case VK_F10:
  207618. case VK_F11:
  207619. case VK_F12:
  207620. case VK_F13:
  207621. case VK_F14:
  207622. case VK_F15:
  207623. case VK_F16:
  207624. used = handleKeyUpOrDown (true);
  207625. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207626. break;
  207627. case VK_ADD:
  207628. case VK_SUBTRACT:
  207629. case VK_MULTIPLY:
  207630. case VK_DIVIDE:
  207631. case VK_SEPARATOR:
  207632. case VK_DECIMAL:
  207633. used = handleKeyUpOrDown (true);
  207634. break;
  207635. default:
  207636. used = handleKeyUpOrDown (true);
  207637. {
  207638. MSG msg;
  207639. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207640. {
  207641. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207642. // manually generate the key-press event that matches this key-down.
  207643. const UINT keyChar = MapVirtualKey (key, 2);
  207644. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207645. }
  207646. }
  207647. break;
  207648. }
  207649. if (Component::getCurrentlyModalComponent() != 0)
  207650. used = true;
  207651. return used;
  207652. }
  207653. bool doKeyChar (int key, const LPARAM flags)
  207654. {
  207655. updateKeyModifiers();
  207656. juce_wchar textChar = (juce_wchar) key;
  207657. const int virtualScanCode = (flags >> 16) & 0xff;
  207658. if (key >= '0' && key <= '9')
  207659. {
  207660. switch (virtualScanCode) // check for a numeric keypad scan-code
  207661. {
  207662. case 0x52:
  207663. case 0x4f:
  207664. case 0x50:
  207665. case 0x51:
  207666. case 0x4b:
  207667. case 0x4c:
  207668. case 0x4d:
  207669. case 0x47:
  207670. case 0x48:
  207671. case 0x49:
  207672. key = (key - '0') + KeyPress::numberPad0;
  207673. break;
  207674. default:
  207675. break;
  207676. }
  207677. }
  207678. else
  207679. {
  207680. // convert the scan code to an unmodified character code..
  207681. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207682. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207683. keyChar = LOWORD (keyChar);
  207684. if (keyChar != 0)
  207685. key = (int) keyChar;
  207686. // avoid sending junk text characters for some control-key combinations
  207687. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207688. textChar = 0;
  207689. }
  207690. return handleKeyPress (key, textChar);
  207691. }
  207692. bool doAppCommand (const LPARAM lParam)
  207693. {
  207694. int key = 0;
  207695. switch (GET_APPCOMMAND_LPARAM (lParam))
  207696. {
  207697. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  207698. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  207699. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  207700. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  207701. default: break;
  207702. }
  207703. if (key != 0)
  207704. {
  207705. updateKeyModifiers();
  207706. if (hwnd == GetActiveWindow())
  207707. {
  207708. handleKeyPress (key, 0);
  207709. return true;
  207710. }
  207711. }
  207712. return false;
  207713. }
  207714. bool isConstrainedNativeWindow() const
  207715. {
  207716. return constrainer != 0
  207717. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable);
  207718. }
  207719. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  207720. {
  207721. if (isConstrainedNativeWindow())
  207722. {
  207723. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  207724. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  207725. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207726. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  207727. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  207728. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  207729. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  207730. r->left = pos.getX();
  207731. r->top = pos.getY();
  207732. r->right = pos.getRight();
  207733. r->bottom = pos.getBottom();
  207734. }
  207735. return TRUE;
  207736. }
  207737. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  207738. {
  207739. if (isConstrainedNativeWindow())
  207740. {
  207741. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  207742. && ! Component::isMouseButtonDownAnywhere())
  207743. {
  207744. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207745. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  207746. constrainer->checkBounds (pos, current,
  207747. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207748. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207749. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207750. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207751. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207752. wp->x = pos.getX();
  207753. wp->y = pos.getY();
  207754. wp->cx = pos.getWidth();
  207755. wp->cy = pos.getHeight();
  207756. }
  207757. }
  207758. return 0;
  207759. }
  207760. void handleAppActivation (const WPARAM wParam)
  207761. {
  207762. modifiersAtLastCallback = -1;
  207763. updateKeyModifiers();
  207764. if (isMinimised())
  207765. {
  207766. component->repaint();
  207767. handleMovedOrResized();
  207768. if (! ComponentPeer::isValidPeer (this))
  207769. return;
  207770. }
  207771. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  207772. {
  207773. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  207774. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207775. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207776. }
  207777. else
  207778. {
  207779. handleBroughtToFront();
  207780. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207781. Component::getCurrentlyModalComponent()->toFront (true);
  207782. }
  207783. }
  207784. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207785. {
  207786. public:
  207787. JuceDropTarget (Win32ComponentPeer* const owner_)
  207788. : owner (owner_)
  207789. {
  207790. }
  207791. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207792. {
  207793. updateFileList (pDataObject);
  207794. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207795. *pdwEffect = DROPEFFECT_COPY;
  207796. return S_OK;
  207797. }
  207798. HRESULT __stdcall DragLeave()
  207799. {
  207800. owner->handleFileDragExit (files);
  207801. return S_OK;
  207802. }
  207803. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207804. {
  207805. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207806. *pdwEffect = DROPEFFECT_COPY;
  207807. return S_OK;
  207808. }
  207809. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207810. {
  207811. updateFileList (pDataObject);
  207812. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207813. *pdwEffect = DROPEFFECT_COPY;
  207814. return S_OK;
  207815. }
  207816. private:
  207817. Win32ComponentPeer* const owner;
  207818. StringArray files;
  207819. void updateFileList (IDataObject* const pDataObject)
  207820. {
  207821. files.clear();
  207822. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207823. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207824. if (pDataObject->GetData (&format, &medium) == S_OK)
  207825. {
  207826. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207827. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207828. unsigned int i = 0;
  207829. if (pDropFiles->fWide)
  207830. {
  207831. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207832. for (;;)
  207833. {
  207834. unsigned int len = 0;
  207835. while (i + len < totalLen && fname [i + len] != 0)
  207836. ++len;
  207837. if (len == 0)
  207838. break;
  207839. files.add (String (fname + i, len));
  207840. i += len + 1;
  207841. }
  207842. }
  207843. else
  207844. {
  207845. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207846. for (;;)
  207847. {
  207848. unsigned int len = 0;
  207849. while (i + len < totalLen && fname [i + len] != 0)
  207850. ++len;
  207851. if (len == 0)
  207852. break;
  207853. files.add (String (fname + i, len));
  207854. i += len + 1;
  207855. }
  207856. }
  207857. GlobalUnlock (medium.hGlobal);
  207858. }
  207859. }
  207860. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  207861. };
  207862. void doSettingChange()
  207863. {
  207864. Desktop::getInstance().refreshMonitorSizes();
  207865. if (fullScreen && ! isMinimised())
  207866. {
  207867. const Rectangle<int> r (component->getParentMonitorArea());
  207868. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207869. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207870. }
  207871. }
  207872. public:
  207873. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207874. {
  207875. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207876. if (peer != 0)
  207877. {
  207878. jassert (isValidPeer (peer));
  207879. return peer->peerWindowProc (h, message, wParam, lParam);
  207880. }
  207881. return DefWindowProcW (h, message, wParam, lParam);
  207882. }
  207883. private:
  207884. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  207885. {
  207886. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  207887. return callback (userData);
  207888. else
  207889. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  207890. }
  207891. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207892. {
  207893. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207894. }
  207895. const Point<int> getCurrentMousePos() throw()
  207896. {
  207897. RECT wr;
  207898. GetWindowRect (hwnd, &wr);
  207899. const DWORD mp = GetMessagePos();
  207900. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207901. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207902. }
  207903. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207904. {
  207905. switch (message)
  207906. {
  207907. case WM_NCHITTEST:
  207908. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207909. return HTTRANSPARENT;
  207910. else if (! hasTitleBar())
  207911. return HTCLIENT;
  207912. break;
  207913. case WM_PAINT:
  207914. handlePaintMessage();
  207915. return 0;
  207916. case WM_NCPAINT:
  207917. if (hasTitleBar())
  207918. break;
  207919. else if (wParam != 1)
  207920. handlePaintMessage();
  207921. return 0;
  207922. case WM_ERASEBKGND:
  207923. case WM_NCCALCSIZE:
  207924. if (hasTitleBar())
  207925. break;
  207926. return 1;
  207927. case WM_MOUSEMOVE:
  207928. doMouseMove (getPointFromLParam (lParam));
  207929. return 0;
  207930. case WM_MOUSELEAVE:
  207931. doMouseExit();
  207932. return 0;
  207933. case WM_LBUTTONDOWN:
  207934. case WM_MBUTTONDOWN:
  207935. case WM_RBUTTONDOWN:
  207936. doMouseDown (getPointFromLParam (lParam), wParam);
  207937. return 0;
  207938. case WM_LBUTTONUP:
  207939. case WM_MBUTTONUP:
  207940. case WM_RBUTTONUP:
  207941. doMouseUp (getPointFromLParam (lParam), wParam);
  207942. return 0;
  207943. case WM_CAPTURECHANGED:
  207944. doCaptureChanged();
  207945. return 0;
  207946. case WM_NCMOUSEMOVE:
  207947. if (hasTitleBar())
  207948. break;
  207949. return 0;
  207950. case 0x020A: /* WM_MOUSEWHEEL */
  207951. case 0x020E: /* WM_MOUSEHWHEEL */
  207952. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  207953. return 0;
  207954. case WM_SIZING:
  207955. return handleSizeConstraining ((RECT*) lParam, wParam);
  207956. case WM_WINDOWPOSCHANGING:
  207957. return handlePositionChanging ((WINDOWPOS*) lParam);
  207958. case WM_WINDOWPOSCHANGED:
  207959. {
  207960. const Point<int> pos (getCurrentMousePos());
  207961. if (contains (pos, false))
  207962. doMouseEvent (pos);
  207963. }
  207964. handleMovedOrResized();
  207965. if (dontRepaint)
  207966. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207967. return 0;
  207968. case WM_KEYDOWN:
  207969. case WM_SYSKEYDOWN:
  207970. if (doKeyDown (wParam))
  207971. return 0;
  207972. break;
  207973. case WM_KEYUP:
  207974. case WM_SYSKEYUP:
  207975. if (doKeyUp (wParam))
  207976. return 0;
  207977. break;
  207978. case WM_CHAR:
  207979. if (doKeyChar ((int) wParam, lParam))
  207980. return 0;
  207981. break;
  207982. case WM_APPCOMMAND:
  207983. if (doAppCommand (lParam))
  207984. return TRUE;
  207985. break;
  207986. case WM_SETFOCUS:
  207987. updateKeyModifiers();
  207988. handleFocusGain();
  207989. break;
  207990. case WM_KILLFOCUS:
  207991. if (hasCreatedCaret)
  207992. {
  207993. hasCreatedCaret = false;
  207994. DestroyCaret();
  207995. }
  207996. handleFocusLoss();
  207997. break;
  207998. case WM_ACTIVATEAPP:
  207999. // Windows does weird things to process priority when you swap apps,
  208000. // so this forces an update when the app is brought to the front
  208001. if (wParam != FALSE)
  208002. juce_repeatLastProcessPriority();
  208003. else
  208004. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208005. juce_CheckCurrentlyFocusedTopLevelWindow();
  208006. modifiersAtLastCallback = -1;
  208007. return 0;
  208008. case WM_ACTIVATE:
  208009. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208010. {
  208011. handleAppActivation (wParam);
  208012. return 0;
  208013. }
  208014. break;
  208015. case WM_NCACTIVATE:
  208016. // while a temporary window is being shown, prevent Windows from deactivating the
  208017. // title bars of our main windows.
  208018. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208019. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208020. break;
  208021. case WM_MOUSEACTIVATE:
  208022. if (! component->getMouseClickGrabsKeyboardFocus())
  208023. return MA_NOACTIVATE;
  208024. break;
  208025. case WM_SHOWWINDOW:
  208026. if (wParam != 0)
  208027. handleBroughtToFront();
  208028. break;
  208029. case WM_CLOSE:
  208030. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208031. handleUserClosingWindow();
  208032. return 0;
  208033. case WM_QUERYENDSESSION:
  208034. if (JUCEApplication::getInstance() != 0)
  208035. {
  208036. JUCEApplication::getInstance()->systemRequestedQuit();
  208037. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208038. }
  208039. return TRUE;
  208040. case WM_TRAYNOTIFY:
  208041. handleTaskBarEvent (lParam);
  208042. break;
  208043. case WM_SYNCPAINT:
  208044. return 0;
  208045. case WM_DISPLAYCHANGE:
  208046. InvalidateRect (h, 0, 0);
  208047. // intentional fall-through...
  208048. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208049. doSettingChange();
  208050. break;
  208051. case WM_INITMENU:
  208052. if (! hasTitleBar())
  208053. {
  208054. if (isFullScreen())
  208055. {
  208056. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208057. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208058. }
  208059. else if (! isMinimised())
  208060. {
  208061. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208062. }
  208063. }
  208064. break;
  208065. case WM_SYSCOMMAND:
  208066. switch (wParam & 0xfff0)
  208067. {
  208068. case SC_CLOSE:
  208069. if (sendInputAttemptWhenModalMessage())
  208070. return 0;
  208071. if (hasTitleBar())
  208072. {
  208073. PostMessage (h, WM_CLOSE, 0, 0);
  208074. return 0;
  208075. }
  208076. break;
  208077. case SC_KEYMENU:
  208078. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  208079. // situations that can arise if a modal loop is started from an alt-key keypress).
  208080. if (hasTitleBar() && h == GetCapture())
  208081. ReleaseCapture();
  208082. break;
  208083. case SC_MAXIMIZE:
  208084. if (! sendInputAttemptWhenModalMessage())
  208085. setFullScreen (true);
  208086. return 0;
  208087. case SC_MINIMIZE:
  208088. if (sendInputAttemptWhenModalMessage())
  208089. return 0;
  208090. if (! hasTitleBar())
  208091. {
  208092. setMinimised (true);
  208093. return 0;
  208094. }
  208095. break;
  208096. case SC_RESTORE:
  208097. if (sendInputAttemptWhenModalMessage())
  208098. return 0;
  208099. if (hasTitleBar())
  208100. {
  208101. if (isFullScreen())
  208102. {
  208103. setFullScreen (false);
  208104. return 0;
  208105. }
  208106. }
  208107. else
  208108. {
  208109. if (isMinimised())
  208110. setMinimised (false);
  208111. else if (isFullScreen())
  208112. setFullScreen (false);
  208113. return 0;
  208114. }
  208115. break;
  208116. }
  208117. break;
  208118. case WM_NCLBUTTONDOWN:
  208119. if (! sendInputAttemptWhenModalMessage())
  208120. {
  208121. switch (wParam)
  208122. {
  208123. case HTBOTTOM:
  208124. case HTBOTTOMLEFT:
  208125. case HTBOTTOMRIGHT:
  208126. case HTGROWBOX:
  208127. case HTLEFT:
  208128. case HTRIGHT:
  208129. case HTTOP:
  208130. case HTTOPLEFT:
  208131. case HTTOPRIGHT:
  208132. if (isConstrainedNativeWindow())
  208133. {
  208134. constrainerIsResizing = true;
  208135. constrainer->resizeStart();
  208136. }
  208137. break;
  208138. default:
  208139. break;
  208140. };
  208141. }
  208142. break;
  208143. case WM_NCRBUTTONDOWN:
  208144. case WM_NCMBUTTONDOWN:
  208145. sendInputAttemptWhenModalMessage();
  208146. break;
  208147. //case WM_IME_STARTCOMPOSITION;
  208148. // return 0;
  208149. case WM_GETDLGCODE:
  208150. return DLGC_WANTALLKEYS;
  208151. default:
  208152. if (taskBarIcon != 0)
  208153. {
  208154. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208155. if (message == taskbarCreatedMessage)
  208156. {
  208157. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208158. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208159. }
  208160. }
  208161. break;
  208162. }
  208163. return DefWindowProcW (h, message, wParam, lParam);
  208164. }
  208165. bool sendInputAttemptWhenModalMessage()
  208166. {
  208167. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208168. {
  208169. Component* const current = Component::getCurrentlyModalComponent();
  208170. if (current != 0)
  208171. current->inputAttemptWhenModal();
  208172. return true;
  208173. }
  208174. return false;
  208175. }
  208176. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208177. };
  208178. ModifierKeys Win32ComponentPeer::currentModifiers;
  208179. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208180. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208181. {
  208182. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208183. }
  208184. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208185. void ModifierKeys::updateCurrentModifiers() throw()
  208186. {
  208187. currentModifiers = Win32ComponentPeer::currentModifiers;
  208188. }
  208189. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208190. {
  208191. Win32ComponentPeer::updateKeyModifiers();
  208192. int mouseMods = 0;
  208193. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208194. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208195. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208196. Win32ComponentPeer::currentModifiers
  208197. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208198. return Win32ComponentPeer::currentModifiers;
  208199. }
  208200. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208201. {
  208202. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208203. if (wp != 0)
  208204. wp->setTaskBarIcon (newImage);
  208205. }
  208206. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208207. {
  208208. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208209. if (wp != 0)
  208210. wp->setTaskBarIconToolTip (tooltip);
  208211. }
  208212. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208213. {
  208214. DWORD val = GetWindowLong (h, styleType);
  208215. if (bitIsSet)
  208216. val |= feature;
  208217. else
  208218. val &= ~feature;
  208219. SetWindowLongPtr (h, styleType, val);
  208220. SetWindowPos (h, 0, 0, 0, 0, 0,
  208221. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208222. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208223. }
  208224. bool Process::isForegroundProcess()
  208225. {
  208226. HWND fg = GetForegroundWindow();
  208227. if (fg == 0)
  208228. return true;
  208229. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208230. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208231. // have to see if any of our windows are children of the foreground window
  208232. fg = GetAncestor (fg, GA_ROOT);
  208233. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208234. {
  208235. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208236. if (wp != 0 && wp->isInside (fg))
  208237. return true;
  208238. }
  208239. return false;
  208240. }
  208241. bool AlertWindow::showNativeDialogBox (const String& title,
  208242. const String& bodyText,
  208243. bool isOkCancel)
  208244. {
  208245. return MessageBox (0, bodyText, title,
  208246. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208247. : MB_OK)) == IDOK;
  208248. }
  208249. void Desktop::createMouseInputSources()
  208250. {
  208251. mouseSources.add (new MouseInputSource (0, true));
  208252. }
  208253. const Point<int> MouseInputSource::getCurrentMousePosition()
  208254. {
  208255. POINT mousePos;
  208256. GetCursorPos (&mousePos);
  208257. return Point<int> (mousePos.x, mousePos.y);
  208258. }
  208259. void Desktop::setMousePosition (const Point<int>& newPosition)
  208260. {
  208261. SetCursorPos (newPosition.getX(), newPosition.getY());
  208262. }
  208263. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208264. {
  208265. return createSoftwareImage (format, width, height, clearImage);
  208266. }
  208267. class ScreenSaverDefeater : public Timer,
  208268. public DeletedAtShutdown
  208269. {
  208270. public:
  208271. ScreenSaverDefeater()
  208272. {
  208273. startTimer (10000);
  208274. timerCallback();
  208275. }
  208276. ~ScreenSaverDefeater() {}
  208277. void timerCallback()
  208278. {
  208279. if (Process::isForegroundProcess())
  208280. {
  208281. // simulate a shift key getting pressed..
  208282. INPUT input[2];
  208283. input[0].type = INPUT_KEYBOARD;
  208284. input[0].ki.wVk = VK_SHIFT;
  208285. input[0].ki.dwFlags = 0;
  208286. input[0].ki.dwExtraInfo = 0;
  208287. input[1].type = INPUT_KEYBOARD;
  208288. input[1].ki.wVk = VK_SHIFT;
  208289. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208290. input[1].ki.dwExtraInfo = 0;
  208291. SendInput (2, input, sizeof (INPUT));
  208292. }
  208293. }
  208294. };
  208295. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208296. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208297. {
  208298. if (isEnabled)
  208299. deleteAndZero (screenSaverDefeater);
  208300. else if (screenSaverDefeater == 0)
  208301. screenSaverDefeater = new ScreenSaverDefeater();
  208302. }
  208303. bool Desktop::isScreenSaverEnabled()
  208304. {
  208305. return screenSaverDefeater == 0;
  208306. }
  208307. /* (The code below is the "correct" way to disable the screen saver, but it
  208308. completely fails on winXP when the saver is password-protected...)
  208309. static bool juce_screenSaverEnabled = true;
  208310. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208311. {
  208312. juce_screenSaverEnabled = isEnabled;
  208313. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208314. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208315. }
  208316. bool Desktop::isScreenSaverEnabled() throw()
  208317. {
  208318. return juce_screenSaverEnabled;
  208319. }
  208320. */
  208321. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208322. {
  208323. if (enableOrDisable)
  208324. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208325. }
  208326. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208327. {
  208328. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208329. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208330. return TRUE;
  208331. }
  208332. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208333. {
  208334. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208335. // make sure the first in the list is the main monitor
  208336. for (int i = 1; i < monitorCoords.size(); ++i)
  208337. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208338. monitorCoords.swap (i, 0);
  208339. if (monitorCoords.size() == 0)
  208340. {
  208341. RECT r;
  208342. GetWindowRect (GetDesktopWindow(), &r);
  208343. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208344. }
  208345. if (clipToWorkArea)
  208346. {
  208347. // clip the main monitor to the active non-taskbar area
  208348. RECT r;
  208349. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208350. Rectangle<int>& screen = monitorCoords.getReference (0);
  208351. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208352. jmax (screen.getY(), (int) r.top));
  208353. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208354. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208355. }
  208356. }
  208357. const Image juce_createIconForFile (const File& file)
  208358. {
  208359. Image image;
  208360. WCHAR filename [1024];
  208361. file.getFullPathName().copyToUnicode (filename, 1023);
  208362. WORD iconNum = 0;
  208363. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208364. filename, &iconNum);
  208365. if (icon != 0)
  208366. {
  208367. image = IconConverters::createImageFromHICON (icon);
  208368. DestroyIcon (icon);
  208369. }
  208370. return image;
  208371. }
  208372. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208373. {
  208374. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208375. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208376. Image im (image);
  208377. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208378. {
  208379. im = im.rescaled (maxW, maxH);
  208380. hotspotX = (hotspotX * maxW) / image.getWidth();
  208381. hotspotY = (hotspotY * maxH) / image.getHeight();
  208382. }
  208383. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208384. }
  208385. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208386. {
  208387. if (cursorHandle != 0 && ! isStandard)
  208388. DestroyCursor ((HCURSOR) cursorHandle);
  208389. }
  208390. enum
  208391. {
  208392. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208393. };
  208394. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208395. {
  208396. LPCTSTR cursorName = IDC_ARROW;
  208397. switch (type)
  208398. {
  208399. case NormalCursor: break;
  208400. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208401. case WaitCursor: cursorName = IDC_WAIT; break;
  208402. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208403. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208404. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208405. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208406. case LeftRightResizeCursor:
  208407. case LeftEdgeResizeCursor:
  208408. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208409. case UpDownResizeCursor:
  208410. case TopEdgeResizeCursor:
  208411. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208412. case TopLeftCornerResizeCursor:
  208413. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208414. case TopRightCornerResizeCursor:
  208415. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208416. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208417. case DraggingHandCursor:
  208418. {
  208419. static void* dragHandCursor = 0;
  208420. if (dragHandCursor == 0)
  208421. {
  208422. static const unsigned char dragHandData[] =
  208423. { 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,
  208424. 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,
  208425. 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 };
  208426. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208427. }
  208428. return dragHandCursor;
  208429. }
  208430. default:
  208431. jassertfalse; break;
  208432. }
  208433. HCURSOR cursorH = LoadCursor (0, cursorName);
  208434. if (cursorH == 0)
  208435. cursorH = LoadCursor (0, IDC_ARROW);
  208436. return cursorH;
  208437. }
  208438. void MouseCursor::showInWindow (ComponentPeer*) const
  208439. {
  208440. HCURSOR c = (HCURSOR) getHandle();
  208441. if (c == 0)
  208442. c = LoadCursor (0, IDC_ARROW);
  208443. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208444. c = 0;
  208445. SetCursor (c);
  208446. }
  208447. void MouseCursor::showInAllWindows() const
  208448. {
  208449. showInWindow (0);
  208450. }
  208451. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208452. {
  208453. public:
  208454. JuceDropSource() {}
  208455. ~JuceDropSource() {}
  208456. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208457. {
  208458. if (escapePressed)
  208459. return DRAGDROP_S_CANCEL;
  208460. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208461. return DRAGDROP_S_DROP;
  208462. return S_OK;
  208463. }
  208464. HRESULT __stdcall GiveFeedback (DWORD)
  208465. {
  208466. return DRAGDROP_S_USEDEFAULTCURSORS;
  208467. }
  208468. };
  208469. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208470. {
  208471. public:
  208472. JuceEnumFormatEtc (const FORMATETC* const format_)
  208473. : format (format_),
  208474. index (0)
  208475. {
  208476. }
  208477. ~JuceEnumFormatEtc() {}
  208478. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208479. {
  208480. if (result == 0)
  208481. return E_POINTER;
  208482. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208483. newOne->index = index;
  208484. *result = newOne;
  208485. return S_OK;
  208486. }
  208487. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208488. {
  208489. if (pceltFetched != 0)
  208490. *pceltFetched = 0;
  208491. else if (celt != 1)
  208492. return S_FALSE;
  208493. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208494. {
  208495. copyFormatEtc (lpFormatEtc [0], *format);
  208496. ++index;
  208497. if (pceltFetched != 0)
  208498. *pceltFetched = 1;
  208499. return S_OK;
  208500. }
  208501. return S_FALSE;
  208502. }
  208503. HRESULT __stdcall Skip (ULONG celt)
  208504. {
  208505. if (index + (int) celt >= 1)
  208506. return S_FALSE;
  208507. index += celt;
  208508. return S_OK;
  208509. }
  208510. HRESULT __stdcall Reset()
  208511. {
  208512. index = 0;
  208513. return S_OK;
  208514. }
  208515. private:
  208516. const FORMATETC* const format;
  208517. int index;
  208518. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208519. {
  208520. dest = source;
  208521. if (source.ptd != 0)
  208522. {
  208523. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208524. *(dest.ptd) = *(source.ptd);
  208525. }
  208526. }
  208527. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208528. };
  208529. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208530. {
  208531. public:
  208532. JuceDataObject (JuceDropSource* const dropSource_,
  208533. const FORMATETC* const format_,
  208534. const STGMEDIUM* const medium_)
  208535. : dropSource (dropSource_),
  208536. format (format_),
  208537. medium (medium_)
  208538. {
  208539. }
  208540. ~JuceDataObject()
  208541. {
  208542. jassert (refCount == 0);
  208543. }
  208544. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208545. {
  208546. if ((pFormatEtc->tymed & format->tymed) != 0
  208547. && pFormatEtc->cfFormat == format->cfFormat
  208548. && pFormatEtc->dwAspect == format->dwAspect)
  208549. {
  208550. pMedium->tymed = format->tymed;
  208551. pMedium->pUnkForRelease = 0;
  208552. if (format->tymed == TYMED_HGLOBAL)
  208553. {
  208554. const SIZE_T len = GlobalSize (medium->hGlobal);
  208555. void* const src = GlobalLock (medium->hGlobal);
  208556. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208557. memcpy (dst, src, len);
  208558. GlobalUnlock (medium->hGlobal);
  208559. pMedium->hGlobal = dst;
  208560. return S_OK;
  208561. }
  208562. }
  208563. return DV_E_FORMATETC;
  208564. }
  208565. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208566. {
  208567. if (f == 0)
  208568. return E_INVALIDARG;
  208569. if (f->tymed == format->tymed
  208570. && f->cfFormat == format->cfFormat
  208571. && f->dwAspect == format->dwAspect)
  208572. return S_OK;
  208573. return DV_E_FORMATETC;
  208574. }
  208575. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208576. {
  208577. pFormatEtcOut->ptd = 0;
  208578. return E_NOTIMPL;
  208579. }
  208580. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208581. {
  208582. if (result == 0)
  208583. return E_POINTER;
  208584. if (direction == DATADIR_GET)
  208585. {
  208586. *result = new JuceEnumFormatEtc (format);
  208587. return S_OK;
  208588. }
  208589. *result = 0;
  208590. return E_NOTIMPL;
  208591. }
  208592. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208593. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208594. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208595. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208596. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208597. private:
  208598. JuceDropSource* const dropSource;
  208599. const FORMATETC* const format;
  208600. const STGMEDIUM* const medium;
  208601. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  208602. };
  208603. static HDROP createHDrop (const StringArray& fileNames)
  208604. {
  208605. int totalChars = 0;
  208606. for (int i = fileNames.size(); --i >= 0;)
  208607. totalChars += fileNames[i].length() + 1;
  208608. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208609. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208610. if (hDrop != 0)
  208611. {
  208612. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208613. pDropFiles->pFiles = sizeof (DROPFILES);
  208614. pDropFiles->fWide = true;
  208615. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208616. for (int i = 0; i < fileNames.size(); ++i)
  208617. {
  208618. fileNames[i].copyToUnicode (fname, 2048);
  208619. fname += fileNames[i].length() + 1;
  208620. }
  208621. *fname = 0;
  208622. GlobalUnlock (hDrop);
  208623. }
  208624. return hDrop;
  208625. }
  208626. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208627. {
  208628. JuceDropSource* const source = new JuceDropSource();
  208629. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208630. DWORD effect;
  208631. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208632. data->Release();
  208633. source->Release();
  208634. return res == DRAGDROP_S_DROP;
  208635. }
  208636. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208637. {
  208638. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208639. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208640. medium.hGlobal = createHDrop (files);
  208641. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208642. : DROPEFFECT_COPY);
  208643. }
  208644. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208645. {
  208646. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208647. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208648. const int numChars = text.length();
  208649. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208650. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208651. text.copyToUnicode (data, numChars + 1);
  208652. format.cfFormat = CF_UNICODETEXT;
  208653. GlobalUnlock (medium.hGlobal);
  208654. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208655. }
  208656. #endif
  208657. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208658. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208659. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208660. // compiled on its own).
  208661. #if JUCE_INCLUDED_FILE
  208662. namespace FileChooserHelpers
  208663. {
  208664. static bool areThereAnyAlwaysOnTopWindows()
  208665. {
  208666. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208667. {
  208668. Component* c = Desktop::getInstance().getComponent (i);
  208669. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208670. return true;
  208671. }
  208672. return false;
  208673. }
  208674. struct FileChooserCallbackInfo
  208675. {
  208676. String initialPath;
  208677. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208678. ScopedPointer<Component> customComponent;
  208679. };
  208680. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208681. {
  208682. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208683. if (msg == BFFM_INITIALIZED)
  208684. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  208685. else if (msg == BFFM_VALIDATEFAILEDW)
  208686. info->returnedString = (LPCWSTR) lParam;
  208687. else if (msg == BFFM_VALIDATEFAILEDA)
  208688. info->returnedString = (const char*) lParam;
  208689. return 0;
  208690. }
  208691. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208692. {
  208693. if (uiMsg == WM_INITDIALOG)
  208694. {
  208695. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208696. HWND dialogH = GetParent (hdlg);
  208697. jassert (dialogH != 0);
  208698. if (dialogH == 0)
  208699. dialogH = hdlg;
  208700. RECT r, cr;
  208701. GetWindowRect (dialogH, &r);
  208702. GetClientRect (dialogH, &cr);
  208703. SetWindowPos (dialogH, 0,
  208704. r.left, r.top,
  208705. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208706. jmax (150, (int) (r.bottom - r.top)),
  208707. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208708. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208709. customComp->addToDesktop (0, dialogH);
  208710. }
  208711. else if (uiMsg == WM_NOTIFY)
  208712. {
  208713. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208714. if (ofn->hdr.code == CDN_SELCHANGE)
  208715. {
  208716. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208717. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208718. if (comp != 0)
  208719. {
  208720. WCHAR path [MAX_PATH * 2];
  208721. zerostruct (path);
  208722. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208723. comp->selectedFileChanged (File (path));
  208724. }
  208725. }
  208726. }
  208727. return 0;
  208728. }
  208729. class CustomComponentHolder : public Component
  208730. {
  208731. public:
  208732. CustomComponentHolder (Component* customComp)
  208733. {
  208734. setVisible (true);
  208735. setOpaque (true);
  208736. addAndMakeVisible (customComp);
  208737. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208738. }
  208739. void paint (Graphics& g)
  208740. {
  208741. g.fillAll (Colours::lightgrey);
  208742. }
  208743. void resized()
  208744. {
  208745. if (getNumChildComponents() > 0)
  208746. getChildComponent(0)->setBounds (getLocalBounds());
  208747. }
  208748. private:
  208749. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  208750. };
  208751. }
  208752. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208753. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208754. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208755. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208756. {
  208757. using namespace FileChooserHelpers;
  208758. HeapBlock<WCHAR> files;
  208759. const int charsAvailableForResult = 32768;
  208760. files.calloc (charsAvailableForResult + 1);
  208761. int filenameOffset = 0;
  208762. FileChooserCallbackInfo info;
  208763. // use a modal window as the parent for this dialog box
  208764. // to block input from other app windows
  208765. Component parentWindow (String::empty);
  208766. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208767. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208768. mainMon.getY() + mainMon.getHeight() / 4,
  208769. 0, 0);
  208770. parentWindow.setOpaque (true);
  208771. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208772. parentWindow.addToDesktop (0);
  208773. if (extraInfoComponent == 0)
  208774. parentWindow.enterModalState();
  208775. if (currentFileOrDirectory.isDirectory())
  208776. {
  208777. info.initialPath = currentFileOrDirectory.getFullPathName();
  208778. }
  208779. else
  208780. {
  208781. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  208782. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208783. }
  208784. if (selectsDirectory)
  208785. {
  208786. BROWSEINFO bi;
  208787. zerostruct (bi);
  208788. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208789. bi.pszDisplayName = files;
  208790. bi.lpszTitle = title;
  208791. bi.lParam = (LPARAM) &info;
  208792. bi.lpfn = browseCallbackProc;
  208793. #ifdef BIF_USENEWUI
  208794. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208795. #else
  208796. bi.ulFlags = 0x50;
  208797. #endif
  208798. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208799. if (! SHGetPathFromIDListW (list, files))
  208800. {
  208801. files[0] = 0;
  208802. info.returnedString = String::empty;
  208803. }
  208804. LPMALLOC al;
  208805. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208806. al->Free (list);
  208807. if (info.returnedString.isNotEmpty())
  208808. {
  208809. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208810. return;
  208811. }
  208812. }
  208813. else
  208814. {
  208815. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208816. if (warnAboutOverwritingExistingFiles)
  208817. flags |= OFN_OVERWRITEPROMPT;
  208818. if (selectMultipleFiles)
  208819. flags |= OFN_ALLOWMULTISELECT;
  208820. if (extraInfoComponent != 0)
  208821. {
  208822. flags |= OFN_ENABLEHOOK;
  208823. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208824. info.customComponent->enterModalState();
  208825. }
  208826. WCHAR filters [1024];
  208827. zerostruct (filters);
  208828. filter.copyToUnicode (filters, 1024);
  208829. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  208830. OPENFILENAMEW of;
  208831. zerostruct (of);
  208832. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208833. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208834. #else
  208835. of.lStructSize = sizeof (of);
  208836. #endif
  208837. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208838. of.lpstrFilter = filters;
  208839. of.nFilterIndex = 1;
  208840. of.lpstrFile = files;
  208841. of.nMaxFile = charsAvailableForResult;
  208842. of.lpstrInitialDir = info.initialPath;
  208843. of.lpstrTitle = title;
  208844. of.Flags = flags;
  208845. of.lCustData = (LPARAM) &info;
  208846. if (extraInfoComponent != 0)
  208847. of.lpfnHook = &openCallback;
  208848. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208849. : GetOpenFileName (&of)))
  208850. return;
  208851. filenameOffset = of.nFileOffset;
  208852. }
  208853. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208854. {
  208855. const WCHAR* filename = files + filenameOffset;
  208856. while (*filename != 0)
  208857. {
  208858. results.add (File (String (files) + "\\" + String (filename)));
  208859. filename += CharacterFunctions::length (filename) + 1;
  208860. }
  208861. }
  208862. else if (files[0] != 0)
  208863. {
  208864. results.add (File (String (files)));
  208865. }
  208866. }
  208867. #endif
  208868. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208869. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208870. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208871. // compiled on its own).
  208872. #if JUCE_INCLUDED_FILE
  208873. void SystemClipboard::copyTextToClipboard (const String& text)
  208874. {
  208875. if (OpenClipboard (0) != 0)
  208876. {
  208877. if (EmptyClipboard() != 0)
  208878. {
  208879. const int len = text.length();
  208880. if (len > 0)
  208881. {
  208882. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  208883. (len + 1) * sizeof (wchar_t));
  208884. if (bufH != 0)
  208885. {
  208886. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208887. text.copyToUnicode (data, len);
  208888. GlobalUnlock (bufH);
  208889. SetClipboardData (CF_UNICODETEXT, bufH);
  208890. }
  208891. }
  208892. }
  208893. CloseClipboard();
  208894. }
  208895. }
  208896. const String SystemClipboard::getTextFromClipboard()
  208897. {
  208898. String result;
  208899. if (OpenClipboard (0) != 0)
  208900. {
  208901. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208902. if (bufH != 0)
  208903. {
  208904. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  208905. if (data != 0)
  208906. {
  208907. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  208908. GlobalUnlock (bufH);
  208909. }
  208910. }
  208911. CloseClipboard();
  208912. }
  208913. return result;
  208914. }
  208915. #endif
  208916. /*** End of inlined file: juce_win32_Misc.cpp ***/
  208917. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  208918. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208919. // compiled on its own).
  208920. #if JUCE_INCLUDED_FILE
  208921. namespace ActiveXHelpers
  208922. {
  208923. class JuceIStorage : public ComBaseClassHelper <IStorage>
  208924. {
  208925. public:
  208926. JuceIStorage() {}
  208927. ~JuceIStorage() {}
  208928. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208929. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208930. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208931. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208932. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208933. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208934. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208935. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208936. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208937. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208938. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208939. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208940. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208941. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208942. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208943. };
  208944. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  208945. {
  208946. HWND window;
  208947. public:
  208948. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  208949. ~JuceOleInPlaceFrame() {}
  208950. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208951. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208952. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208953. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208954. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208955. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208956. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208957. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208958. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208959. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208960. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208961. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208962. };
  208963. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  208964. {
  208965. HWND window;
  208966. JuceOleInPlaceFrame* frame;
  208967. public:
  208968. JuceIOleInPlaceSite (HWND window_)
  208969. : window (window_),
  208970. frame (new JuceOleInPlaceFrame (window))
  208971. {}
  208972. ~JuceIOleInPlaceSite()
  208973. {
  208974. frame->Release();
  208975. }
  208976. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208977. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208978. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208979. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208980. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208981. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208982. {
  208983. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  208984. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  208985. */
  208986. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  208987. if (lplpDoc != 0) *lplpDoc = 0;
  208988. lpFrameInfo->fMDIApp = FALSE;
  208989. lpFrameInfo->hwndFrame = window;
  208990. lpFrameInfo->haccel = 0;
  208991. lpFrameInfo->cAccelEntries = 0;
  208992. return S_OK;
  208993. }
  208994. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  208995. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  208996. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  208997. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  208998. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  208999. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209000. };
  209001. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209002. {
  209003. JuceIOleInPlaceSite* inplaceSite;
  209004. public:
  209005. JuceIOleClientSite (HWND window)
  209006. : inplaceSite (new JuceIOleInPlaceSite (window))
  209007. {}
  209008. ~JuceIOleClientSite()
  209009. {
  209010. inplaceSite->Release();
  209011. }
  209012. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209013. {
  209014. if (type == IID_IOleInPlaceSite)
  209015. {
  209016. inplaceSite->AddRef();
  209017. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209018. return S_OK;
  209019. }
  209020. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209021. }
  209022. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209023. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209024. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209025. HRESULT __stdcall ShowObject() { return S_OK; }
  209026. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209027. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209028. };
  209029. static Array<ActiveXControlComponent*> activeXComps;
  209030. static HWND getHWND (const ActiveXControlComponent* const component)
  209031. {
  209032. HWND hwnd = 0;
  209033. const IID iid = IID_IOleWindow;
  209034. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209035. if (window != 0)
  209036. {
  209037. window->GetWindow (&hwnd);
  209038. window->Release();
  209039. }
  209040. return hwnd;
  209041. }
  209042. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209043. {
  209044. RECT activeXRect, peerRect;
  209045. GetWindowRect (hwnd, &activeXRect);
  209046. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209047. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209048. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209049. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209050. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209051. switch (message)
  209052. {
  209053. case WM_MOUSEMOVE:
  209054. case WM_LBUTTONDOWN:
  209055. case WM_MBUTTONDOWN:
  209056. case WM_RBUTTONDOWN:
  209057. case WM_LBUTTONUP:
  209058. case WM_MBUTTONUP:
  209059. case WM_RBUTTONUP:
  209060. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209061. break;
  209062. default:
  209063. break;
  209064. }
  209065. }
  209066. }
  209067. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209068. {
  209069. public:
  209070. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209071. : ComponentMovementWatcher (&owner_),
  209072. owner (owner_),
  209073. controlHWND (0),
  209074. storage (new ActiveXHelpers::JuceIStorage()),
  209075. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209076. control (0)
  209077. {
  209078. }
  209079. ~Pimpl()
  209080. {
  209081. if (control != 0)
  209082. {
  209083. control->Close (OLECLOSE_NOSAVE);
  209084. control->Release();
  209085. }
  209086. clientSite->Release();
  209087. storage->Release();
  209088. }
  209089. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209090. {
  209091. Component* const topComp = owner.getTopLevelComponent();
  209092. if (topComp->getPeer() != 0)
  209093. {
  209094. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  209095. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209096. }
  209097. }
  209098. void componentPeerChanged()
  209099. {
  209100. componentMovedOrResized (true, true);
  209101. }
  209102. void componentVisibilityChanged()
  209103. {
  209104. owner.setControlVisible (owner.isShowing());
  209105. componentPeerChanged();
  209106. }
  209107. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209108. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209109. {
  209110. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209111. {
  209112. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209113. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209114. {
  209115. switch (message)
  209116. {
  209117. case WM_MOUSEMOVE:
  209118. case WM_LBUTTONDOWN:
  209119. case WM_MBUTTONDOWN:
  209120. case WM_RBUTTONDOWN:
  209121. case WM_LBUTTONUP:
  209122. case WM_MBUTTONUP:
  209123. case WM_RBUTTONUP:
  209124. case WM_LBUTTONDBLCLK:
  209125. case WM_MBUTTONDBLCLK:
  209126. case WM_RBUTTONDBLCLK:
  209127. if (ax->isShowing())
  209128. {
  209129. ComponentPeer* const peer = ax->getPeer();
  209130. if (peer != 0)
  209131. {
  209132. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209133. if (! ax->areMouseEventsAllowed())
  209134. return 0;
  209135. }
  209136. }
  209137. break;
  209138. default:
  209139. break;
  209140. }
  209141. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209142. }
  209143. }
  209144. return DefWindowProc (hwnd, message, wParam, lParam);
  209145. }
  209146. private:
  209147. ActiveXControlComponent& owner;
  209148. public:
  209149. HWND controlHWND;
  209150. IStorage* storage;
  209151. IOleClientSite* clientSite;
  209152. IOleObject* control;
  209153. };
  209154. ActiveXControlComponent::ActiveXControlComponent()
  209155. : originalWndProc (0),
  209156. mouseEventsAllowed (true)
  209157. {
  209158. ActiveXHelpers::activeXComps.add (this);
  209159. }
  209160. ActiveXControlComponent::~ActiveXControlComponent()
  209161. {
  209162. deleteControl();
  209163. ActiveXHelpers::activeXComps.removeValue (this);
  209164. }
  209165. void ActiveXControlComponent::paint (Graphics& g)
  209166. {
  209167. if (control == 0)
  209168. g.fillAll (Colours::lightgrey);
  209169. }
  209170. bool ActiveXControlComponent::createControl (const void* controlIID)
  209171. {
  209172. deleteControl();
  209173. ComponentPeer* const peer = getPeer();
  209174. // the component must have already been added to a real window when you call this!
  209175. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209176. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209177. {
  209178. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209179. HWND hwnd = (HWND) peer->getNativeHandle();
  209180. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209181. HRESULT hr;
  209182. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209183. newControl->clientSite, newControl->storage,
  209184. (void**) &(newControl->control))) == S_OK)
  209185. {
  209186. newControl->control->SetHostNames (L"Juce", 0);
  209187. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209188. {
  209189. RECT rect;
  209190. rect.left = pos.getX();
  209191. rect.top = pos.getY();
  209192. rect.right = pos.getX() + getWidth();
  209193. rect.bottom = pos.getY() + getHeight();
  209194. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209195. {
  209196. control = newControl;
  209197. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209198. control->controlHWND = ActiveXHelpers::getHWND (this);
  209199. if (control->controlHWND != 0)
  209200. {
  209201. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209202. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209203. }
  209204. return true;
  209205. }
  209206. }
  209207. }
  209208. }
  209209. return false;
  209210. }
  209211. void ActiveXControlComponent::deleteControl()
  209212. {
  209213. control = 0;
  209214. originalWndProc = 0;
  209215. }
  209216. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209217. {
  209218. void* result = 0;
  209219. if (control != 0 && control->control != 0
  209220. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209221. return result;
  209222. return 0;
  209223. }
  209224. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209225. {
  209226. if (control->controlHWND != 0)
  209227. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209228. }
  209229. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209230. {
  209231. if (control->controlHWND != 0)
  209232. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209233. }
  209234. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209235. {
  209236. mouseEventsAllowed = eventsCanReachControl;
  209237. }
  209238. #endif
  209239. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209240. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209241. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209242. // compiled on its own).
  209243. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209244. using namespace QTOLibrary;
  209245. using namespace QTOControlLib;
  209246. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209247. static bool isQTAvailable = false;
  209248. class QuickTimeMovieComponent::Pimpl
  209249. {
  209250. public:
  209251. Pimpl() : dataHandle (0)
  209252. {
  209253. }
  209254. ~Pimpl()
  209255. {
  209256. clearHandle();
  209257. }
  209258. void clearHandle()
  209259. {
  209260. if (dataHandle != 0)
  209261. {
  209262. DisposeHandle (dataHandle);
  209263. dataHandle = 0;
  209264. }
  209265. }
  209266. IQTControlPtr qtControl;
  209267. IQTMoviePtr qtMovie;
  209268. Handle dataHandle;
  209269. };
  209270. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209271. : movieLoaded (false),
  209272. controllerVisible (true)
  209273. {
  209274. pimpl = new Pimpl();
  209275. setMouseEventsAllowed (false);
  209276. }
  209277. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209278. {
  209279. closeMovie();
  209280. pimpl->qtControl = 0;
  209281. deleteControl();
  209282. pimpl = 0;
  209283. }
  209284. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209285. {
  209286. if (! isQTAvailable)
  209287. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209288. return isQTAvailable;
  209289. }
  209290. void QuickTimeMovieComponent::createControlIfNeeded()
  209291. {
  209292. if (isShowing() && ! isControlCreated())
  209293. {
  209294. const IID qtIID = __uuidof (QTControl);
  209295. if (createControl (&qtIID))
  209296. {
  209297. const IID qtInterfaceIID = __uuidof (IQTControl);
  209298. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209299. if (pimpl->qtControl != 0)
  209300. {
  209301. pimpl->qtControl->Release(); // it has one ref too many at this point
  209302. pimpl->qtControl->QuickTimeInitialize();
  209303. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209304. if (movieFile != File::nonexistent)
  209305. loadMovie (movieFile, controllerVisible);
  209306. }
  209307. }
  209308. }
  209309. }
  209310. bool QuickTimeMovieComponent::isControlCreated() const
  209311. {
  209312. return isControlOpen();
  209313. }
  209314. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209315. const bool isControllerVisible)
  209316. {
  209317. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209318. movieFile = File::nonexistent;
  209319. movieLoaded = false;
  209320. pimpl->qtMovie = 0;
  209321. controllerVisible = isControllerVisible;
  209322. createControlIfNeeded();
  209323. if (isControlCreated())
  209324. {
  209325. if (pimpl->qtControl != 0)
  209326. {
  209327. pimpl->qtControl->Put_MovieHandle (0);
  209328. pimpl->clearHandle();
  209329. Movie movie;
  209330. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209331. {
  209332. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209333. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209334. if (pimpl->qtMovie != 0)
  209335. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209336. : qtMovieControllerTypeNone);
  209337. }
  209338. if (movie == 0)
  209339. pimpl->clearHandle();
  209340. }
  209341. movieLoaded = (pimpl->qtMovie != 0);
  209342. }
  209343. else
  209344. {
  209345. // You're trying to open a movie when the control hasn't yet been created, probably because
  209346. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209347. jassertfalse;
  209348. }
  209349. return movieLoaded;
  209350. }
  209351. void QuickTimeMovieComponent::closeMovie()
  209352. {
  209353. stop();
  209354. movieFile = File::nonexistent;
  209355. movieLoaded = false;
  209356. pimpl->qtMovie = 0;
  209357. if (pimpl->qtControl != 0)
  209358. pimpl->qtControl->Put_MovieHandle (0);
  209359. pimpl->clearHandle();
  209360. }
  209361. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209362. {
  209363. return movieFile;
  209364. }
  209365. bool QuickTimeMovieComponent::isMovieOpen() const
  209366. {
  209367. return movieLoaded;
  209368. }
  209369. double QuickTimeMovieComponent::getMovieDuration() const
  209370. {
  209371. if (pimpl->qtMovie != 0)
  209372. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209373. return 0.0;
  209374. }
  209375. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209376. {
  209377. if (pimpl->qtMovie != 0)
  209378. {
  209379. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209380. width = r.right - r.left;
  209381. height = r.bottom - r.top;
  209382. }
  209383. else
  209384. {
  209385. width = height = 0;
  209386. }
  209387. }
  209388. void QuickTimeMovieComponent::play()
  209389. {
  209390. if (pimpl->qtMovie != 0)
  209391. pimpl->qtMovie->Play();
  209392. }
  209393. void QuickTimeMovieComponent::stop()
  209394. {
  209395. if (pimpl->qtMovie != 0)
  209396. pimpl->qtMovie->Stop();
  209397. }
  209398. bool QuickTimeMovieComponent::isPlaying() const
  209399. {
  209400. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209401. }
  209402. void QuickTimeMovieComponent::setPosition (const double seconds)
  209403. {
  209404. if (pimpl->qtMovie != 0)
  209405. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209406. }
  209407. double QuickTimeMovieComponent::getPosition() const
  209408. {
  209409. if (pimpl->qtMovie != 0)
  209410. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209411. return 0.0;
  209412. }
  209413. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209414. {
  209415. if (pimpl->qtMovie != 0)
  209416. pimpl->qtMovie->PutRate (newSpeed);
  209417. }
  209418. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209419. {
  209420. if (pimpl->qtMovie != 0)
  209421. {
  209422. pimpl->qtMovie->PutAudioVolume (newVolume);
  209423. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209424. }
  209425. }
  209426. float QuickTimeMovieComponent::getMovieVolume() const
  209427. {
  209428. if (pimpl->qtMovie != 0)
  209429. return pimpl->qtMovie->GetAudioVolume();
  209430. return 0.0f;
  209431. }
  209432. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209433. {
  209434. if (pimpl->qtMovie != 0)
  209435. pimpl->qtMovie->PutLoop (shouldLoop);
  209436. }
  209437. bool QuickTimeMovieComponent::isLooping() const
  209438. {
  209439. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209440. }
  209441. bool QuickTimeMovieComponent::isControllerVisible() const
  209442. {
  209443. return controllerVisible;
  209444. }
  209445. void QuickTimeMovieComponent::parentHierarchyChanged()
  209446. {
  209447. createControlIfNeeded();
  209448. QTCompBaseClass::parentHierarchyChanged();
  209449. }
  209450. void QuickTimeMovieComponent::visibilityChanged()
  209451. {
  209452. createControlIfNeeded();
  209453. QTCompBaseClass::visibilityChanged();
  209454. }
  209455. void QuickTimeMovieComponent::paint (Graphics& g)
  209456. {
  209457. if (! isControlCreated())
  209458. g.fillAll (Colours::black);
  209459. }
  209460. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209461. {
  209462. Handle dataRef = 0;
  209463. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209464. if (err == noErr)
  209465. {
  209466. Str255 suffix;
  209467. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209468. StringPtr name = suffix;
  209469. err = PtrAndHand (name, dataRef, name[0] + 1);
  209470. if (err == noErr)
  209471. {
  209472. long atoms[3];
  209473. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209474. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209475. atoms[2] = EndianU32_NtoB (MovieFileType);
  209476. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209477. if (err == noErr)
  209478. return dataRef;
  209479. }
  209480. DisposeHandle (dataRef);
  209481. }
  209482. return 0;
  209483. }
  209484. static CFStringRef juceStringToCFString (const String& s)
  209485. {
  209486. const int len = s.length();
  209487. const juce_wchar* const t = s;
  209488. HeapBlock <UniChar> temp (len + 2);
  209489. for (int i = 0; i <= len; ++i)
  209490. temp[i] = t[i];
  209491. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209492. }
  209493. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209494. {
  209495. Boolean trueBool = true;
  209496. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209497. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209498. props[prop].propValueSize = sizeof (trueBool);
  209499. props[prop].propValueAddress = &trueBool;
  209500. ++prop;
  209501. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209502. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209503. props[prop].propValueSize = sizeof (trueBool);
  209504. props[prop].propValueAddress = &trueBool;
  209505. ++prop;
  209506. Boolean isActive = true;
  209507. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209508. props[prop].propID = kQTNewMoviePropertyID_Active;
  209509. props[prop].propValueSize = sizeof (isActive);
  209510. props[prop].propValueAddress = &isActive;
  209511. ++prop;
  209512. MacSetPort (0);
  209513. jassert (prop <= 5);
  209514. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209515. return err == noErr;
  209516. }
  209517. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209518. {
  209519. if (input == 0)
  209520. return false;
  209521. dataHandle = 0;
  209522. bool ok = false;
  209523. QTNewMoviePropertyElement props[5];
  209524. zeromem (props, sizeof (props));
  209525. int prop = 0;
  209526. DataReferenceRecord dr;
  209527. props[prop].propClass = kQTPropertyClass_DataLocation;
  209528. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209529. props[prop].propValueSize = sizeof (dr);
  209530. props[prop].propValueAddress = &dr;
  209531. ++prop;
  209532. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209533. if (fin != 0)
  209534. {
  209535. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209536. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209537. &dr.dataRef, &dr.dataRefType);
  209538. ok = openMovie (props, prop, movie);
  209539. DisposeHandle (dr.dataRef);
  209540. CFRelease (filePath);
  209541. }
  209542. else
  209543. {
  209544. // sanity-check because this currently needs to load the whole stream into memory..
  209545. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209546. dataHandle = NewHandle ((Size) input->getTotalLength());
  209547. HLock (dataHandle);
  209548. // read the entire stream into memory - this is a pain, but can't get it to work
  209549. // properly using a custom callback to supply the data.
  209550. input->read (*dataHandle, (int) input->getTotalLength());
  209551. HUnlock (dataHandle);
  209552. // different types to get QT to try. (We should really be a bit smarter here by
  209553. // working out in advance which one the stream contains, rather than just trying
  209554. // each one)
  209555. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209556. "\04.avi", "\04.m4a" };
  209557. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209558. {
  209559. /* // this fails for some bizarre reason - it can be bodged to work with
  209560. // movies, but can't seem to do it for other file types..
  209561. QTNewMovieUserProcRecord procInfo;
  209562. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209563. procInfo.getMovieUserProcRefcon = this;
  209564. procInfo.defaultDataRef.dataRef = dataRef;
  209565. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209566. props[prop].propClass = kQTPropertyClass_DataLocation;
  209567. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209568. props[prop].propValueSize = sizeof (procInfo);
  209569. props[prop].propValueAddress = (void*) &procInfo;
  209570. ++prop; */
  209571. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209572. dr.dataRefType = HandleDataHandlerSubType;
  209573. ok = openMovie (props, prop, movie);
  209574. DisposeHandle (dr.dataRef);
  209575. }
  209576. }
  209577. return ok;
  209578. }
  209579. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209580. const bool isControllerVisible)
  209581. {
  209582. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209583. movieFile = movieFile_;
  209584. return ok;
  209585. }
  209586. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209587. const bool isControllerVisible)
  209588. {
  209589. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209590. }
  209591. void QuickTimeMovieComponent::goToStart()
  209592. {
  209593. setPosition (0.0);
  209594. }
  209595. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209596. const RectanglePlacement& placement)
  209597. {
  209598. int normalWidth, normalHeight;
  209599. getMovieNormalSize (normalWidth, normalHeight);
  209600. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  209601. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  209602. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  209603. else
  209604. setBounds (spaceToFitWithin);
  209605. }
  209606. #endif
  209607. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209608. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209609. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209610. // compiled on its own).
  209611. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209612. class WebBrowserComponentInternal : public ActiveXControlComponent
  209613. {
  209614. public:
  209615. WebBrowserComponentInternal()
  209616. : browser (0),
  209617. connectionPoint (0),
  209618. adviseCookie (0)
  209619. {
  209620. }
  209621. ~WebBrowserComponentInternal()
  209622. {
  209623. if (connectionPoint != 0)
  209624. connectionPoint->Unadvise (adviseCookie);
  209625. if (browser != 0)
  209626. browser->Release();
  209627. }
  209628. void createBrowser()
  209629. {
  209630. createControl (&CLSID_WebBrowser);
  209631. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209632. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209633. if (connectionPointContainer != 0)
  209634. {
  209635. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209636. &connectionPoint);
  209637. if (connectionPoint != 0)
  209638. {
  209639. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209640. jassert (owner != 0);
  209641. EventHandler* handler = new EventHandler (*owner);
  209642. connectionPoint->Advise (handler, &adviseCookie);
  209643. handler->Release();
  209644. }
  209645. }
  209646. }
  209647. void goToURL (const String& url,
  209648. const StringArray* headers,
  209649. const MemoryBlock* postData)
  209650. {
  209651. if (browser != 0)
  209652. {
  209653. LPSAFEARRAY sa = 0;
  209654. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209655. VariantInit (&flags);
  209656. VariantInit (&frame);
  209657. VariantInit (&postDataVar);
  209658. VariantInit (&headersVar);
  209659. if (headers != 0)
  209660. {
  209661. V_VT (&headersVar) = VT_BSTR;
  209662. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209663. }
  209664. if (postData != 0 && postData->getSize() > 0)
  209665. {
  209666. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209667. if (sa != 0)
  209668. {
  209669. void* data = 0;
  209670. SafeArrayAccessData (sa, &data);
  209671. jassert (data != 0);
  209672. if (data != 0)
  209673. {
  209674. postData->copyTo (data, 0, postData->getSize());
  209675. SafeArrayUnaccessData (sa);
  209676. VARIANT postDataVar2;
  209677. VariantInit (&postDataVar2);
  209678. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209679. V_ARRAY (&postDataVar2) = sa;
  209680. postDataVar = postDataVar2;
  209681. }
  209682. }
  209683. }
  209684. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209685. &flags, &frame,
  209686. &postDataVar, &headersVar);
  209687. if (sa != 0)
  209688. SafeArrayDestroy (sa);
  209689. VariantClear (&flags);
  209690. VariantClear (&frame);
  209691. VariantClear (&postDataVar);
  209692. VariantClear (&headersVar);
  209693. }
  209694. }
  209695. IWebBrowser2* browser;
  209696. private:
  209697. IConnectionPoint* connectionPoint;
  209698. DWORD adviseCookie;
  209699. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209700. public ComponentMovementWatcher
  209701. {
  209702. public:
  209703. EventHandler (WebBrowserComponent& owner_)
  209704. : ComponentMovementWatcher (&owner_),
  209705. owner (owner_)
  209706. {
  209707. }
  209708. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  209709. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  209710. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  209711. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  209712. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  209713. {
  209714. if (dispIdMember == DISPID_BEFORENAVIGATE2)
  209715. {
  209716. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209717. String url;
  209718. if ((vurl->vt & VT_BYREF) != 0)
  209719. url = *vurl->pbstrVal;
  209720. else
  209721. url = vurl->bstrVal;
  209722. *pDispParams->rgvarg->pboolVal
  209723. = owner.pageAboutToLoad (url) ? VARIANT_FALSE
  209724. : VARIANT_TRUE;
  209725. return S_OK;
  209726. }
  209727. return E_NOTIMPL;
  209728. }
  209729. void componentMovedOrResized (bool, bool ) {}
  209730. void componentPeerChanged() {}
  209731. void componentVisibilityChanged() { owner.visibilityChanged(); }
  209732. private:
  209733. WebBrowserComponent& owner;
  209734. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  209735. };
  209736. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  209737. };
  209738. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209739. : browser (0),
  209740. blankPageShown (false),
  209741. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209742. {
  209743. setOpaque (true);
  209744. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209745. }
  209746. WebBrowserComponent::~WebBrowserComponent()
  209747. {
  209748. delete browser;
  209749. }
  209750. void WebBrowserComponent::goToURL (const String& url,
  209751. const StringArray* headers,
  209752. const MemoryBlock* postData)
  209753. {
  209754. lastURL = url;
  209755. lastHeaders.clear();
  209756. if (headers != 0)
  209757. lastHeaders = *headers;
  209758. lastPostData.setSize (0);
  209759. if (postData != 0)
  209760. lastPostData = *postData;
  209761. blankPageShown = false;
  209762. browser->goToURL (url, headers, postData);
  209763. }
  209764. void WebBrowserComponent::stop()
  209765. {
  209766. if (browser->browser != 0)
  209767. browser->browser->Stop();
  209768. }
  209769. void WebBrowserComponent::goBack()
  209770. {
  209771. lastURL = String::empty;
  209772. blankPageShown = false;
  209773. if (browser->browser != 0)
  209774. browser->browser->GoBack();
  209775. }
  209776. void WebBrowserComponent::goForward()
  209777. {
  209778. lastURL = String::empty;
  209779. if (browser->browser != 0)
  209780. browser->browser->GoForward();
  209781. }
  209782. void WebBrowserComponent::refresh()
  209783. {
  209784. if (browser->browser != 0)
  209785. browser->browser->Refresh();
  209786. }
  209787. void WebBrowserComponent::paint (Graphics& g)
  209788. {
  209789. if (browser->browser == 0)
  209790. g.fillAll (Colours::white);
  209791. }
  209792. void WebBrowserComponent::checkWindowAssociation()
  209793. {
  209794. if (isShowing())
  209795. {
  209796. if (browser->browser == 0 && getPeer() != 0)
  209797. {
  209798. browser->createBrowser();
  209799. reloadLastURL();
  209800. }
  209801. else
  209802. {
  209803. if (blankPageShown)
  209804. goBack();
  209805. }
  209806. }
  209807. else
  209808. {
  209809. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209810. {
  209811. // when the component becomes invisible, some stuff like flash
  209812. // carries on playing audio, so we need to force it onto a blank
  209813. // page to avoid this..
  209814. blankPageShown = true;
  209815. browser->goToURL ("about:blank", 0, 0);
  209816. }
  209817. }
  209818. }
  209819. void WebBrowserComponent::reloadLastURL()
  209820. {
  209821. if (lastURL.isNotEmpty())
  209822. {
  209823. goToURL (lastURL, &lastHeaders, &lastPostData);
  209824. lastURL = String::empty;
  209825. }
  209826. }
  209827. void WebBrowserComponent::parentHierarchyChanged()
  209828. {
  209829. checkWindowAssociation();
  209830. }
  209831. void WebBrowserComponent::resized()
  209832. {
  209833. browser->setSize (getWidth(), getHeight());
  209834. }
  209835. void WebBrowserComponent::visibilityChanged()
  209836. {
  209837. checkWindowAssociation();
  209838. }
  209839. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209840. {
  209841. return true;
  209842. }
  209843. #endif
  209844. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209845. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209846. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209847. // compiled on its own).
  209848. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209849. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209850. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209851. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209852. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209853. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209854. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209855. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209856. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209857. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209858. #define WGL_ACCELERATION_ARB 0x2003
  209859. #define WGL_SWAP_METHOD_ARB 0x2007
  209860. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209861. #define WGL_PIXEL_TYPE_ARB 0x2013
  209862. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209863. #define WGL_COLOR_BITS_ARB 0x2014
  209864. #define WGL_RED_BITS_ARB 0x2015
  209865. #define WGL_GREEN_BITS_ARB 0x2017
  209866. #define WGL_BLUE_BITS_ARB 0x2019
  209867. #define WGL_ALPHA_BITS_ARB 0x201B
  209868. #define WGL_DEPTH_BITS_ARB 0x2022
  209869. #define WGL_STENCIL_BITS_ARB 0x2023
  209870. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209871. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209872. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209873. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209874. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209875. #define WGL_STEREO_ARB 0x2012
  209876. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  209877. #define WGL_SAMPLES_ARB 0x2042
  209878. #define WGL_TYPE_RGBA_ARB 0x202B
  209879. static void getWglExtensions (HDC dc, StringArray& result) throw()
  209880. {
  209881. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  209882. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  209883. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  209884. else
  209885. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  209886. }
  209887. class WindowedGLContext : public OpenGLContext
  209888. {
  209889. public:
  209890. WindowedGLContext (Component* const component_,
  209891. HGLRC contextToShareWith,
  209892. const OpenGLPixelFormat& pixelFormat)
  209893. : renderContext (0),
  209894. dc (0),
  209895. component (component_)
  209896. {
  209897. jassert (component != 0);
  209898. createNativeWindow();
  209899. // Use a default pixel format that should be supported everywhere
  209900. PIXELFORMATDESCRIPTOR pfd;
  209901. zerostruct (pfd);
  209902. pfd.nSize = sizeof (pfd);
  209903. pfd.nVersion = 1;
  209904. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  209905. pfd.iPixelType = PFD_TYPE_RGBA;
  209906. pfd.cColorBits = 24;
  209907. pfd.cDepthBits = 16;
  209908. const int format = ChoosePixelFormat (dc, &pfd);
  209909. if (format != 0)
  209910. SetPixelFormat (dc, format, &pfd);
  209911. renderContext = wglCreateContext (dc);
  209912. makeActive();
  209913. setPixelFormat (pixelFormat);
  209914. if (contextToShareWith != 0 && renderContext != 0)
  209915. wglShareLists (contextToShareWith, renderContext);
  209916. }
  209917. ~WindowedGLContext()
  209918. {
  209919. deleteContext();
  209920. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209921. nativeWindow = 0;
  209922. }
  209923. void deleteContext()
  209924. {
  209925. makeInactive();
  209926. if (renderContext != 0)
  209927. {
  209928. wglDeleteContext (renderContext);
  209929. renderContext = 0;
  209930. }
  209931. }
  209932. bool makeActive() const throw()
  209933. {
  209934. jassert (renderContext != 0);
  209935. return wglMakeCurrent (dc, renderContext) != 0;
  209936. }
  209937. bool makeInactive() const throw()
  209938. {
  209939. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  209940. }
  209941. bool isActive() const throw()
  209942. {
  209943. return wglGetCurrentContext() == renderContext;
  209944. }
  209945. const OpenGLPixelFormat getPixelFormat() const
  209946. {
  209947. OpenGLPixelFormat pf;
  209948. makeActive();
  209949. StringArray availableExtensions;
  209950. getWglExtensions (dc, availableExtensions);
  209951. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  209952. return pf;
  209953. }
  209954. void* getRawContext() const throw()
  209955. {
  209956. return renderContext;
  209957. }
  209958. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  209959. {
  209960. makeActive();
  209961. PIXELFORMATDESCRIPTOR pfd;
  209962. zerostruct (pfd);
  209963. pfd.nSize = sizeof (pfd);
  209964. pfd.nVersion = 1;
  209965. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  209966. pfd.iPixelType = PFD_TYPE_RGBA;
  209967. pfd.iLayerType = PFD_MAIN_PLANE;
  209968. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  209969. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  209970. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  209971. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  209972. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  209973. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  209974. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  209975. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  209976. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  209977. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  209978. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  209979. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  209980. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  209981. int format = 0;
  209982. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  209983. StringArray availableExtensions;
  209984. getWglExtensions (dc, availableExtensions);
  209985. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  209986. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  209987. {
  209988. int attributes[64];
  209989. int n = 0;
  209990. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  209991. attributes[n++] = GL_TRUE;
  209992. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  209993. attributes[n++] = GL_TRUE;
  209994. attributes[n++] = WGL_ACCELERATION_ARB;
  209995. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  209996. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  209997. attributes[n++] = GL_TRUE;
  209998. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  209999. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210000. attributes[n++] = WGL_COLOR_BITS_ARB;
  210001. attributes[n++] = pfd.cColorBits;
  210002. attributes[n++] = WGL_RED_BITS_ARB;
  210003. attributes[n++] = pixelFormat.redBits;
  210004. attributes[n++] = WGL_GREEN_BITS_ARB;
  210005. attributes[n++] = pixelFormat.greenBits;
  210006. attributes[n++] = WGL_BLUE_BITS_ARB;
  210007. attributes[n++] = pixelFormat.blueBits;
  210008. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210009. attributes[n++] = pixelFormat.alphaBits;
  210010. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210011. attributes[n++] = pixelFormat.depthBufferBits;
  210012. if (pixelFormat.stencilBufferBits > 0)
  210013. {
  210014. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210015. attributes[n++] = pixelFormat.stencilBufferBits;
  210016. }
  210017. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210018. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210019. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210020. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210021. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210022. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210023. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210024. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210025. if (availableExtensions.contains ("WGL_ARB_multisample")
  210026. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210027. {
  210028. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210029. attributes[n++] = 1;
  210030. attributes[n++] = WGL_SAMPLES_ARB;
  210031. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210032. }
  210033. attributes[n++] = 0;
  210034. UINT formatsCount;
  210035. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210036. (void) ok;
  210037. jassert (ok);
  210038. }
  210039. else
  210040. {
  210041. format = ChoosePixelFormat (dc, &pfd);
  210042. }
  210043. if (format != 0)
  210044. {
  210045. makeInactive();
  210046. // win32 can't change the pixel format of a window, so need to delete the
  210047. // old one and create a new one..
  210048. jassert (nativeWindow != 0);
  210049. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210050. nativeWindow = 0;
  210051. createNativeWindow();
  210052. if (SetPixelFormat (dc, format, &pfd))
  210053. {
  210054. wglDeleteContext (renderContext);
  210055. renderContext = wglCreateContext (dc);
  210056. jassert (renderContext != 0);
  210057. return renderContext != 0;
  210058. }
  210059. }
  210060. return false;
  210061. }
  210062. void updateWindowPosition (int x, int y, int w, int h, int)
  210063. {
  210064. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210065. x, y, w, h,
  210066. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210067. }
  210068. void repaint()
  210069. {
  210070. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210071. }
  210072. void swapBuffers()
  210073. {
  210074. SwapBuffers (dc);
  210075. }
  210076. bool setSwapInterval (int numFramesPerSwap)
  210077. {
  210078. makeActive();
  210079. StringArray availableExtensions;
  210080. getWglExtensions (dc, availableExtensions);
  210081. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210082. return availableExtensions.contains ("WGL_EXT_swap_control")
  210083. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210084. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210085. }
  210086. int getSwapInterval() const
  210087. {
  210088. makeActive();
  210089. StringArray availableExtensions;
  210090. getWglExtensions (dc, availableExtensions);
  210091. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210092. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210093. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210094. return wglGetSwapIntervalEXT();
  210095. return 0;
  210096. }
  210097. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210098. {
  210099. jassert (isActive());
  210100. StringArray availableExtensions;
  210101. getWglExtensions (dc, availableExtensions);
  210102. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210103. int numTypes = 0;
  210104. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210105. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210106. {
  210107. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210108. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210109. jassertfalse;
  210110. }
  210111. else
  210112. {
  210113. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210114. }
  210115. OpenGLPixelFormat pf;
  210116. for (int i = 0; i < numTypes; ++i)
  210117. {
  210118. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210119. {
  210120. bool alreadyListed = false;
  210121. for (int j = results.size(); --j >= 0;)
  210122. if (pf == *results.getUnchecked(j))
  210123. alreadyListed = true;
  210124. if (! alreadyListed)
  210125. results.add (new OpenGLPixelFormat (pf));
  210126. }
  210127. }
  210128. }
  210129. void* getNativeWindowHandle() const
  210130. {
  210131. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210132. }
  210133. HGLRC renderContext;
  210134. private:
  210135. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210136. Component* const component;
  210137. HDC dc;
  210138. void createNativeWindow()
  210139. {
  210140. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210141. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210142. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210143. nativeWindow->dontRepaint = true;
  210144. nativeWindow->setVisible (true);
  210145. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210146. }
  210147. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210148. OpenGLPixelFormat& result,
  210149. const StringArray& availableExtensions) const throw()
  210150. {
  210151. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210152. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210153. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210154. {
  210155. int attributes[32];
  210156. int numAttributes = 0;
  210157. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210158. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210159. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210160. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210161. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210162. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210163. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210164. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210165. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210166. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210167. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210168. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210169. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210170. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210171. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210172. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210173. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210174. int values[32];
  210175. zeromem (values, sizeof (values));
  210176. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210177. {
  210178. int n = 0;
  210179. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210180. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210181. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210182. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210183. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210184. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210185. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210186. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210187. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210188. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210189. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210190. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210191. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210192. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210193. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210194. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210195. return isValidFormat;
  210196. }
  210197. else
  210198. {
  210199. jassertfalse;
  210200. }
  210201. }
  210202. else
  210203. {
  210204. PIXELFORMATDESCRIPTOR pfd;
  210205. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210206. {
  210207. result.redBits = pfd.cRedBits;
  210208. result.greenBits = pfd.cGreenBits;
  210209. result.blueBits = pfd.cBlueBits;
  210210. result.alphaBits = pfd.cAlphaBits;
  210211. result.depthBufferBits = pfd.cDepthBits;
  210212. result.stencilBufferBits = pfd.cStencilBits;
  210213. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210214. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210215. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210216. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210217. result.fullSceneAntiAliasingNumSamples = 0;
  210218. return true;
  210219. }
  210220. else
  210221. {
  210222. jassertfalse;
  210223. }
  210224. }
  210225. return false;
  210226. }
  210227. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210228. };
  210229. OpenGLContext* OpenGLComponent::createContext()
  210230. {
  210231. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210232. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210233. preferredPixelFormat));
  210234. return (c->renderContext != 0) ? c.release() : 0;
  210235. }
  210236. void* OpenGLComponent::getNativeWindowHandle() const
  210237. {
  210238. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210239. }
  210240. void juce_glViewport (const int w, const int h)
  210241. {
  210242. glViewport (0, 0, w, h);
  210243. }
  210244. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210245. OwnedArray <OpenGLPixelFormat>& results)
  210246. {
  210247. Component tempComp;
  210248. {
  210249. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210250. wc.makeActive();
  210251. wc.findAlternativeOpenGLPixelFormats (results);
  210252. }
  210253. }
  210254. #endif
  210255. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210256. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210257. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210258. // compiled on its own).
  210259. #if JUCE_INCLUDED_FILE
  210260. #if JUCE_USE_CDREADER
  210261. namespace CDReaderHelpers
  210262. {
  210263. #define FILE_ANY_ACCESS 0
  210264. #ifndef FILE_READ_ACCESS
  210265. #define FILE_READ_ACCESS 1
  210266. #endif
  210267. #ifndef FILE_WRITE_ACCESS
  210268. #define FILE_WRITE_ACCESS 2
  210269. #endif
  210270. #define METHOD_BUFFERED 0
  210271. #define IOCTL_SCSI_BASE 4
  210272. #define SCSI_IOCTL_DATA_OUT 0
  210273. #define SCSI_IOCTL_DATA_IN 1
  210274. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210275. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210276. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210277. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210278. #define SENSE_LEN 14
  210279. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210280. #define SRB_DIR_IN 0x08
  210281. #define SRB_DIR_OUT 0x10
  210282. #define SRB_EVENT_NOTIFY 0x40
  210283. #define SC_HA_INQUIRY 0x00
  210284. #define SC_GET_DEV_TYPE 0x01
  210285. #define SC_EXEC_SCSI_CMD 0x02
  210286. #define SS_PENDING 0x00
  210287. #define SS_COMP 0x01
  210288. #define SS_ERR 0x04
  210289. enum
  210290. {
  210291. READTYPE_ANY = 0,
  210292. READTYPE_ATAPI1 = 1,
  210293. READTYPE_ATAPI2 = 2,
  210294. READTYPE_READ6 = 3,
  210295. READTYPE_READ10 = 4,
  210296. READTYPE_READ_D8 = 5,
  210297. READTYPE_READ_D4 = 6,
  210298. READTYPE_READ_D4_1 = 7,
  210299. READTYPE_READ10_2 = 8
  210300. };
  210301. struct SCSI_PASS_THROUGH
  210302. {
  210303. USHORT Length;
  210304. UCHAR ScsiStatus;
  210305. UCHAR PathId;
  210306. UCHAR TargetId;
  210307. UCHAR Lun;
  210308. UCHAR CdbLength;
  210309. UCHAR SenseInfoLength;
  210310. UCHAR DataIn;
  210311. ULONG DataTransferLength;
  210312. ULONG TimeOutValue;
  210313. ULONG DataBufferOffset;
  210314. ULONG SenseInfoOffset;
  210315. UCHAR Cdb[16];
  210316. };
  210317. struct SCSI_PASS_THROUGH_DIRECT
  210318. {
  210319. USHORT Length;
  210320. UCHAR ScsiStatus;
  210321. UCHAR PathId;
  210322. UCHAR TargetId;
  210323. UCHAR Lun;
  210324. UCHAR CdbLength;
  210325. UCHAR SenseInfoLength;
  210326. UCHAR DataIn;
  210327. ULONG DataTransferLength;
  210328. ULONG TimeOutValue;
  210329. PVOID DataBuffer;
  210330. ULONG SenseInfoOffset;
  210331. UCHAR Cdb[16];
  210332. };
  210333. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210334. {
  210335. SCSI_PASS_THROUGH_DIRECT spt;
  210336. ULONG Filler;
  210337. UCHAR ucSenseBuf[32];
  210338. };
  210339. struct SCSI_ADDRESS
  210340. {
  210341. ULONG Length;
  210342. UCHAR PortNumber;
  210343. UCHAR PathId;
  210344. UCHAR TargetId;
  210345. UCHAR Lun;
  210346. };
  210347. #pragma pack(1)
  210348. struct SRB_GDEVBlock
  210349. {
  210350. BYTE SRB_Cmd;
  210351. BYTE SRB_Status;
  210352. BYTE SRB_HaID;
  210353. BYTE SRB_Flags;
  210354. DWORD SRB_Hdr_Rsvd;
  210355. BYTE SRB_Target;
  210356. BYTE SRB_Lun;
  210357. BYTE SRB_DeviceType;
  210358. BYTE SRB_Rsvd1;
  210359. BYTE pad[68];
  210360. };
  210361. struct SRB_ExecSCSICmd
  210362. {
  210363. BYTE SRB_Cmd;
  210364. BYTE SRB_Status;
  210365. BYTE SRB_HaID;
  210366. BYTE SRB_Flags;
  210367. DWORD SRB_Hdr_Rsvd;
  210368. BYTE SRB_Target;
  210369. BYTE SRB_Lun;
  210370. WORD SRB_Rsvd1;
  210371. DWORD SRB_BufLen;
  210372. BYTE *SRB_BufPointer;
  210373. BYTE SRB_SenseLen;
  210374. BYTE SRB_CDBLen;
  210375. BYTE SRB_HaStat;
  210376. BYTE SRB_TargStat;
  210377. VOID *SRB_PostProc;
  210378. BYTE SRB_Rsvd2[20];
  210379. BYTE CDBByte[16];
  210380. BYTE SenseArea[SENSE_LEN + 2];
  210381. };
  210382. struct SRB
  210383. {
  210384. BYTE SRB_Cmd;
  210385. BYTE SRB_Status;
  210386. BYTE SRB_HaId;
  210387. BYTE SRB_Flags;
  210388. DWORD SRB_Hdr_Rsvd;
  210389. };
  210390. struct TOCTRACK
  210391. {
  210392. BYTE rsvd;
  210393. BYTE ADR;
  210394. BYTE trackNumber;
  210395. BYTE rsvd2;
  210396. BYTE addr[4];
  210397. };
  210398. struct TOC
  210399. {
  210400. WORD tocLen;
  210401. BYTE firstTrack;
  210402. BYTE lastTrack;
  210403. TOCTRACK tracks[100];
  210404. };
  210405. #pragma pack()
  210406. struct CDDeviceDescription
  210407. {
  210408. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210409. {
  210410. }
  210411. void createDescription (const char* data)
  210412. {
  210413. description << String (data + 8, 8).trim() // vendor
  210414. << ' ' << String (data + 16, 16).trim() // product id
  210415. << ' ' << String (data + 32, 4).trim(); // rev
  210416. }
  210417. String description;
  210418. BYTE ha, tgt, lun;
  210419. char scsiDriveLetter; // will be 0 if not using scsi
  210420. };
  210421. class CDReadBuffer
  210422. {
  210423. public:
  210424. CDReadBuffer (const int numberOfFrames)
  210425. : startFrame (0), numFrames (0), dataStartOffset (0),
  210426. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210427. buffer (bufferSize), wantsIndex (false)
  210428. {
  210429. }
  210430. bool isZero() const throw()
  210431. {
  210432. for (int i = 0; i < dataLength; ++i)
  210433. if (buffer [dataStartOffset + i] != 0)
  210434. return false;
  210435. return true;
  210436. }
  210437. int startFrame, numFrames, dataStartOffset;
  210438. int dataLength, bufferSize, index;
  210439. HeapBlock<BYTE> buffer;
  210440. bool wantsIndex;
  210441. };
  210442. class CDDeviceHandle;
  210443. class CDController
  210444. {
  210445. public:
  210446. CDController() : initialised (false) {}
  210447. virtual ~CDController() {}
  210448. virtual bool read (CDReadBuffer&) = 0;
  210449. virtual void shutDown() {}
  210450. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210451. int getLastIndex();
  210452. public:
  210453. CDDeviceHandle* deviceInfo;
  210454. int framesToCheck, framesOverlap;
  210455. bool initialised;
  210456. void prepare (SRB_ExecSCSICmd& s);
  210457. void perform (SRB_ExecSCSICmd& s);
  210458. void setPaused (bool paused);
  210459. };
  210460. class CDDeviceHandle
  210461. {
  210462. public:
  210463. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210464. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210465. {
  210466. }
  210467. ~CDDeviceHandle()
  210468. {
  210469. if (controller != 0)
  210470. {
  210471. controller->shutDown();
  210472. controller = 0;
  210473. }
  210474. if (scsiHandle != 0)
  210475. CloseHandle (scsiHandle);
  210476. }
  210477. bool readTOC (TOC* lpToc);
  210478. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210479. void openDrawer (bool shouldBeOpen);
  210480. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210481. CDDeviceDescription info;
  210482. HANDLE scsiHandle;
  210483. BYTE readType;
  210484. private:
  210485. ScopedPointer<CDController> controller;
  210486. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210487. };
  210488. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210489. {
  210490. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210491. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210492. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210493. if (h == INVALID_HANDLE_VALUE)
  210494. {
  210495. flags ^= GENERIC_WRITE;
  210496. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210497. }
  210498. return h;
  210499. }
  210500. void findCDDevices (Array<CDDeviceDescription>& list)
  210501. {
  210502. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210503. {
  210504. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210505. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210506. {
  210507. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210508. if (h != INVALID_HANDLE_VALUE)
  210509. {
  210510. char buffer[100];
  210511. zeromem (buffer, sizeof (buffer));
  210512. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210513. zerostruct (p);
  210514. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210515. p.spt.CdbLength = 6;
  210516. p.spt.SenseInfoLength = 24;
  210517. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210518. p.spt.DataTransferLength = sizeof (buffer);
  210519. p.spt.TimeOutValue = 2;
  210520. p.spt.DataBuffer = buffer;
  210521. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210522. p.spt.Cdb[0] = 0x12;
  210523. p.spt.Cdb[4] = 100;
  210524. DWORD bytesReturned = 0;
  210525. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210526. &p, sizeof (p), &p, sizeof (p),
  210527. &bytesReturned, 0) != 0)
  210528. {
  210529. CDDeviceDescription dev;
  210530. dev.scsiDriveLetter = driveLetter;
  210531. dev.createDescription (buffer);
  210532. SCSI_ADDRESS scsiAddr;
  210533. zerostruct (scsiAddr);
  210534. scsiAddr.Length = sizeof (scsiAddr);
  210535. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210536. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210537. &bytesReturned, 0) != 0)
  210538. {
  210539. dev.ha = scsiAddr.PortNumber;
  210540. dev.tgt = scsiAddr.TargetId;
  210541. dev.lun = scsiAddr.Lun;
  210542. list.add (dev);
  210543. }
  210544. }
  210545. CloseHandle (h);
  210546. }
  210547. }
  210548. }
  210549. }
  210550. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210551. HANDLE& deviceHandle, const bool retryOnFailure)
  210552. {
  210553. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210554. zerostruct (s);
  210555. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210556. s.spt.CdbLength = srb->SRB_CDBLen;
  210557. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210558. ? SCSI_IOCTL_DATA_IN
  210559. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210560. ? SCSI_IOCTL_DATA_OUT
  210561. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210562. s.spt.DataTransferLength = srb->SRB_BufLen;
  210563. s.spt.TimeOutValue = 5;
  210564. s.spt.DataBuffer = srb->SRB_BufPointer;
  210565. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210566. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210567. srb->SRB_Status = SS_ERR;
  210568. srb->SRB_TargStat = 0x0004;
  210569. DWORD bytesReturned = 0;
  210570. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210571. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210572. {
  210573. srb->SRB_Status = SS_COMP;
  210574. }
  210575. else if (retryOnFailure)
  210576. {
  210577. const DWORD error = GetLastError();
  210578. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210579. {
  210580. if (error != ERROR_INVALID_HANDLE)
  210581. CloseHandle (deviceHandle);
  210582. deviceHandle = createSCSIDeviceHandle (driveLetter);
  210583. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210584. }
  210585. }
  210586. return srb->SRB_Status;
  210587. }
  210588. // Controller types..
  210589. class ControllerType1 : public CDController
  210590. {
  210591. public:
  210592. ControllerType1() {}
  210593. bool read (CDReadBuffer& rb)
  210594. {
  210595. if (rb.numFrames * 2352 > rb.bufferSize)
  210596. return false;
  210597. SRB_ExecSCSICmd s;
  210598. prepare (s);
  210599. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210600. s.SRB_BufLen = rb.bufferSize;
  210601. s.SRB_BufPointer = rb.buffer;
  210602. s.SRB_CDBLen = 12;
  210603. s.CDBByte[0] = 0xBE;
  210604. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210605. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210606. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210607. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210608. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  210609. perform (s);
  210610. if (s.SRB_Status != SS_COMP)
  210611. return false;
  210612. rb.dataLength = rb.numFrames * 2352;
  210613. rb.dataStartOffset = 0;
  210614. return true;
  210615. }
  210616. };
  210617. class ControllerType2 : public CDController
  210618. {
  210619. public:
  210620. ControllerType2() {}
  210621. void shutDown()
  210622. {
  210623. if (initialised)
  210624. {
  210625. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  210626. SRB_ExecSCSICmd s;
  210627. prepare (s);
  210628. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  210629. s.SRB_BufLen = 0x0C;
  210630. s.SRB_BufPointer = bufPointer;
  210631. s.SRB_CDBLen = 6;
  210632. s.CDBByte[0] = 0x15;
  210633. s.CDBByte[4] = 0x0C;
  210634. perform (s);
  210635. }
  210636. }
  210637. bool init()
  210638. {
  210639. SRB_ExecSCSICmd s;
  210640. s.SRB_Status = SS_ERR;
  210641. if (deviceInfo->readType == READTYPE_READ10_2)
  210642. {
  210643. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  210644. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  210645. for (int i = 0; i < 2; ++i)
  210646. {
  210647. prepare (s);
  210648. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210649. s.SRB_BufLen = 0x14;
  210650. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  210651. s.SRB_CDBLen = 6;
  210652. s.CDBByte[0] = 0x15;
  210653. s.CDBByte[1] = 0x10;
  210654. s.CDBByte[4] = 0x14;
  210655. perform (s);
  210656. if (s.SRB_Status != SS_COMP)
  210657. return false;
  210658. }
  210659. }
  210660. else
  210661. {
  210662. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  210663. prepare (s);
  210664. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210665. s.SRB_BufLen = 0x0C;
  210666. s.SRB_BufPointer = bufPointer;
  210667. s.SRB_CDBLen = 6;
  210668. s.CDBByte[0] = 0x15;
  210669. s.CDBByte[4] = 0x0C;
  210670. perform (s);
  210671. }
  210672. return s.SRB_Status == SS_COMP;
  210673. }
  210674. bool read (CDReadBuffer& rb)
  210675. {
  210676. if (rb.numFrames * 2352 > rb.bufferSize)
  210677. return false;
  210678. if (! initialised)
  210679. {
  210680. initialised = init();
  210681. if (! initialised)
  210682. return false;
  210683. }
  210684. SRB_ExecSCSICmd s;
  210685. prepare (s);
  210686. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210687. s.SRB_BufLen = rb.bufferSize;
  210688. s.SRB_BufPointer = rb.buffer;
  210689. s.SRB_CDBLen = 10;
  210690. s.CDBByte[0] = 0x28;
  210691. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210692. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210693. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210694. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210695. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210696. perform (s);
  210697. if (s.SRB_Status != SS_COMP)
  210698. return false;
  210699. rb.dataLength = rb.numFrames * 2352;
  210700. rb.dataStartOffset = 0;
  210701. return true;
  210702. }
  210703. };
  210704. class ControllerType3 : public CDController
  210705. {
  210706. public:
  210707. ControllerType3() {}
  210708. bool read (CDReadBuffer& rb)
  210709. {
  210710. if (rb.numFrames * 2352 > rb.bufferSize)
  210711. return false;
  210712. if (! initialised)
  210713. {
  210714. setPaused (false);
  210715. initialised = true;
  210716. }
  210717. SRB_ExecSCSICmd s;
  210718. prepare (s);
  210719. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210720. s.SRB_BufLen = rb.numFrames * 2352;
  210721. s.SRB_BufPointer = rb.buffer;
  210722. s.SRB_CDBLen = 12;
  210723. s.CDBByte[0] = 0xD8;
  210724. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210725. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210726. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210727. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  210728. perform (s);
  210729. if (s.SRB_Status != SS_COMP)
  210730. return false;
  210731. rb.dataLength = rb.numFrames * 2352;
  210732. rb.dataStartOffset = 0;
  210733. return true;
  210734. }
  210735. };
  210736. class ControllerType4 : public CDController
  210737. {
  210738. public:
  210739. ControllerType4() {}
  210740. bool selectD4Mode()
  210741. {
  210742. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  210743. SRB_ExecSCSICmd s;
  210744. prepare (s);
  210745. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210746. s.SRB_CDBLen = 6;
  210747. s.SRB_BufLen = 12;
  210748. s.SRB_BufPointer = bufPointer;
  210749. s.CDBByte[0] = 0x15;
  210750. s.CDBByte[1] = 0x10;
  210751. s.CDBByte[4] = 0x08;
  210752. perform (s);
  210753. return s.SRB_Status == SS_COMP;
  210754. }
  210755. bool read (CDReadBuffer& rb)
  210756. {
  210757. if (rb.numFrames * 2352 > rb.bufferSize)
  210758. return false;
  210759. if (! initialised)
  210760. {
  210761. setPaused (true);
  210762. if (deviceInfo->readType == READTYPE_READ_D4_1)
  210763. selectD4Mode();
  210764. initialised = true;
  210765. }
  210766. SRB_ExecSCSICmd s;
  210767. prepare (s);
  210768. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210769. s.SRB_BufLen = rb.bufferSize;
  210770. s.SRB_BufPointer = rb.buffer;
  210771. s.SRB_CDBLen = 10;
  210772. s.CDBByte[0] = 0xD4;
  210773. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210774. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210775. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210776. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210777. perform (s);
  210778. if (s.SRB_Status != SS_COMP)
  210779. return false;
  210780. rb.dataLength = rb.numFrames * 2352;
  210781. rb.dataStartOffset = 0;
  210782. return true;
  210783. }
  210784. };
  210785. void CDController::prepare (SRB_ExecSCSICmd& s)
  210786. {
  210787. zerostruct (s);
  210788. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210789. s.SRB_HaID = deviceInfo->info.ha;
  210790. s.SRB_Target = deviceInfo->info.tgt;
  210791. s.SRB_Lun = deviceInfo->info.lun;
  210792. s.SRB_SenseLen = SENSE_LEN;
  210793. }
  210794. void CDController::perform (SRB_ExecSCSICmd& s)
  210795. {
  210796. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210797. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  210798. }
  210799. void CDController::setPaused (bool paused)
  210800. {
  210801. SRB_ExecSCSICmd s;
  210802. prepare (s);
  210803. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210804. s.SRB_CDBLen = 10;
  210805. s.CDBByte[0] = 0x4B;
  210806. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  210807. perform (s);
  210808. }
  210809. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  210810. {
  210811. if (overlapBuffer != 0)
  210812. {
  210813. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  210814. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  210815. if (doJitter
  210816. && overlapBuffer->startFrame > 0
  210817. && overlapBuffer->numFrames > 0
  210818. && overlapBuffer->dataLength > 0)
  210819. {
  210820. const int numFrames = rb.numFrames;
  210821. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  210822. {
  210823. rb.startFrame -= framesOverlap;
  210824. if (framesToCheck < framesOverlap
  210825. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  210826. rb.numFrames += framesOverlap;
  210827. }
  210828. else
  210829. {
  210830. overlapBuffer->dataLength = 0;
  210831. overlapBuffer->startFrame = 0;
  210832. overlapBuffer->numFrames = 0;
  210833. }
  210834. }
  210835. if (! read (rb))
  210836. return false;
  210837. if (doJitter)
  210838. {
  210839. const int checkLen = framesToCheck * 2352;
  210840. const int maxToCheck = rb.dataLength - checkLen;
  210841. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  210842. return true;
  210843. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  210844. bool found = false;
  210845. for (int i = 0; i < maxToCheck; ++i)
  210846. {
  210847. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  210848. {
  210849. i += checkLen;
  210850. rb.dataStartOffset = i;
  210851. rb.dataLength -= i;
  210852. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  210853. found = true;
  210854. break;
  210855. }
  210856. }
  210857. rb.numFrames = rb.dataLength / 2352;
  210858. rb.dataLength = 2352 * rb.numFrames;
  210859. if (! found)
  210860. return false;
  210861. }
  210862. if (canDoJitter)
  210863. {
  210864. memcpy (overlapBuffer->buffer,
  210865. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  210866. 2352 * framesToCheck);
  210867. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  210868. overlapBuffer->numFrames = framesToCheck;
  210869. overlapBuffer->dataLength = 2352 * framesToCheck;
  210870. overlapBuffer->dataStartOffset = 0;
  210871. }
  210872. else
  210873. {
  210874. overlapBuffer->startFrame = 0;
  210875. overlapBuffer->numFrames = 0;
  210876. overlapBuffer->dataLength = 0;
  210877. }
  210878. return true;
  210879. }
  210880. return read (rb);
  210881. }
  210882. int CDController::getLastIndex()
  210883. {
  210884. char qdata[100];
  210885. SRB_ExecSCSICmd s;
  210886. prepare (s);
  210887. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210888. s.SRB_BufLen = sizeof (qdata);
  210889. s.SRB_BufPointer = (BYTE*) qdata;
  210890. s.SRB_CDBLen = 12;
  210891. s.CDBByte[0] = 0x42;
  210892. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210893. s.CDBByte[2] = 64;
  210894. s.CDBByte[3] = 1; // get current position
  210895. s.CDBByte[7] = 0;
  210896. s.CDBByte[8] = (BYTE) sizeof (qdata);
  210897. perform (s);
  210898. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  210899. }
  210900. bool CDDeviceHandle::readTOC (TOC* lpToc)
  210901. {
  210902. SRB_ExecSCSICmd s;
  210903. zerostruct (s);
  210904. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210905. s.SRB_HaID = info.ha;
  210906. s.SRB_Target = info.tgt;
  210907. s.SRB_Lun = info.lun;
  210908. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210909. s.SRB_BufLen = 0x324;
  210910. s.SRB_BufPointer = (BYTE*) lpToc;
  210911. s.SRB_SenseLen = 0x0E;
  210912. s.SRB_CDBLen = 0x0A;
  210913. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210914. s.CDBByte[0] = 0x43;
  210915. s.CDBByte[1] = 0x00;
  210916. s.CDBByte[7] = 0x03;
  210917. s.CDBByte[8] = 0x24;
  210918. performScsiCommand (s.SRB_PostProc, s);
  210919. return (s.SRB_Status == SS_COMP);
  210920. }
  210921. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  210922. {
  210923. ResetEvent (event);
  210924. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  210925. if (status == SS_PENDING)
  210926. WaitForSingleObject (event, 4000);
  210927. CloseHandle (event);
  210928. }
  210929. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  210930. {
  210931. if (controller == 0)
  210932. {
  210933. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  210934. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  210935. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  210936. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  210937. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  210938. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  210939. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  210940. }
  210941. buffer.index = 0;
  210942. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  210943. {
  210944. if (buffer.wantsIndex)
  210945. buffer.index = controller->getLastIndex();
  210946. return true;
  210947. }
  210948. return false;
  210949. }
  210950. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  210951. {
  210952. if (shouldBeOpen)
  210953. {
  210954. if (controller != 0)
  210955. {
  210956. controller->shutDown();
  210957. controller = 0;
  210958. }
  210959. if (scsiHandle != 0)
  210960. {
  210961. CloseHandle (scsiHandle);
  210962. scsiHandle = 0;
  210963. }
  210964. }
  210965. SRB_ExecSCSICmd s;
  210966. zerostruct (s);
  210967. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210968. s.SRB_HaID = info.ha;
  210969. s.SRB_Target = info.tgt;
  210970. s.SRB_Lun = info.lun;
  210971. s.SRB_SenseLen = SENSE_LEN;
  210972. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210973. s.SRB_BufLen = 0;
  210974. s.SRB_BufPointer = 0;
  210975. s.SRB_CDBLen = 12;
  210976. s.CDBByte[0] = 0x1b;
  210977. s.CDBByte[1] = (BYTE) (info.lun << 5);
  210978. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  210979. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210980. performScsiCommand (s.SRB_PostProc, s);
  210981. }
  210982. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  210983. {
  210984. controller = newController;
  210985. readType = (BYTE) type;
  210986. controller->deviceInfo = this;
  210987. controller->framesToCheck = 1;
  210988. controller->framesOverlap = 3;
  210989. bool passed = false;
  210990. memset (rb.buffer, 0xcd, rb.bufferSize);
  210991. if (controller->read (rb))
  210992. {
  210993. passed = true;
  210994. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  210995. int wrong = 0;
  210996. for (int i = rb.dataLength / 4; --i >= 0;)
  210997. {
  210998. if (*p++ == (int) 0xcdcdcdcd)
  210999. {
  211000. if (++wrong == 4)
  211001. {
  211002. passed = false;
  211003. break;
  211004. }
  211005. }
  211006. else
  211007. {
  211008. wrong = 0;
  211009. }
  211010. }
  211011. }
  211012. if (! passed)
  211013. {
  211014. controller->shutDown();
  211015. controller = 0;
  211016. }
  211017. return passed;
  211018. }
  211019. struct CDDeviceWrapper
  211020. {
  211021. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  211022. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  211023. {
  211024. // xxx jitter never seemed to actually be enabled (??)
  211025. }
  211026. CDDeviceHandle deviceHandle;
  211027. CDReadBuffer overlapBuffer;
  211028. bool jitter;
  211029. };
  211030. int getAddressOfTrack (const TOCTRACK& t) throw()
  211031. {
  211032. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  211033. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  211034. }
  211035. const int samplesPerFrame = 44100 / 75;
  211036. const int bytesPerFrame = samplesPerFrame * 4;
  211037. const int framesPerIndexRead = 4;
  211038. }
  211039. const StringArray AudioCDReader::getAvailableCDNames()
  211040. {
  211041. using namespace CDReaderHelpers;
  211042. StringArray results;
  211043. Array<CDDeviceDescription> list;
  211044. findCDDevices (list);
  211045. for (int i = 0; i < list.size(); ++i)
  211046. {
  211047. String s;
  211048. if (list[i].scsiDriveLetter > 0)
  211049. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211050. s << list[i].description;
  211051. results.add (s);
  211052. }
  211053. return results;
  211054. }
  211055. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211056. {
  211057. using namespace CDReaderHelpers;
  211058. Array<CDDeviceDescription> list;
  211059. findCDDevices (list);
  211060. if (isPositiveAndBelow (deviceIndex, list.size()))
  211061. {
  211062. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  211063. if (h != INVALID_HANDLE_VALUE)
  211064. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  211065. }
  211066. return 0;
  211067. }
  211068. AudioCDReader::AudioCDReader (void* handle_)
  211069. : AudioFormatReader (0, "CD Audio"),
  211070. handle (handle_),
  211071. indexingEnabled (false),
  211072. lastIndex (0),
  211073. firstFrameInBuffer (0),
  211074. samplesInBuffer (0)
  211075. {
  211076. using namespace CDReaderHelpers;
  211077. jassert (handle_ != 0);
  211078. refreshTrackLengths();
  211079. sampleRate = 44100.0;
  211080. bitsPerSample = 16;
  211081. numChannels = 2;
  211082. usesFloatingPointData = false;
  211083. buffer.setSize (4 * bytesPerFrame, true);
  211084. }
  211085. AudioCDReader::~AudioCDReader()
  211086. {
  211087. using namespace CDReaderHelpers;
  211088. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211089. delete device;
  211090. }
  211091. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211092. int64 startSampleInFile, int numSamples)
  211093. {
  211094. using namespace CDReaderHelpers;
  211095. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211096. bool ok = true;
  211097. while (numSamples > 0)
  211098. {
  211099. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211100. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211101. if (startSampleInFile >= bufferStartSample
  211102. && startSampleInFile < bufferEndSample)
  211103. {
  211104. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211105. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211106. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211107. const short* src = (const short*) buffer.getData();
  211108. src += 2 * (startSampleInFile - bufferStartSample);
  211109. for (int i = 0; i < toDo; ++i)
  211110. {
  211111. l[i] = src [i << 1] << 16;
  211112. if (r != 0)
  211113. r[i] = src [(i << 1) + 1] << 16;
  211114. }
  211115. startOffsetInDestBuffer += toDo;
  211116. startSampleInFile += toDo;
  211117. numSamples -= toDo;
  211118. }
  211119. else
  211120. {
  211121. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211122. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211123. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211124. {
  211125. device->overlapBuffer.dataLength = 0;
  211126. device->overlapBuffer.startFrame = 0;
  211127. device->overlapBuffer.numFrames = 0;
  211128. device->jitter = false;
  211129. }
  211130. firstFrameInBuffer = frameNeeded;
  211131. lastIndex = 0;
  211132. CDReadBuffer readBuffer (framesInBuffer + 4);
  211133. readBuffer.wantsIndex = indexingEnabled;
  211134. int i;
  211135. for (i = 5; --i >= 0;)
  211136. {
  211137. readBuffer.startFrame = frameNeeded;
  211138. readBuffer.numFrames = framesInBuffer;
  211139. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  211140. break;
  211141. else
  211142. device->overlapBuffer.dataLength = 0;
  211143. }
  211144. if (i >= 0)
  211145. {
  211146. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  211147. samplesInBuffer = readBuffer.dataLength >> 2;
  211148. lastIndex = readBuffer.index;
  211149. }
  211150. else
  211151. {
  211152. int* l = destSamples[0] + startOffsetInDestBuffer;
  211153. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211154. while (--numSamples >= 0)
  211155. {
  211156. *l++ = 0;
  211157. if (r != 0)
  211158. *r++ = 0;
  211159. }
  211160. // sometimes the read fails for just the very last couple of blocks, so
  211161. // we'll ignore and errors in the last half-second of the disk..
  211162. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211163. break;
  211164. }
  211165. }
  211166. }
  211167. return ok;
  211168. }
  211169. bool AudioCDReader::isCDStillPresent() const
  211170. {
  211171. using namespace CDReaderHelpers;
  211172. TOC toc;
  211173. zerostruct (toc);
  211174. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  211175. }
  211176. void AudioCDReader::refreshTrackLengths()
  211177. {
  211178. using namespace CDReaderHelpers;
  211179. trackStartSamples.clear();
  211180. zeromem (audioTracks, sizeof (audioTracks));
  211181. TOC toc;
  211182. zerostruct (toc);
  211183. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211184. {
  211185. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211186. for (int i = 0; i <= numTracks; ++i)
  211187. {
  211188. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211189. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211190. }
  211191. }
  211192. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211193. }
  211194. bool AudioCDReader::isTrackAudio (int trackNum) const
  211195. {
  211196. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211197. }
  211198. void AudioCDReader::enableIndexScanning (bool b)
  211199. {
  211200. indexingEnabled = b;
  211201. }
  211202. int AudioCDReader::getLastIndex() const
  211203. {
  211204. return lastIndex;
  211205. }
  211206. int AudioCDReader::getIndexAt (int samplePos)
  211207. {
  211208. using namespace CDReaderHelpers;
  211209. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211210. const int frameNeeded = samplePos / samplesPerFrame;
  211211. device->overlapBuffer.dataLength = 0;
  211212. device->overlapBuffer.startFrame = 0;
  211213. device->overlapBuffer.numFrames = 0;
  211214. device->jitter = false;
  211215. firstFrameInBuffer = 0;
  211216. lastIndex = 0;
  211217. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211218. readBuffer.wantsIndex = true;
  211219. int i;
  211220. for (i = 5; --i >= 0;)
  211221. {
  211222. readBuffer.startFrame = frameNeeded;
  211223. readBuffer.numFrames = framesPerIndexRead;
  211224. if (device->deviceHandle.readAudio (readBuffer))
  211225. break;
  211226. }
  211227. if (i >= 0)
  211228. return readBuffer.index;
  211229. return -1;
  211230. }
  211231. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211232. {
  211233. using namespace CDReaderHelpers;
  211234. Array <int> indexes;
  211235. const int trackStart = getPositionOfTrackStart (trackNumber);
  211236. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211237. bool needToScan = true;
  211238. if (trackEnd - trackStart > 20 * 44100)
  211239. {
  211240. // check the end of the track for indexes before scanning the whole thing
  211241. needToScan = false;
  211242. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211243. bool seenAnIndex = false;
  211244. while (pos <= trackEnd - samplesPerFrame)
  211245. {
  211246. const int index = getIndexAt (pos);
  211247. if (index == 0)
  211248. {
  211249. // lead-out, so skip back a bit if we've not found any indexes yet..
  211250. if (seenAnIndex)
  211251. break;
  211252. pos -= 44100 * 5;
  211253. if (pos < trackStart)
  211254. break;
  211255. }
  211256. else
  211257. {
  211258. if (index > 0)
  211259. seenAnIndex = true;
  211260. if (index > 1)
  211261. {
  211262. needToScan = true;
  211263. break;
  211264. }
  211265. pos += samplesPerFrame * framesPerIndexRead;
  211266. }
  211267. }
  211268. }
  211269. if (needToScan)
  211270. {
  211271. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211272. int pos = trackStart;
  211273. int last = -1;
  211274. while (pos < trackEnd - samplesPerFrame * 10)
  211275. {
  211276. const int frameNeeded = pos / samplesPerFrame;
  211277. device->overlapBuffer.dataLength = 0;
  211278. device->overlapBuffer.startFrame = 0;
  211279. device->overlapBuffer.numFrames = 0;
  211280. device->jitter = false;
  211281. firstFrameInBuffer = 0;
  211282. CDReadBuffer readBuffer (4);
  211283. readBuffer.wantsIndex = true;
  211284. int i;
  211285. for (i = 5; --i >= 0;)
  211286. {
  211287. readBuffer.startFrame = frameNeeded;
  211288. readBuffer.numFrames = framesPerIndexRead;
  211289. if (device->deviceHandle.readAudio (readBuffer))
  211290. break;
  211291. }
  211292. if (i < 0)
  211293. break;
  211294. if (readBuffer.index > last && readBuffer.index > 1)
  211295. {
  211296. last = readBuffer.index;
  211297. indexes.add (pos);
  211298. }
  211299. pos += samplesPerFrame * framesPerIndexRead;
  211300. }
  211301. indexes.removeValue (trackStart);
  211302. }
  211303. return indexes;
  211304. }
  211305. void AudioCDReader::ejectDisk()
  211306. {
  211307. using namespace CDReaderHelpers;
  211308. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211309. }
  211310. #endif
  211311. #if JUCE_USE_CDBURNER
  211312. namespace CDBurnerHelpers
  211313. {
  211314. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211315. {
  211316. CoInitialize (0);
  211317. IDiscMaster* dm;
  211318. IDiscRecorder* result = 0;
  211319. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211320. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211321. IID_IDiscMaster,
  211322. (void**) &dm)))
  211323. {
  211324. if (SUCCEEDED (dm->Open()))
  211325. {
  211326. IEnumDiscRecorders* drEnum = 0;
  211327. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211328. {
  211329. IDiscRecorder* dr = 0;
  211330. DWORD dummy;
  211331. int index = 0;
  211332. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211333. {
  211334. if (indexToOpen == index)
  211335. {
  211336. result = dr;
  211337. break;
  211338. }
  211339. else if (list != 0)
  211340. {
  211341. BSTR path;
  211342. if (SUCCEEDED (dr->GetPath (&path)))
  211343. list->add ((const WCHAR*) path);
  211344. }
  211345. ++index;
  211346. dr->Release();
  211347. }
  211348. drEnum->Release();
  211349. }
  211350. if (master == 0)
  211351. dm->Close();
  211352. }
  211353. if (master != 0)
  211354. *master = dm;
  211355. else
  211356. dm->Release();
  211357. }
  211358. return result;
  211359. }
  211360. }
  211361. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211362. public Timer
  211363. {
  211364. public:
  211365. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211366. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211367. listener (0), progress (0), shouldCancel (false)
  211368. {
  211369. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211370. jassert (SUCCEEDED (hr));
  211371. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211372. //jassert (SUCCEEDED (hr));
  211373. lastState = getDiskState();
  211374. startTimer (2000);
  211375. }
  211376. ~Pimpl() {}
  211377. void releaseObjects()
  211378. {
  211379. discRecorder->Close();
  211380. if (redbook != 0)
  211381. redbook->Release();
  211382. discRecorder->Release();
  211383. discMaster->Release();
  211384. Release();
  211385. }
  211386. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211387. {
  211388. if (listener != 0 && ! shouldCancel)
  211389. shouldCancel = listener->audioCDBurnProgress (progress);
  211390. *pbCancel = shouldCancel;
  211391. return S_OK;
  211392. }
  211393. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211394. {
  211395. progress = nCompleted / (float) nTotal;
  211396. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211397. return E_NOTIMPL;
  211398. }
  211399. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211400. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211401. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211402. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211403. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211404. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211405. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211406. class ScopedDiscOpener
  211407. {
  211408. public:
  211409. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211410. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211411. private:
  211412. Pimpl& pimpl;
  211413. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211414. };
  211415. DiskState getDiskState()
  211416. {
  211417. const ScopedDiscOpener opener (*this);
  211418. long type, flags;
  211419. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211420. if (FAILED (hr))
  211421. return unknown;
  211422. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211423. return writableDiskPresent;
  211424. if (type == 0)
  211425. return noDisc;
  211426. else
  211427. return readOnlyDiskPresent;
  211428. }
  211429. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211430. {
  211431. ComSmartPtr<IPropertyStorage> prop;
  211432. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211433. return defaultReturn;
  211434. PROPSPEC iPropSpec;
  211435. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211436. iPropSpec.lpwstr = name;
  211437. PROPVARIANT iPropVariant;
  211438. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211439. ? defaultReturn : (int) iPropVariant.lVal;
  211440. }
  211441. bool setIntProperty (const LPOLESTR name, const int value) const
  211442. {
  211443. ComSmartPtr<IPropertyStorage> prop;
  211444. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211445. return false;
  211446. PROPSPEC iPropSpec;
  211447. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211448. iPropSpec.lpwstr = name;
  211449. PROPVARIANT iPropVariant;
  211450. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211451. return false;
  211452. iPropVariant.lVal = (long) value;
  211453. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211454. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211455. }
  211456. void timerCallback()
  211457. {
  211458. const DiskState state = getDiskState();
  211459. if (state != lastState)
  211460. {
  211461. lastState = state;
  211462. owner.sendChangeMessage();
  211463. }
  211464. }
  211465. AudioCDBurner& owner;
  211466. DiskState lastState;
  211467. IDiscMaster* discMaster;
  211468. IDiscRecorder* discRecorder;
  211469. IRedbookDiscMaster* redbook;
  211470. AudioCDBurner::BurnProgressListener* listener;
  211471. float progress;
  211472. bool shouldCancel;
  211473. };
  211474. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211475. {
  211476. IDiscMaster* discMaster = 0;
  211477. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211478. if (discRecorder != 0)
  211479. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211480. }
  211481. AudioCDBurner::~AudioCDBurner()
  211482. {
  211483. if (pimpl != 0)
  211484. pimpl.release()->releaseObjects();
  211485. }
  211486. const StringArray AudioCDBurner::findAvailableDevices()
  211487. {
  211488. StringArray devs;
  211489. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211490. return devs;
  211491. }
  211492. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211493. {
  211494. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211495. if (b->pimpl == 0)
  211496. b = 0;
  211497. return b.release();
  211498. }
  211499. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211500. {
  211501. return pimpl->getDiskState();
  211502. }
  211503. bool AudioCDBurner::isDiskPresent() const
  211504. {
  211505. return getDiskState() == writableDiskPresent;
  211506. }
  211507. bool AudioCDBurner::openTray()
  211508. {
  211509. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211510. return SUCCEEDED (pimpl->discRecorder->Eject());
  211511. }
  211512. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211513. {
  211514. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211515. DiskState oldState = getDiskState();
  211516. DiskState newState = oldState;
  211517. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211518. {
  211519. newState = getDiskState();
  211520. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211521. }
  211522. return newState;
  211523. }
  211524. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211525. {
  211526. Array<int> results;
  211527. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211528. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211529. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211530. if (speeds[i] <= maxSpeed)
  211531. results.add (speeds[i]);
  211532. results.addIfNotAlreadyThere (maxSpeed);
  211533. return results;
  211534. }
  211535. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211536. {
  211537. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211538. return false;
  211539. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211540. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211541. }
  211542. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211543. {
  211544. long blocksFree = 0;
  211545. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211546. return blocksFree;
  211547. }
  211548. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211549. bool performFakeBurnForTesting, int writeSpeed)
  211550. {
  211551. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211552. pimpl->listener = listener;
  211553. pimpl->progress = 0;
  211554. pimpl->shouldCancel = false;
  211555. UINT_PTR cookie;
  211556. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211557. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211558. ejectDiscAfterwards);
  211559. String error;
  211560. if (hr != S_OK)
  211561. {
  211562. const char* e = "Couldn't open or write to the CD device";
  211563. if (hr == IMAPI_E_USERABORT)
  211564. e = "User cancelled the write operation";
  211565. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211566. e = "No Disk present";
  211567. error = e;
  211568. }
  211569. pimpl->discMaster->ProgressUnadvise (cookie);
  211570. pimpl->listener = 0;
  211571. return error;
  211572. }
  211573. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211574. {
  211575. if (audioSource == 0)
  211576. return false;
  211577. ScopedPointer<AudioSource> source (audioSource);
  211578. long bytesPerBlock;
  211579. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211580. const int samplesPerBlock = bytesPerBlock / 4;
  211581. bool ok = true;
  211582. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  211583. HeapBlock <byte> buffer (bytesPerBlock);
  211584. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  211585. int samplesDone = 0;
  211586. source->prepareToPlay (samplesPerBlock, 44100.0);
  211587. while (ok)
  211588. {
  211589. {
  211590. AudioSourceChannelInfo info;
  211591. info.buffer = &sourceBuffer;
  211592. info.numSamples = samplesPerBlock;
  211593. info.startSample = 0;
  211594. sourceBuffer.clear();
  211595. source->getNextAudioBlock (info);
  211596. }
  211597. zeromem (buffer, bytesPerBlock);
  211598. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  211599. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  211600. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  211601. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  211602. CDSampleFormat left (buffer, 2);
  211603. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  211604. CDSampleFormat right (buffer + 2, 2);
  211605. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  211606. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  211607. if (FAILED (hr))
  211608. ok = false;
  211609. samplesDone += samplesPerBlock;
  211610. if (samplesDone >= numSamples)
  211611. break;
  211612. }
  211613. hr = pimpl->redbook->CloseAudioTrack();
  211614. return ok && hr == S_OK;
  211615. }
  211616. #endif
  211617. #endif
  211618. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  211619. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  211620. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211621. // compiled on its own).
  211622. #if JUCE_INCLUDED_FILE
  211623. class MidiInCollector
  211624. {
  211625. public:
  211626. MidiInCollector (MidiInput* const input_,
  211627. MidiInputCallback& callback_)
  211628. : deviceHandle (0),
  211629. input (input_),
  211630. callback (callback_),
  211631. concatenator (4096),
  211632. isStarted (false),
  211633. startTime (0)
  211634. {
  211635. }
  211636. ~MidiInCollector()
  211637. {
  211638. stop();
  211639. if (deviceHandle != 0)
  211640. {
  211641. int count = 5;
  211642. while (--count >= 0)
  211643. {
  211644. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  211645. break;
  211646. Sleep (20);
  211647. }
  211648. }
  211649. }
  211650. void handleMessage (const uint32 message, const uint32 timeStamp)
  211651. {
  211652. if ((message & 0xff) >= 0x80 && isStarted)
  211653. {
  211654. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  211655. writeFinishedBlocks();
  211656. }
  211657. }
  211658. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  211659. {
  211660. if (isStarted)
  211661. {
  211662. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  211663. writeFinishedBlocks();
  211664. }
  211665. }
  211666. void start()
  211667. {
  211668. jassert (deviceHandle != 0);
  211669. if (deviceHandle != 0 && ! isStarted)
  211670. {
  211671. activeMidiCollectors.addIfNotAlreadyThere (this);
  211672. for (int i = 0; i < (int) numHeaders; ++i)
  211673. headers[i].write (deviceHandle);
  211674. startTime = Time::getMillisecondCounter();
  211675. MMRESULT res = midiInStart (deviceHandle);
  211676. if (res == MMSYSERR_NOERROR)
  211677. {
  211678. concatenator.reset();
  211679. isStarted = true;
  211680. }
  211681. else
  211682. {
  211683. unprepareAllHeaders();
  211684. }
  211685. }
  211686. }
  211687. void stop()
  211688. {
  211689. if (isStarted)
  211690. {
  211691. isStarted = false;
  211692. midiInReset (deviceHandle);
  211693. midiInStop (deviceHandle);
  211694. activeMidiCollectors.removeValue (this);
  211695. unprepareAllHeaders();
  211696. concatenator.reset();
  211697. }
  211698. }
  211699. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  211700. {
  211701. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  211702. if (activeMidiCollectors.contains (collector))
  211703. {
  211704. if (uMsg == MIM_DATA)
  211705. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  211706. else if (uMsg == MIM_LONGDATA)
  211707. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  211708. }
  211709. }
  211710. HMIDIIN deviceHandle;
  211711. private:
  211712. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  211713. MidiInput* input;
  211714. MidiInputCallback& callback;
  211715. MidiDataConcatenator concatenator;
  211716. bool volatile isStarted;
  211717. uint32 startTime;
  211718. class MidiHeader
  211719. {
  211720. public:
  211721. MidiHeader()
  211722. {
  211723. zerostruct (hdr);
  211724. hdr.lpData = data;
  211725. hdr.dwBufferLength = numElementsInArray (data);
  211726. }
  211727. void write (HMIDIIN deviceHandle)
  211728. {
  211729. hdr.dwBytesRecorded = 0;
  211730. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211731. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  211732. }
  211733. void writeIfFinished (HMIDIIN deviceHandle)
  211734. {
  211735. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211736. {
  211737. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211738. (void) res;
  211739. write (deviceHandle);
  211740. }
  211741. }
  211742. void unprepare (HMIDIIN deviceHandle)
  211743. {
  211744. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211745. {
  211746. int c = 10;
  211747. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  211748. Thread::sleep (20);
  211749. jassert (c >= 0);
  211750. }
  211751. }
  211752. private:
  211753. MIDIHDR hdr;
  211754. char data [256];
  211755. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  211756. };
  211757. enum { numHeaders = 32 };
  211758. MidiHeader headers [numHeaders];
  211759. void writeFinishedBlocks()
  211760. {
  211761. for (int i = 0; i < (int) numHeaders; ++i)
  211762. headers[i].writeIfFinished (deviceHandle);
  211763. }
  211764. void unprepareAllHeaders()
  211765. {
  211766. for (int i = 0; i < (int) numHeaders; ++i)
  211767. headers[i].unprepare (deviceHandle);
  211768. }
  211769. double convertTimeStamp (uint32 timeStamp)
  211770. {
  211771. timeStamp += startTime;
  211772. const uint32 now = Time::getMillisecondCounter();
  211773. if (timeStamp > now)
  211774. {
  211775. if (timeStamp > now + 2)
  211776. --startTime;
  211777. timeStamp = now;
  211778. }
  211779. return timeStamp * 0.001;
  211780. }
  211781. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  211782. };
  211783. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  211784. const StringArray MidiInput::getDevices()
  211785. {
  211786. StringArray s;
  211787. const int num = midiInGetNumDevs();
  211788. for (int i = 0; i < num; ++i)
  211789. {
  211790. MIDIINCAPS mc;
  211791. zerostruct (mc);
  211792. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211793. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211794. }
  211795. return s;
  211796. }
  211797. int MidiInput::getDefaultDeviceIndex()
  211798. {
  211799. return 0;
  211800. }
  211801. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  211802. {
  211803. if (callback == 0)
  211804. return 0;
  211805. UINT deviceId = MIDI_MAPPER;
  211806. int n = 0;
  211807. String name;
  211808. const int num = midiInGetNumDevs();
  211809. for (int i = 0; i < num; ++i)
  211810. {
  211811. MIDIINCAPS mc;
  211812. zerostruct (mc);
  211813. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211814. {
  211815. if (index == n)
  211816. {
  211817. deviceId = i;
  211818. name = String (mc.szPname, numElementsInArray (mc.szPname));
  211819. break;
  211820. }
  211821. ++n;
  211822. }
  211823. }
  211824. ScopedPointer <MidiInput> in (new MidiInput (name));
  211825. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  211826. HMIDIIN h;
  211827. HRESULT err = midiInOpen (&h, deviceId,
  211828. (DWORD_PTR) &MidiInCollector::midiInCallback,
  211829. (DWORD_PTR) (MidiInCollector*) collector,
  211830. CALLBACK_FUNCTION);
  211831. if (err == MMSYSERR_NOERROR)
  211832. {
  211833. collector->deviceHandle = h;
  211834. in->internal = collector.release();
  211835. return in.release();
  211836. }
  211837. return 0;
  211838. }
  211839. MidiInput::MidiInput (const String& name_)
  211840. : name (name_),
  211841. internal (0)
  211842. {
  211843. }
  211844. MidiInput::~MidiInput()
  211845. {
  211846. delete static_cast <MidiInCollector*> (internal);
  211847. }
  211848. void MidiInput::start()
  211849. {
  211850. static_cast <MidiInCollector*> (internal)->start();
  211851. }
  211852. void MidiInput::stop()
  211853. {
  211854. static_cast <MidiInCollector*> (internal)->stop();
  211855. }
  211856. struct MidiOutHandle
  211857. {
  211858. int refCount;
  211859. UINT deviceId;
  211860. HMIDIOUT handle;
  211861. static Array<MidiOutHandle*> activeHandles;
  211862. private:
  211863. JUCE_LEAK_DETECTOR (MidiOutHandle);
  211864. };
  211865. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  211866. const StringArray MidiOutput::getDevices()
  211867. {
  211868. StringArray s;
  211869. const int num = midiOutGetNumDevs();
  211870. for (int i = 0; i < num; ++i)
  211871. {
  211872. MIDIOUTCAPS mc;
  211873. zerostruct (mc);
  211874. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211875. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211876. }
  211877. return s;
  211878. }
  211879. int MidiOutput::getDefaultDeviceIndex()
  211880. {
  211881. const int num = midiOutGetNumDevs();
  211882. int n = 0;
  211883. for (int i = 0; i < num; ++i)
  211884. {
  211885. MIDIOUTCAPS mc;
  211886. zerostruct (mc);
  211887. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211888. {
  211889. if ((mc.wTechnology & MOD_MAPPER) != 0)
  211890. return n;
  211891. ++n;
  211892. }
  211893. }
  211894. return 0;
  211895. }
  211896. MidiOutput* MidiOutput::openDevice (int index)
  211897. {
  211898. UINT deviceId = MIDI_MAPPER;
  211899. const int num = midiOutGetNumDevs();
  211900. int i, n = 0;
  211901. for (i = 0; i < num; ++i)
  211902. {
  211903. MIDIOUTCAPS mc;
  211904. zerostruct (mc);
  211905. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211906. {
  211907. // use the microsoft sw synth as a default - best not to allow deviceId
  211908. // to be MIDI_MAPPER, or else device sharing breaks
  211909. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  211910. deviceId = i;
  211911. if (index == n)
  211912. {
  211913. deviceId = i;
  211914. break;
  211915. }
  211916. ++n;
  211917. }
  211918. }
  211919. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  211920. {
  211921. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  211922. if (han != 0 && han->deviceId == deviceId)
  211923. {
  211924. han->refCount++;
  211925. MidiOutput* const out = new MidiOutput();
  211926. out->internal = han;
  211927. return out;
  211928. }
  211929. }
  211930. for (i = 4; --i >= 0;)
  211931. {
  211932. HMIDIOUT h = 0;
  211933. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211934. if (res == MMSYSERR_NOERROR)
  211935. {
  211936. MidiOutHandle* const han = new MidiOutHandle();
  211937. han->deviceId = deviceId;
  211938. han->refCount = 1;
  211939. han->handle = h;
  211940. MidiOutHandle::activeHandles.add (han);
  211941. MidiOutput* const out = new MidiOutput();
  211942. out->internal = han;
  211943. return out;
  211944. }
  211945. else if (res == MMSYSERR_ALLOCATED)
  211946. {
  211947. Sleep (100);
  211948. }
  211949. else
  211950. {
  211951. break;
  211952. }
  211953. }
  211954. return 0;
  211955. }
  211956. MidiOutput::~MidiOutput()
  211957. {
  211958. stopBackgroundThread();
  211959. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211960. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211961. {
  211962. midiOutClose (h->handle);
  211963. MidiOutHandle::activeHandles.removeValue (h);
  211964. delete h;
  211965. }
  211966. }
  211967. void MidiOutput::reset()
  211968. {
  211969. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211970. midiOutReset (h->handle);
  211971. }
  211972. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  211973. {
  211974. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211975. DWORD n;
  211976. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211977. {
  211978. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  211979. rightVol = nn[0] / (float) 0xffff;
  211980. leftVol = nn[1] / (float) 0xffff;
  211981. return true;
  211982. }
  211983. else
  211984. {
  211985. rightVol = leftVol = 1.0f;
  211986. return false;
  211987. }
  211988. }
  211989. void MidiOutput::setVolume (float leftVol, float rightVol)
  211990. {
  211991. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211992. DWORD n;
  211993. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  211994. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211995. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211996. midiOutSetVolume (handle->handle, n);
  211997. }
  211998. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211999. {
  212000. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212001. if (message.getRawDataSize() > 3
  212002. || message.isSysEx())
  212003. {
  212004. MIDIHDR h;
  212005. zerostruct (h);
  212006. h.lpData = (char*) message.getRawData();
  212007. h.dwBufferLength = message.getRawDataSize();
  212008. h.dwBytesRecorded = message.getRawDataSize();
  212009. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212010. {
  212011. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212012. if (res == MMSYSERR_NOERROR)
  212013. {
  212014. while ((h.dwFlags & MHDR_DONE) == 0)
  212015. Sleep (1);
  212016. int count = 500; // 1 sec timeout
  212017. while (--count >= 0)
  212018. {
  212019. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212020. if (res == MIDIERR_STILLPLAYING)
  212021. Sleep (2);
  212022. else
  212023. break;
  212024. }
  212025. }
  212026. }
  212027. }
  212028. else
  212029. {
  212030. midiOutShortMsg (handle->handle,
  212031. *(unsigned int*) message.getRawData());
  212032. }
  212033. }
  212034. #endif
  212035. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212036. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212037. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212038. // compiled on its own).
  212039. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212040. #undef WINDOWS
  212041. // #define ASIO_DEBUGGING 1
  212042. #undef log
  212043. #if ASIO_DEBUGGING
  212044. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212045. #else
  212046. #define log(a) {}
  212047. #endif
  212048. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212049. to be pretty random about whether or not they do this. If you hit an error using these functions
  212050. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212051. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212052. */
  212053. #define JUCE_ASIOCALLBACK __cdecl
  212054. namespace ASIODebugging
  212055. {
  212056. #if ASIO_DEBUGGING
  212057. static void log (const String& context, long error)
  212058. {
  212059. String err ("unknown error");
  212060. if (error == ASE_NotPresent) err = "Not Present";
  212061. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212062. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212063. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212064. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212065. else if (error == ASE_NoClock) err = "No Clock";
  212066. else if (error == ASE_NoMemory) err = "Out of memory";
  212067. log ("!!error: " + context + " - " + err);
  212068. }
  212069. #define logError(a, b) ASIODebugging::log ((a), (b))
  212070. #else
  212071. #define logError(a, b) {}
  212072. #endif
  212073. }
  212074. class ASIOAudioIODevice;
  212075. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212076. static const int maxASIOChannels = 160;
  212077. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212078. private Timer
  212079. {
  212080. public:
  212081. Component ourWindow;
  212082. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212083. const String& optionalDllForDirectLoading_)
  212084. : AudioIODevice (name_, "ASIO"),
  212085. asioObject (0),
  212086. classId (classId_),
  212087. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212088. currentBitDepth (16),
  212089. currentSampleRate (0),
  212090. isOpen_ (false),
  212091. isStarted (false),
  212092. postOutput (true),
  212093. insideControlPanelModalLoop (false),
  212094. shouldUsePreferredSize (false)
  212095. {
  212096. name = name_;
  212097. ourWindow.addToDesktop (0);
  212098. windowHandle = ourWindow.getWindowHandle();
  212099. jassert (currentASIODev [slotNumber] == 0);
  212100. currentASIODev [slotNumber] = this;
  212101. openDevice();
  212102. }
  212103. ~ASIOAudioIODevice()
  212104. {
  212105. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212106. if (currentASIODev[i] == this)
  212107. currentASIODev[i] = 0;
  212108. close();
  212109. log ("ASIO - exiting");
  212110. removeCurrentDriver();
  212111. }
  212112. void updateSampleRates()
  212113. {
  212114. // find a list of sample rates..
  212115. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212116. sampleRates.clear();
  212117. if (asioObject != 0)
  212118. {
  212119. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212120. {
  212121. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212122. if (err == 0)
  212123. {
  212124. sampleRates.add ((int) possibleSampleRates[index]);
  212125. log ("rate: " + String ((int) possibleSampleRates[index]));
  212126. }
  212127. else if (err != ASE_NoClock)
  212128. {
  212129. logError ("CanSampleRate", err);
  212130. }
  212131. }
  212132. if (sampleRates.size() == 0)
  212133. {
  212134. double cr = 0;
  212135. const long err = asioObject->getSampleRate (&cr);
  212136. log ("No sample rates supported - current rate: " + String ((int) cr));
  212137. if (err == 0)
  212138. sampleRates.add ((int) cr);
  212139. }
  212140. }
  212141. }
  212142. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212143. const StringArray getInputChannelNames() { return inputChannelNames; }
  212144. int getNumSampleRates() { return sampleRates.size(); }
  212145. double getSampleRate (int index) { return sampleRates [index]; }
  212146. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212147. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212148. int getDefaultBufferSize() { return preferredSize; }
  212149. const String open (const BigInteger& inputChannels,
  212150. const BigInteger& outputChannels,
  212151. double sr,
  212152. int bufferSizeSamples)
  212153. {
  212154. close();
  212155. currentCallback = 0;
  212156. if (bufferSizeSamples <= 0)
  212157. shouldUsePreferredSize = true;
  212158. if (asioObject == 0 || ! isASIOOpen)
  212159. {
  212160. log ("Warning: device not open");
  212161. const String err (openDevice());
  212162. if (asioObject == 0 || ! isASIOOpen)
  212163. return err;
  212164. }
  212165. isStarted = false;
  212166. bufferIndex = -1;
  212167. long err = 0;
  212168. long newPreferredSize = 0;
  212169. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212170. minSize = 0;
  212171. maxSize = 0;
  212172. newPreferredSize = 0;
  212173. granularity = 0;
  212174. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212175. {
  212176. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212177. shouldUsePreferredSize = true;
  212178. preferredSize = newPreferredSize;
  212179. }
  212180. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212181. // dynamic changes to the buffer size...
  212182. shouldUsePreferredSize = shouldUsePreferredSize
  212183. || getName().containsIgnoreCase ("Digidesign");
  212184. if (shouldUsePreferredSize)
  212185. {
  212186. log ("Using preferred size for buffer..");
  212187. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212188. {
  212189. bufferSizeSamples = preferredSize;
  212190. }
  212191. else
  212192. {
  212193. bufferSizeSamples = 1024;
  212194. logError ("GetBufferSize1", err);
  212195. }
  212196. shouldUsePreferredSize = false;
  212197. }
  212198. int sampleRate = roundDoubleToInt (sr);
  212199. currentSampleRate = sampleRate;
  212200. currentBlockSizeSamples = bufferSizeSamples;
  212201. currentChansOut.clear();
  212202. currentChansIn.clear();
  212203. zeromem (inBuffers, sizeof (inBuffers));
  212204. zeromem (outBuffers, sizeof (outBuffers));
  212205. updateSampleRates();
  212206. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212207. sampleRate = sampleRates[0];
  212208. jassert (sampleRate != 0);
  212209. if (sampleRate == 0)
  212210. sampleRate = 44100;
  212211. long numSources = 32;
  212212. ASIOClockSource clocks[32];
  212213. zeromem (clocks, sizeof (clocks));
  212214. asioObject->getClockSources (clocks, &numSources);
  212215. bool isSourceSet = false;
  212216. // careful not to remove this loop because it does more than just logging!
  212217. int i;
  212218. for (i = 0; i < numSources; ++i)
  212219. {
  212220. String s ("clock: ");
  212221. s += clocks[i].name;
  212222. if (clocks[i].isCurrentSource)
  212223. {
  212224. isSourceSet = true;
  212225. s << " (cur)";
  212226. }
  212227. log (s);
  212228. }
  212229. if (numSources > 1 && ! isSourceSet)
  212230. {
  212231. log ("setting clock source");
  212232. asioObject->setClockSource (clocks[0].index);
  212233. Thread::sleep (20);
  212234. }
  212235. else
  212236. {
  212237. if (numSources == 0)
  212238. {
  212239. log ("ASIO - no clock sources!");
  212240. }
  212241. }
  212242. double cr = 0;
  212243. err = asioObject->getSampleRate (&cr);
  212244. if (err == 0)
  212245. {
  212246. currentSampleRate = cr;
  212247. }
  212248. else
  212249. {
  212250. logError ("GetSampleRate", err);
  212251. currentSampleRate = 0;
  212252. }
  212253. error = String::empty;
  212254. needToReset = false;
  212255. isReSync = false;
  212256. err = 0;
  212257. bool buffersCreated = false;
  212258. if (currentSampleRate != sampleRate)
  212259. {
  212260. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212261. err = asioObject->setSampleRate (sampleRate);
  212262. if (err == ASE_NoClock && numSources > 0)
  212263. {
  212264. log ("trying to set a clock source..");
  212265. Thread::sleep (10);
  212266. err = asioObject->setClockSource (clocks[0].index);
  212267. if (err != 0)
  212268. {
  212269. logError ("SetClock", err);
  212270. }
  212271. Thread::sleep (10);
  212272. err = asioObject->setSampleRate (sampleRate);
  212273. }
  212274. }
  212275. if (err == 0)
  212276. {
  212277. currentSampleRate = sampleRate;
  212278. if (needToReset)
  212279. {
  212280. if (isReSync)
  212281. {
  212282. log ("Resync request");
  212283. }
  212284. log ("! Resetting ASIO after sample rate change");
  212285. removeCurrentDriver();
  212286. loadDriver();
  212287. const String error (initDriver());
  212288. if (error.isNotEmpty())
  212289. {
  212290. log ("ASIOInit: " + error);
  212291. }
  212292. needToReset = false;
  212293. isReSync = false;
  212294. }
  212295. numActiveInputChans = 0;
  212296. numActiveOutputChans = 0;
  212297. ASIOBufferInfo* info = bufferInfos;
  212298. int i;
  212299. for (i = 0; i < totalNumInputChans; ++i)
  212300. {
  212301. if (inputChannels[i])
  212302. {
  212303. currentChansIn.setBit (i);
  212304. info->isInput = 1;
  212305. info->channelNum = i;
  212306. info->buffers[0] = info->buffers[1] = 0;
  212307. ++info;
  212308. ++numActiveInputChans;
  212309. }
  212310. }
  212311. for (i = 0; i < totalNumOutputChans; ++i)
  212312. {
  212313. if (outputChannels[i])
  212314. {
  212315. currentChansOut.setBit (i);
  212316. info->isInput = 0;
  212317. info->channelNum = i;
  212318. info->buffers[0] = info->buffers[1] = 0;
  212319. ++info;
  212320. ++numActiveOutputChans;
  212321. }
  212322. }
  212323. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212324. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212325. if (currentASIODev[0] == this)
  212326. {
  212327. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212328. callbacks.asioMessage = &asioMessagesCallback0;
  212329. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212330. }
  212331. else if (currentASIODev[1] == this)
  212332. {
  212333. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212334. callbacks.asioMessage = &asioMessagesCallback1;
  212335. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212336. }
  212337. else if (currentASIODev[2] == this)
  212338. {
  212339. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212340. callbacks.asioMessage = &asioMessagesCallback2;
  212341. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212342. }
  212343. else
  212344. {
  212345. jassertfalse;
  212346. }
  212347. log ("disposing buffers");
  212348. err = asioObject->disposeBuffers();
  212349. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212350. err = asioObject->createBuffers (bufferInfos,
  212351. totalBuffers,
  212352. currentBlockSizeSamples,
  212353. &callbacks);
  212354. if (err != 0)
  212355. {
  212356. currentBlockSizeSamples = preferredSize;
  212357. logError ("create buffers 2", err);
  212358. asioObject->disposeBuffers();
  212359. err = asioObject->createBuffers (bufferInfos,
  212360. totalBuffers,
  212361. currentBlockSizeSamples,
  212362. &callbacks);
  212363. }
  212364. if (err == 0)
  212365. {
  212366. buffersCreated = true;
  212367. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212368. int n = 0;
  212369. Array <int> types;
  212370. currentBitDepth = 16;
  212371. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212372. {
  212373. if (inputChannels[i])
  212374. {
  212375. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212376. ASIOChannelInfo channelInfo;
  212377. zerostruct (channelInfo);
  212378. channelInfo.channel = i;
  212379. channelInfo.isInput = 1;
  212380. asioObject->getChannelInfo (&channelInfo);
  212381. types.addIfNotAlreadyThere (channelInfo.type);
  212382. typeToFormatParameters (channelInfo.type,
  212383. inputChannelBitDepths[n],
  212384. inputChannelBytesPerSample[n],
  212385. inputChannelIsFloat[n],
  212386. inputChannelLittleEndian[n]);
  212387. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212388. ++n;
  212389. }
  212390. }
  212391. jassert (numActiveInputChans == n);
  212392. n = 0;
  212393. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212394. {
  212395. if (outputChannels[i])
  212396. {
  212397. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212398. ASIOChannelInfo channelInfo;
  212399. zerostruct (channelInfo);
  212400. channelInfo.channel = i;
  212401. channelInfo.isInput = 0;
  212402. asioObject->getChannelInfo (&channelInfo);
  212403. types.addIfNotAlreadyThere (channelInfo.type);
  212404. typeToFormatParameters (channelInfo.type,
  212405. outputChannelBitDepths[n],
  212406. outputChannelBytesPerSample[n],
  212407. outputChannelIsFloat[n],
  212408. outputChannelLittleEndian[n]);
  212409. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212410. ++n;
  212411. }
  212412. }
  212413. jassert (numActiveOutputChans == n);
  212414. for (i = types.size(); --i >= 0;)
  212415. {
  212416. log ("channel format: " + String (types[i]));
  212417. }
  212418. jassert (n <= totalBuffers);
  212419. for (i = 0; i < numActiveOutputChans; ++i)
  212420. {
  212421. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212422. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212423. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212424. {
  212425. log ("!! Null buffers");
  212426. }
  212427. else
  212428. {
  212429. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212430. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212431. }
  212432. }
  212433. inputLatency = outputLatency = 0;
  212434. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212435. {
  212436. log ("ASIO - no latencies");
  212437. }
  212438. else
  212439. {
  212440. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212441. }
  212442. isOpen_ = true;
  212443. log ("starting ASIO");
  212444. calledback = false;
  212445. err = asioObject->start();
  212446. if (err != 0)
  212447. {
  212448. isOpen_ = false;
  212449. log ("ASIO - stop on failure");
  212450. Thread::sleep (10);
  212451. asioObject->stop();
  212452. error = "Can't start device";
  212453. Thread::sleep (10);
  212454. }
  212455. else
  212456. {
  212457. int count = 300;
  212458. while (--count > 0 && ! calledback)
  212459. Thread::sleep (10);
  212460. isStarted = true;
  212461. if (! calledback)
  212462. {
  212463. error = "Device didn't start correctly";
  212464. log ("ASIO didn't callback - stopping..");
  212465. asioObject->stop();
  212466. }
  212467. }
  212468. }
  212469. else
  212470. {
  212471. error = "Can't create i/o buffers";
  212472. }
  212473. }
  212474. else
  212475. {
  212476. error = "Can't set sample rate: ";
  212477. error << sampleRate;
  212478. }
  212479. if (error.isNotEmpty())
  212480. {
  212481. logError (error, err);
  212482. if (asioObject != 0 && buffersCreated)
  212483. asioObject->disposeBuffers();
  212484. Thread::sleep (20);
  212485. isStarted = false;
  212486. isOpen_ = false;
  212487. const String errorCopy (error);
  212488. close(); // (this resets the error string)
  212489. error = errorCopy;
  212490. }
  212491. needToReset = false;
  212492. isReSync = false;
  212493. return error;
  212494. }
  212495. void close()
  212496. {
  212497. error = String::empty;
  212498. stopTimer();
  212499. stop();
  212500. if (isASIOOpen && isOpen_)
  212501. {
  212502. const ScopedLock sl (callbackLock);
  212503. isOpen_ = false;
  212504. isStarted = false;
  212505. needToReset = false;
  212506. isReSync = false;
  212507. log ("ASIO - stopping");
  212508. if (asioObject != 0)
  212509. {
  212510. Thread::sleep (20);
  212511. asioObject->stop();
  212512. Thread::sleep (10);
  212513. asioObject->disposeBuffers();
  212514. }
  212515. Thread::sleep (10);
  212516. }
  212517. }
  212518. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212519. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212520. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212521. double getCurrentSampleRate() { return currentSampleRate; }
  212522. int getCurrentBitDepth() { return currentBitDepth; }
  212523. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212524. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212525. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212526. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212527. void start (AudioIODeviceCallback* callback)
  212528. {
  212529. if (callback != 0)
  212530. {
  212531. callback->audioDeviceAboutToStart (this);
  212532. const ScopedLock sl (callbackLock);
  212533. currentCallback = callback;
  212534. }
  212535. }
  212536. void stop()
  212537. {
  212538. AudioIODeviceCallback* const lastCallback = currentCallback;
  212539. {
  212540. const ScopedLock sl (callbackLock);
  212541. currentCallback = 0;
  212542. }
  212543. if (lastCallback != 0)
  212544. lastCallback->audioDeviceStopped();
  212545. }
  212546. const String getLastError() { return error; }
  212547. bool hasControlPanel() const { return true; }
  212548. bool showControlPanel()
  212549. {
  212550. log ("ASIO - showing control panel");
  212551. Component modalWindow (String::empty);
  212552. modalWindow.setOpaque (true);
  212553. modalWindow.addToDesktop (0);
  212554. modalWindow.enterModalState();
  212555. bool done = false;
  212556. JUCE_TRY
  212557. {
  212558. // are there are devices that need to be closed before showing their control panel?
  212559. // close();
  212560. insideControlPanelModalLoop = true;
  212561. const uint32 started = Time::getMillisecondCounter();
  212562. if (asioObject != 0)
  212563. {
  212564. asioObject->controlPanel();
  212565. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212566. log ("spent: " + String (spent));
  212567. if (spent > 300)
  212568. {
  212569. shouldUsePreferredSize = true;
  212570. done = true;
  212571. }
  212572. }
  212573. }
  212574. JUCE_CATCH_ALL
  212575. insideControlPanelModalLoop = false;
  212576. return done;
  212577. }
  212578. void resetRequest() throw()
  212579. {
  212580. needToReset = true;
  212581. }
  212582. void resyncRequest() throw()
  212583. {
  212584. needToReset = true;
  212585. isReSync = true;
  212586. }
  212587. void timerCallback()
  212588. {
  212589. if (! insideControlPanelModalLoop)
  212590. {
  212591. stopTimer();
  212592. // used to cause a reset
  212593. log ("! ASIO restart request!");
  212594. if (isOpen_)
  212595. {
  212596. AudioIODeviceCallback* const oldCallback = currentCallback;
  212597. close();
  212598. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212599. currentSampleRate, currentBlockSizeSamples);
  212600. if (oldCallback != 0)
  212601. start (oldCallback);
  212602. }
  212603. }
  212604. else
  212605. {
  212606. startTimer (100);
  212607. }
  212608. }
  212609. private:
  212610. IASIO* volatile asioObject;
  212611. ASIOCallbacks callbacks;
  212612. void* windowHandle;
  212613. CLSID classId;
  212614. const String optionalDllForDirectLoading;
  212615. String error;
  212616. long totalNumInputChans, totalNumOutputChans;
  212617. StringArray inputChannelNames, outputChannelNames;
  212618. Array<int> sampleRates, bufferSizes;
  212619. long inputLatency, outputLatency;
  212620. long minSize, maxSize, preferredSize, granularity;
  212621. int volatile currentBlockSizeSamples;
  212622. int volatile currentBitDepth;
  212623. double volatile currentSampleRate;
  212624. BigInteger currentChansOut, currentChansIn;
  212625. AudioIODeviceCallback* volatile currentCallback;
  212626. CriticalSection callbackLock;
  212627. ASIOBufferInfo bufferInfos [maxASIOChannels];
  212628. float* inBuffers [maxASIOChannels];
  212629. float* outBuffers [maxASIOChannels];
  212630. int inputChannelBitDepths [maxASIOChannels];
  212631. int outputChannelBitDepths [maxASIOChannels];
  212632. int inputChannelBytesPerSample [maxASIOChannels];
  212633. int outputChannelBytesPerSample [maxASIOChannels];
  212634. bool inputChannelIsFloat [maxASIOChannels];
  212635. bool outputChannelIsFloat [maxASIOChannels];
  212636. bool inputChannelLittleEndian [maxASIOChannels];
  212637. bool outputChannelLittleEndian [maxASIOChannels];
  212638. WaitableEvent event1;
  212639. HeapBlock <float> tempBuffer;
  212640. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  212641. bool isOpen_, isStarted;
  212642. bool volatile isASIOOpen;
  212643. bool volatile calledback;
  212644. bool volatile littleEndian, postOutput, needToReset, isReSync;
  212645. bool volatile insideControlPanelModalLoop;
  212646. bool volatile shouldUsePreferredSize;
  212647. void removeCurrentDriver()
  212648. {
  212649. if (asioObject != 0)
  212650. {
  212651. asioObject->Release();
  212652. asioObject = 0;
  212653. }
  212654. }
  212655. bool loadDriver()
  212656. {
  212657. removeCurrentDriver();
  212658. JUCE_TRY
  212659. {
  212660. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  212661. classId, (void**) &asioObject) == S_OK)
  212662. {
  212663. return true;
  212664. }
  212665. // If a class isn't registered but we have a path for it, we can fallback to
  212666. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  212667. if (optionalDllForDirectLoading.isNotEmpty())
  212668. {
  212669. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  212670. if (h != 0)
  212671. {
  212672. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  212673. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  212674. if (dllGetClassObject != 0)
  212675. {
  212676. IClassFactory* classFactory = 0;
  212677. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  212678. if (classFactory != 0)
  212679. {
  212680. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  212681. classFactory->Release();
  212682. }
  212683. return asioObject != 0;
  212684. }
  212685. }
  212686. }
  212687. }
  212688. JUCE_CATCH_ALL
  212689. asioObject = 0;
  212690. return false;
  212691. }
  212692. const String initDriver()
  212693. {
  212694. if (asioObject != 0)
  212695. {
  212696. char buffer [256];
  212697. zeromem (buffer, sizeof (buffer));
  212698. if (! asioObject->init (windowHandle))
  212699. {
  212700. asioObject->getErrorMessage (buffer);
  212701. return String (buffer, sizeof (buffer) - 1);
  212702. }
  212703. // just in case any daft drivers expect this to be called..
  212704. asioObject->getDriverName (buffer);
  212705. return String::empty;
  212706. }
  212707. return "No Driver";
  212708. }
  212709. const String openDevice()
  212710. {
  212711. // use this in case the driver starts opening dialog boxes..
  212712. Component modalWindow (String::empty);
  212713. modalWindow.setOpaque (true);
  212714. modalWindow.addToDesktop (0);
  212715. modalWindow.enterModalState();
  212716. // open the device and get its info..
  212717. log ("opening ASIO device: " + getName());
  212718. needToReset = false;
  212719. isReSync = false;
  212720. outputChannelNames.clear();
  212721. inputChannelNames.clear();
  212722. bufferSizes.clear();
  212723. sampleRates.clear();
  212724. isASIOOpen = false;
  212725. isOpen_ = false;
  212726. totalNumInputChans = 0;
  212727. totalNumOutputChans = 0;
  212728. numActiveInputChans = 0;
  212729. numActiveOutputChans = 0;
  212730. currentCallback = 0;
  212731. error = String::empty;
  212732. if (getName().isEmpty())
  212733. return error;
  212734. long err = 0;
  212735. if (loadDriver())
  212736. {
  212737. if ((error = initDriver()).isEmpty())
  212738. {
  212739. numActiveInputChans = 0;
  212740. numActiveOutputChans = 0;
  212741. totalNumInputChans = 0;
  212742. totalNumOutputChans = 0;
  212743. if (asioObject != 0
  212744. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  212745. {
  212746. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  212747. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212748. {
  212749. // find a list of buffer sizes..
  212750. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  212751. if (granularity >= 0)
  212752. {
  212753. granularity = jmax (1, (int) granularity);
  212754. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212755. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212756. }
  212757. else if (granularity < 0)
  212758. {
  212759. for (int i = 0; i < 18; ++i)
  212760. {
  212761. const int s = (1 << i);
  212762. if (s >= minSize && s <= maxSize)
  212763. bufferSizes.add (s);
  212764. }
  212765. }
  212766. if (! bufferSizes.contains (preferredSize))
  212767. bufferSizes.insert (0, preferredSize);
  212768. double currentRate = 0;
  212769. asioObject->getSampleRate (&currentRate);
  212770. if (currentRate <= 0.0 || currentRate > 192001.0)
  212771. {
  212772. log ("setting sample rate");
  212773. err = asioObject->setSampleRate (44100.0);
  212774. if (err != 0)
  212775. {
  212776. logError ("setting sample rate", err);
  212777. }
  212778. asioObject->getSampleRate (&currentRate);
  212779. }
  212780. currentSampleRate = currentRate;
  212781. postOutput = (asioObject->outputReady() == 0);
  212782. if (postOutput)
  212783. {
  212784. log ("ASIO outputReady = ok");
  212785. }
  212786. updateSampleRates();
  212787. // ..because cubase does it at this point
  212788. inputLatency = outputLatency = 0;
  212789. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212790. {
  212791. log ("ASIO - no latencies");
  212792. }
  212793. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212794. // create some dummy buffers now.. because cubase does..
  212795. numActiveInputChans = 0;
  212796. numActiveOutputChans = 0;
  212797. ASIOBufferInfo* info = bufferInfos;
  212798. int i, numChans = 0;
  212799. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212800. {
  212801. info->isInput = 1;
  212802. info->channelNum = i;
  212803. info->buffers[0] = info->buffers[1] = 0;
  212804. ++info;
  212805. ++numChans;
  212806. }
  212807. const int outputBufferIndex = numChans;
  212808. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212809. {
  212810. info->isInput = 0;
  212811. info->channelNum = i;
  212812. info->buffers[0] = info->buffers[1] = 0;
  212813. ++info;
  212814. ++numChans;
  212815. }
  212816. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212817. if (currentASIODev[0] == this)
  212818. {
  212819. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212820. callbacks.asioMessage = &asioMessagesCallback0;
  212821. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212822. }
  212823. else if (currentASIODev[1] == this)
  212824. {
  212825. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212826. callbacks.asioMessage = &asioMessagesCallback1;
  212827. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212828. }
  212829. else if (currentASIODev[2] == this)
  212830. {
  212831. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212832. callbacks.asioMessage = &asioMessagesCallback2;
  212833. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212834. }
  212835. else
  212836. {
  212837. jassertfalse;
  212838. }
  212839. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  212840. if (preferredSize > 0)
  212841. {
  212842. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  212843. if (err != 0)
  212844. {
  212845. logError ("dummy buffers", err);
  212846. }
  212847. }
  212848. long newInps = 0, newOuts = 0;
  212849. asioObject->getChannels (&newInps, &newOuts);
  212850. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  212851. {
  212852. totalNumInputChans = newInps;
  212853. totalNumOutputChans = newOuts;
  212854. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  212855. }
  212856. updateSampleRates();
  212857. ASIOChannelInfo channelInfo;
  212858. channelInfo.type = 0;
  212859. for (i = 0; i < totalNumInputChans; ++i)
  212860. {
  212861. zerostruct (channelInfo);
  212862. channelInfo.channel = i;
  212863. channelInfo.isInput = 1;
  212864. asioObject->getChannelInfo (&channelInfo);
  212865. inputChannelNames.add (String (channelInfo.name));
  212866. }
  212867. for (i = 0; i < totalNumOutputChans; ++i)
  212868. {
  212869. zerostruct (channelInfo);
  212870. channelInfo.channel = i;
  212871. channelInfo.isInput = 0;
  212872. asioObject->getChannelInfo (&channelInfo);
  212873. outputChannelNames.add (String (channelInfo.name));
  212874. typeToFormatParameters (channelInfo.type,
  212875. outputChannelBitDepths[i],
  212876. outputChannelBytesPerSample[i],
  212877. outputChannelIsFloat[i],
  212878. outputChannelLittleEndian[i]);
  212879. if (i < 2)
  212880. {
  212881. // clear the channels that are used with the dummy stuff
  212882. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212883. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212884. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212885. }
  212886. }
  212887. outputChannelNames.trim();
  212888. inputChannelNames.trim();
  212889. outputChannelNames.appendNumbersToDuplicates (false, true);
  212890. inputChannelNames.appendNumbersToDuplicates (false, true);
  212891. // start and stop because cubase does it..
  212892. asioObject->getLatencies (&inputLatency, &outputLatency);
  212893. if ((err = asioObject->start()) != 0)
  212894. {
  212895. // ignore an error here, as it might start later after setting other stuff up
  212896. logError ("ASIO start", err);
  212897. }
  212898. Thread::sleep (100);
  212899. asioObject->stop();
  212900. }
  212901. else
  212902. {
  212903. error = "Can't detect buffer sizes";
  212904. }
  212905. }
  212906. else
  212907. {
  212908. error = "Can't detect asio channels";
  212909. }
  212910. }
  212911. }
  212912. else
  212913. {
  212914. error = "No such device";
  212915. }
  212916. if (error.isNotEmpty())
  212917. {
  212918. logError (error, err);
  212919. if (asioObject != 0)
  212920. asioObject->disposeBuffers();
  212921. removeCurrentDriver();
  212922. isASIOOpen = false;
  212923. }
  212924. else
  212925. {
  212926. isASIOOpen = true;
  212927. log ("ASIO device open");
  212928. }
  212929. isOpen_ = false;
  212930. needToReset = false;
  212931. isReSync = false;
  212932. return error;
  212933. }
  212934. void JUCE_ASIOCALLBACK callback (const long index)
  212935. {
  212936. if (isStarted)
  212937. {
  212938. bufferIndex = index;
  212939. processBuffer();
  212940. }
  212941. else
  212942. {
  212943. if (postOutput && (asioObject != 0))
  212944. asioObject->outputReady();
  212945. }
  212946. calledback = true;
  212947. }
  212948. void processBuffer()
  212949. {
  212950. const ASIOBufferInfo* const infos = bufferInfos;
  212951. const int bi = bufferIndex;
  212952. const ScopedLock sl (callbackLock);
  212953. if (needToReset)
  212954. {
  212955. needToReset = false;
  212956. if (isReSync)
  212957. {
  212958. log ("! ASIO resync");
  212959. isReSync = false;
  212960. }
  212961. else
  212962. {
  212963. startTimer (20);
  212964. }
  212965. }
  212966. if (bi >= 0)
  212967. {
  212968. const int samps = currentBlockSizeSamples;
  212969. if (currentCallback != 0)
  212970. {
  212971. int i;
  212972. for (i = 0; i < numActiveInputChans; ++i)
  212973. {
  212974. float* const dst = inBuffers[i];
  212975. jassert (dst != 0);
  212976. const char* const src = (const char*) (infos[i].buffers[bi]);
  212977. if (inputChannelIsFloat[i])
  212978. {
  212979. memcpy (dst, src, samps * sizeof (float));
  212980. }
  212981. else
  212982. {
  212983. jassert (dst == tempBuffer + (samps * i));
  212984. switch (inputChannelBitDepths[i])
  212985. {
  212986. case 16:
  212987. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212988. samps, inputChannelLittleEndian[i]);
  212989. break;
  212990. case 24:
  212991. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212992. samps, inputChannelLittleEndian[i]);
  212993. break;
  212994. case 32:
  212995. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212996. samps, inputChannelLittleEndian[i]);
  212997. break;
  212998. case 64:
  212999. jassertfalse;
  213000. break;
  213001. }
  213002. }
  213003. }
  213004. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213005. outBuffers, numActiveOutputChans, samps);
  213006. for (i = 0; i < numActiveOutputChans; ++i)
  213007. {
  213008. float* const src = outBuffers[i];
  213009. jassert (src != 0);
  213010. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213011. if (outputChannelIsFloat[i])
  213012. {
  213013. memcpy (dst, src, samps * sizeof (float));
  213014. }
  213015. else
  213016. {
  213017. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213018. switch (outputChannelBitDepths[i])
  213019. {
  213020. case 16:
  213021. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213022. samps, outputChannelLittleEndian[i]);
  213023. break;
  213024. case 24:
  213025. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213026. samps, outputChannelLittleEndian[i]);
  213027. break;
  213028. case 32:
  213029. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213030. samps, outputChannelLittleEndian[i]);
  213031. break;
  213032. case 64:
  213033. jassertfalse;
  213034. break;
  213035. }
  213036. }
  213037. }
  213038. }
  213039. else
  213040. {
  213041. for (int i = 0; i < numActiveOutputChans; ++i)
  213042. {
  213043. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213044. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213045. }
  213046. }
  213047. }
  213048. if (postOutput)
  213049. asioObject->outputReady();
  213050. }
  213051. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213052. {
  213053. if (currentASIODev[0] != 0)
  213054. currentASIODev[0]->callback (index);
  213055. return 0;
  213056. }
  213057. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213058. {
  213059. if (currentASIODev[1] != 0)
  213060. currentASIODev[1]->callback (index);
  213061. return 0;
  213062. }
  213063. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213064. {
  213065. if (currentASIODev[2] != 0)
  213066. currentASIODev[2]->callback (index);
  213067. return 0;
  213068. }
  213069. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213070. {
  213071. if (currentASIODev[0] != 0)
  213072. currentASIODev[0]->callback (index);
  213073. }
  213074. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213075. {
  213076. if (currentASIODev[1] != 0)
  213077. currentASIODev[1]->callback (index);
  213078. }
  213079. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213080. {
  213081. if (currentASIODev[2] != 0)
  213082. currentASIODev[2]->callback (index);
  213083. }
  213084. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213085. {
  213086. return asioMessagesCallback (selector, value, 0);
  213087. }
  213088. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213089. {
  213090. return asioMessagesCallback (selector, value, 1);
  213091. }
  213092. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213093. {
  213094. return asioMessagesCallback (selector, value, 2);
  213095. }
  213096. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213097. {
  213098. switch (selector)
  213099. {
  213100. case kAsioSelectorSupported:
  213101. if (value == kAsioResetRequest
  213102. || value == kAsioEngineVersion
  213103. || value == kAsioResyncRequest
  213104. || value == kAsioLatenciesChanged
  213105. || value == kAsioSupportsInputMonitor)
  213106. return 1;
  213107. break;
  213108. case kAsioBufferSizeChange:
  213109. break;
  213110. case kAsioResetRequest:
  213111. if (currentASIODev[deviceIndex] != 0)
  213112. currentASIODev[deviceIndex]->resetRequest();
  213113. return 1;
  213114. case kAsioResyncRequest:
  213115. if (currentASIODev[deviceIndex] != 0)
  213116. currentASIODev[deviceIndex]->resyncRequest();
  213117. return 1;
  213118. case kAsioLatenciesChanged:
  213119. return 1;
  213120. case kAsioEngineVersion:
  213121. return 2;
  213122. case kAsioSupportsTimeInfo:
  213123. case kAsioSupportsTimeCode:
  213124. return 0;
  213125. }
  213126. return 0;
  213127. }
  213128. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213129. {
  213130. }
  213131. static void convertInt16ToFloat (const char* src,
  213132. float* dest,
  213133. const int srcStrideBytes,
  213134. int numSamples,
  213135. const bool littleEndian) throw()
  213136. {
  213137. const double g = 1.0 / 32768.0;
  213138. if (littleEndian)
  213139. {
  213140. while (--numSamples >= 0)
  213141. {
  213142. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213143. src += srcStrideBytes;
  213144. }
  213145. }
  213146. else
  213147. {
  213148. while (--numSamples >= 0)
  213149. {
  213150. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213151. src += srcStrideBytes;
  213152. }
  213153. }
  213154. }
  213155. static void convertFloatToInt16 (const float* src,
  213156. char* dest,
  213157. const int dstStrideBytes,
  213158. int numSamples,
  213159. const bool littleEndian) throw()
  213160. {
  213161. const double maxVal = (double) 0x7fff;
  213162. if (littleEndian)
  213163. {
  213164. while (--numSamples >= 0)
  213165. {
  213166. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213167. dest += dstStrideBytes;
  213168. }
  213169. }
  213170. else
  213171. {
  213172. while (--numSamples >= 0)
  213173. {
  213174. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213175. dest += dstStrideBytes;
  213176. }
  213177. }
  213178. }
  213179. static void convertInt24ToFloat (const char* src,
  213180. float* dest,
  213181. const int srcStrideBytes,
  213182. int numSamples,
  213183. const bool littleEndian) throw()
  213184. {
  213185. const double g = 1.0 / 0x7fffff;
  213186. if (littleEndian)
  213187. {
  213188. while (--numSamples >= 0)
  213189. {
  213190. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213191. src += srcStrideBytes;
  213192. }
  213193. }
  213194. else
  213195. {
  213196. while (--numSamples >= 0)
  213197. {
  213198. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213199. src += srcStrideBytes;
  213200. }
  213201. }
  213202. }
  213203. static void convertFloatToInt24 (const float* src,
  213204. char* dest,
  213205. const int dstStrideBytes,
  213206. int numSamples,
  213207. const bool littleEndian) throw()
  213208. {
  213209. const double maxVal = (double) 0x7fffff;
  213210. if (littleEndian)
  213211. {
  213212. while (--numSamples >= 0)
  213213. {
  213214. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213215. dest += dstStrideBytes;
  213216. }
  213217. }
  213218. else
  213219. {
  213220. while (--numSamples >= 0)
  213221. {
  213222. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213223. dest += dstStrideBytes;
  213224. }
  213225. }
  213226. }
  213227. static void convertInt32ToFloat (const char* src,
  213228. float* dest,
  213229. const int srcStrideBytes,
  213230. int numSamples,
  213231. const bool littleEndian) throw()
  213232. {
  213233. const double g = 1.0 / 0x7fffffff;
  213234. if (littleEndian)
  213235. {
  213236. while (--numSamples >= 0)
  213237. {
  213238. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213239. src += srcStrideBytes;
  213240. }
  213241. }
  213242. else
  213243. {
  213244. while (--numSamples >= 0)
  213245. {
  213246. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213247. src += srcStrideBytes;
  213248. }
  213249. }
  213250. }
  213251. static void convertFloatToInt32 (const float* src,
  213252. char* dest,
  213253. const int dstStrideBytes,
  213254. int numSamples,
  213255. const bool littleEndian) throw()
  213256. {
  213257. const double maxVal = (double) 0x7fffffff;
  213258. if (littleEndian)
  213259. {
  213260. while (--numSamples >= 0)
  213261. {
  213262. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213263. dest += dstStrideBytes;
  213264. }
  213265. }
  213266. else
  213267. {
  213268. while (--numSamples >= 0)
  213269. {
  213270. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213271. dest += dstStrideBytes;
  213272. }
  213273. }
  213274. }
  213275. static void typeToFormatParameters (const long type,
  213276. int& bitDepth,
  213277. int& byteStride,
  213278. bool& formatIsFloat,
  213279. bool& littleEndian) throw()
  213280. {
  213281. bitDepth = 0;
  213282. littleEndian = false;
  213283. formatIsFloat = false;
  213284. switch (type)
  213285. {
  213286. case ASIOSTInt16MSB:
  213287. case ASIOSTInt16LSB:
  213288. case ASIOSTInt32MSB16:
  213289. case ASIOSTInt32LSB16:
  213290. bitDepth = 16; break;
  213291. case ASIOSTFloat32MSB:
  213292. case ASIOSTFloat32LSB:
  213293. formatIsFloat = true;
  213294. bitDepth = 32; break;
  213295. case ASIOSTInt32MSB:
  213296. case ASIOSTInt32LSB:
  213297. bitDepth = 32; break;
  213298. case ASIOSTInt24MSB:
  213299. case ASIOSTInt24LSB:
  213300. case ASIOSTInt32MSB24:
  213301. case ASIOSTInt32LSB24:
  213302. case ASIOSTInt32MSB18:
  213303. case ASIOSTInt32MSB20:
  213304. case ASIOSTInt32LSB18:
  213305. case ASIOSTInt32LSB20:
  213306. bitDepth = 24; break;
  213307. case ASIOSTFloat64MSB:
  213308. case ASIOSTFloat64LSB:
  213309. default:
  213310. bitDepth = 64;
  213311. break;
  213312. }
  213313. switch (type)
  213314. {
  213315. case ASIOSTInt16MSB:
  213316. case ASIOSTInt32MSB16:
  213317. case ASIOSTFloat32MSB:
  213318. case ASIOSTFloat64MSB:
  213319. case ASIOSTInt32MSB:
  213320. case ASIOSTInt32MSB18:
  213321. case ASIOSTInt32MSB20:
  213322. case ASIOSTInt32MSB24:
  213323. case ASIOSTInt24MSB:
  213324. littleEndian = false; break;
  213325. case ASIOSTInt16LSB:
  213326. case ASIOSTInt32LSB16:
  213327. case ASIOSTFloat32LSB:
  213328. case ASIOSTFloat64LSB:
  213329. case ASIOSTInt32LSB:
  213330. case ASIOSTInt32LSB18:
  213331. case ASIOSTInt32LSB20:
  213332. case ASIOSTInt32LSB24:
  213333. case ASIOSTInt24LSB:
  213334. littleEndian = true; break;
  213335. default:
  213336. break;
  213337. }
  213338. switch (type)
  213339. {
  213340. case ASIOSTInt16LSB:
  213341. case ASIOSTInt16MSB:
  213342. byteStride = 2; break;
  213343. case ASIOSTInt24LSB:
  213344. case ASIOSTInt24MSB:
  213345. byteStride = 3; break;
  213346. case ASIOSTInt32MSB16:
  213347. case ASIOSTInt32LSB16:
  213348. case ASIOSTInt32MSB:
  213349. case ASIOSTInt32MSB18:
  213350. case ASIOSTInt32MSB20:
  213351. case ASIOSTInt32MSB24:
  213352. case ASIOSTInt32LSB:
  213353. case ASIOSTInt32LSB18:
  213354. case ASIOSTInt32LSB20:
  213355. case ASIOSTInt32LSB24:
  213356. case ASIOSTFloat32LSB:
  213357. case ASIOSTFloat32MSB:
  213358. byteStride = 4; break;
  213359. case ASIOSTFloat64MSB:
  213360. case ASIOSTFloat64LSB:
  213361. byteStride = 8; break;
  213362. default:
  213363. break;
  213364. }
  213365. }
  213366. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213367. };
  213368. class ASIOAudioIODeviceType : public AudioIODeviceType
  213369. {
  213370. public:
  213371. ASIOAudioIODeviceType()
  213372. : AudioIODeviceType ("ASIO"),
  213373. hasScanned (false)
  213374. {
  213375. CoInitialize (0);
  213376. }
  213377. ~ASIOAudioIODeviceType()
  213378. {
  213379. }
  213380. void scanForDevices()
  213381. {
  213382. hasScanned = true;
  213383. deviceNames.clear();
  213384. classIds.clear();
  213385. HKEY hk = 0;
  213386. int index = 0;
  213387. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213388. {
  213389. for (;;)
  213390. {
  213391. char name [256];
  213392. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213393. {
  213394. addDriverInfo (name, hk);
  213395. }
  213396. else
  213397. {
  213398. break;
  213399. }
  213400. }
  213401. RegCloseKey (hk);
  213402. }
  213403. }
  213404. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213405. {
  213406. jassert (hasScanned); // need to call scanForDevices() before doing this
  213407. return deviceNames;
  213408. }
  213409. int getDefaultDeviceIndex (bool) const
  213410. {
  213411. jassert (hasScanned); // need to call scanForDevices() before doing this
  213412. for (int i = deviceNames.size(); --i >= 0;)
  213413. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213414. return i; // asio4all is a safe choice for a default..
  213415. #if JUCE_DEBUG
  213416. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213417. return 1; // (the digi m-box driver crashes the app when you run
  213418. // it in the debugger, which can be a bit annoying)
  213419. #endif
  213420. return 0;
  213421. }
  213422. static int findFreeSlot()
  213423. {
  213424. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213425. if (currentASIODev[i] == 0)
  213426. return i;
  213427. jassertfalse; // unfortunately you can only have a finite number
  213428. // of ASIO devices open at the same time..
  213429. return -1;
  213430. }
  213431. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213432. {
  213433. jassert (hasScanned); // need to call scanForDevices() before doing this
  213434. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213435. }
  213436. bool hasSeparateInputsAndOutputs() const { return false; }
  213437. AudioIODevice* createDevice (const String& outputDeviceName,
  213438. const String& inputDeviceName)
  213439. {
  213440. // ASIO can't open two different devices for input and output - they must be the same one.
  213441. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213442. jassert (hasScanned); // need to call scanForDevices() before doing this
  213443. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213444. : inputDeviceName);
  213445. if (index >= 0)
  213446. {
  213447. const int freeSlot = findFreeSlot();
  213448. if (freeSlot >= 0)
  213449. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213450. }
  213451. return 0;
  213452. }
  213453. private:
  213454. StringArray deviceNames;
  213455. OwnedArray <CLSID> classIds;
  213456. bool hasScanned;
  213457. static bool checkClassIsOk (const String& classId)
  213458. {
  213459. HKEY hk = 0;
  213460. bool ok = false;
  213461. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213462. {
  213463. int index = 0;
  213464. for (;;)
  213465. {
  213466. WCHAR buf [512];
  213467. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213468. {
  213469. if (classId.equalsIgnoreCase (buf))
  213470. {
  213471. HKEY subKey, pathKey;
  213472. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213473. {
  213474. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213475. {
  213476. WCHAR pathName [1024];
  213477. DWORD dtype = REG_SZ;
  213478. DWORD dsize = sizeof (pathName);
  213479. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213480. ok = File (pathName).exists();
  213481. RegCloseKey (pathKey);
  213482. }
  213483. RegCloseKey (subKey);
  213484. }
  213485. break;
  213486. }
  213487. }
  213488. else
  213489. {
  213490. break;
  213491. }
  213492. }
  213493. RegCloseKey (hk);
  213494. }
  213495. return ok;
  213496. }
  213497. void addDriverInfo (const String& keyName, HKEY hk)
  213498. {
  213499. HKEY subKey;
  213500. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213501. {
  213502. WCHAR buf [256];
  213503. zerostruct (buf);
  213504. DWORD dtype = REG_SZ;
  213505. DWORD dsize = sizeof (buf);
  213506. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213507. {
  213508. if (dsize > 0 && checkClassIsOk (buf))
  213509. {
  213510. CLSID classId;
  213511. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213512. {
  213513. dtype = REG_SZ;
  213514. dsize = sizeof (buf);
  213515. String deviceName;
  213516. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213517. deviceName = buf;
  213518. else
  213519. deviceName = keyName;
  213520. log ("found " + deviceName);
  213521. deviceNames.add (deviceName);
  213522. classIds.add (new CLSID (classId));
  213523. }
  213524. }
  213525. RegCloseKey (subKey);
  213526. }
  213527. }
  213528. }
  213529. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213530. };
  213531. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  213532. {
  213533. return new ASIOAudioIODeviceType();
  213534. }
  213535. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213536. void* guid,
  213537. const String& optionalDllForDirectLoading)
  213538. {
  213539. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213540. if (freeSlot < 0)
  213541. return 0;
  213542. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213543. }
  213544. #undef logError
  213545. #undef log
  213546. #endif
  213547. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213548. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213549. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213550. // compiled on its own).
  213551. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213552. END_JUCE_NAMESPACE
  213553. extern "C"
  213554. {
  213555. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213556. typedef struct typeDSBUFFERDESC
  213557. {
  213558. DWORD dwSize;
  213559. DWORD dwFlags;
  213560. DWORD dwBufferBytes;
  213561. DWORD dwReserved;
  213562. LPWAVEFORMATEX lpwfxFormat;
  213563. GUID guid3DAlgorithm;
  213564. } DSBUFFERDESC;
  213565. struct IDirectSoundBuffer;
  213566. #undef INTERFACE
  213567. #define INTERFACE IDirectSound
  213568. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213569. {
  213570. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213571. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213572. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213573. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213574. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213575. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213576. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213577. STDMETHOD(Compact) (THIS) PURE;
  213578. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213579. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213580. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213581. };
  213582. #undef INTERFACE
  213583. #define INTERFACE IDirectSoundBuffer
  213584. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213585. {
  213586. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213587. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213588. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213589. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213590. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213591. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213592. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213593. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213594. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213595. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213596. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213597. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213598. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213599. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213600. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213601. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213602. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213603. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213604. STDMETHOD(Stop) (THIS) PURE;
  213605. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213606. STDMETHOD(Restore) (THIS) PURE;
  213607. };
  213608. typedef struct typeDSCBUFFERDESC
  213609. {
  213610. DWORD dwSize;
  213611. DWORD dwFlags;
  213612. DWORD dwBufferBytes;
  213613. DWORD dwReserved;
  213614. LPWAVEFORMATEX lpwfxFormat;
  213615. } DSCBUFFERDESC;
  213616. struct IDirectSoundCaptureBuffer;
  213617. #undef INTERFACE
  213618. #define INTERFACE IDirectSoundCapture
  213619. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  213620. {
  213621. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213622. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213623. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213624. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  213625. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213626. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213627. };
  213628. #undef INTERFACE
  213629. #define INTERFACE IDirectSoundCaptureBuffer
  213630. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  213631. {
  213632. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213633. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213634. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213635. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213636. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213637. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213638. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213639. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  213640. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213641. STDMETHOD(Start) (THIS_ DWORD) PURE;
  213642. STDMETHOD(Stop) (THIS) PURE;
  213643. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213644. };
  213645. };
  213646. BEGIN_JUCE_NAMESPACE
  213647. namespace
  213648. {
  213649. const String getDSErrorMessage (HRESULT hr)
  213650. {
  213651. const char* result = 0;
  213652. switch (hr)
  213653. {
  213654. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  213655. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  213656. case E_INVALIDARG: result = "Invalid parameter"; break;
  213657. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  213658. case E_FAIL: result = "Generic error"; break;
  213659. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  213660. case E_OUTOFMEMORY: result = "Out of memory"; break;
  213661. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  213662. case E_NOTIMPL: result = "Unsupported function"; break;
  213663. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  213664. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  213665. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  213666. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  213667. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  213668. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  213669. case E_NOINTERFACE: result = "No interface"; break;
  213670. case S_OK: result = "No error"; break;
  213671. default: return "Unknown error: " + String ((int) hr);
  213672. }
  213673. return result;
  213674. }
  213675. #define DS_DEBUGGING 1
  213676. #ifdef DS_DEBUGGING
  213677. #define CATCH JUCE_CATCH_EXCEPTION
  213678. #undef log
  213679. #define log(a) Logger::writeToLog(a);
  213680. #undef logError
  213681. #define logError(a) logDSError(a, __LINE__);
  213682. static void logDSError (HRESULT hr, int lineNum)
  213683. {
  213684. if (hr != S_OK)
  213685. {
  213686. String error ("DS error at line ");
  213687. error << lineNum << " - " << getDSErrorMessage (hr);
  213688. log (error);
  213689. }
  213690. }
  213691. #else
  213692. #define CATCH JUCE_CATCH_ALL
  213693. #define log(a)
  213694. #define logError(a)
  213695. #endif
  213696. #define DSOUND_FUNCTION(functionName, params) \
  213697. typedef HRESULT (WINAPI *type##functionName) params; \
  213698. static type##functionName ds##functionName = 0;
  213699. #define DSOUND_FUNCTION_LOAD(functionName) \
  213700. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  213701. jassert (ds##functionName != 0);
  213702. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  213703. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  213704. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  213705. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  213706. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213707. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213708. void initialiseDSoundFunctions()
  213709. {
  213710. if (dsDirectSoundCreate == 0)
  213711. {
  213712. HMODULE h = LoadLibraryA ("dsound.dll");
  213713. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  213714. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  213715. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  213716. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  213717. }
  213718. }
  213719. }
  213720. class DSoundInternalOutChannel
  213721. {
  213722. public:
  213723. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  213724. int bufferSize, float* left, float* right)
  213725. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213726. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213727. pDirectSound (0), pOutputBuffer (0)
  213728. {
  213729. }
  213730. ~DSoundInternalOutChannel()
  213731. {
  213732. close();
  213733. }
  213734. void close()
  213735. {
  213736. HRESULT hr;
  213737. if (pOutputBuffer != 0)
  213738. {
  213739. log ("closing dsound out: " + name);
  213740. hr = pOutputBuffer->Stop();
  213741. logError (hr);
  213742. hr = pOutputBuffer->Release();
  213743. pOutputBuffer = 0;
  213744. logError (hr);
  213745. }
  213746. if (pDirectSound != 0)
  213747. {
  213748. hr = pDirectSound->Release();
  213749. pDirectSound = 0;
  213750. logError (hr);
  213751. }
  213752. }
  213753. const String open()
  213754. {
  213755. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213756. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213757. pDirectSound = 0;
  213758. pOutputBuffer = 0;
  213759. writeOffset = 0;
  213760. String error;
  213761. HRESULT hr = E_NOINTERFACE;
  213762. if (dsDirectSoundCreate != 0)
  213763. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213764. if (hr == S_OK)
  213765. {
  213766. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213767. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213768. const int numChannels = 2;
  213769. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213770. logError (hr);
  213771. if (hr == S_OK)
  213772. {
  213773. IDirectSoundBuffer* pPrimaryBuffer;
  213774. DSBUFFERDESC primaryDesc;
  213775. zerostruct (primaryDesc);
  213776. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213777. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213778. primaryDesc.dwBufferBytes = 0;
  213779. primaryDesc.lpwfxFormat = 0;
  213780. log ("opening dsound out step 2");
  213781. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213782. logError (hr);
  213783. if (hr == S_OK)
  213784. {
  213785. WAVEFORMATEX wfFormat;
  213786. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213787. wfFormat.nChannels = (unsigned short) numChannels;
  213788. wfFormat.nSamplesPerSec = sampleRate;
  213789. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213790. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213791. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213792. wfFormat.cbSize = 0;
  213793. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213794. logError (hr);
  213795. if (hr == S_OK)
  213796. {
  213797. DSBUFFERDESC secondaryDesc;
  213798. zerostruct (secondaryDesc);
  213799. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213800. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213801. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213802. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213803. secondaryDesc.lpwfxFormat = &wfFormat;
  213804. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213805. logError (hr);
  213806. if (hr == S_OK)
  213807. {
  213808. log ("opening dsound out step 3");
  213809. DWORD dwDataLen;
  213810. unsigned char* pDSBuffData;
  213811. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213812. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213813. logError (hr);
  213814. if (hr == S_OK)
  213815. {
  213816. zeromem (pDSBuffData, dwDataLen);
  213817. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213818. if (hr == S_OK)
  213819. {
  213820. hr = pOutputBuffer->SetCurrentPosition (0);
  213821. if (hr == S_OK)
  213822. {
  213823. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213824. if (hr == S_OK)
  213825. return String::empty;
  213826. }
  213827. }
  213828. }
  213829. }
  213830. }
  213831. }
  213832. }
  213833. }
  213834. error = getDSErrorMessage (hr);
  213835. close();
  213836. return error;
  213837. }
  213838. void synchronisePosition()
  213839. {
  213840. if (pOutputBuffer != 0)
  213841. {
  213842. DWORD playCursor;
  213843. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213844. }
  213845. }
  213846. bool service()
  213847. {
  213848. if (pOutputBuffer == 0)
  213849. return true;
  213850. DWORD playCursor, writeCursor;
  213851. for (;;)
  213852. {
  213853. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213854. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213855. {
  213856. pOutputBuffer->Restore();
  213857. continue;
  213858. }
  213859. if (hr == S_OK)
  213860. break;
  213861. logError (hr);
  213862. jassertfalse;
  213863. return true;
  213864. }
  213865. int playWriteGap = writeCursor - playCursor;
  213866. if (playWriteGap < 0)
  213867. playWriteGap += totalBytesPerBuffer;
  213868. int bytesEmpty = playCursor - writeOffset;
  213869. if (bytesEmpty < 0)
  213870. bytesEmpty += totalBytesPerBuffer;
  213871. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213872. {
  213873. writeOffset = writeCursor;
  213874. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213875. }
  213876. if (bytesEmpty >= bytesPerBuffer)
  213877. {
  213878. void* lpbuf1 = 0;
  213879. void* lpbuf2 = 0;
  213880. DWORD dwSize1 = 0;
  213881. DWORD dwSize2 = 0;
  213882. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  213883. &lpbuf1, &dwSize1,
  213884. &lpbuf2, &dwSize2, 0);
  213885. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213886. {
  213887. pOutputBuffer->Restore();
  213888. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  213889. &lpbuf1, &dwSize1,
  213890. &lpbuf2, &dwSize2, 0);
  213891. }
  213892. if (hr == S_OK)
  213893. {
  213894. if (bitDepth == 16)
  213895. {
  213896. int* dest = static_cast<int*> (lpbuf1);
  213897. const float* left = leftBuffer;
  213898. const float* right = rightBuffer;
  213899. int samples1 = dwSize1 >> 2;
  213900. int samples2 = dwSize2 >> 2;
  213901. if (left == 0)
  213902. {
  213903. while (--samples1 >= 0)
  213904. *dest++ = (convertInputValue (*right++) << 16);
  213905. dest = static_cast<int*> (lpbuf2);
  213906. while (--samples2 >= 0)
  213907. *dest++ = (convertInputValue (*right++) << 16);
  213908. }
  213909. else if (right == 0)
  213910. {
  213911. while (--samples1 >= 0)
  213912. *dest++ = (0xffff & convertInputValue (*left++));
  213913. dest = static_cast<int*> (lpbuf2);
  213914. while (--samples2 >= 0)
  213915. *dest++ = (0xffff & convertInputValue (*left++));
  213916. }
  213917. else
  213918. {
  213919. while (--samples1 >= 0)
  213920. {
  213921. const int l = convertInputValue (*left++);
  213922. const int r = convertInputValue (*right++);
  213923. *dest++ = (r << 16) | (0xffff & l);
  213924. }
  213925. dest = static_cast<int*> (lpbuf2);
  213926. while (--samples2 >= 0)
  213927. {
  213928. const int l = convertInputValue (*left++);
  213929. const int r = convertInputValue (*right++);
  213930. *dest++ = (r << 16) | (0xffff & l);
  213931. }
  213932. }
  213933. }
  213934. else
  213935. {
  213936. jassertfalse;
  213937. }
  213938. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213939. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213940. }
  213941. else
  213942. {
  213943. jassertfalse;
  213944. logError (hr);
  213945. }
  213946. bytesEmpty -= bytesPerBuffer;
  213947. return true;
  213948. }
  213949. else
  213950. {
  213951. return false;
  213952. }
  213953. }
  213954. int bitDepth;
  213955. bool doneFlag;
  213956. private:
  213957. String name;
  213958. LPGUID guid;
  213959. int sampleRate, bufferSizeSamples;
  213960. float* leftBuffer;
  213961. float* rightBuffer;
  213962. IDirectSound* pDirectSound;
  213963. IDirectSoundBuffer* pOutputBuffer;
  213964. DWORD writeOffset;
  213965. int totalBytesPerBuffer, bytesPerBuffer;
  213966. unsigned int lastPlayCursor;
  213967. static inline int convertInputValue (const float v) throw()
  213968. {
  213969. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  213970. }
  213971. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  213972. };
  213973. struct DSoundInternalInChannel
  213974. {
  213975. public:
  213976. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  213977. int bufferSize, float* left, float* right)
  213978. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213979. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213980. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  213981. {
  213982. }
  213983. ~DSoundInternalInChannel()
  213984. {
  213985. close();
  213986. }
  213987. void close()
  213988. {
  213989. HRESULT hr;
  213990. if (pInputBuffer != 0)
  213991. {
  213992. log ("closing dsound in: " + name);
  213993. hr = pInputBuffer->Stop();
  213994. logError (hr);
  213995. hr = pInputBuffer->Release();
  213996. pInputBuffer = 0;
  213997. logError (hr);
  213998. }
  213999. if (pDirectSoundCapture != 0)
  214000. {
  214001. hr = pDirectSoundCapture->Release();
  214002. pDirectSoundCapture = 0;
  214003. logError (hr);
  214004. }
  214005. if (pDirectSound != 0)
  214006. {
  214007. hr = pDirectSound->Release();
  214008. pDirectSound = 0;
  214009. logError (hr);
  214010. }
  214011. }
  214012. const String open()
  214013. {
  214014. log ("opening dsound in device: " + name
  214015. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214016. pDirectSound = 0;
  214017. pDirectSoundCapture = 0;
  214018. pInputBuffer = 0;
  214019. readOffset = 0;
  214020. totalBytesPerBuffer = 0;
  214021. String error;
  214022. HRESULT hr = E_NOINTERFACE;
  214023. if (dsDirectSoundCaptureCreate != 0)
  214024. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214025. logError (hr);
  214026. if (hr == S_OK)
  214027. {
  214028. const int numChannels = 2;
  214029. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214030. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214031. WAVEFORMATEX wfFormat;
  214032. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214033. wfFormat.nChannels = (unsigned short)numChannels;
  214034. wfFormat.nSamplesPerSec = sampleRate;
  214035. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214036. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214037. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214038. wfFormat.cbSize = 0;
  214039. DSCBUFFERDESC captureDesc;
  214040. zerostruct (captureDesc);
  214041. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214042. captureDesc.dwFlags = 0;
  214043. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214044. captureDesc.lpwfxFormat = &wfFormat;
  214045. log ("opening dsound in step 2");
  214046. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214047. logError (hr);
  214048. if (hr == S_OK)
  214049. {
  214050. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214051. logError (hr);
  214052. if (hr == S_OK)
  214053. return String::empty;
  214054. }
  214055. }
  214056. error = getDSErrorMessage (hr);
  214057. close();
  214058. return error;
  214059. }
  214060. void synchronisePosition()
  214061. {
  214062. if (pInputBuffer != 0)
  214063. {
  214064. DWORD capturePos;
  214065. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214066. }
  214067. }
  214068. bool service()
  214069. {
  214070. if (pInputBuffer == 0)
  214071. return true;
  214072. DWORD capturePos, readPos;
  214073. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214074. logError (hr);
  214075. if (hr != S_OK)
  214076. return true;
  214077. int bytesFilled = readPos - readOffset;
  214078. if (bytesFilled < 0)
  214079. bytesFilled += totalBytesPerBuffer;
  214080. if (bytesFilled >= bytesPerBuffer)
  214081. {
  214082. LPBYTE lpbuf1 = 0;
  214083. LPBYTE lpbuf2 = 0;
  214084. DWORD dwsize1 = 0;
  214085. DWORD dwsize2 = 0;
  214086. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  214087. (void**) &lpbuf1, &dwsize1,
  214088. (void**) &lpbuf2, &dwsize2, 0);
  214089. if (hr == S_OK)
  214090. {
  214091. if (bitDepth == 16)
  214092. {
  214093. const float g = 1.0f / 32768.0f;
  214094. float* destL = leftBuffer;
  214095. float* destR = rightBuffer;
  214096. int samples1 = dwsize1 >> 2;
  214097. int samples2 = dwsize2 >> 2;
  214098. const short* src = (const short*)lpbuf1;
  214099. if (destL == 0)
  214100. {
  214101. while (--samples1 >= 0)
  214102. {
  214103. ++src;
  214104. *destR++ = *src++ * g;
  214105. }
  214106. src = (const short*)lpbuf2;
  214107. while (--samples2 >= 0)
  214108. {
  214109. ++src;
  214110. *destR++ = *src++ * g;
  214111. }
  214112. }
  214113. else if (destR == 0)
  214114. {
  214115. while (--samples1 >= 0)
  214116. {
  214117. *destL++ = *src++ * g;
  214118. ++src;
  214119. }
  214120. src = (const short*)lpbuf2;
  214121. while (--samples2 >= 0)
  214122. {
  214123. *destL++ = *src++ * g;
  214124. ++src;
  214125. }
  214126. }
  214127. else
  214128. {
  214129. while (--samples1 >= 0)
  214130. {
  214131. *destL++ = *src++ * g;
  214132. *destR++ = *src++ * g;
  214133. }
  214134. src = (const short*)lpbuf2;
  214135. while (--samples2 >= 0)
  214136. {
  214137. *destL++ = *src++ * g;
  214138. *destR++ = *src++ * g;
  214139. }
  214140. }
  214141. }
  214142. else
  214143. {
  214144. jassertfalse;
  214145. }
  214146. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214147. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214148. }
  214149. else
  214150. {
  214151. logError (hr);
  214152. jassertfalse;
  214153. }
  214154. bytesFilled -= bytesPerBuffer;
  214155. return true;
  214156. }
  214157. else
  214158. {
  214159. return false;
  214160. }
  214161. }
  214162. unsigned int readOffset;
  214163. int bytesPerBuffer, totalBytesPerBuffer;
  214164. int bitDepth;
  214165. bool doneFlag;
  214166. private:
  214167. String name;
  214168. LPGUID guid;
  214169. int sampleRate, bufferSizeSamples;
  214170. float* leftBuffer;
  214171. float* rightBuffer;
  214172. IDirectSound* pDirectSound;
  214173. IDirectSoundCapture* pDirectSoundCapture;
  214174. IDirectSoundCaptureBuffer* pInputBuffer;
  214175. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  214176. };
  214177. class DSoundAudioIODevice : public AudioIODevice,
  214178. public Thread
  214179. {
  214180. public:
  214181. DSoundAudioIODevice (const String& deviceName,
  214182. const int outputDeviceIndex_,
  214183. const int inputDeviceIndex_)
  214184. : AudioIODevice (deviceName, "DirectSound"),
  214185. Thread ("Juce DSound"),
  214186. isOpen_ (false),
  214187. isStarted (false),
  214188. outputDeviceIndex (outputDeviceIndex_),
  214189. inputDeviceIndex (inputDeviceIndex_),
  214190. totalSamplesOut (0),
  214191. sampleRate (0.0),
  214192. inputBuffers (1, 1),
  214193. outputBuffers (1, 1),
  214194. callback (0),
  214195. bufferSizeSamples (0)
  214196. {
  214197. if (outputDeviceIndex_ >= 0)
  214198. {
  214199. outChannels.add (TRANS("Left"));
  214200. outChannels.add (TRANS("Right"));
  214201. }
  214202. if (inputDeviceIndex_ >= 0)
  214203. {
  214204. inChannels.add (TRANS("Left"));
  214205. inChannels.add (TRANS("Right"));
  214206. }
  214207. }
  214208. ~DSoundAudioIODevice()
  214209. {
  214210. close();
  214211. }
  214212. const String open (const BigInteger& inputChannels,
  214213. const BigInteger& outputChannels,
  214214. double sampleRate, int bufferSizeSamples)
  214215. {
  214216. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214217. isOpen_ = lastError.isEmpty();
  214218. return lastError;
  214219. }
  214220. void close()
  214221. {
  214222. stop();
  214223. if (isOpen_)
  214224. {
  214225. closeDevice();
  214226. isOpen_ = false;
  214227. }
  214228. }
  214229. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214230. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214231. double getCurrentSampleRate() { return sampleRate; }
  214232. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214233. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214234. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214235. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214236. const StringArray getOutputChannelNames() { return outChannels; }
  214237. const StringArray getInputChannelNames() { return inChannels; }
  214238. int getNumSampleRates() { return 4; }
  214239. int getDefaultBufferSize() { return 2560; }
  214240. int getNumBufferSizesAvailable() { return 50; }
  214241. double getSampleRate (int index)
  214242. {
  214243. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214244. return samps [jlimit (0, 3, index)];
  214245. }
  214246. int getBufferSizeSamples (int index)
  214247. {
  214248. int n = 64;
  214249. for (int i = 0; i < index; ++i)
  214250. n += (n < 512) ? 32
  214251. : ((n < 1024) ? 64
  214252. : ((n < 2048) ? 128 : 256));
  214253. return n;
  214254. }
  214255. int getCurrentBitDepth()
  214256. {
  214257. int i, bits = 256;
  214258. for (i = inChans.size(); --i >= 0;)
  214259. bits = jmin (bits, inChans[i]->bitDepth);
  214260. for (i = outChans.size(); --i >= 0;)
  214261. bits = jmin (bits, outChans[i]->bitDepth);
  214262. if (bits > 32)
  214263. bits = 16;
  214264. return bits;
  214265. }
  214266. void start (AudioIODeviceCallback* call)
  214267. {
  214268. if (isOpen_ && call != 0 && ! isStarted)
  214269. {
  214270. if (! isThreadRunning())
  214271. {
  214272. // something gone wrong and the thread's stopped..
  214273. isOpen_ = false;
  214274. return;
  214275. }
  214276. call->audioDeviceAboutToStart (this);
  214277. const ScopedLock sl (startStopLock);
  214278. callback = call;
  214279. isStarted = true;
  214280. }
  214281. }
  214282. void stop()
  214283. {
  214284. if (isStarted)
  214285. {
  214286. AudioIODeviceCallback* const callbackLocal = callback;
  214287. {
  214288. const ScopedLock sl (startStopLock);
  214289. isStarted = false;
  214290. }
  214291. if (callbackLocal != 0)
  214292. callbackLocal->audioDeviceStopped();
  214293. }
  214294. }
  214295. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214296. const String getLastError() { return lastError; }
  214297. StringArray inChannels, outChannels;
  214298. int outputDeviceIndex, inputDeviceIndex;
  214299. private:
  214300. bool isOpen_;
  214301. bool isStarted;
  214302. String lastError;
  214303. OwnedArray <DSoundInternalInChannel> inChans;
  214304. OwnedArray <DSoundInternalOutChannel> outChans;
  214305. WaitableEvent startEvent;
  214306. int bufferSizeSamples;
  214307. int volatile totalSamplesOut;
  214308. int64 volatile lastBlockTime;
  214309. double sampleRate;
  214310. BigInteger enabledInputs, enabledOutputs;
  214311. AudioSampleBuffer inputBuffers, outputBuffers;
  214312. AudioIODeviceCallback* callback;
  214313. CriticalSection startStopLock;
  214314. const String openDevice (const BigInteger& inputChannels,
  214315. const BigInteger& outputChannels,
  214316. double sampleRate_, int bufferSizeSamples_);
  214317. void closeDevice()
  214318. {
  214319. isStarted = false;
  214320. stopThread (5000);
  214321. inChans.clear();
  214322. outChans.clear();
  214323. inputBuffers.setSize (1, 1);
  214324. outputBuffers.setSize (1, 1);
  214325. }
  214326. void resync()
  214327. {
  214328. if (! threadShouldExit())
  214329. {
  214330. sleep (5);
  214331. int i;
  214332. for (i = 0; i < outChans.size(); ++i)
  214333. outChans.getUnchecked(i)->synchronisePosition();
  214334. for (i = 0; i < inChans.size(); ++i)
  214335. inChans.getUnchecked(i)->synchronisePosition();
  214336. }
  214337. }
  214338. public:
  214339. void run()
  214340. {
  214341. while (! threadShouldExit())
  214342. {
  214343. if (wait (100))
  214344. break;
  214345. }
  214346. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214347. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214348. while (! threadShouldExit())
  214349. {
  214350. int numToDo = 0;
  214351. uint32 startTime = Time::getMillisecondCounter();
  214352. int i;
  214353. for (i = inChans.size(); --i >= 0;)
  214354. {
  214355. inChans.getUnchecked(i)->doneFlag = false;
  214356. ++numToDo;
  214357. }
  214358. for (i = outChans.size(); --i >= 0;)
  214359. {
  214360. outChans.getUnchecked(i)->doneFlag = false;
  214361. ++numToDo;
  214362. }
  214363. if (numToDo > 0)
  214364. {
  214365. const int maxCount = 3;
  214366. int count = maxCount;
  214367. for (;;)
  214368. {
  214369. for (i = inChans.size(); --i >= 0;)
  214370. {
  214371. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214372. if ((! in->doneFlag) && in->service())
  214373. {
  214374. in->doneFlag = true;
  214375. --numToDo;
  214376. }
  214377. }
  214378. for (i = outChans.size(); --i >= 0;)
  214379. {
  214380. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214381. if ((! out->doneFlag) && out->service())
  214382. {
  214383. out->doneFlag = true;
  214384. --numToDo;
  214385. }
  214386. }
  214387. if (numToDo <= 0)
  214388. break;
  214389. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214390. {
  214391. resync();
  214392. break;
  214393. }
  214394. if (--count <= 0)
  214395. {
  214396. Sleep (1);
  214397. count = maxCount;
  214398. }
  214399. if (threadShouldExit())
  214400. return;
  214401. }
  214402. }
  214403. else
  214404. {
  214405. sleep (1);
  214406. }
  214407. const ScopedLock sl (startStopLock);
  214408. if (isStarted)
  214409. {
  214410. JUCE_TRY
  214411. {
  214412. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214413. inputBuffers.getNumChannels(),
  214414. outputBuffers.getArrayOfChannels(),
  214415. outputBuffers.getNumChannels(),
  214416. bufferSizeSamples);
  214417. }
  214418. JUCE_CATCH_EXCEPTION
  214419. totalSamplesOut += bufferSizeSamples;
  214420. }
  214421. else
  214422. {
  214423. outputBuffers.clear();
  214424. totalSamplesOut = 0;
  214425. sleep (1);
  214426. }
  214427. }
  214428. }
  214429. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214430. };
  214431. class DSoundAudioIODeviceType : public AudioIODeviceType
  214432. {
  214433. public:
  214434. DSoundAudioIODeviceType()
  214435. : AudioIODeviceType ("DirectSound"),
  214436. hasScanned (false)
  214437. {
  214438. initialiseDSoundFunctions();
  214439. }
  214440. void scanForDevices()
  214441. {
  214442. hasScanned = true;
  214443. outputDeviceNames.clear();
  214444. outputGuids.clear();
  214445. inputDeviceNames.clear();
  214446. inputGuids.clear();
  214447. if (dsDirectSoundEnumerateW != 0)
  214448. {
  214449. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214450. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214451. }
  214452. }
  214453. const StringArray getDeviceNames (bool wantInputNames) const
  214454. {
  214455. jassert (hasScanned); // need to call scanForDevices() before doing this
  214456. return wantInputNames ? inputDeviceNames
  214457. : outputDeviceNames;
  214458. }
  214459. int getDefaultDeviceIndex (bool /*forInput*/) const
  214460. {
  214461. jassert (hasScanned); // need to call scanForDevices() before doing this
  214462. return 0;
  214463. }
  214464. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214465. {
  214466. jassert (hasScanned); // need to call scanForDevices() before doing this
  214467. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214468. if (d == 0)
  214469. return -1;
  214470. return asInput ? d->inputDeviceIndex
  214471. : d->outputDeviceIndex;
  214472. }
  214473. bool hasSeparateInputsAndOutputs() const { return true; }
  214474. AudioIODevice* createDevice (const String& outputDeviceName,
  214475. const String& inputDeviceName)
  214476. {
  214477. jassert (hasScanned); // need to call scanForDevices() before doing this
  214478. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214479. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214480. if (outputIndex >= 0 || inputIndex >= 0)
  214481. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214482. : inputDeviceName,
  214483. outputIndex, inputIndex);
  214484. return 0;
  214485. }
  214486. StringArray outputDeviceNames, inputDeviceNames;
  214487. OwnedArray <GUID> outputGuids, inputGuids;
  214488. private:
  214489. bool hasScanned;
  214490. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214491. {
  214492. desc = desc.trim();
  214493. if (desc.isNotEmpty())
  214494. {
  214495. const String origDesc (desc);
  214496. int n = 2;
  214497. while (outputDeviceNames.contains (desc))
  214498. desc = origDesc + " (" + String (n++) + ")";
  214499. outputDeviceNames.add (desc);
  214500. if (lpGUID != 0)
  214501. outputGuids.add (new GUID (*lpGUID));
  214502. else
  214503. outputGuids.add (0);
  214504. }
  214505. return TRUE;
  214506. }
  214507. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214508. {
  214509. return ((DSoundAudioIODeviceType*) object)
  214510. ->outputEnumProc (lpGUID, String (description));
  214511. }
  214512. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214513. {
  214514. return ((DSoundAudioIODeviceType*) object)
  214515. ->outputEnumProc (lpGUID, String (description));
  214516. }
  214517. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214518. {
  214519. desc = desc.trim();
  214520. if (desc.isNotEmpty())
  214521. {
  214522. const String origDesc (desc);
  214523. int n = 2;
  214524. while (inputDeviceNames.contains (desc))
  214525. desc = origDesc + " (" + String (n++) + ")";
  214526. inputDeviceNames.add (desc);
  214527. if (lpGUID != 0)
  214528. inputGuids.add (new GUID (*lpGUID));
  214529. else
  214530. inputGuids.add (0);
  214531. }
  214532. return TRUE;
  214533. }
  214534. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214535. {
  214536. return ((DSoundAudioIODeviceType*) object)
  214537. ->inputEnumProc (lpGUID, String (description));
  214538. }
  214539. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214540. {
  214541. return ((DSoundAudioIODeviceType*) object)
  214542. ->inputEnumProc (lpGUID, String (description));
  214543. }
  214544. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214545. };
  214546. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214547. const BigInteger& outputChannels,
  214548. double sampleRate_, int bufferSizeSamples_)
  214549. {
  214550. closeDevice();
  214551. totalSamplesOut = 0;
  214552. sampleRate = sampleRate_;
  214553. if (bufferSizeSamples_ <= 0)
  214554. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214555. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214556. DSoundAudioIODeviceType dlh;
  214557. dlh.scanForDevices();
  214558. enabledInputs = inputChannels;
  214559. enabledInputs.setRange (inChannels.size(),
  214560. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214561. false);
  214562. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214563. inputBuffers.clear();
  214564. int i, numIns = 0;
  214565. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214566. {
  214567. float* left = 0;
  214568. if (enabledInputs[i])
  214569. left = inputBuffers.getSampleData (numIns++);
  214570. float* right = 0;
  214571. if (enabledInputs[i + 1])
  214572. right = inputBuffers.getSampleData (numIns++);
  214573. if (left != 0 || right != 0)
  214574. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214575. dlh.inputGuids [inputDeviceIndex],
  214576. (int) sampleRate, bufferSizeSamples,
  214577. left, right));
  214578. }
  214579. enabledOutputs = outputChannels;
  214580. enabledOutputs.setRange (outChannels.size(),
  214581. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214582. false);
  214583. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214584. outputBuffers.clear();
  214585. int numOuts = 0;
  214586. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214587. {
  214588. float* left = 0;
  214589. if (enabledOutputs[i])
  214590. left = outputBuffers.getSampleData (numOuts++);
  214591. float* right = 0;
  214592. if (enabledOutputs[i + 1])
  214593. right = outputBuffers.getSampleData (numOuts++);
  214594. if (left != 0 || right != 0)
  214595. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214596. dlh.outputGuids [outputDeviceIndex],
  214597. (int) sampleRate, bufferSizeSamples,
  214598. left, right));
  214599. }
  214600. String error;
  214601. // boost our priority while opening the devices to try to get better sync between them
  214602. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214603. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214604. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214605. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214606. for (i = 0; i < outChans.size(); ++i)
  214607. {
  214608. error = outChans[i]->open();
  214609. if (error.isNotEmpty())
  214610. {
  214611. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214612. break;
  214613. }
  214614. }
  214615. if (error.isEmpty())
  214616. {
  214617. for (i = 0; i < inChans.size(); ++i)
  214618. {
  214619. error = inChans[i]->open();
  214620. if (error.isNotEmpty())
  214621. {
  214622. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214623. break;
  214624. }
  214625. }
  214626. }
  214627. if (error.isEmpty())
  214628. {
  214629. totalSamplesOut = 0;
  214630. for (i = 0; i < outChans.size(); ++i)
  214631. outChans.getUnchecked(i)->synchronisePosition();
  214632. for (i = 0; i < inChans.size(); ++i)
  214633. inChans.getUnchecked(i)->synchronisePosition();
  214634. startThread (9);
  214635. sleep (10);
  214636. notify();
  214637. }
  214638. else
  214639. {
  214640. log (error);
  214641. }
  214642. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214643. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214644. return error;
  214645. }
  214646. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214647. {
  214648. return new DSoundAudioIODeviceType();
  214649. }
  214650. #undef log
  214651. #endif
  214652. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214653. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214654. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214655. // compiled on its own).
  214656. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214657. #ifndef WASAPI_ENABLE_LOGGING
  214658. #define WASAPI_ENABLE_LOGGING 0
  214659. #endif
  214660. namespace WasapiClasses
  214661. {
  214662. void logFailure (HRESULT hr)
  214663. {
  214664. (void) hr;
  214665. #if WASAPI_ENABLE_LOGGING
  214666. if (FAILED (hr))
  214667. {
  214668. String e;
  214669. e << Time::getCurrentTime().toString (true, true, true, true)
  214670. << " -- WASAPI error: ";
  214671. switch (hr)
  214672. {
  214673. case E_POINTER: e << "E_POINTER"; break;
  214674. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  214675. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  214676. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214677. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214678. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214679. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  214680. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214681. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  214682. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214683. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  214684. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  214685. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214686. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214687. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214688. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214689. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214690. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214691. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214692. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214693. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214694. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214695. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214696. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  214697. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214698. default: e << String::toHexString ((int) hr); break;
  214699. }
  214700. DBG (e);
  214701. jassertfalse;
  214702. }
  214703. #endif
  214704. }
  214705. #undef check
  214706. bool check (HRESULT hr)
  214707. {
  214708. logFailure (hr);
  214709. return SUCCEEDED (hr);
  214710. }
  214711. const String getDeviceID (IMMDevice* const device)
  214712. {
  214713. String s;
  214714. WCHAR* deviceId = 0;
  214715. if (check (device->GetId (&deviceId)))
  214716. {
  214717. s = String (deviceId);
  214718. CoTaskMemFree (deviceId);
  214719. }
  214720. return s;
  214721. }
  214722. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  214723. {
  214724. EDataFlow flow = eRender;
  214725. ComSmartPtr <IMMEndpoint> endPoint;
  214726. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  214727. (void) check (endPoint->GetDataFlow (&flow));
  214728. return flow;
  214729. }
  214730. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214731. {
  214732. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214733. }
  214734. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214735. {
  214736. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214737. : sizeof (WAVEFORMATEX));
  214738. }
  214739. class WASAPIDeviceBase
  214740. {
  214741. public:
  214742. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214743. : device (device_),
  214744. sampleRate (0),
  214745. numChannels (0),
  214746. actualNumChannels (0),
  214747. defaultSampleRate (0),
  214748. minBufferSize (0),
  214749. defaultBufferSize (0),
  214750. latencySamples (0),
  214751. useExclusiveMode (useExclusiveMode_)
  214752. {
  214753. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214754. ComSmartPtr <IAudioClient> tempClient (createClient());
  214755. if (tempClient == 0)
  214756. return;
  214757. REFERENCE_TIME defaultPeriod, minPeriod;
  214758. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214759. return;
  214760. WAVEFORMATEX* mixFormat = 0;
  214761. if (! check (tempClient->GetMixFormat (&mixFormat)))
  214762. return;
  214763. WAVEFORMATEXTENSIBLE format;
  214764. copyWavFormat (format, mixFormat);
  214765. CoTaskMemFree (mixFormat);
  214766. actualNumChannels = numChannels = format.Format.nChannels;
  214767. defaultSampleRate = format.Format.nSamplesPerSec;
  214768. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  214769. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  214770. rates.addUsingDefaultSort (defaultSampleRate);
  214771. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214772. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214773. {
  214774. if (ratesToTest[i] == defaultSampleRate)
  214775. continue;
  214776. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214777. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214778. (WAVEFORMATEX*) &format, 0)))
  214779. if (! rates.contains (ratesToTest[i]))
  214780. rates.addUsingDefaultSort (ratesToTest[i]);
  214781. }
  214782. }
  214783. ~WASAPIDeviceBase()
  214784. {
  214785. device = 0;
  214786. CloseHandle (clientEvent);
  214787. }
  214788. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214789. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214790. {
  214791. sampleRate = newSampleRate;
  214792. channels = newChannels;
  214793. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214794. numChannels = channels.getHighestBit() + 1;
  214795. if (numChannels == 0)
  214796. return true;
  214797. client = createClient();
  214798. if (client != 0
  214799. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214800. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214801. {
  214802. channelMaps.clear();
  214803. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214804. if (channels[i])
  214805. channelMaps.add (i);
  214806. REFERENCE_TIME latency;
  214807. if (check (client->GetStreamLatency (&latency)))
  214808. latencySamples = refTimeToSamples (latency, sampleRate);
  214809. (void) check (client->GetBufferSize (&actualBufferSize));
  214810. return check (client->SetEventHandle (clientEvent));
  214811. }
  214812. return false;
  214813. }
  214814. void closeClient()
  214815. {
  214816. if (client != 0)
  214817. client->Stop();
  214818. client = 0;
  214819. ResetEvent (clientEvent);
  214820. }
  214821. ComSmartPtr <IMMDevice> device;
  214822. ComSmartPtr <IAudioClient> client;
  214823. double sampleRate, defaultSampleRate;
  214824. int numChannels, actualNumChannels;
  214825. int minBufferSize, defaultBufferSize, latencySamples;
  214826. const bool useExclusiveMode;
  214827. Array <double> rates;
  214828. HANDLE clientEvent;
  214829. BigInteger channels;
  214830. Array <int> channelMaps;
  214831. UINT32 actualBufferSize;
  214832. int bytesPerSample;
  214833. virtual void updateFormat (bool isFloat) = 0;
  214834. private:
  214835. const ComSmartPtr <IAudioClient> createClient()
  214836. {
  214837. ComSmartPtr <IAudioClient> client;
  214838. if (device != 0)
  214839. {
  214840. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  214841. logFailure (hr);
  214842. }
  214843. return client;
  214844. }
  214845. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214846. {
  214847. WAVEFORMATEXTENSIBLE format;
  214848. zerostruct (format);
  214849. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214850. {
  214851. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214852. }
  214853. else
  214854. {
  214855. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214856. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214857. }
  214858. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214859. format.Format.nChannels = (WORD) numChannels;
  214860. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214861. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214862. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214863. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214864. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214865. switch (numChannels)
  214866. {
  214867. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214868. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214869. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214870. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214871. 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;
  214872. default: break;
  214873. }
  214874. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214875. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214876. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214877. logFailure (hr);
  214878. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214879. {
  214880. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214881. hr = S_OK;
  214882. }
  214883. CoTaskMemFree (nearestFormat);
  214884. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214885. if (useExclusiveMode)
  214886. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214887. GUID session;
  214888. if (hr == S_OK
  214889. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214890. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214891. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214892. {
  214893. actualNumChannels = format.Format.nChannels;
  214894. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214895. bytesPerSample = format.Format.wBitsPerSample / 8;
  214896. updateFormat (isFloat);
  214897. return true;
  214898. }
  214899. return false;
  214900. }
  214901. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  214902. };
  214903. class WASAPIInputDevice : public WASAPIDeviceBase
  214904. {
  214905. public:
  214906. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214907. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214908. reservoir (1, 1)
  214909. {
  214910. }
  214911. ~WASAPIInputDevice()
  214912. {
  214913. close();
  214914. }
  214915. bool open (const double newSampleRate, const BigInteger& newChannels)
  214916. {
  214917. reservoirSize = 0;
  214918. reservoirCapacity = 16384;
  214919. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214920. return openClient (newSampleRate, newChannels)
  214921. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  214922. (void**) captureClient.resetAndGetPointerAddress())));
  214923. }
  214924. void close()
  214925. {
  214926. closeClient();
  214927. captureClient = 0;
  214928. reservoir.setSize (0);
  214929. }
  214930. template <class SourceType>
  214931. void updateFormatWithType (SourceType*)
  214932. {
  214933. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  214934. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  214935. }
  214936. void updateFormat (bool isFloat)
  214937. {
  214938. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  214939. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  214940. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  214941. else updateFormatWithType ((AudioData::Int16*) 0);
  214942. }
  214943. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214944. {
  214945. if (numChannels <= 0)
  214946. return;
  214947. int offset = 0;
  214948. while (bufferSize > 0)
  214949. {
  214950. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214951. {
  214952. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214953. for (int i = 0; i < numDestBuffers; ++i)
  214954. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  214955. bufferSize -= samplesToDo;
  214956. offset += samplesToDo;
  214957. reservoirSize = 0;
  214958. }
  214959. else
  214960. {
  214961. UINT32 packetLength = 0;
  214962. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  214963. break;
  214964. if (packetLength == 0)
  214965. {
  214966. if (thread.threadShouldExit()
  214967. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  214968. break;
  214969. continue;
  214970. }
  214971. uint8* inputData;
  214972. UINT32 numSamplesAvailable;
  214973. DWORD flags;
  214974. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214975. {
  214976. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214977. for (int i = 0; i < numDestBuffers; ++i)
  214978. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  214979. bufferSize -= samplesToDo;
  214980. offset += samplesToDo;
  214981. if (samplesToDo < (int) numSamplesAvailable)
  214982. {
  214983. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214984. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214985. bytesPerSample * actualNumChannels * reservoirSize);
  214986. }
  214987. captureClient->ReleaseBuffer (numSamplesAvailable);
  214988. }
  214989. }
  214990. }
  214991. }
  214992. ComSmartPtr <IAudioCaptureClient> captureClient;
  214993. MemoryBlock reservoir;
  214994. int reservoirSize, reservoirCapacity;
  214995. ScopedPointer <AudioData::Converter> converter;
  214996. private:
  214997. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  214998. };
  214999. class WASAPIOutputDevice : public WASAPIDeviceBase
  215000. {
  215001. public:
  215002. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215003. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215004. {
  215005. }
  215006. ~WASAPIOutputDevice()
  215007. {
  215008. close();
  215009. }
  215010. bool open (const double newSampleRate, const BigInteger& newChannels)
  215011. {
  215012. return openClient (newSampleRate, newChannels)
  215013. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215014. }
  215015. void close()
  215016. {
  215017. closeClient();
  215018. renderClient = 0;
  215019. }
  215020. template <class DestType>
  215021. void updateFormatWithType (DestType*)
  215022. {
  215023. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215024. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215025. }
  215026. void updateFormat (bool isFloat)
  215027. {
  215028. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215029. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215030. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215031. else updateFormatWithType ((AudioData::Int16*) 0);
  215032. }
  215033. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215034. {
  215035. if (numChannels <= 0)
  215036. return;
  215037. int offset = 0;
  215038. while (bufferSize > 0)
  215039. {
  215040. UINT32 padding = 0;
  215041. if (! check (client->GetCurrentPadding (&padding)))
  215042. return;
  215043. int samplesToDo = useExclusiveMode ? bufferSize
  215044. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215045. if (samplesToDo <= 0)
  215046. {
  215047. if (thread.threadShouldExit()
  215048. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215049. break;
  215050. continue;
  215051. }
  215052. uint8* outputData = 0;
  215053. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215054. {
  215055. for (int i = 0; i < numSrcBuffers; ++i)
  215056. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  215057. renderClient->ReleaseBuffer (samplesToDo, 0);
  215058. offset += samplesToDo;
  215059. bufferSize -= samplesToDo;
  215060. }
  215061. }
  215062. }
  215063. ComSmartPtr <IAudioRenderClient> renderClient;
  215064. ScopedPointer <AudioData::Converter> converter;
  215065. private:
  215066. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  215067. };
  215068. class WASAPIAudioIODevice : public AudioIODevice,
  215069. public Thread
  215070. {
  215071. public:
  215072. WASAPIAudioIODevice (const String& deviceName,
  215073. const String& outputDeviceId_,
  215074. const String& inputDeviceId_,
  215075. const bool useExclusiveMode_)
  215076. : AudioIODevice (deviceName, "Windows Audio"),
  215077. Thread ("Juce WASAPI"),
  215078. isOpen_ (false),
  215079. isStarted (false),
  215080. outputDeviceId (outputDeviceId_),
  215081. inputDeviceId (inputDeviceId_),
  215082. useExclusiveMode (useExclusiveMode_),
  215083. currentBufferSizeSamples (0),
  215084. currentSampleRate (0),
  215085. callback (0)
  215086. {
  215087. }
  215088. ~WASAPIAudioIODevice()
  215089. {
  215090. close();
  215091. }
  215092. bool initialise()
  215093. {
  215094. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215095. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215096. latencyIn = latencyOut = 0;
  215097. Array <double> ratesIn, ratesOut;
  215098. if (createDevices())
  215099. {
  215100. jassert (inputDevice != 0 || outputDevice != 0);
  215101. if (inputDevice != 0 && outputDevice != 0)
  215102. {
  215103. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215104. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215105. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215106. sampleRates = inputDevice->rates;
  215107. sampleRates.removeValuesNotIn (outputDevice->rates);
  215108. }
  215109. else
  215110. {
  215111. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215112. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215113. defaultSampleRate = d->defaultSampleRate;
  215114. minBufferSize = d->minBufferSize;
  215115. defaultBufferSize = d->defaultBufferSize;
  215116. sampleRates = d->rates;
  215117. }
  215118. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215119. if (minBufferSize != defaultBufferSize)
  215120. bufferSizes.addUsingDefaultSort (minBufferSize);
  215121. int n = 64;
  215122. for (int i = 0; i < 40; ++i)
  215123. {
  215124. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215125. bufferSizes.addUsingDefaultSort (n);
  215126. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215127. }
  215128. return true;
  215129. }
  215130. return false;
  215131. }
  215132. const StringArray getOutputChannelNames()
  215133. {
  215134. StringArray outChannels;
  215135. if (outputDevice != 0)
  215136. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215137. outChannels.add ("Output channel " + String (i));
  215138. return outChannels;
  215139. }
  215140. const StringArray getInputChannelNames()
  215141. {
  215142. StringArray inChannels;
  215143. if (inputDevice != 0)
  215144. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215145. inChannels.add ("Input channel " + String (i));
  215146. return inChannels;
  215147. }
  215148. int getNumSampleRates() { return sampleRates.size(); }
  215149. double getSampleRate (int index) { return sampleRates [index]; }
  215150. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215151. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215152. int getDefaultBufferSize() { return defaultBufferSize; }
  215153. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215154. double getCurrentSampleRate() { return currentSampleRate; }
  215155. int getCurrentBitDepth() { return 32; }
  215156. int getOutputLatencyInSamples() { return latencyOut; }
  215157. int getInputLatencyInSamples() { return latencyIn; }
  215158. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215159. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215160. const String getLastError() { return lastError; }
  215161. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215162. double sampleRate, int bufferSizeSamples)
  215163. {
  215164. close();
  215165. lastError = String::empty;
  215166. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215167. {
  215168. lastError = "The input and output devices don't share a common sample rate!";
  215169. return lastError;
  215170. }
  215171. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215172. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215173. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215174. {
  215175. lastError = "Couldn't open the input device!";
  215176. return lastError;
  215177. }
  215178. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215179. {
  215180. close();
  215181. lastError = "Couldn't open the output device!";
  215182. return lastError;
  215183. }
  215184. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215185. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215186. startThread (8);
  215187. Thread::sleep (5);
  215188. if (inputDevice != 0 && inputDevice->client != 0)
  215189. {
  215190. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215191. HRESULT hr = inputDevice->client->Start();
  215192. logFailure (hr); //xxx handle this
  215193. }
  215194. if (outputDevice != 0 && outputDevice->client != 0)
  215195. {
  215196. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215197. HRESULT hr = outputDevice->client->Start();
  215198. logFailure (hr); //xxx handle this
  215199. }
  215200. isOpen_ = true;
  215201. return lastError;
  215202. }
  215203. void close()
  215204. {
  215205. stop();
  215206. signalThreadShouldExit();
  215207. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215208. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215209. stopThread (5000);
  215210. if (inputDevice != 0) inputDevice->close();
  215211. if (outputDevice != 0) outputDevice->close();
  215212. isOpen_ = false;
  215213. }
  215214. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215215. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215216. void start (AudioIODeviceCallback* call)
  215217. {
  215218. if (isOpen_ && call != 0 && ! isStarted)
  215219. {
  215220. if (! isThreadRunning())
  215221. {
  215222. // something's gone wrong and the thread's stopped..
  215223. isOpen_ = false;
  215224. return;
  215225. }
  215226. call->audioDeviceAboutToStart (this);
  215227. const ScopedLock sl (startStopLock);
  215228. callback = call;
  215229. isStarted = true;
  215230. }
  215231. }
  215232. void stop()
  215233. {
  215234. if (isStarted)
  215235. {
  215236. AudioIODeviceCallback* const callbackLocal = callback;
  215237. {
  215238. const ScopedLock sl (startStopLock);
  215239. isStarted = false;
  215240. }
  215241. if (callbackLocal != 0)
  215242. callbackLocal->audioDeviceStopped();
  215243. }
  215244. }
  215245. void setMMThreadPriority()
  215246. {
  215247. DynamicLibraryLoader dll ("avrt.dll");
  215248. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215249. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215250. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215251. {
  215252. DWORD dummy = 0;
  215253. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215254. if (h != 0)
  215255. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215256. }
  215257. }
  215258. void run()
  215259. {
  215260. setMMThreadPriority();
  215261. const int bufferSize = currentBufferSizeSamples;
  215262. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215263. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215264. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215265. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215266. float** const inputBuffers = ins.getArrayOfChannels();
  215267. float** const outputBuffers = outs.getArrayOfChannels();
  215268. ins.clear();
  215269. while (! threadShouldExit())
  215270. {
  215271. if (inputDevice != 0)
  215272. {
  215273. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215274. if (threadShouldExit())
  215275. break;
  215276. }
  215277. JUCE_TRY
  215278. {
  215279. const ScopedLock sl (startStopLock);
  215280. if (isStarted)
  215281. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215282. outputBuffers, numOutputBuffers, bufferSize);
  215283. else
  215284. outs.clear();
  215285. }
  215286. JUCE_CATCH_EXCEPTION
  215287. if (outputDevice != 0)
  215288. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215289. }
  215290. }
  215291. String outputDeviceId, inputDeviceId;
  215292. String lastError;
  215293. private:
  215294. // Device stats...
  215295. ScopedPointer<WASAPIInputDevice> inputDevice;
  215296. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215297. const bool useExclusiveMode;
  215298. double defaultSampleRate;
  215299. int minBufferSize, defaultBufferSize;
  215300. int latencyIn, latencyOut;
  215301. Array <double> sampleRates;
  215302. Array <int> bufferSizes;
  215303. // Active state...
  215304. bool isOpen_, isStarted;
  215305. int currentBufferSizeSamples;
  215306. double currentSampleRate;
  215307. AudioIODeviceCallback* callback;
  215308. CriticalSection startStopLock;
  215309. bool createDevices()
  215310. {
  215311. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215312. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215313. return false;
  215314. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215315. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215316. return false;
  215317. UINT32 numDevices = 0;
  215318. if (! check (deviceCollection->GetCount (&numDevices)))
  215319. return false;
  215320. for (UINT32 i = 0; i < numDevices; ++i)
  215321. {
  215322. ComSmartPtr <IMMDevice> device;
  215323. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215324. continue;
  215325. const String deviceId (getDeviceID (device));
  215326. if (deviceId.isEmpty())
  215327. continue;
  215328. const EDataFlow flow = getDataFlow (device);
  215329. if (deviceId == inputDeviceId && flow == eCapture)
  215330. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215331. else if (deviceId == outputDeviceId && flow == eRender)
  215332. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215333. }
  215334. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215335. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215336. }
  215337. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215338. };
  215339. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215340. {
  215341. public:
  215342. WASAPIAudioIODeviceType()
  215343. : AudioIODeviceType ("Windows Audio"),
  215344. hasScanned (false)
  215345. {
  215346. }
  215347. ~WASAPIAudioIODeviceType()
  215348. {
  215349. }
  215350. void scanForDevices()
  215351. {
  215352. hasScanned = true;
  215353. outputDeviceNames.clear();
  215354. inputDeviceNames.clear();
  215355. outputDeviceIds.clear();
  215356. inputDeviceIds.clear();
  215357. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215358. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215359. return;
  215360. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215361. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215362. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215363. UINT32 numDevices = 0;
  215364. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215365. && check (deviceCollection->GetCount (&numDevices))))
  215366. return;
  215367. for (UINT32 i = 0; i < numDevices; ++i)
  215368. {
  215369. ComSmartPtr <IMMDevice> device;
  215370. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215371. continue;
  215372. const String deviceId (getDeviceID (device));
  215373. DWORD state = 0;
  215374. if (! check (device->GetState (&state)))
  215375. continue;
  215376. if (state != DEVICE_STATE_ACTIVE)
  215377. continue;
  215378. String name;
  215379. {
  215380. ComSmartPtr <IPropertyStore> properties;
  215381. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215382. continue;
  215383. PROPVARIANT value;
  215384. PropVariantInit (&value);
  215385. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215386. name = value.pwszVal;
  215387. PropVariantClear (&value);
  215388. }
  215389. const EDataFlow flow = getDataFlow (device);
  215390. if (flow == eRender)
  215391. {
  215392. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215393. outputDeviceIds.insert (index, deviceId);
  215394. outputDeviceNames.insert (index, name);
  215395. }
  215396. else if (flow == eCapture)
  215397. {
  215398. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215399. inputDeviceIds.insert (index, deviceId);
  215400. inputDeviceNames.insert (index, name);
  215401. }
  215402. }
  215403. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215404. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215405. }
  215406. const StringArray getDeviceNames (bool wantInputNames) const
  215407. {
  215408. jassert (hasScanned); // need to call scanForDevices() before doing this
  215409. return wantInputNames ? inputDeviceNames
  215410. : outputDeviceNames;
  215411. }
  215412. int getDefaultDeviceIndex (bool /*forInput*/) const
  215413. {
  215414. jassert (hasScanned); // need to call scanForDevices() before doing this
  215415. return 0;
  215416. }
  215417. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215418. {
  215419. jassert (hasScanned); // need to call scanForDevices() before doing this
  215420. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215421. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215422. : outputDeviceIds.indexOf (d->outputDeviceId));
  215423. }
  215424. bool hasSeparateInputsAndOutputs() const { return true; }
  215425. AudioIODevice* createDevice (const String& outputDeviceName,
  215426. const String& inputDeviceName)
  215427. {
  215428. jassert (hasScanned); // need to call scanForDevices() before doing this
  215429. const bool useExclusiveMode = false;
  215430. ScopedPointer<WASAPIAudioIODevice> device;
  215431. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215432. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215433. if (outputIndex >= 0 || inputIndex >= 0)
  215434. {
  215435. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215436. : inputDeviceName,
  215437. outputDeviceIds [outputIndex],
  215438. inputDeviceIds [inputIndex],
  215439. useExclusiveMode);
  215440. if (! device->initialise())
  215441. device = 0;
  215442. }
  215443. return device.release();
  215444. }
  215445. StringArray outputDeviceNames, outputDeviceIds;
  215446. StringArray inputDeviceNames, inputDeviceIds;
  215447. private:
  215448. bool hasScanned;
  215449. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215450. {
  215451. String s;
  215452. IMMDevice* dev = 0;
  215453. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215454. eMultimedia, &dev)))
  215455. {
  215456. WCHAR* deviceId = 0;
  215457. if (check (dev->GetId (&deviceId)))
  215458. {
  215459. s = String (deviceId);
  215460. CoTaskMemFree (deviceId);
  215461. }
  215462. dev->Release();
  215463. }
  215464. return s;
  215465. }
  215466. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215467. };
  215468. }
  215469. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215470. {
  215471. return new WasapiClasses::WASAPIAudioIODeviceType();
  215472. }
  215473. #endif
  215474. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215475. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215476. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215477. // compiled on its own).
  215478. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215479. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215480. {
  215481. public:
  215482. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215483. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215484. const ComSmartPtr <IBaseFilter>& filter_,
  215485. int minWidth, int minHeight,
  215486. int maxWidth, int maxHeight)
  215487. : owner (owner_),
  215488. captureGraphBuilder (captureGraphBuilder_),
  215489. filter (filter_),
  215490. ok (false),
  215491. imageNeedsFlipping (false),
  215492. width (0),
  215493. height (0),
  215494. activeUsers (0),
  215495. recordNextFrameTime (false),
  215496. previewMaxFPS (60)
  215497. {
  215498. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215499. if (FAILED (hr))
  215500. return;
  215501. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215502. if (FAILED (hr))
  215503. return;
  215504. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215505. if (FAILED (hr))
  215506. return;
  215507. {
  215508. ComSmartPtr <IAMStreamConfig> streamConfig;
  215509. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215510. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215511. if (streamConfig != 0)
  215512. {
  215513. getVideoSizes (streamConfig);
  215514. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215515. return;
  215516. }
  215517. }
  215518. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215519. if (FAILED (hr))
  215520. return;
  215521. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215522. if (FAILED (hr))
  215523. return;
  215524. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215525. if (FAILED (hr))
  215526. return;
  215527. if (! connectFilters (filter, smartTee))
  215528. return;
  215529. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215530. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215531. if (FAILED (hr))
  215532. return;
  215533. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215534. if (FAILED (hr))
  215535. return;
  215536. AM_MEDIA_TYPE mt;
  215537. zerostruct (mt);
  215538. mt.majortype = MEDIATYPE_Video;
  215539. mt.subtype = MEDIASUBTYPE_RGB24;
  215540. mt.formattype = FORMAT_VideoInfo;
  215541. sampleGrabber->SetMediaType (&mt);
  215542. callback = new GrabberCallback (*this);
  215543. hr = sampleGrabber->SetCallback (callback, 1);
  215544. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215545. if (FAILED (hr))
  215546. return;
  215547. ComSmartPtr <IPin> grabberInputPin;
  215548. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215549. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215550. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215551. return;
  215552. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215553. if (FAILED (hr))
  215554. return;
  215555. zerostruct (mt);
  215556. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215557. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215558. width = pVih->bmiHeader.biWidth;
  215559. height = pVih->bmiHeader.biHeight;
  215560. ComSmartPtr <IBaseFilter> nullFilter;
  215561. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215562. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215563. if (connectFilters (sampleGrabberBase, nullFilter)
  215564. && addGraphToRot())
  215565. {
  215566. activeImage = Image (Image::RGB, width, height, true);
  215567. loadingImage = Image (Image::RGB, width, height, true);
  215568. ok = true;
  215569. }
  215570. }
  215571. ~DShowCameraDeviceInteral()
  215572. {
  215573. if (mediaControl != 0)
  215574. mediaControl->Stop();
  215575. removeGraphFromRot();
  215576. for (int i = viewerComps.size(); --i >= 0;)
  215577. viewerComps.getUnchecked(i)->ownerDeleted();
  215578. callback = 0;
  215579. graphBuilder = 0;
  215580. sampleGrabber = 0;
  215581. mediaControl = 0;
  215582. filter = 0;
  215583. captureGraphBuilder = 0;
  215584. smartTee = 0;
  215585. smartTeePreviewOutputPin = 0;
  215586. smartTeeCaptureOutputPin = 0;
  215587. asfWriter = 0;
  215588. }
  215589. void addUser()
  215590. {
  215591. if (ok && activeUsers++ == 0)
  215592. mediaControl->Run();
  215593. }
  215594. void removeUser()
  215595. {
  215596. if (ok && --activeUsers == 0)
  215597. mediaControl->Stop();
  215598. }
  215599. int getPreviewMaxFPS() const
  215600. {
  215601. return previewMaxFPS;
  215602. }
  215603. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215604. {
  215605. if (recordNextFrameTime)
  215606. {
  215607. const double defaultCameraLatency = 0.1;
  215608. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215609. recordNextFrameTime = false;
  215610. ComSmartPtr <IPin> pin;
  215611. if (getPin (filter, PINDIR_OUTPUT, pin))
  215612. {
  215613. ComSmartPtr <IAMPushSource> pushSource;
  215614. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  215615. if (pushSource != 0)
  215616. {
  215617. REFERENCE_TIME latency = 0;
  215618. hr = pushSource->GetLatency (&latency);
  215619. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215620. }
  215621. }
  215622. }
  215623. {
  215624. const int lineStride = width * 3;
  215625. const ScopedLock sl (imageSwapLock);
  215626. {
  215627. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215628. for (int i = 0; i < height; ++i)
  215629. memcpy (destData.getLinePointer ((height - 1) - i),
  215630. buffer + lineStride * i,
  215631. lineStride);
  215632. }
  215633. imageNeedsFlipping = true;
  215634. }
  215635. if (listeners.size() > 0)
  215636. callListeners (loadingImage);
  215637. sendChangeMessage();
  215638. }
  215639. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215640. {
  215641. if (imageNeedsFlipping)
  215642. {
  215643. const ScopedLock sl (imageSwapLock);
  215644. swapVariables (loadingImage, activeImage);
  215645. imageNeedsFlipping = false;
  215646. }
  215647. RectanglePlacement rp (RectanglePlacement::centred);
  215648. double dx = 0, dy = 0, dw = width, dh = height;
  215649. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215650. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215651. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215652. {
  215653. Graphics::ScopedSaveState ss (g);
  215654. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215655. g.fillAll (Colours::black);
  215656. }
  215657. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215658. }
  215659. bool createFileCaptureFilter (const File& file, int quality)
  215660. {
  215661. removeFileCaptureFilter();
  215662. file.deleteFile();
  215663. mediaControl->Stop();
  215664. firstRecordedTime = Time();
  215665. recordNextFrameTime = true;
  215666. previewMaxFPS = 60;
  215667. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215668. if (SUCCEEDED (hr))
  215669. {
  215670. ComSmartPtr <IFileSinkFilter> fileSink;
  215671. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  215672. if (SUCCEEDED (hr))
  215673. {
  215674. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  215675. if (SUCCEEDED (hr))
  215676. {
  215677. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215678. if (SUCCEEDED (hr))
  215679. {
  215680. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215681. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  215682. asfConfig->SetIndexMode (true);
  215683. ComSmartPtr <IWMProfileManager> profileManager;
  215684. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  215685. // This gibberish is the DirectShow profile for a video-only wmv file.
  215686. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  215687. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  215688. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215689. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  215690. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215691. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  215692. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  215693. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  215694. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215695. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215696. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215697. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  215698. "biclrused=\"0\" biclrimportant=\"0\"/>"
  215699. "</videoinfoheader>"
  215700. "</wmmediatype>"
  215701. "</streamconfig>"
  215702. "</profile>");
  215703. const int fps[] = { 10, 15, 30 };
  215704. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  215705. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215706. maxFramesPerSecond = (quality >> 24) & 0xff;
  215707. prof = prof.replace ("$WIDTH", String (width))
  215708. .replace ("$HEIGHT", String (height))
  215709. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  215710. ComSmartPtr <IWMProfile> currentProfile;
  215711. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  215712. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215713. if (SUCCEEDED (hr))
  215714. {
  215715. ComSmartPtr <IPin> asfWriterInputPin;
  215716. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  215717. {
  215718. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215719. if (SUCCEEDED (hr) && ok && activeUsers > 0
  215720. && SUCCEEDED (mediaControl->Run()))
  215721. {
  215722. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  215723. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215724. previewMaxFPS = (quality >> 16) & 0xff;
  215725. return true;
  215726. }
  215727. }
  215728. }
  215729. }
  215730. }
  215731. }
  215732. }
  215733. removeFileCaptureFilter();
  215734. if (ok && activeUsers > 0)
  215735. mediaControl->Run();
  215736. return false;
  215737. }
  215738. void removeFileCaptureFilter()
  215739. {
  215740. mediaControl->Stop();
  215741. if (asfWriter != 0)
  215742. {
  215743. graphBuilder->RemoveFilter (asfWriter);
  215744. asfWriter = 0;
  215745. }
  215746. if (ok && activeUsers > 0)
  215747. mediaControl->Run();
  215748. previewMaxFPS = 60;
  215749. }
  215750. void addListener (CameraDevice::Listener* listenerToAdd)
  215751. {
  215752. const ScopedLock sl (listenerLock);
  215753. if (listeners.size() == 0)
  215754. addUser();
  215755. listeners.addIfNotAlreadyThere (listenerToAdd);
  215756. }
  215757. void removeListener (CameraDevice::Listener* listenerToRemove)
  215758. {
  215759. const ScopedLock sl (listenerLock);
  215760. listeners.removeValue (listenerToRemove);
  215761. if (listeners.size() == 0)
  215762. removeUser();
  215763. }
  215764. void callListeners (const Image& image)
  215765. {
  215766. const ScopedLock sl (listenerLock);
  215767. for (int i = listeners.size(); --i >= 0;)
  215768. {
  215769. CameraDevice::Listener* const l = listeners[i];
  215770. if (l != 0)
  215771. l->imageReceived (image);
  215772. }
  215773. }
  215774. class DShowCaptureViewerComp : public Component,
  215775. public ChangeListener
  215776. {
  215777. public:
  215778. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215779. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  215780. {
  215781. setOpaque (true);
  215782. owner->addChangeListener (this);
  215783. owner->addUser();
  215784. owner->viewerComps.add (this);
  215785. setSize (owner->width, owner->height);
  215786. }
  215787. ~DShowCaptureViewerComp()
  215788. {
  215789. if (owner != 0)
  215790. {
  215791. owner->viewerComps.removeValue (this);
  215792. owner->removeUser();
  215793. owner->removeChangeListener (this);
  215794. }
  215795. }
  215796. void ownerDeleted()
  215797. {
  215798. owner = 0;
  215799. }
  215800. void paint (Graphics& g)
  215801. {
  215802. g.setColour (Colours::black);
  215803. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215804. if (owner != 0)
  215805. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215806. else
  215807. g.fillAll (Colours::black);
  215808. }
  215809. void changeListenerCallback (ChangeBroadcaster*)
  215810. {
  215811. const int64 now = Time::currentTimeMillis();
  215812. if (now >= lastRepaintTime + (1000 / maxFPS))
  215813. {
  215814. lastRepaintTime = now;
  215815. repaint();
  215816. if (owner != 0)
  215817. maxFPS = owner->getPreviewMaxFPS();
  215818. }
  215819. }
  215820. private:
  215821. DShowCameraDeviceInteral* owner;
  215822. int maxFPS;
  215823. int64 lastRepaintTime;
  215824. };
  215825. bool ok;
  215826. int width, height;
  215827. Time firstRecordedTime;
  215828. Array <DShowCaptureViewerComp*> viewerComps;
  215829. private:
  215830. CameraDevice* const owner;
  215831. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215832. ComSmartPtr <IBaseFilter> filter;
  215833. ComSmartPtr <IBaseFilter> smartTee;
  215834. ComSmartPtr <IGraphBuilder> graphBuilder;
  215835. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215836. ComSmartPtr <IMediaControl> mediaControl;
  215837. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215838. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215839. ComSmartPtr <IBaseFilter> asfWriter;
  215840. int activeUsers;
  215841. Array <int> widths, heights;
  215842. DWORD graphRegistrationID;
  215843. CriticalSection imageSwapLock;
  215844. bool imageNeedsFlipping;
  215845. Image loadingImage;
  215846. Image activeImage;
  215847. bool recordNextFrameTime;
  215848. int previewMaxFPS;
  215849. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215850. {
  215851. widths.clear();
  215852. heights.clear();
  215853. int count = 0, size = 0;
  215854. streamConfig->GetNumberOfCapabilities (&count, &size);
  215855. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215856. {
  215857. for (int i = 0; i < count; ++i)
  215858. {
  215859. VIDEO_STREAM_CONFIG_CAPS scc;
  215860. AM_MEDIA_TYPE* config;
  215861. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215862. if (SUCCEEDED (hr))
  215863. {
  215864. const int w = scc.InputSize.cx;
  215865. const int h = scc.InputSize.cy;
  215866. bool duplicate = false;
  215867. for (int j = widths.size(); --j >= 0;)
  215868. {
  215869. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215870. {
  215871. duplicate = true;
  215872. break;
  215873. }
  215874. }
  215875. if (! duplicate)
  215876. {
  215877. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215878. widths.add (w);
  215879. heights.add (h);
  215880. }
  215881. deleteMediaType (config);
  215882. }
  215883. }
  215884. }
  215885. }
  215886. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215887. const int minWidth, const int minHeight,
  215888. const int maxWidth, const int maxHeight)
  215889. {
  215890. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215891. streamConfig->GetNumberOfCapabilities (&count, &size);
  215892. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215893. {
  215894. AM_MEDIA_TYPE* config;
  215895. VIDEO_STREAM_CONFIG_CAPS scc;
  215896. for (int i = 0; i < count; ++i)
  215897. {
  215898. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215899. if (SUCCEEDED (hr))
  215900. {
  215901. if (scc.InputSize.cx >= minWidth
  215902. && scc.InputSize.cy >= minHeight
  215903. && scc.InputSize.cx <= maxWidth
  215904. && scc.InputSize.cy <= maxHeight)
  215905. {
  215906. int area = scc.InputSize.cx * scc.InputSize.cy;
  215907. if (area > bestArea)
  215908. {
  215909. bestIndex = i;
  215910. bestArea = area;
  215911. }
  215912. }
  215913. deleteMediaType (config);
  215914. }
  215915. }
  215916. if (bestIndex >= 0)
  215917. {
  215918. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215919. hr = streamConfig->SetFormat (config);
  215920. deleteMediaType (config);
  215921. return SUCCEEDED (hr);
  215922. }
  215923. }
  215924. return false;
  215925. }
  215926. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  215927. {
  215928. ComSmartPtr <IEnumPins> enumerator;
  215929. ComSmartPtr <IPin> pin;
  215930. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  215931. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  215932. {
  215933. PIN_DIRECTION dir;
  215934. pin->QueryDirection (&dir);
  215935. if (wantedDirection == dir)
  215936. {
  215937. PIN_INFO info;
  215938. zerostruct (info);
  215939. pin->QueryPinInfo (&info);
  215940. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215941. {
  215942. result = pin;
  215943. return true;
  215944. }
  215945. }
  215946. }
  215947. return false;
  215948. }
  215949. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215950. {
  215951. ComSmartPtr <IPin> in, out;
  215952. return getPin (first, PINDIR_OUTPUT, out)
  215953. && getPin (second, PINDIR_INPUT, in)
  215954. && SUCCEEDED (graphBuilder->Connect (out, in));
  215955. }
  215956. bool addGraphToRot()
  215957. {
  215958. ComSmartPtr <IRunningObjectTable> rot;
  215959. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  215960. return false;
  215961. ComSmartPtr <IMoniker> moniker;
  215962. WCHAR buffer[128];
  215963. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  215964. if (FAILED (hr))
  215965. return false;
  215966. graphRegistrationID = 0;
  215967. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215968. }
  215969. void removeGraphFromRot()
  215970. {
  215971. ComSmartPtr <IRunningObjectTable> rot;
  215972. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  215973. rot->Revoke (graphRegistrationID);
  215974. }
  215975. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215976. {
  215977. if (pmt->cbFormat != 0)
  215978. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215979. if (pmt->pUnk != 0)
  215980. pmt->pUnk->Release();
  215981. CoTaskMemFree (pmt);
  215982. }
  215983. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215984. {
  215985. public:
  215986. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215987. : owner (owner_)
  215988. {
  215989. }
  215990. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215991. {
  215992. return E_FAIL;
  215993. }
  215994. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215995. {
  215996. owner.handleFrame (time, buffer, bufferSize);
  215997. return S_OK;
  215998. }
  215999. private:
  216000. DShowCameraDeviceInteral& owner;
  216001. GrabberCallback (const GrabberCallback&);
  216002. GrabberCallback& operator= (const GrabberCallback&);
  216003. };
  216004. ComSmartPtr <GrabberCallback> callback;
  216005. Array <CameraDevice::Listener*> listeners;
  216006. CriticalSection listenerLock;
  216007. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  216008. };
  216009. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216010. : name (name_)
  216011. {
  216012. isRecording = false;
  216013. }
  216014. CameraDevice::~CameraDevice()
  216015. {
  216016. stopRecording();
  216017. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216018. internal = 0;
  216019. }
  216020. Component* CameraDevice::createViewerComponent()
  216021. {
  216022. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216023. }
  216024. const String CameraDevice::getFileExtension()
  216025. {
  216026. return ".wmv";
  216027. }
  216028. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216029. {
  216030. stopRecording();
  216031. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216032. d->addUser();
  216033. isRecording = d->createFileCaptureFilter (file, quality);
  216034. }
  216035. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216036. {
  216037. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216038. return d->firstRecordedTime;
  216039. }
  216040. void CameraDevice::stopRecording()
  216041. {
  216042. if (isRecording)
  216043. {
  216044. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216045. d->removeFileCaptureFilter();
  216046. d->removeUser();
  216047. isRecording = false;
  216048. }
  216049. }
  216050. void CameraDevice::addListener (Listener* listenerToAdd)
  216051. {
  216052. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216053. if (listenerToAdd != 0)
  216054. d->addListener (listenerToAdd);
  216055. }
  216056. void CameraDevice::removeListener (Listener* listenerToRemove)
  216057. {
  216058. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216059. if (listenerToRemove != 0)
  216060. d->removeListener (listenerToRemove);
  216061. }
  216062. namespace
  216063. {
  216064. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216065. const int deviceIndexToOpen,
  216066. String& name)
  216067. {
  216068. int index = 0;
  216069. ComSmartPtr <IBaseFilter> result;
  216070. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216071. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216072. if (SUCCEEDED (hr))
  216073. {
  216074. ComSmartPtr <IEnumMoniker> enumerator;
  216075. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216076. if (SUCCEEDED (hr) && enumerator != 0)
  216077. {
  216078. ComSmartPtr <IMoniker> moniker;
  216079. ULONG fetched;
  216080. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216081. {
  216082. ComSmartPtr <IBaseFilter> captureFilter;
  216083. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216084. if (SUCCEEDED (hr))
  216085. {
  216086. ComSmartPtr <IPropertyBag> propertyBag;
  216087. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216088. if (SUCCEEDED (hr))
  216089. {
  216090. VARIANT var;
  216091. var.vt = VT_BSTR;
  216092. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216093. propertyBag = 0;
  216094. if (SUCCEEDED (hr))
  216095. {
  216096. if (names != 0)
  216097. names->add (var.bstrVal);
  216098. if (index == deviceIndexToOpen)
  216099. {
  216100. name = var.bstrVal;
  216101. result = captureFilter;
  216102. break;
  216103. }
  216104. ++index;
  216105. }
  216106. }
  216107. }
  216108. }
  216109. }
  216110. }
  216111. return result;
  216112. }
  216113. }
  216114. const StringArray CameraDevice::getAvailableDevices()
  216115. {
  216116. StringArray devs;
  216117. String dummy;
  216118. enumerateCameras (&devs, -1, dummy);
  216119. return devs;
  216120. }
  216121. CameraDevice* CameraDevice::openDevice (int index,
  216122. int minWidth, int minHeight,
  216123. int maxWidth, int maxHeight)
  216124. {
  216125. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216126. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216127. if (SUCCEEDED (hr))
  216128. {
  216129. String name;
  216130. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216131. if (filter != 0)
  216132. {
  216133. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216134. DShowCameraDeviceInteral* const intern
  216135. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216136. minWidth, minHeight, maxWidth, maxHeight);
  216137. cam->internal = intern;
  216138. if (intern->ok)
  216139. return cam.release();
  216140. }
  216141. }
  216142. return 0;
  216143. }
  216144. #endif
  216145. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216146. #endif
  216147. // Auto-link the other win32 libs that are needed by library calls..
  216148. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216149. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216150. // Auto-links to various win32 libs that are needed by library calls..
  216151. #pragma comment(lib, "kernel32.lib")
  216152. #pragma comment(lib, "user32.lib")
  216153. #pragma comment(lib, "shell32.lib")
  216154. #pragma comment(lib, "gdi32.lib")
  216155. #pragma comment(lib, "vfw32.lib")
  216156. #pragma comment(lib, "comdlg32.lib")
  216157. #pragma comment(lib, "winmm.lib")
  216158. #pragma comment(lib, "wininet.lib")
  216159. #pragma comment(lib, "ole32.lib")
  216160. #pragma comment(lib, "oleaut32.lib")
  216161. #pragma comment(lib, "advapi32.lib")
  216162. #pragma comment(lib, "ws2_32.lib")
  216163. #pragma comment(lib, "version.lib")
  216164. #ifdef _NATIVE_WCHAR_T_DEFINED
  216165. #ifdef _DEBUG
  216166. #pragma comment(lib, "comsuppwd.lib")
  216167. #else
  216168. #pragma comment(lib, "comsuppw.lib")
  216169. #endif
  216170. #else
  216171. #ifdef _DEBUG
  216172. #pragma comment(lib, "comsuppd.lib")
  216173. #else
  216174. #pragma comment(lib, "comsupp.lib")
  216175. #endif
  216176. #endif
  216177. #if JUCE_OPENGL
  216178. #pragma comment(lib, "OpenGL32.Lib")
  216179. #pragma comment(lib, "GlU32.Lib")
  216180. #endif
  216181. #if JUCE_QUICKTIME
  216182. #pragma comment (lib, "QTMLClient.lib")
  216183. #endif
  216184. #if JUCE_USE_CAMERA
  216185. #pragma comment (lib, "Strmiids.lib")
  216186. #pragma comment (lib, "wmvcore.lib")
  216187. #endif
  216188. #if JUCE_DIRECT2D
  216189. #pragma comment (lib, "Dwrite.lib")
  216190. #pragma comment (lib, "D2d1.lib")
  216191. #endif
  216192. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216193. #endif
  216194. END_JUCE_NAMESPACE
  216195. #endif
  216196. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216197. #endif
  216198. #if JUCE_LINUX
  216199. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216200. /*
  216201. This file wraps together all the mac-specific code, so that
  216202. we can include all the native headers just once, and compile all our
  216203. platform-specific stuff in one big lump, keeping it out of the way of
  216204. the rest of the codebase.
  216205. */
  216206. #if JUCE_LINUX
  216207. #undef JUCE_BUILD_NATIVE
  216208. #define JUCE_BUILD_NATIVE 1
  216209. BEGIN_JUCE_NAMESPACE
  216210. #define JUCE_INCLUDED_FILE 1
  216211. // Now include the actual code files..
  216212. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216213. /*
  216214. This file contains posix routines that are common to both the Linux and Mac builds.
  216215. It gets included directly in the cpp files for these platforms.
  216216. */
  216217. CriticalSection::CriticalSection() throw()
  216218. {
  216219. pthread_mutexattr_t atts;
  216220. pthread_mutexattr_init (&atts);
  216221. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216222. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216223. pthread_mutex_init (&internal, &atts);
  216224. }
  216225. CriticalSection::~CriticalSection() throw()
  216226. {
  216227. pthread_mutex_destroy (&internal);
  216228. }
  216229. void CriticalSection::enter() const throw()
  216230. {
  216231. pthread_mutex_lock (&internal);
  216232. }
  216233. bool CriticalSection::tryEnter() const throw()
  216234. {
  216235. return pthread_mutex_trylock (&internal) == 0;
  216236. }
  216237. void CriticalSection::exit() const throw()
  216238. {
  216239. pthread_mutex_unlock (&internal);
  216240. }
  216241. class WaitableEventImpl
  216242. {
  216243. public:
  216244. WaitableEventImpl (const bool manualReset_)
  216245. : triggered (false),
  216246. manualReset (manualReset_)
  216247. {
  216248. pthread_cond_init (&condition, 0);
  216249. pthread_mutexattr_t atts;
  216250. pthread_mutexattr_init (&atts);
  216251. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216252. pthread_mutex_init (&mutex, &atts);
  216253. }
  216254. ~WaitableEventImpl()
  216255. {
  216256. pthread_cond_destroy (&condition);
  216257. pthread_mutex_destroy (&mutex);
  216258. }
  216259. bool wait (const int timeOutMillisecs) throw()
  216260. {
  216261. pthread_mutex_lock (&mutex);
  216262. if (! triggered)
  216263. {
  216264. if (timeOutMillisecs < 0)
  216265. {
  216266. do
  216267. {
  216268. pthread_cond_wait (&condition, &mutex);
  216269. }
  216270. while (! triggered);
  216271. }
  216272. else
  216273. {
  216274. struct timeval now;
  216275. gettimeofday (&now, 0);
  216276. struct timespec time;
  216277. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216278. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216279. if (time.tv_nsec >= 1000000000)
  216280. {
  216281. time.tv_nsec -= 1000000000;
  216282. time.tv_sec++;
  216283. }
  216284. do
  216285. {
  216286. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216287. {
  216288. pthread_mutex_unlock (&mutex);
  216289. return false;
  216290. }
  216291. }
  216292. while (! triggered);
  216293. }
  216294. }
  216295. if (! manualReset)
  216296. triggered = false;
  216297. pthread_mutex_unlock (&mutex);
  216298. return true;
  216299. }
  216300. void signal() throw()
  216301. {
  216302. pthread_mutex_lock (&mutex);
  216303. triggered = true;
  216304. pthread_cond_broadcast (&condition);
  216305. pthread_mutex_unlock (&mutex);
  216306. }
  216307. void reset() throw()
  216308. {
  216309. pthread_mutex_lock (&mutex);
  216310. triggered = false;
  216311. pthread_mutex_unlock (&mutex);
  216312. }
  216313. private:
  216314. pthread_cond_t condition;
  216315. pthread_mutex_t mutex;
  216316. bool triggered;
  216317. const bool manualReset;
  216318. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216319. };
  216320. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216321. : internal (new WaitableEventImpl (manualReset))
  216322. {
  216323. }
  216324. WaitableEvent::~WaitableEvent() throw()
  216325. {
  216326. delete static_cast <WaitableEventImpl*> (internal);
  216327. }
  216328. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216329. {
  216330. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216331. }
  216332. void WaitableEvent::signal() const throw()
  216333. {
  216334. static_cast <WaitableEventImpl*> (internal)->signal();
  216335. }
  216336. void WaitableEvent::reset() const throw()
  216337. {
  216338. static_cast <WaitableEventImpl*> (internal)->reset();
  216339. }
  216340. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216341. {
  216342. struct timespec time;
  216343. time.tv_sec = millisecs / 1000;
  216344. time.tv_nsec = (millisecs % 1000) * 1000000;
  216345. nanosleep (&time, 0);
  216346. }
  216347. const juce_wchar File::separator = '/';
  216348. const String File::separatorString ("/");
  216349. const File File::getCurrentWorkingDirectory()
  216350. {
  216351. HeapBlock<char> heapBuffer;
  216352. char localBuffer [1024];
  216353. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216354. int bufferSize = 4096;
  216355. while (cwd == 0 && errno == ERANGE)
  216356. {
  216357. heapBuffer.malloc (bufferSize);
  216358. cwd = getcwd (heapBuffer, bufferSize - 1);
  216359. bufferSize += 1024;
  216360. }
  216361. return File (String::fromUTF8 (cwd));
  216362. }
  216363. bool File::setAsCurrentWorkingDirectory() const
  216364. {
  216365. return chdir (getFullPathName().toUTF8()) == 0;
  216366. }
  216367. namespace
  216368. {
  216369. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216370. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216371. #else
  216372. typedef struct stat juce_statStruct;
  216373. #endif
  216374. bool juce_stat (const String& fileName, juce_statStruct& info)
  216375. {
  216376. return fileName.isNotEmpty()
  216377. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216378. && (stat64 (fileName.toUTF8(), &info) == 0);
  216379. #else
  216380. && (stat (fileName.toUTF8(), &info) == 0);
  216381. #endif
  216382. }
  216383. // if this file doesn't exist, find a parent of it that does..
  216384. bool juce_doStatFS (File f, struct statfs& result)
  216385. {
  216386. for (int i = 5; --i >= 0;)
  216387. {
  216388. if (f.exists())
  216389. break;
  216390. f = f.getParentDirectory();
  216391. }
  216392. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216393. }
  216394. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  216395. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216396. {
  216397. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216398. {
  216399. juce_statStruct info;
  216400. const bool statOk = juce_stat (path, info);
  216401. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216402. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216403. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  216404. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  216405. }
  216406. if (isReadOnly != 0)
  216407. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216408. }
  216409. }
  216410. bool File::isDirectory() const
  216411. {
  216412. juce_statStruct info;
  216413. return fullPath.isEmpty()
  216414. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216415. }
  216416. bool File::exists() const
  216417. {
  216418. juce_statStruct info;
  216419. return fullPath.isNotEmpty()
  216420. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216421. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216422. #else
  216423. && (lstat (fullPath.toUTF8(), &info) == 0);
  216424. #endif
  216425. }
  216426. bool File::existsAsFile() const
  216427. {
  216428. return exists() && ! isDirectory();
  216429. }
  216430. int64 File::getSize() const
  216431. {
  216432. juce_statStruct info;
  216433. return juce_stat (fullPath, info) ? info.st_size : 0;
  216434. }
  216435. bool File::hasWriteAccess() const
  216436. {
  216437. if (exists())
  216438. return access (fullPath.toUTF8(), W_OK) == 0;
  216439. if ((! isDirectory()) && fullPath.containsChar (separator))
  216440. return getParentDirectory().hasWriteAccess();
  216441. return false;
  216442. }
  216443. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216444. {
  216445. juce_statStruct info;
  216446. if (! juce_stat (fullPath, info))
  216447. return false;
  216448. info.st_mode &= 0777; // Just permissions
  216449. if (shouldBeReadOnly)
  216450. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216451. else
  216452. // Give everybody write permission?
  216453. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216454. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216455. }
  216456. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216457. {
  216458. modificationTime = 0;
  216459. accessTime = 0;
  216460. creationTime = 0;
  216461. juce_statStruct info;
  216462. if (juce_stat (fullPath, info))
  216463. {
  216464. modificationTime = (int64) info.st_mtime * 1000;
  216465. accessTime = (int64) info.st_atime * 1000;
  216466. creationTime = (int64) info.st_ctime * 1000;
  216467. }
  216468. }
  216469. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216470. {
  216471. struct utimbuf times;
  216472. times.actime = (time_t) (accessTime / 1000);
  216473. times.modtime = (time_t) (modificationTime / 1000);
  216474. return utime (fullPath.toUTF8(), &times) == 0;
  216475. }
  216476. bool File::deleteFile() const
  216477. {
  216478. if (! exists())
  216479. return true;
  216480. else if (isDirectory())
  216481. return rmdir (fullPath.toUTF8()) == 0;
  216482. else
  216483. return remove (fullPath.toUTF8()) == 0;
  216484. }
  216485. bool File::moveInternal (const File& dest) const
  216486. {
  216487. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216488. return true;
  216489. if (hasWriteAccess() && copyInternal (dest))
  216490. {
  216491. if (deleteFile())
  216492. return true;
  216493. dest.deleteFile();
  216494. }
  216495. return false;
  216496. }
  216497. void File::createDirectoryInternal (const String& fileName) const
  216498. {
  216499. mkdir (fileName.toUTF8(), 0777);
  216500. }
  216501. int64 juce_fileSetPosition (void* handle, int64 pos)
  216502. {
  216503. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216504. return pos;
  216505. return -1;
  216506. }
  216507. void FileInputStream::openHandle()
  216508. {
  216509. totalSize = file.getSize();
  216510. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216511. if (f != -1)
  216512. fileHandle = (void*) f;
  216513. }
  216514. void FileInputStream::closeHandle()
  216515. {
  216516. if (fileHandle != 0)
  216517. {
  216518. close ((int) (pointer_sized_int) fileHandle);
  216519. fileHandle = 0;
  216520. }
  216521. }
  216522. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216523. {
  216524. if (fileHandle != 0)
  216525. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216526. return 0;
  216527. }
  216528. void FileOutputStream::openHandle()
  216529. {
  216530. if (file.exists())
  216531. {
  216532. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216533. if (f != -1)
  216534. {
  216535. currentPosition = lseek (f, 0, SEEK_END);
  216536. if (currentPosition >= 0)
  216537. fileHandle = (void*) f;
  216538. else
  216539. close (f);
  216540. }
  216541. }
  216542. else
  216543. {
  216544. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216545. if (f != -1)
  216546. fileHandle = (void*) f;
  216547. }
  216548. }
  216549. void FileOutputStream::closeHandle()
  216550. {
  216551. if (fileHandle != 0)
  216552. {
  216553. close ((int) (pointer_sized_int) fileHandle);
  216554. fileHandle = 0;
  216555. }
  216556. }
  216557. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216558. {
  216559. if (fileHandle != 0)
  216560. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216561. return 0;
  216562. }
  216563. void FileOutputStream::flushInternal()
  216564. {
  216565. if (fileHandle != 0)
  216566. fsync ((int) (pointer_sized_int) fileHandle);
  216567. }
  216568. const File juce_getExecutableFile()
  216569. {
  216570. Dl_info exeInfo;
  216571. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  216572. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216573. }
  216574. int64 File::getBytesFreeOnVolume() const
  216575. {
  216576. struct statfs buf;
  216577. if (juce_doStatFS (*this, buf))
  216578. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216579. return 0;
  216580. }
  216581. int64 File::getVolumeTotalSize() const
  216582. {
  216583. struct statfs buf;
  216584. if (juce_doStatFS (*this, buf))
  216585. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216586. return 0;
  216587. }
  216588. const String File::getVolumeLabel() const
  216589. {
  216590. #if JUCE_MAC
  216591. struct VolAttrBuf
  216592. {
  216593. u_int32_t length;
  216594. attrreference_t mountPointRef;
  216595. char mountPointSpace [MAXPATHLEN];
  216596. } attrBuf;
  216597. struct attrlist attrList;
  216598. zerostruct (attrList);
  216599. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216600. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216601. File f (*this);
  216602. for (;;)
  216603. {
  216604. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  216605. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  216606. (int) attrBuf.mountPointRef.attr_length);
  216607. const File parent (f.getParentDirectory());
  216608. if (f == parent)
  216609. break;
  216610. f = parent;
  216611. }
  216612. #endif
  216613. return String::empty;
  216614. }
  216615. int File::getVolumeSerialNumber() const
  216616. {
  216617. return 0; // xxx
  216618. }
  216619. void juce_runSystemCommand (const String& command)
  216620. {
  216621. int result = system (command.toUTF8());
  216622. (void) result;
  216623. }
  216624. const String juce_getOutputFromCommand (const String& command)
  216625. {
  216626. // slight bodge here, as we just pipe the output into a temp file and read it...
  216627. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  216628. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  216629. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  216630. String result (tempFile.loadFileAsString());
  216631. tempFile.deleteFile();
  216632. return result;
  216633. }
  216634. class InterProcessLock::Pimpl
  216635. {
  216636. public:
  216637. Pimpl (const String& name, const int timeOutMillisecs)
  216638. : handle (0), refCount (1)
  216639. {
  216640. #if JUCE_MAC
  216641. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216642. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216643. #else
  216644. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216645. #endif
  216646. temp.create();
  216647. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216648. if (handle != 0)
  216649. {
  216650. struct flock fl;
  216651. zerostruct (fl);
  216652. fl.l_whence = SEEK_SET;
  216653. fl.l_type = F_WRLCK;
  216654. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216655. for (;;)
  216656. {
  216657. const int result = fcntl (handle, F_SETLK, &fl);
  216658. if (result >= 0)
  216659. return;
  216660. if (errno != EINTR)
  216661. {
  216662. if (timeOutMillisecs == 0
  216663. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216664. break;
  216665. Thread::sleep (10);
  216666. }
  216667. }
  216668. }
  216669. closeFile();
  216670. }
  216671. ~Pimpl()
  216672. {
  216673. closeFile();
  216674. }
  216675. void closeFile()
  216676. {
  216677. if (handle != 0)
  216678. {
  216679. struct flock fl;
  216680. zerostruct (fl);
  216681. fl.l_whence = SEEK_SET;
  216682. fl.l_type = F_UNLCK;
  216683. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216684. {}
  216685. close (handle);
  216686. handle = 0;
  216687. }
  216688. }
  216689. int handle, refCount;
  216690. };
  216691. InterProcessLock::InterProcessLock (const String& name_)
  216692. : name (name_)
  216693. {
  216694. }
  216695. InterProcessLock::~InterProcessLock()
  216696. {
  216697. }
  216698. bool InterProcessLock::enter (const int timeOutMillisecs)
  216699. {
  216700. const ScopedLock sl (lock);
  216701. if (pimpl == 0)
  216702. {
  216703. pimpl = new Pimpl (name, timeOutMillisecs);
  216704. if (pimpl->handle == 0)
  216705. pimpl = 0;
  216706. }
  216707. else
  216708. {
  216709. pimpl->refCount++;
  216710. }
  216711. return pimpl != 0;
  216712. }
  216713. void InterProcessLock::exit()
  216714. {
  216715. const ScopedLock sl (lock);
  216716. // Trying to release the lock too many times!
  216717. jassert (pimpl != 0);
  216718. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216719. pimpl = 0;
  216720. }
  216721. void JUCE_API juce_threadEntryPoint (void*);
  216722. void* threadEntryProc (void* userData)
  216723. {
  216724. JUCE_AUTORELEASEPOOL
  216725. juce_threadEntryPoint (userData);
  216726. return 0;
  216727. }
  216728. void Thread::launchThread()
  216729. {
  216730. threadHandle_ = 0;
  216731. pthread_t handle = 0;
  216732. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  216733. {
  216734. pthread_detach (handle);
  216735. threadHandle_ = (void*) handle;
  216736. threadId_ = (ThreadID) threadHandle_;
  216737. }
  216738. }
  216739. void Thread::closeThreadHandle()
  216740. {
  216741. threadId_ = 0;
  216742. threadHandle_ = 0;
  216743. }
  216744. void Thread::killThread()
  216745. {
  216746. if (threadHandle_ != 0)
  216747. pthread_cancel ((pthread_t) threadHandle_);
  216748. }
  216749. void Thread::setCurrentThreadName (const String& /*name*/)
  216750. {
  216751. }
  216752. bool Thread::setThreadPriority (void* handle, int priority)
  216753. {
  216754. struct sched_param param;
  216755. int policy;
  216756. priority = jlimit (0, 10, priority);
  216757. if (handle == 0)
  216758. handle = (void*) pthread_self();
  216759. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  216760. return false;
  216761. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  216762. const int minPriority = sched_get_priority_min (policy);
  216763. const int maxPriority = sched_get_priority_max (policy);
  216764. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  216765. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216766. }
  216767. Thread::ThreadID Thread::getCurrentThreadId()
  216768. {
  216769. return (ThreadID) pthread_self();
  216770. }
  216771. void Thread::yield()
  216772. {
  216773. sched_yield();
  216774. }
  216775. /* Remove this macro if you're having problems compiling the cpu affinity
  216776. calls (the API for these has changed about quite a bit in various Linux
  216777. versions, and a lot of distros seem to ship with obsolete versions)
  216778. */
  216779. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216780. #define SUPPORT_AFFINITIES 1
  216781. #endif
  216782. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216783. {
  216784. #if SUPPORT_AFFINITIES
  216785. cpu_set_t affinity;
  216786. CPU_ZERO (&affinity);
  216787. for (int i = 0; i < 32; ++i)
  216788. if ((affinityMask & (1 << i)) != 0)
  216789. CPU_SET (i, &affinity);
  216790. /*
  216791. N.B. If this line causes a compile error, then you've probably not got the latest
  216792. version of glibc installed.
  216793. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216794. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216795. */
  216796. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216797. sched_yield();
  216798. #else
  216799. /* affinities aren't supported because either the appropriate header files weren't found,
  216800. or the SUPPORT_AFFINITIES macro was turned off
  216801. */
  216802. jassertfalse;
  216803. (void) affinityMask;
  216804. #endif
  216805. }
  216806. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216807. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216808. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216809. // compiled on its own).
  216810. #if JUCE_INCLUDED_FILE
  216811. enum
  216812. {
  216813. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  216814. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  216815. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  216816. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  216817. };
  216818. bool File::copyInternal (const File& dest) const
  216819. {
  216820. FileInputStream in (*this);
  216821. if (dest.deleteFile())
  216822. {
  216823. {
  216824. FileOutputStream out (dest);
  216825. if (out.failedToOpen())
  216826. return false;
  216827. if (out.writeFromInputStream (in, -1) == getSize())
  216828. return true;
  216829. }
  216830. dest.deleteFile();
  216831. }
  216832. return false;
  216833. }
  216834. void File::findFileSystemRoots (Array<File>& destArray)
  216835. {
  216836. destArray.add (File ("/"));
  216837. }
  216838. bool File::isOnCDRomDrive() const
  216839. {
  216840. struct statfs buf;
  216841. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216842. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  216843. }
  216844. bool File::isOnHardDisk() const
  216845. {
  216846. struct statfs buf;
  216847. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216848. {
  216849. switch (buf.f_type)
  216850. {
  216851. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216852. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216853. case U_NFS_SUPER_MAGIC: // Network NFS
  216854. case U_SMB_SUPER_MAGIC: // Network Samba
  216855. return false;
  216856. default:
  216857. // Assume anything else is a hard-disk (but note it could
  216858. // be a RAM disk. There isn't a good way of determining
  216859. // this for sure)
  216860. return true;
  216861. }
  216862. }
  216863. // Assume so if this fails for some reason
  216864. return true;
  216865. }
  216866. bool File::isOnRemovableDrive() const
  216867. {
  216868. jassertfalse; // xxx not implemented for linux!
  216869. return false;
  216870. }
  216871. bool File::isHidden() const
  216872. {
  216873. return getFileName().startsWithChar ('.');
  216874. }
  216875. namespace
  216876. {
  216877. const File juce_readlink (const String& file, const File& defaultFile)
  216878. {
  216879. const int size = 8192;
  216880. HeapBlock<char> buffer;
  216881. buffer.malloc (size + 4);
  216882. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  216883. if (numBytes > 0 && numBytes <= size)
  216884. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  216885. return defaultFile;
  216886. }
  216887. }
  216888. const File File::getLinkedTarget() const
  216889. {
  216890. return juce_readlink (getFullPathName().toUTF8(), *this);
  216891. }
  216892. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216893. const File File::getSpecialLocation (const SpecialLocationType type)
  216894. {
  216895. switch (type)
  216896. {
  216897. case userHomeDirectory:
  216898. {
  216899. const char* homeDir = getenv ("HOME");
  216900. if (homeDir == 0)
  216901. {
  216902. struct passwd* const pw = getpwuid (getuid());
  216903. if (pw != 0)
  216904. homeDir = pw->pw_dir;
  216905. }
  216906. return File (String::fromUTF8 (homeDir));
  216907. }
  216908. case userDocumentsDirectory:
  216909. case userMusicDirectory:
  216910. case userMoviesDirectory:
  216911. case userApplicationDataDirectory:
  216912. return File ("~");
  216913. case userDesktopDirectory:
  216914. return File ("~/Desktop");
  216915. case commonApplicationDataDirectory:
  216916. return File ("/var");
  216917. case globalApplicationsDirectory:
  216918. return File ("/usr");
  216919. case tempDirectory:
  216920. {
  216921. File tmp ("/var/tmp");
  216922. if (! tmp.isDirectory())
  216923. {
  216924. tmp = "/tmp";
  216925. if (! tmp.isDirectory())
  216926. tmp = File::getCurrentWorkingDirectory();
  216927. }
  216928. return tmp;
  216929. }
  216930. case invokedExecutableFile:
  216931. if (juce_Argv0 != 0)
  216932. return File (String::fromUTF8 (juce_Argv0));
  216933. // deliberate fall-through...
  216934. case currentExecutableFile:
  216935. case currentApplicationFile:
  216936. return juce_getExecutableFile();
  216937. case hostApplicationPath:
  216938. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  216939. default:
  216940. jassertfalse; // unknown type?
  216941. break;
  216942. }
  216943. return File::nonexistent;
  216944. }
  216945. const String File::getVersion() const
  216946. {
  216947. return String::empty; // xxx not yet implemented
  216948. }
  216949. bool File::moveToTrash() const
  216950. {
  216951. if (! exists())
  216952. return true;
  216953. File trashCan ("~/.Trash");
  216954. if (! trashCan.isDirectory())
  216955. trashCan = "~/.local/share/Trash/files";
  216956. if (! trashCan.isDirectory())
  216957. return false;
  216958. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216959. getFileExtension()));
  216960. }
  216961. class DirectoryIterator::NativeIterator::Pimpl
  216962. {
  216963. public:
  216964. Pimpl (const File& directory, const String& wildCard_)
  216965. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216966. wildCard (wildCard_),
  216967. dir (opendir (directory.getFullPathName().toUTF8()))
  216968. {
  216969. wildcardUTF8 = wildCard.toUTF8();
  216970. }
  216971. ~Pimpl()
  216972. {
  216973. if (dir != 0)
  216974. closedir (dir);
  216975. }
  216976. bool next (String& filenameFound,
  216977. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216978. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216979. {
  216980. if (dir != 0)
  216981. {
  216982. for (;;)
  216983. {
  216984. struct dirent* const de = readdir (dir);
  216985. if (de == 0)
  216986. break;
  216987. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216988. {
  216989. filenameFound = String::fromUTF8 (de->d_name);
  216990. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  216991. if (isHidden != 0)
  216992. *isHidden = filenameFound.startsWithChar ('.');
  216993. return true;
  216994. }
  216995. }
  216996. }
  216997. return false;
  216998. }
  216999. private:
  217000. String parentDir, wildCard;
  217001. const char* wildcardUTF8;
  217002. DIR* dir;
  217003. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  217004. };
  217005. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217006. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217007. {
  217008. }
  217009. DirectoryIterator::NativeIterator::~NativeIterator()
  217010. {
  217011. }
  217012. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217013. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217014. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217015. {
  217016. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217017. }
  217018. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217019. {
  217020. String cmdString (fileName.replace (" ", "\\ ",false));
  217021. cmdString << " " << parameters;
  217022. if (URL::isProbablyAWebsiteURL (fileName)
  217023. || cmdString.startsWithIgnoreCase ("file:")
  217024. || URL::isProbablyAnEmailAddress (fileName))
  217025. {
  217026. // create a command that tries to launch a bunch of likely browsers
  217027. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217028. StringArray cmdLines;
  217029. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217030. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217031. cmdString = cmdLines.joinIntoString (" || ");
  217032. }
  217033. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217034. const int cpid = fork();
  217035. if (cpid == 0)
  217036. {
  217037. setsid();
  217038. // Child process
  217039. execve (argv[0], (char**) argv, environ);
  217040. exit (0);
  217041. }
  217042. return cpid >= 0;
  217043. }
  217044. void File::revealToUser() const
  217045. {
  217046. if (isDirectory())
  217047. startAsProcess();
  217048. else if (getParentDirectory().exists())
  217049. getParentDirectory().startAsProcess();
  217050. }
  217051. #endif
  217052. /*** End of inlined file: juce_linux_Files.cpp ***/
  217053. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217054. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217055. // compiled on its own).
  217056. #if JUCE_INCLUDED_FILE
  217057. struct NamedPipeInternal
  217058. {
  217059. String pipeInName, pipeOutName;
  217060. int pipeIn, pipeOut;
  217061. bool volatile createdPipe, blocked, stopReadOperation;
  217062. static void signalHandler (int) {}
  217063. };
  217064. void NamedPipe::cancelPendingReads()
  217065. {
  217066. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217067. {
  217068. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217069. intern->stopReadOperation = true;
  217070. char buffer [1] = { 0 };
  217071. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217072. (void) bytesWritten;
  217073. int timeout = 2000;
  217074. while (intern->blocked && --timeout >= 0)
  217075. Thread::sleep (2);
  217076. intern->stopReadOperation = false;
  217077. }
  217078. }
  217079. void NamedPipe::close()
  217080. {
  217081. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217082. if (intern != 0)
  217083. {
  217084. internal = 0;
  217085. if (intern->pipeIn != -1)
  217086. ::close (intern->pipeIn);
  217087. if (intern->pipeOut != -1)
  217088. ::close (intern->pipeOut);
  217089. if (intern->createdPipe)
  217090. {
  217091. unlink (intern->pipeInName.toUTF8());
  217092. unlink (intern->pipeOutName.toUTF8());
  217093. }
  217094. delete intern;
  217095. }
  217096. }
  217097. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217098. {
  217099. close();
  217100. NamedPipeInternal* const intern = new NamedPipeInternal();
  217101. internal = intern;
  217102. intern->createdPipe = createPipe;
  217103. intern->blocked = false;
  217104. intern->stopReadOperation = false;
  217105. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217106. siginterrupt (SIGPIPE, 1);
  217107. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217108. intern->pipeInName = pipePath + "_in";
  217109. intern->pipeOutName = pipePath + "_out";
  217110. intern->pipeIn = -1;
  217111. intern->pipeOut = -1;
  217112. if (createPipe)
  217113. {
  217114. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217115. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217116. {
  217117. delete intern;
  217118. internal = 0;
  217119. return false;
  217120. }
  217121. }
  217122. return true;
  217123. }
  217124. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217125. {
  217126. int bytesRead = -1;
  217127. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217128. if (intern != 0)
  217129. {
  217130. intern->blocked = true;
  217131. if (intern->pipeIn == -1)
  217132. {
  217133. if (intern->createdPipe)
  217134. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217135. else
  217136. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217137. if (intern->pipeIn == -1)
  217138. {
  217139. intern->blocked = false;
  217140. return -1;
  217141. }
  217142. }
  217143. bytesRead = 0;
  217144. char* p = static_cast<char*> (destBuffer);
  217145. while (bytesRead < maxBytesToRead)
  217146. {
  217147. const int bytesThisTime = maxBytesToRead - bytesRead;
  217148. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217149. if (numRead <= 0 || intern->stopReadOperation)
  217150. {
  217151. bytesRead = -1;
  217152. break;
  217153. }
  217154. bytesRead += numRead;
  217155. p += bytesRead;
  217156. }
  217157. intern->blocked = false;
  217158. }
  217159. return bytesRead;
  217160. }
  217161. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217162. {
  217163. int bytesWritten = -1;
  217164. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217165. if (intern != 0)
  217166. {
  217167. if (intern->pipeOut == -1)
  217168. {
  217169. if (intern->createdPipe)
  217170. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217171. else
  217172. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217173. if (intern->pipeOut == -1)
  217174. {
  217175. return -1;
  217176. }
  217177. }
  217178. const char* p = static_cast<const char*> (sourceBuffer);
  217179. bytesWritten = 0;
  217180. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217181. while (bytesWritten < numBytesToWrite
  217182. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217183. {
  217184. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217185. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217186. if (numWritten <= 0)
  217187. {
  217188. bytesWritten = -1;
  217189. break;
  217190. }
  217191. bytesWritten += numWritten;
  217192. p += bytesWritten;
  217193. }
  217194. }
  217195. return bytesWritten;
  217196. }
  217197. #endif
  217198. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217199. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217200. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217201. // compiled on its own).
  217202. #if JUCE_INCLUDED_FILE
  217203. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217204. {
  217205. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217206. if (s != -1)
  217207. {
  217208. char buf [1024];
  217209. struct ifconf ifc;
  217210. ifc.ifc_len = sizeof (buf);
  217211. ifc.ifc_buf = buf;
  217212. ioctl (s, SIOCGIFCONF, &ifc);
  217213. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217214. {
  217215. struct ifreq ifr;
  217216. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217217. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217218. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217219. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217220. {
  217221. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217222. }
  217223. }
  217224. close (s);
  217225. }
  217226. }
  217227. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217228. const String& emailSubject,
  217229. const String& bodyText,
  217230. const StringArray& filesToAttach)
  217231. {
  217232. jassertfalse; // xxx todo
  217233. return false;
  217234. }
  217235. class WebInputStream : public InputStream
  217236. {
  217237. public:
  217238. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217239. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217240. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217241. : socketHandle (-1), levelsOfRedirection (0),
  217242. address (address_), headers (headers_), postData (postData_), position (0),
  217243. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217244. {
  217245. createConnection (progressCallback, progressCallbackContext);
  217246. if (responseHeaders != 0 && ! isError())
  217247. {
  217248. for (int i = 0; i < headerLines.size(); ++i)
  217249. {
  217250. const String& headersEntry = headerLines[i];
  217251. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217252. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217253. const String previousValue ((*responseHeaders) [key]);
  217254. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217255. }
  217256. }
  217257. }
  217258. ~WebInputStream()
  217259. {
  217260. closeSocket();
  217261. }
  217262. bool isError() const { return socketHandle < 0; }
  217263. bool isExhausted() { return finished; }
  217264. int64 getPosition() { return position; }
  217265. int64 getTotalLength()
  217266. {
  217267. jassertfalse; //xxx to do
  217268. return -1;
  217269. }
  217270. int read (void* buffer, int bytesToRead)
  217271. {
  217272. if (finished || isError())
  217273. return 0;
  217274. fd_set readbits;
  217275. FD_ZERO (&readbits);
  217276. FD_SET (socketHandle, &readbits);
  217277. struct timeval tv;
  217278. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217279. tv.tv_usec = 0;
  217280. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217281. return 0; // (timeout)
  217282. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217283. if (bytesRead == 0)
  217284. finished = true;
  217285. position += bytesRead;
  217286. return bytesRead;
  217287. }
  217288. bool setPosition (int64 wantedPos)
  217289. {
  217290. if (isError())
  217291. return false;
  217292. if (wantedPos != position)
  217293. {
  217294. finished = false;
  217295. if (wantedPos < position)
  217296. {
  217297. closeSocket();
  217298. position = 0;
  217299. createConnection (0, 0);
  217300. }
  217301. skipNextBytes (wantedPos - position);
  217302. }
  217303. return true;
  217304. }
  217305. private:
  217306. int socketHandle, levelsOfRedirection;
  217307. StringArray headerLines;
  217308. String address, headers;
  217309. MemoryBlock postData;
  217310. int64 position;
  217311. bool finished;
  217312. const bool isPost;
  217313. const int timeOutMs;
  217314. void closeSocket()
  217315. {
  217316. if (socketHandle >= 0)
  217317. close (socketHandle);
  217318. socketHandle = -1;
  217319. levelsOfRedirection = 0;
  217320. }
  217321. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217322. {
  217323. closeSocket();
  217324. uint32 timeOutTime = Time::getMillisecondCounter();
  217325. if (timeOutMs == 0)
  217326. timeOutTime += 60000;
  217327. else if (timeOutMs < 0)
  217328. timeOutTime = 0xffffffff;
  217329. else
  217330. timeOutTime += timeOutMs;
  217331. String hostName, hostPath;
  217332. int hostPort;
  217333. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217334. return;
  217335. const struct hostent* host = 0;
  217336. int port = 0;
  217337. String proxyName, proxyPath;
  217338. int proxyPort = 0;
  217339. String proxyURL (getenv ("http_proxy"));
  217340. if (proxyURL.startsWithIgnoreCase ("http://"))
  217341. {
  217342. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217343. return;
  217344. host = gethostbyname (proxyName.toUTF8());
  217345. port = proxyPort;
  217346. }
  217347. else
  217348. {
  217349. host = gethostbyname (hostName.toUTF8());
  217350. port = hostPort;
  217351. }
  217352. if (host == 0)
  217353. return;
  217354. {
  217355. struct sockaddr_in socketAddress;
  217356. zerostruct (socketAddress);
  217357. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217358. socketAddress.sin_family = host->h_addrtype;
  217359. socketAddress.sin_port = htons (port);
  217360. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217361. if (socketHandle == -1)
  217362. return;
  217363. int receiveBufferSize = 16384;
  217364. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217365. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217366. #if JUCE_MAC
  217367. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217368. #endif
  217369. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217370. {
  217371. closeSocket();
  217372. return;
  217373. }
  217374. }
  217375. {
  217376. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217377. hostPath, address, headers, postData, isPost));
  217378. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217379. {
  217380. closeSocket();
  217381. return;
  217382. }
  217383. }
  217384. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217385. if (responseHeader.isNotEmpty())
  217386. {
  217387. headerLines.clear();
  217388. headerLines.addLines (responseHeader);
  217389. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217390. .substring (0, 3).getIntValue();
  217391. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217392. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217393. String location (findHeaderItem (headerLines, "Location:"));
  217394. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217395. {
  217396. if (! location.startsWithIgnoreCase ("http://"))
  217397. location = "http://" + location;
  217398. if (++levelsOfRedirection <= 3)
  217399. {
  217400. address = location;
  217401. createConnection (progressCallback, progressCallbackContext);
  217402. return;
  217403. }
  217404. }
  217405. else
  217406. {
  217407. levelsOfRedirection = 0;
  217408. return;
  217409. }
  217410. }
  217411. closeSocket();
  217412. }
  217413. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217414. {
  217415. int bytesRead = 0, numConsecutiveLFs = 0;
  217416. MemoryBlock buffer (1024, true);
  217417. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217418. && Time::getMillisecondCounter() <= timeOutTime)
  217419. {
  217420. fd_set readbits;
  217421. FD_ZERO (&readbits);
  217422. FD_SET (socketHandle, &readbits);
  217423. struct timeval tv;
  217424. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217425. tv.tv_usec = 0;
  217426. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217427. return String::empty; // (timeout)
  217428. buffer.ensureSize (bytesRead + 8, true);
  217429. char* const dest = (char*) buffer.getData() + bytesRead;
  217430. if (recv (socketHandle, dest, 1, 0) == -1)
  217431. return String::empty;
  217432. const char lastByte = *dest;
  217433. ++bytesRead;
  217434. if (lastByte == '\n')
  217435. ++numConsecutiveLFs;
  217436. else if (lastByte != '\r')
  217437. numConsecutiveLFs = 0;
  217438. }
  217439. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217440. if (header.startsWithIgnoreCase ("HTTP/"))
  217441. return header.trimEnd();
  217442. return String::empty;
  217443. }
  217444. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217445. const String& proxyName, const int proxyPort,
  217446. const String& hostPath, const String& originalURL,
  217447. const String& headers, const MemoryBlock& postData,
  217448. const bool isPost)
  217449. {
  217450. String header (isPost ? "POST " : "GET ");
  217451. if (proxyName.isEmpty())
  217452. {
  217453. header << hostPath << " HTTP/1.0\r\nHost: "
  217454. << hostName << ':' << hostPort;
  217455. }
  217456. else
  217457. {
  217458. header << originalURL << " HTTP/1.0\r\nHost: "
  217459. << proxyName << ':' << proxyPort;
  217460. }
  217461. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217462. << "\r\nConnection: Close\r\nContent-Length: "
  217463. << postData.getSize() << "\r\n"
  217464. << headers << "\r\n";
  217465. MemoryBlock mb;
  217466. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217467. mb.append (postData.getData(), postData.getSize());
  217468. return mb;
  217469. }
  217470. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217471. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217472. {
  217473. size_t totalHeaderSent = 0;
  217474. while (totalHeaderSent < requestHeader.getSize())
  217475. {
  217476. if (Time::getMillisecondCounter() > timeOutTime)
  217477. return false;
  217478. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217479. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217480. return false;
  217481. totalHeaderSent += numToSend;
  217482. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217483. return false;
  217484. }
  217485. return true;
  217486. }
  217487. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217488. {
  217489. if (! url.startsWithIgnoreCase ("http://"))
  217490. return false;
  217491. const int nextSlash = url.indexOfChar (7, '/');
  217492. int nextColon = url.indexOfChar (7, ':');
  217493. if (nextColon > nextSlash && nextSlash > 0)
  217494. nextColon = -1;
  217495. if (nextColon >= 0)
  217496. {
  217497. host = url.substring (7, nextColon);
  217498. if (nextSlash >= 0)
  217499. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217500. else
  217501. port = url.substring (nextColon + 1).getIntValue();
  217502. }
  217503. else
  217504. {
  217505. port = 80;
  217506. if (nextSlash >= 0)
  217507. host = url.substring (7, nextSlash);
  217508. else
  217509. host = url.substring (7);
  217510. }
  217511. if (nextSlash >= 0)
  217512. path = url.substring (nextSlash);
  217513. else
  217514. path = "/";
  217515. return true;
  217516. }
  217517. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217518. {
  217519. for (int i = 0; i < lines.size(); ++i)
  217520. if (lines[i].startsWithIgnoreCase (itemName))
  217521. return lines[i].substring (itemName.length()).trim();
  217522. return String::empty;
  217523. }
  217524. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217525. };
  217526. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217527. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217528. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217529. {
  217530. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217531. progressCallback, progressCallbackContext,
  217532. headers, timeOutMs, responseHeaders));
  217533. return wi->isError() ? 0 : wi.release();
  217534. }
  217535. #endif
  217536. /*** End of inlined file: juce_linux_Network.cpp ***/
  217537. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217538. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217539. // compiled on its own).
  217540. #if JUCE_INCLUDED_FILE
  217541. void Logger::outputDebugString (const String& text)
  217542. {
  217543. std::cerr << text << std::endl;
  217544. }
  217545. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217546. {
  217547. return Linux;
  217548. }
  217549. const String SystemStats::getOperatingSystemName()
  217550. {
  217551. return "Linux";
  217552. }
  217553. bool SystemStats::isOperatingSystem64Bit()
  217554. {
  217555. #if JUCE_64BIT
  217556. return true;
  217557. #else
  217558. //xxx not sure how to find this out?..
  217559. return false;
  217560. #endif
  217561. }
  217562. namespace LinuxStatsHelpers
  217563. {
  217564. const String getCpuInfo (const char* const key)
  217565. {
  217566. StringArray lines;
  217567. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217568. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217569. if (lines[i].startsWithIgnoreCase (key))
  217570. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217571. return String::empty;
  217572. }
  217573. }
  217574. const String SystemStats::getCpuVendor()
  217575. {
  217576. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  217577. }
  217578. int SystemStats::getCpuSpeedInMegaherz()
  217579. {
  217580. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  217581. }
  217582. int SystemStats::getMemorySizeInMegabytes()
  217583. {
  217584. struct sysinfo sysi;
  217585. if (sysinfo (&sysi) == 0)
  217586. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217587. return 0;
  217588. }
  217589. int SystemStats::getPageSize()
  217590. {
  217591. return sysconf (_SC_PAGESIZE);
  217592. }
  217593. const String SystemStats::getLogonName()
  217594. {
  217595. const char* user = getenv ("USER");
  217596. if (user == 0)
  217597. {
  217598. struct passwd* const pw = getpwuid (getuid());
  217599. if (pw != 0)
  217600. user = pw->pw_name;
  217601. }
  217602. return String::fromUTF8 (user);
  217603. }
  217604. const String SystemStats::getFullUserName()
  217605. {
  217606. return getLogonName();
  217607. }
  217608. void SystemStats::initialiseStats()
  217609. {
  217610. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  217611. cpuFlags.hasMMX = flags.contains ("mmx");
  217612. cpuFlags.hasSSE = flags.contains ("sse");
  217613. cpuFlags.hasSSE2 = flags.contains ("sse2");
  217614. cpuFlags.has3DNow = flags.contains ("3dnow");
  217615. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  217616. }
  217617. void PlatformUtilities::fpuReset()
  217618. {
  217619. }
  217620. uint32 juce_millisecondsSinceStartup() throw()
  217621. {
  217622. timespec t;
  217623. clock_gettime (CLOCK_MONOTONIC, &t);
  217624. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  217625. }
  217626. int64 Time::getHighResolutionTicks() throw()
  217627. {
  217628. timespec t;
  217629. clock_gettime (CLOCK_MONOTONIC, &t);
  217630. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  217631. }
  217632. int64 Time::getHighResolutionTicksPerSecond() throw()
  217633. {
  217634. return 1000000; // (microseconds)
  217635. }
  217636. double Time::getMillisecondCounterHiRes() throw()
  217637. {
  217638. return getHighResolutionTicks() * 0.001;
  217639. }
  217640. bool Time::setSystemTimeToThisTime() const
  217641. {
  217642. timeval t;
  217643. t.tv_sec = millisSinceEpoch / 1000;
  217644. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  217645. return settimeofday (&t, 0) == 0;
  217646. }
  217647. #endif
  217648. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  217649. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  217650. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217651. // compiled on its own).
  217652. #if JUCE_INCLUDED_FILE
  217653. /*
  217654. Note that a lot of methods that you'd expect to find in this file actually
  217655. live in juce_posix_SharedCode.h!
  217656. */
  217657. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217658. void Process::setPriority (ProcessPriority prior)
  217659. {
  217660. struct sched_param param;
  217661. int policy, maxp, minp;
  217662. const int p = (int) prior;
  217663. if (p <= 1)
  217664. policy = SCHED_OTHER;
  217665. else
  217666. policy = SCHED_RR;
  217667. minp = sched_get_priority_min (policy);
  217668. maxp = sched_get_priority_max (policy);
  217669. if (p < 2)
  217670. param.sched_priority = 0;
  217671. else if (p == 2 )
  217672. // Set to middle of lower realtime priority range
  217673. param.sched_priority = minp + (maxp - minp) / 4;
  217674. else
  217675. // Set to middle of higher realtime priority range
  217676. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217677. pthread_setschedparam (pthread_self(), policy, &param);
  217678. }
  217679. void Process::terminate()
  217680. {
  217681. exit (0);
  217682. }
  217683. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  217684. {
  217685. static char testResult = 0;
  217686. if (testResult == 0)
  217687. {
  217688. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217689. if (testResult >= 0)
  217690. {
  217691. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217692. testResult = 1;
  217693. }
  217694. }
  217695. return testResult < 0;
  217696. }
  217697. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217698. {
  217699. return juce_isRunningUnderDebugger();
  217700. }
  217701. void Process::raisePrivilege()
  217702. {
  217703. // If running suid root, change effective user
  217704. // to root
  217705. if (geteuid() != 0 && getuid() == 0)
  217706. {
  217707. setreuid (geteuid(), getuid());
  217708. setregid (getegid(), getgid());
  217709. }
  217710. }
  217711. void Process::lowerPrivilege()
  217712. {
  217713. // If runing suid root, change effective user
  217714. // back to real user
  217715. if (geteuid() == 0 && getuid() != 0)
  217716. {
  217717. setreuid (geteuid(), getuid());
  217718. setregid (getegid(), getgid());
  217719. }
  217720. }
  217721. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217722. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217723. {
  217724. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217725. }
  217726. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217727. {
  217728. dlclose(handle);
  217729. }
  217730. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217731. {
  217732. return dlsym (libraryHandle, procedureName.toCString());
  217733. }
  217734. #endif
  217735. #endif
  217736. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217737. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217738. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217739. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217740. // compiled on its own).
  217741. #if JUCE_INCLUDED_FILE
  217742. extern Display* display;
  217743. extern Window juce_messageWindowHandle;
  217744. namespace ClipboardHelpers
  217745. {
  217746. static String localClipboardContent;
  217747. static Atom atom_UTF8_STRING;
  217748. static Atom atom_CLIPBOARD;
  217749. static Atom atom_TARGETS;
  217750. static void initSelectionAtoms()
  217751. {
  217752. static bool isInitialised = false;
  217753. if (! isInitialised)
  217754. {
  217755. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217756. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217757. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217758. }
  217759. }
  217760. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217761. // works only for strings shorter than 1000000 bytes
  217762. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217763. {
  217764. String returnData;
  217765. char* clipData;
  217766. Atom actualType;
  217767. int actualFormat;
  217768. unsigned long numItems, bytesLeft;
  217769. if (XGetWindowProperty (display, window, prop,
  217770. 0L /* offset */, 1000000 /* length (max) */, False,
  217771. AnyPropertyType /* format */,
  217772. &actualType, &actualFormat, &numItems, &bytesLeft,
  217773. (unsigned char**) &clipData) == Success)
  217774. {
  217775. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217776. returnData = String::fromUTF8 (clipData, numItems);
  217777. else if (actualType == XA_STRING && actualFormat == 8)
  217778. returnData = String (clipData, numItems);
  217779. if (clipData != 0)
  217780. XFree (clipData);
  217781. jassert (bytesLeft == 0 || numItems == 1000000);
  217782. }
  217783. XDeleteProperty (display, window, prop);
  217784. return returnData;
  217785. }
  217786. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217787. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217788. {
  217789. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217790. // The selection owner will be asked to set the JUCE_SEL property on the
  217791. // juce_messageWindowHandle with the selection content
  217792. XConvertSelection (display, selection, requestedFormat, property_name,
  217793. juce_messageWindowHandle, CurrentTime);
  217794. int count = 50; // will wait at most for 200 ms
  217795. while (--count >= 0)
  217796. {
  217797. XEvent event;
  217798. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217799. {
  217800. if (event.xselection.property == property_name)
  217801. {
  217802. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217803. selectionContent = readWindowProperty (event.xselection.requestor,
  217804. event.xselection.property,
  217805. requestedFormat);
  217806. return true;
  217807. }
  217808. else
  217809. {
  217810. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217811. }
  217812. }
  217813. // not very elegant.. we could do a select() or something like that...
  217814. // however clipboard content requesting is inherently slow on x11, it
  217815. // often takes 50ms or more so...
  217816. Thread::sleep (4);
  217817. }
  217818. return false;
  217819. }
  217820. }
  217821. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217822. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217823. {
  217824. ClipboardHelpers::initSelectionAtoms();
  217825. // the selection content is sent to the target window as a window property
  217826. XSelectionEvent reply;
  217827. reply.type = SelectionNotify;
  217828. reply.display = evt.display;
  217829. reply.requestor = evt.requestor;
  217830. reply.selection = evt.selection;
  217831. reply.target = evt.target;
  217832. reply.property = None; // == "fail"
  217833. reply.time = evt.time;
  217834. HeapBlock <char> data;
  217835. int propertyFormat = 0, numDataItems = 0;
  217836. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217837. {
  217838. if (evt.target == XA_STRING)
  217839. {
  217840. // format data according to system locale
  217841. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217842. data.calloc (numDataItems + 1);
  217843. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217844. propertyFormat = 8; // bits/item
  217845. }
  217846. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217847. {
  217848. // translate to utf8
  217849. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217850. data.calloc (numDataItems + 1);
  217851. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217852. propertyFormat = 8; // bits/item
  217853. }
  217854. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217855. {
  217856. // another application wants to know what we are able to send
  217857. numDataItems = 2;
  217858. propertyFormat = 32; // atoms are 32-bit
  217859. data.calloc (numDataItems * 4);
  217860. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217861. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217862. atoms[1] = XA_STRING;
  217863. }
  217864. }
  217865. else
  217866. {
  217867. DBG ("requested unsupported clipboard");
  217868. }
  217869. if (data != 0)
  217870. {
  217871. const int maxReasonableSelectionSize = 1000000;
  217872. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217873. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217874. {
  217875. XChangeProperty (evt.display, evt.requestor,
  217876. evt.property, evt.target,
  217877. propertyFormat /* 8 or 32 */, PropModeReplace,
  217878. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217879. reply.property = evt.property; // " == success"
  217880. }
  217881. }
  217882. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217883. }
  217884. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217885. {
  217886. ClipboardHelpers::initSelectionAtoms();
  217887. ClipboardHelpers::localClipboardContent = clipText;
  217888. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217889. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217890. }
  217891. const String SystemClipboard::getTextFromClipboard()
  217892. {
  217893. ClipboardHelpers::initSelectionAtoms();
  217894. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217895. level" clipboard that is supposed to be filled by ctrl-C
  217896. etc). When a clipboard manager is running, the content of this
  217897. selection is preserved even when the original selection owner
  217898. exits.
  217899. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217900. filled by good old x11 apps such as xterm)
  217901. */
  217902. String content;
  217903. Atom selection = XA_PRIMARY;
  217904. Window selectionOwner = None;
  217905. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217906. {
  217907. selection = ClipboardHelpers::atom_CLIPBOARD;
  217908. selectionOwner = XGetSelectionOwner (display, selection);
  217909. }
  217910. if (selectionOwner != None)
  217911. {
  217912. if (selectionOwner == juce_messageWindowHandle)
  217913. {
  217914. content = ClipboardHelpers::localClipboardContent;
  217915. }
  217916. else
  217917. {
  217918. // first try: we want an utf8 string
  217919. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217920. if (! ok)
  217921. {
  217922. // second chance, ask for a good old locale-dependent string ..
  217923. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217924. }
  217925. }
  217926. }
  217927. return content;
  217928. }
  217929. #endif
  217930. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217931. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217932. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217933. // compiled on its own).
  217934. #if JUCE_INCLUDED_FILE
  217935. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217936. #define JUCE_DEBUG_XERRORS 1
  217937. #endif
  217938. Display* display = 0;
  217939. Window juce_messageWindowHandle = None;
  217940. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217941. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217942. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217943. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217944. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217945. class InternalMessageQueue
  217946. {
  217947. public:
  217948. InternalMessageQueue()
  217949. : bytesInSocket (0),
  217950. totalEventCount (0)
  217951. {
  217952. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217953. (void) ret; jassert (ret == 0);
  217954. //setNonBlocking (fd[0]);
  217955. //setNonBlocking (fd[1]);
  217956. }
  217957. ~InternalMessageQueue()
  217958. {
  217959. close (fd[0]);
  217960. close (fd[1]);
  217961. clearSingletonInstance();
  217962. }
  217963. void postMessage (Message* msg)
  217964. {
  217965. const int maxBytesInSocketQueue = 128;
  217966. ScopedLock sl (lock);
  217967. queue.add (msg);
  217968. if (bytesInSocket < maxBytesInSocketQueue)
  217969. {
  217970. ++bytesInSocket;
  217971. ScopedUnlock ul (lock);
  217972. const unsigned char x = 0xff;
  217973. size_t bytesWritten = write (fd[0], &x, 1);
  217974. (void) bytesWritten;
  217975. }
  217976. }
  217977. bool isEmpty() const
  217978. {
  217979. ScopedLock sl (lock);
  217980. return queue.size() == 0;
  217981. }
  217982. bool dispatchNextEvent()
  217983. {
  217984. // This alternates between giving priority to XEvents or internal messages,
  217985. // to keep everything running smoothly..
  217986. if ((++totalEventCount & 1) != 0)
  217987. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217988. else
  217989. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217990. }
  217991. // Wait for an event (either XEvent, or an internal Message)
  217992. bool sleepUntilEvent (const int timeoutMs)
  217993. {
  217994. if (! isEmpty())
  217995. return true;
  217996. if (display != 0)
  217997. {
  217998. ScopedXLock xlock;
  217999. if (XPending (display))
  218000. return true;
  218001. }
  218002. struct timeval tv;
  218003. tv.tv_sec = 0;
  218004. tv.tv_usec = timeoutMs * 1000;
  218005. int fd0 = getWaitHandle();
  218006. int fdmax = fd0;
  218007. fd_set readset;
  218008. FD_ZERO (&readset);
  218009. FD_SET (fd0, &readset);
  218010. if (display != 0)
  218011. {
  218012. ScopedXLock xlock;
  218013. int fd1 = XConnectionNumber (display);
  218014. FD_SET (fd1, &readset);
  218015. fdmax = jmax (fd0, fd1);
  218016. }
  218017. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218018. return (ret > 0); // ret <= 0 if error or timeout
  218019. }
  218020. struct MessageThreadFuncCall
  218021. {
  218022. enum { uniqueID = 0x73774623 };
  218023. MessageCallbackFunction* func;
  218024. void* parameter;
  218025. void* result;
  218026. CriticalSection lock;
  218027. WaitableEvent event;
  218028. };
  218029. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218030. private:
  218031. CriticalSection lock;
  218032. ReferenceCountedArray <Message> queue;
  218033. int fd[2];
  218034. int bytesInSocket;
  218035. int totalEventCount;
  218036. int getWaitHandle() const throw() { return fd[1]; }
  218037. static bool setNonBlocking (int handle)
  218038. {
  218039. int socketFlags = fcntl (handle, F_GETFL, 0);
  218040. if (socketFlags == -1)
  218041. return false;
  218042. socketFlags |= O_NONBLOCK;
  218043. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218044. }
  218045. static bool dispatchNextXEvent()
  218046. {
  218047. if (display == 0)
  218048. return false;
  218049. XEvent evt;
  218050. {
  218051. ScopedXLock xlock;
  218052. if (! XPending (display))
  218053. return false;
  218054. XNextEvent (display, &evt);
  218055. }
  218056. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218057. juce_handleSelectionRequest (evt.xselectionrequest);
  218058. else if (evt.xany.window != juce_messageWindowHandle)
  218059. juce_windowMessageReceive (&evt);
  218060. return true;
  218061. }
  218062. const Message::Ptr popNextMessage()
  218063. {
  218064. const ScopedLock sl (lock);
  218065. if (bytesInSocket > 0)
  218066. {
  218067. --bytesInSocket;
  218068. const ScopedUnlock ul (lock);
  218069. unsigned char x;
  218070. size_t numBytes = read (fd[1], &x, 1);
  218071. (void) numBytes;
  218072. }
  218073. return queue.removeAndReturn (0);
  218074. }
  218075. bool dispatchNextInternalMessage()
  218076. {
  218077. const Message::Ptr msg (popNextMessage());
  218078. if (msg == 0)
  218079. return false;
  218080. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218081. {
  218082. // Handle callback message
  218083. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218084. call->result = (*(call->func)) (call->parameter);
  218085. call->event.signal();
  218086. }
  218087. else
  218088. {
  218089. // Handle "normal" messages
  218090. MessageManager::getInstance()->deliverMessage (msg);
  218091. }
  218092. return true;
  218093. }
  218094. };
  218095. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218096. namespace LinuxErrorHandling
  218097. {
  218098. static bool errorOccurred = false;
  218099. static bool keyboardBreakOccurred = false;
  218100. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218101. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218102. // Usually happens when client-server connection is broken
  218103. static int ioErrorHandler (Display* display)
  218104. {
  218105. DBG ("ERROR: connection to X server broken.. terminating.");
  218106. if (JUCEApplication::isStandaloneApp())
  218107. MessageManager::getInstance()->stopDispatchLoop();
  218108. errorOccurred = true;
  218109. return 0;
  218110. }
  218111. // A protocol error has occurred
  218112. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218113. {
  218114. #if JUCE_DEBUG_XERRORS
  218115. char errorStr[64] = { 0 };
  218116. char requestStr[64] = { 0 };
  218117. XGetErrorText (display, event->error_code, errorStr, 64);
  218118. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218119. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218120. #endif
  218121. return 0;
  218122. }
  218123. static void installXErrorHandlers()
  218124. {
  218125. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218126. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218127. }
  218128. static void removeXErrorHandlers()
  218129. {
  218130. if (JUCEApplication::isStandaloneApp())
  218131. {
  218132. XSetIOErrorHandler (oldIOErrorHandler);
  218133. oldIOErrorHandler = 0;
  218134. XSetErrorHandler (oldErrorHandler);
  218135. oldErrorHandler = 0;
  218136. }
  218137. }
  218138. static void keyboardBreakSignalHandler (int sig)
  218139. {
  218140. if (sig == SIGINT)
  218141. keyboardBreakOccurred = true;
  218142. }
  218143. static void installKeyboardBreakHandler()
  218144. {
  218145. struct sigaction saction;
  218146. sigset_t maskSet;
  218147. sigemptyset (&maskSet);
  218148. saction.sa_handler = keyboardBreakSignalHandler;
  218149. saction.sa_mask = maskSet;
  218150. saction.sa_flags = 0;
  218151. sigaction (SIGINT, &saction, 0);
  218152. }
  218153. }
  218154. void MessageManager::doPlatformSpecificInitialisation()
  218155. {
  218156. if (JUCEApplication::isStandaloneApp())
  218157. {
  218158. // Initialise xlib for multiple thread support
  218159. static bool initThreadCalled = false;
  218160. if (! initThreadCalled)
  218161. {
  218162. if (! XInitThreads())
  218163. {
  218164. // This is fatal! Print error and closedown
  218165. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218166. Process::terminate();
  218167. return;
  218168. }
  218169. initThreadCalled = true;
  218170. }
  218171. LinuxErrorHandling::installXErrorHandlers();
  218172. LinuxErrorHandling::installKeyboardBreakHandler();
  218173. }
  218174. // Create the internal message queue
  218175. InternalMessageQueue::getInstance();
  218176. // Try to connect to a display
  218177. String displayName (getenv ("DISPLAY"));
  218178. if (displayName.isEmpty())
  218179. displayName = ":0.0";
  218180. display = XOpenDisplay (displayName.toCString());
  218181. if (display != 0) // This is not fatal! we can run headless.
  218182. {
  218183. // Create a context to store user data associated with Windows we create in WindowDriver
  218184. windowHandleXContext = XUniqueContext();
  218185. // We're only interested in client messages for this window, which are always sent
  218186. XSetWindowAttributes swa;
  218187. swa.event_mask = NoEventMask;
  218188. // Create our message window (this will never be mapped)
  218189. const int screen = DefaultScreen (display);
  218190. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218191. 0, 0, 1, 1, 0, 0, InputOnly,
  218192. DefaultVisual (display, screen),
  218193. CWEventMask, &swa);
  218194. }
  218195. }
  218196. void MessageManager::doPlatformSpecificShutdown()
  218197. {
  218198. InternalMessageQueue::deleteInstance();
  218199. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218200. {
  218201. XDestroyWindow (display, juce_messageWindowHandle);
  218202. XCloseDisplay (display);
  218203. juce_messageWindowHandle = 0;
  218204. display = 0;
  218205. LinuxErrorHandling::removeXErrorHandlers();
  218206. }
  218207. }
  218208. bool juce_postMessageToSystemQueue (Message* message)
  218209. {
  218210. if (LinuxErrorHandling::errorOccurred)
  218211. return false;
  218212. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218213. return true;
  218214. }
  218215. void MessageManager::broadcastMessage (const String& value)
  218216. {
  218217. /* TODO */
  218218. }
  218219. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218220. {
  218221. if (LinuxErrorHandling::errorOccurred)
  218222. return 0;
  218223. if (isThisTheMessageThread())
  218224. return func (parameter);
  218225. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  218226. messageCallContext.func = func;
  218227. messageCallContext.parameter = parameter;
  218228. InternalMessageQueue::getInstanceWithoutCreating()
  218229. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  218230. 0, 0, &messageCallContext));
  218231. // Wait for it to complete before continuing
  218232. messageCallContext.event.wait();
  218233. return messageCallContext.result;
  218234. }
  218235. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218236. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218237. {
  218238. while (! LinuxErrorHandling::errorOccurred)
  218239. {
  218240. if (LinuxErrorHandling::keyboardBreakOccurred)
  218241. {
  218242. LinuxErrorHandling::errorOccurred = true;
  218243. if (JUCEApplication::isStandaloneApp())
  218244. Process::terminate();
  218245. break;
  218246. }
  218247. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218248. return true;
  218249. if (returnIfNoPendingMessages)
  218250. break;
  218251. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218252. }
  218253. return false;
  218254. }
  218255. #endif
  218256. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218257. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218258. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218259. // compiled on its own).
  218260. #if JUCE_INCLUDED_FILE
  218261. class FreeTypeFontFace
  218262. {
  218263. public:
  218264. enum FontStyle
  218265. {
  218266. Plain = 0,
  218267. Bold = 1,
  218268. Italic = 2
  218269. };
  218270. FreeTypeFontFace (const String& familyName)
  218271. : hasSerif (false),
  218272. monospaced (false)
  218273. {
  218274. family = familyName;
  218275. }
  218276. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218277. {
  218278. if (names [(int) style].fileName.isEmpty())
  218279. {
  218280. names [(int) style].fileName = name;
  218281. names [(int) style].faceIndex = faceIndex;
  218282. }
  218283. }
  218284. const String& getFamilyName() const throw() { return family; }
  218285. const String& getFileName (const int style, int& faceIndex) const throw()
  218286. {
  218287. faceIndex = names[style].faceIndex;
  218288. return names[style].fileName;
  218289. }
  218290. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218291. bool getMonospaced() const throw() { return monospaced; }
  218292. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218293. bool getSerif() const throw() { return hasSerif; }
  218294. private:
  218295. String family;
  218296. struct FontNameIndex
  218297. {
  218298. String fileName;
  218299. int faceIndex;
  218300. };
  218301. FontNameIndex names[4];
  218302. bool hasSerif, monospaced;
  218303. };
  218304. class FreeTypeInterface : public DeletedAtShutdown
  218305. {
  218306. public:
  218307. FreeTypeInterface()
  218308. : ftLib (0),
  218309. lastFace (0),
  218310. lastBold (false),
  218311. lastItalic (false)
  218312. {
  218313. if (FT_Init_FreeType (&ftLib) != 0)
  218314. {
  218315. ftLib = 0;
  218316. DBG ("Failed to initialize FreeType");
  218317. }
  218318. StringArray fontDirs;
  218319. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218320. fontDirs.removeEmptyStrings (true);
  218321. if (fontDirs.size() == 0)
  218322. {
  218323. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218324. if (fontsInfo != 0)
  218325. {
  218326. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218327. {
  218328. fontDirs.add (e->getAllSubText().trim());
  218329. }
  218330. }
  218331. }
  218332. if (fontDirs.size() == 0)
  218333. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218334. for (int i = 0; i < fontDirs.size(); ++i)
  218335. enumerateFaces (fontDirs[i]);
  218336. }
  218337. ~FreeTypeInterface()
  218338. {
  218339. if (lastFace != 0)
  218340. FT_Done_Face (lastFace);
  218341. if (ftLib != 0)
  218342. FT_Done_FreeType (ftLib);
  218343. clearSingletonInstance();
  218344. }
  218345. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218346. {
  218347. for (int i = 0; i < faces.size(); i++)
  218348. if (faces[i]->getFamilyName() == familyName)
  218349. return faces[i];
  218350. if (! create)
  218351. return 0;
  218352. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218353. faces.add (newFace);
  218354. return newFace;
  218355. }
  218356. // Enumerate all font faces available in a given directory
  218357. void enumerateFaces (const String& path)
  218358. {
  218359. File dirPath (path);
  218360. if (path.isEmpty() || ! dirPath.isDirectory())
  218361. return;
  218362. DirectoryIterator di (dirPath, true);
  218363. while (di.next())
  218364. {
  218365. File possible (di.getFile());
  218366. if (possible.hasFileExtension ("ttf")
  218367. || possible.hasFileExtension ("pfb")
  218368. || possible.hasFileExtension ("pcf"))
  218369. {
  218370. FT_Face face;
  218371. int faceIndex = 0;
  218372. int numFaces = 0;
  218373. do
  218374. {
  218375. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218376. faceIndex, &face) == 0)
  218377. {
  218378. if (faceIndex == 0)
  218379. numFaces = face->num_faces;
  218380. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218381. {
  218382. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218383. int style = (int) FreeTypeFontFace::Plain;
  218384. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218385. style |= (int) FreeTypeFontFace::Bold;
  218386. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218387. style |= (int) FreeTypeFontFace::Italic;
  218388. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218389. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218390. // Surely there must be a better way to do this?
  218391. const String name (face->family_name);
  218392. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218393. || name.containsIgnoreCase ("Verdana")
  218394. || name.containsIgnoreCase ("Arial")));
  218395. }
  218396. FT_Done_Face (face);
  218397. }
  218398. ++faceIndex;
  218399. }
  218400. while (faceIndex < numFaces);
  218401. }
  218402. }
  218403. }
  218404. // Create a FreeType face object for a given font
  218405. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218406. {
  218407. FT_Face face = 0;
  218408. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218409. {
  218410. face = lastFace;
  218411. }
  218412. else
  218413. {
  218414. if (lastFace != 0)
  218415. {
  218416. FT_Done_Face (lastFace);
  218417. lastFace = 0;
  218418. }
  218419. lastFontName = fontName;
  218420. lastBold = bold;
  218421. lastItalic = italic;
  218422. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218423. if (ftFace != 0)
  218424. {
  218425. int style = (int) FreeTypeFontFace::Plain;
  218426. if (bold)
  218427. style |= (int) FreeTypeFontFace::Bold;
  218428. if (italic)
  218429. style |= (int) FreeTypeFontFace::Italic;
  218430. int faceIndex;
  218431. String fileName (ftFace->getFileName (style, faceIndex));
  218432. if (fileName.isEmpty())
  218433. {
  218434. style ^= (int) FreeTypeFontFace::Bold;
  218435. fileName = ftFace->getFileName (style, faceIndex);
  218436. if (fileName.isEmpty())
  218437. {
  218438. style ^= (int) FreeTypeFontFace::Bold;
  218439. style ^= (int) FreeTypeFontFace::Italic;
  218440. fileName = ftFace->getFileName (style, faceIndex);
  218441. if (! fileName.length())
  218442. {
  218443. style ^= (int) FreeTypeFontFace::Bold;
  218444. fileName = ftFace->getFileName (style, faceIndex);
  218445. }
  218446. }
  218447. }
  218448. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218449. {
  218450. face = lastFace;
  218451. // If there isn't a unicode charmap then select the first one.
  218452. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218453. FT_Set_Charmap (face, face->charmaps[0]);
  218454. }
  218455. }
  218456. }
  218457. return face;
  218458. }
  218459. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218460. {
  218461. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218462. const float height = (float) (face->ascender - face->descender);
  218463. const float scaleX = 1.0f / height;
  218464. const float scaleY = -1.0f / height;
  218465. Path destShape;
  218466. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218467. || face->glyph->format != ft_glyph_format_outline)
  218468. {
  218469. return false;
  218470. }
  218471. const FT_Outline* const outline = &face->glyph->outline;
  218472. const short* const contours = outline->contours;
  218473. const char* const tags = outline->tags;
  218474. FT_Vector* const points = outline->points;
  218475. for (int c = 0; c < outline->n_contours; c++)
  218476. {
  218477. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218478. const int endPoint = contours[c];
  218479. for (int p = startPoint; p <= endPoint; p++)
  218480. {
  218481. const float x = scaleX * points[p].x;
  218482. const float y = scaleY * points[p].y;
  218483. if (p == startPoint)
  218484. {
  218485. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218486. {
  218487. float x2 = scaleX * points [endPoint].x;
  218488. float y2 = scaleY * points [endPoint].y;
  218489. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218490. {
  218491. x2 = (x + x2) * 0.5f;
  218492. y2 = (y + y2) * 0.5f;
  218493. }
  218494. destShape.startNewSubPath (x2, y2);
  218495. }
  218496. else
  218497. {
  218498. destShape.startNewSubPath (x, y);
  218499. }
  218500. }
  218501. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218502. {
  218503. if (p != startPoint)
  218504. destShape.lineTo (x, y);
  218505. }
  218506. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218507. {
  218508. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218509. float x2 = scaleX * points [nextIndex].x;
  218510. float y2 = scaleY * points [nextIndex].y;
  218511. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218512. {
  218513. x2 = (x + x2) * 0.5f;
  218514. y2 = (y + y2) * 0.5f;
  218515. }
  218516. else
  218517. {
  218518. ++p;
  218519. }
  218520. destShape.quadraticTo (x, y, x2, y2);
  218521. }
  218522. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218523. {
  218524. if (p >= endPoint)
  218525. return false;
  218526. const int next1 = p + 1;
  218527. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218528. const float x2 = scaleX * points [next1].x;
  218529. const float y2 = scaleY * points [next1].y;
  218530. const float x3 = scaleX * points [next2].x;
  218531. const float y3 = scaleY * points [next2].y;
  218532. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218533. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218534. return false;
  218535. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218536. p += 2;
  218537. }
  218538. }
  218539. destShape.closeSubPath();
  218540. }
  218541. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218542. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218543. addKerning (face, dest, character, glyphIndex);
  218544. return true;
  218545. }
  218546. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218547. {
  218548. const float height = (float) (face->ascender - face->descender);
  218549. uint32 rightGlyphIndex;
  218550. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218551. while (rightGlyphIndex != 0)
  218552. {
  218553. FT_Vector kerning;
  218554. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218555. {
  218556. if (kerning.x != 0)
  218557. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218558. }
  218559. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218560. }
  218561. }
  218562. // Add a glyph to a font
  218563. bool addGlyphToFont (const uint32 character, const String& fontName,
  218564. bool bold, bool italic, CustomTypeface& dest)
  218565. {
  218566. FT_Face face = createFT_Face (fontName, bold, italic);
  218567. return face != 0 && addGlyph (face, dest, character);
  218568. }
  218569. void getFamilyNames (StringArray& familyNames) const
  218570. {
  218571. for (int i = 0; i < faces.size(); i++)
  218572. familyNames.add (faces[i]->getFamilyName());
  218573. }
  218574. void getMonospacedNames (StringArray& monoSpaced) const
  218575. {
  218576. for (int i = 0; i < faces.size(); i++)
  218577. if (faces[i]->getMonospaced())
  218578. monoSpaced.add (faces[i]->getFamilyName());
  218579. }
  218580. void getSerifNames (StringArray& serif) const
  218581. {
  218582. for (int i = 0; i < faces.size(); i++)
  218583. if (faces[i]->getSerif())
  218584. serif.add (faces[i]->getFamilyName());
  218585. }
  218586. void getSansSerifNames (StringArray& sansSerif) const
  218587. {
  218588. for (int i = 0; i < faces.size(); i++)
  218589. if (! faces[i]->getSerif())
  218590. sansSerif.add (faces[i]->getFamilyName());
  218591. }
  218592. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  218593. private:
  218594. FT_Library ftLib;
  218595. FT_Face lastFace;
  218596. String lastFontName;
  218597. bool lastBold, lastItalic;
  218598. OwnedArray<FreeTypeFontFace> faces;
  218599. };
  218600. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218601. class FreetypeTypeface : public CustomTypeface
  218602. {
  218603. public:
  218604. FreetypeTypeface (const Font& font)
  218605. {
  218606. FT_Face face = FreeTypeInterface::getInstance()
  218607. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218608. if (face == 0)
  218609. {
  218610. #if JUCE_DEBUG
  218611. String msg ("Failed to create typeface: ");
  218612. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218613. DBG (msg);
  218614. #endif
  218615. }
  218616. else
  218617. {
  218618. setCharacteristics (font.getTypefaceName(),
  218619. face->ascender / (float) (face->ascender - face->descender),
  218620. font.isBold(), font.isItalic(),
  218621. L' ');
  218622. }
  218623. }
  218624. bool loadGlyphIfPossible (juce_wchar character)
  218625. {
  218626. return FreeTypeInterface::getInstance()
  218627. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218628. }
  218629. };
  218630. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218631. {
  218632. return new FreetypeTypeface (font);
  218633. }
  218634. const StringArray Font::findAllTypefaceNames()
  218635. {
  218636. StringArray s;
  218637. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218638. s.sort (true);
  218639. return s;
  218640. }
  218641. namespace
  218642. {
  218643. const String pickBestFont (const StringArray& names,
  218644. const char* const choicesString)
  218645. {
  218646. StringArray choices;
  218647. choices.addTokens (String (choicesString), ",", String::empty);
  218648. choices.trim();
  218649. choices.removeEmptyStrings();
  218650. int i, j;
  218651. for (j = 0; j < choices.size(); ++j)
  218652. if (names.contains (choices[j], true))
  218653. return choices[j];
  218654. for (j = 0; j < choices.size(); ++j)
  218655. for (i = 0; i < names.size(); i++)
  218656. if (names[i].startsWithIgnoreCase (choices[j]))
  218657. return names[i];
  218658. for (j = 0; j < choices.size(); ++j)
  218659. for (i = 0; i < names.size(); i++)
  218660. if (names[i].containsIgnoreCase (choices[j]))
  218661. return names[i];
  218662. return names[0];
  218663. }
  218664. const String linux_getDefaultSansSerifFontName()
  218665. {
  218666. StringArray allFonts;
  218667. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218668. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218669. }
  218670. const String linux_getDefaultSerifFontName()
  218671. {
  218672. StringArray allFonts;
  218673. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218674. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218675. }
  218676. const String linux_getDefaultMonospacedFontName()
  218677. {
  218678. StringArray allFonts;
  218679. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218680. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218681. }
  218682. }
  218683. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  218684. {
  218685. defaultSans = linux_getDefaultSansSerifFontName();
  218686. defaultSerif = linux_getDefaultSerifFontName();
  218687. defaultFixed = linux_getDefaultMonospacedFontName();
  218688. }
  218689. #endif
  218690. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218691. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218692. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218693. // compiled on its own).
  218694. #if JUCE_INCLUDED_FILE
  218695. // These are defined in juce_linux_Messaging.cpp
  218696. extern Display* display;
  218697. extern XContext windowHandleXContext;
  218698. namespace Atoms
  218699. {
  218700. enum ProtocolItems
  218701. {
  218702. TAKE_FOCUS = 0,
  218703. DELETE_WINDOW = 1,
  218704. PING = 2
  218705. };
  218706. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218707. ActiveWin, Pid, WindowType, WindowState,
  218708. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218709. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218710. XdndActionDescription, XdndActionCopy,
  218711. allowedActions[5],
  218712. allowedMimeTypes[2];
  218713. const unsigned long DndVersion = 3;
  218714. static void initialiseAtoms()
  218715. {
  218716. static bool atomsInitialised = false;
  218717. if (! atomsInitialised)
  218718. {
  218719. atomsInitialised = true;
  218720. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218721. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218722. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218723. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218724. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218725. State = XInternAtom (display, "WM_STATE", True);
  218726. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218727. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218728. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218729. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218730. XdndAware = XInternAtom (display, "XdndAware", False);
  218731. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218732. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218733. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218734. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218735. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218736. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218737. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218738. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218739. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218740. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218741. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218742. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218743. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218744. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218745. allowedActions[1] = XdndActionCopy;
  218746. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218747. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218748. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218749. }
  218750. }
  218751. }
  218752. namespace Keys
  218753. {
  218754. enum MouseButtons
  218755. {
  218756. NoButton = 0,
  218757. LeftButton = 1,
  218758. MiddleButton = 2,
  218759. RightButton = 3,
  218760. WheelUp = 4,
  218761. WheelDown = 5
  218762. };
  218763. static int AltMask = 0;
  218764. static int NumLockMask = 0;
  218765. static bool numLock = false;
  218766. static bool capsLock = false;
  218767. static char keyStates [32];
  218768. static const int extendedKeyModifier = 0x10000000;
  218769. }
  218770. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218771. {
  218772. int keysym;
  218773. if (keyCode & Keys::extendedKeyModifier)
  218774. {
  218775. keysym = 0xff00 | (keyCode & 0xff);
  218776. }
  218777. else
  218778. {
  218779. keysym = keyCode;
  218780. if (keysym == (XK_Tab & 0xff)
  218781. || keysym == (XK_Return & 0xff)
  218782. || keysym == (XK_Escape & 0xff)
  218783. || keysym == (XK_BackSpace & 0xff))
  218784. {
  218785. keysym |= 0xff00;
  218786. }
  218787. }
  218788. ScopedXLock xlock;
  218789. const int keycode = XKeysymToKeycode (display, keysym);
  218790. const int keybyte = keycode >> 3;
  218791. const int keybit = (1 << (keycode & 7));
  218792. return (Keys::keyStates [keybyte] & keybit) != 0;
  218793. }
  218794. #if JUCE_USE_XSHM
  218795. namespace XSHMHelpers
  218796. {
  218797. static int trappedErrorCode = 0;
  218798. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218799. {
  218800. trappedErrorCode = err->error_code;
  218801. return 0;
  218802. }
  218803. static bool isShmAvailable() throw()
  218804. {
  218805. static bool isChecked = false;
  218806. static bool isAvailable = false;
  218807. if (! isChecked)
  218808. {
  218809. isChecked = true;
  218810. int major, minor;
  218811. Bool pixmaps;
  218812. ScopedXLock xlock;
  218813. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218814. {
  218815. trappedErrorCode = 0;
  218816. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218817. XShmSegmentInfo segmentInfo;
  218818. zerostruct (segmentInfo);
  218819. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218820. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218821. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218822. xImage->bytes_per_line * xImage->height,
  218823. IPC_CREAT | 0777)) >= 0)
  218824. {
  218825. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218826. if (segmentInfo.shmaddr != (void*) -1)
  218827. {
  218828. segmentInfo.readOnly = False;
  218829. xImage->data = segmentInfo.shmaddr;
  218830. XSync (display, False);
  218831. if (XShmAttach (display, &segmentInfo) != 0)
  218832. {
  218833. XSync (display, False);
  218834. XShmDetach (display, &segmentInfo);
  218835. isAvailable = true;
  218836. }
  218837. }
  218838. XFlush (display);
  218839. XDestroyImage (xImage);
  218840. shmdt (segmentInfo.shmaddr);
  218841. }
  218842. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218843. XSetErrorHandler (oldHandler);
  218844. if (trappedErrorCode != 0)
  218845. isAvailable = false;
  218846. }
  218847. }
  218848. return isAvailable;
  218849. }
  218850. }
  218851. #endif
  218852. #if JUCE_USE_XRENDER
  218853. namespace XRender
  218854. {
  218855. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218856. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218857. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218858. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218859. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218860. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218861. static tXRenderFindFormat xRenderFindFormat = 0;
  218862. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218863. static bool isAvailable()
  218864. {
  218865. static bool hasLoaded = false;
  218866. if (! hasLoaded)
  218867. {
  218868. ScopedXLock xlock;
  218869. hasLoaded = true;
  218870. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218871. if (h != 0)
  218872. {
  218873. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218874. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218875. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218876. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218877. }
  218878. if (xRenderQueryVersion != 0
  218879. && xRenderFindStandardFormat != 0
  218880. && xRenderFindFormat != 0
  218881. && xRenderFindVisualFormat != 0)
  218882. {
  218883. int major, minor;
  218884. if (xRenderQueryVersion (display, &major, &minor))
  218885. return true;
  218886. }
  218887. xRenderQueryVersion = 0;
  218888. }
  218889. return xRenderQueryVersion != 0;
  218890. }
  218891. static XRenderPictFormat* findPictureFormat()
  218892. {
  218893. ScopedXLock xlock;
  218894. XRenderPictFormat* pictFormat = 0;
  218895. if (isAvailable())
  218896. {
  218897. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218898. if (pictFormat == 0)
  218899. {
  218900. XRenderPictFormat desiredFormat;
  218901. desiredFormat.type = PictTypeDirect;
  218902. desiredFormat.depth = 32;
  218903. desiredFormat.direct.alphaMask = 0xff;
  218904. desiredFormat.direct.redMask = 0xff;
  218905. desiredFormat.direct.greenMask = 0xff;
  218906. desiredFormat.direct.blueMask = 0xff;
  218907. desiredFormat.direct.alpha = 24;
  218908. desiredFormat.direct.red = 16;
  218909. desiredFormat.direct.green = 8;
  218910. desiredFormat.direct.blue = 0;
  218911. pictFormat = xRenderFindFormat (display,
  218912. PictFormatType | PictFormatDepth
  218913. | PictFormatRedMask | PictFormatRed
  218914. | PictFormatGreenMask | PictFormatGreen
  218915. | PictFormatBlueMask | PictFormatBlue
  218916. | PictFormatAlphaMask | PictFormatAlpha,
  218917. &desiredFormat,
  218918. 0);
  218919. }
  218920. }
  218921. return pictFormat;
  218922. }
  218923. }
  218924. #endif
  218925. namespace Visuals
  218926. {
  218927. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218928. {
  218929. ScopedXLock xlock;
  218930. Visual* visual = 0;
  218931. int numVisuals = 0;
  218932. long desiredMask = VisualNoMask;
  218933. XVisualInfo desiredVisual;
  218934. desiredVisual.screen = DefaultScreen (display);
  218935. desiredVisual.depth = desiredDepth;
  218936. desiredMask = VisualScreenMask | VisualDepthMask;
  218937. if (desiredDepth == 32)
  218938. {
  218939. desiredVisual.c_class = TrueColor;
  218940. desiredVisual.red_mask = 0x00FF0000;
  218941. desiredVisual.green_mask = 0x0000FF00;
  218942. desiredVisual.blue_mask = 0x000000FF;
  218943. desiredVisual.bits_per_rgb = 8;
  218944. desiredMask |= VisualClassMask;
  218945. desiredMask |= VisualRedMaskMask;
  218946. desiredMask |= VisualGreenMaskMask;
  218947. desiredMask |= VisualBlueMaskMask;
  218948. desiredMask |= VisualBitsPerRGBMask;
  218949. }
  218950. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218951. desiredMask,
  218952. &desiredVisual,
  218953. &numVisuals);
  218954. if (xvinfos != 0)
  218955. {
  218956. for (int i = 0; i < numVisuals; i++)
  218957. {
  218958. if (xvinfos[i].depth == desiredDepth)
  218959. {
  218960. visual = xvinfos[i].visual;
  218961. break;
  218962. }
  218963. }
  218964. XFree (xvinfos);
  218965. }
  218966. return visual;
  218967. }
  218968. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218969. {
  218970. Visual* visual = 0;
  218971. if (desiredDepth == 32)
  218972. {
  218973. #if JUCE_USE_XSHM
  218974. if (XSHMHelpers::isShmAvailable())
  218975. {
  218976. #if JUCE_USE_XRENDER
  218977. if (XRender::isAvailable())
  218978. {
  218979. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218980. if (pictFormat != 0)
  218981. {
  218982. int numVisuals = 0;
  218983. XVisualInfo desiredVisual;
  218984. desiredVisual.screen = DefaultScreen (display);
  218985. desiredVisual.depth = 32;
  218986. desiredVisual.bits_per_rgb = 8;
  218987. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218988. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218989. &desiredVisual, &numVisuals);
  218990. if (xvinfos != 0)
  218991. {
  218992. for (int i = 0; i < numVisuals; ++i)
  218993. {
  218994. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218995. if (pictVisualFormat != 0
  218996. && pictVisualFormat->type == PictTypeDirect
  218997. && pictVisualFormat->direct.alphaMask)
  218998. {
  218999. visual = xvinfos[i].visual;
  219000. matchedDepth = 32;
  219001. break;
  219002. }
  219003. }
  219004. XFree (xvinfos);
  219005. }
  219006. }
  219007. }
  219008. #endif
  219009. if (visual == 0)
  219010. {
  219011. visual = findVisualWithDepth (32);
  219012. if (visual != 0)
  219013. matchedDepth = 32;
  219014. }
  219015. }
  219016. #endif
  219017. }
  219018. if (visual == 0 && desiredDepth >= 24)
  219019. {
  219020. visual = findVisualWithDepth (24);
  219021. if (visual != 0)
  219022. matchedDepth = 24;
  219023. }
  219024. if (visual == 0 && desiredDepth >= 16)
  219025. {
  219026. visual = findVisualWithDepth (16);
  219027. if (visual != 0)
  219028. matchedDepth = 16;
  219029. }
  219030. return visual;
  219031. }
  219032. }
  219033. class XBitmapImage : public Image::SharedImage
  219034. {
  219035. public:
  219036. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219037. const bool clearImage, const int imageDepth_, Visual* visual)
  219038. : Image::SharedImage (format_, w, h),
  219039. imageDepth (imageDepth_),
  219040. gc (None)
  219041. {
  219042. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219043. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219044. lineStride = ((w * pixelStride + 3) & ~3);
  219045. ScopedXLock xlock;
  219046. #if JUCE_USE_XSHM
  219047. usingXShm = false;
  219048. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219049. {
  219050. zerostruct (segmentInfo);
  219051. segmentInfo.shmid = -1;
  219052. segmentInfo.shmaddr = (char *) -1;
  219053. segmentInfo.readOnly = False;
  219054. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219055. if (xImage != 0)
  219056. {
  219057. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219058. xImage->bytes_per_line * xImage->height,
  219059. IPC_CREAT | 0777)) >= 0)
  219060. {
  219061. if (segmentInfo.shmid != -1)
  219062. {
  219063. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219064. if (segmentInfo.shmaddr != (void*) -1)
  219065. {
  219066. segmentInfo.readOnly = False;
  219067. xImage->data = segmentInfo.shmaddr;
  219068. imageData = (uint8*) segmentInfo.shmaddr;
  219069. if (XShmAttach (display, &segmentInfo) != 0)
  219070. usingXShm = true;
  219071. else
  219072. jassertfalse;
  219073. }
  219074. else
  219075. {
  219076. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219077. }
  219078. }
  219079. }
  219080. }
  219081. }
  219082. if (! usingXShm)
  219083. #endif
  219084. {
  219085. imageDataAllocated.malloc (lineStride * h);
  219086. imageData = imageDataAllocated;
  219087. if (format_ == Image::ARGB && clearImage)
  219088. zeromem (imageData, h * lineStride);
  219089. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219090. xImage->width = w;
  219091. xImage->height = h;
  219092. xImage->xoffset = 0;
  219093. xImage->format = ZPixmap;
  219094. xImage->data = (char*) imageData;
  219095. xImage->byte_order = ImageByteOrder (display);
  219096. xImage->bitmap_unit = BitmapUnit (display);
  219097. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219098. xImage->bitmap_pad = 32;
  219099. xImage->depth = pixelStride * 8;
  219100. xImage->bytes_per_line = lineStride;
  219101. xImage->bits_per_pixel = pixelStride * 8;
  219102. xImage->red_mask = 0x00FF0000;
  219103. xImage->green_mask = 0x0000FF00;
  219104. xImage->blue_mask = 0x000000FF;
  219105. if (imageDepth == 16)
  219106. {
  219107. const int pixelStride = 2;
  219108. const int lineStride = ((w * pixelStride + 3) & ~3);
  219109. imageData16Bit.malloc (lineStride * h);
  219110. xImage->data = imageData16Bit;
  219111. xImage->bitmap_pad = 16;
  219112. xImage->depth = pixelStride * 8;
  219113. xImage->bytes_per_line = lineStride;
  219114. xImage->bits_per_pixel = pixelStride * 8;
  219115. xImage->red_mask = visual->red_mask;
  219116. xImage->green_mask = visual->green_mask;
  219117. xImage->blue_mask = visual->blue_mask;
  219118. }
  219119. if (! XInitImage (xImage))
  219120. jassertfalse;
  219121. }
  219122. }
  219123. ~XBitmapImage()
  219124. {
  219125. ScopedXLock xlock;
  219126. if (gc != None)
  219127. XFreeGC (display, gc);
  219128. #if JUCE_USE_XSHM
  219129. if (usingXShm)
  219130. {
  219131. XShmDetach (display, &segmentInfo);
  219132. XFlush (display);
  219133. XDestroyImage (xImage);
  219134. shmdt (segmentInfo.shmaddr);
  219135. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219136. }
  219137. else
  219138. #endif
  219139. {
  219140. xImage->data = 0;
  219141. XDestroyImage (xImage);
  219142. }
  219143. }
  219144. Image::ImageType getType() const { return Image::NativeImage; }
  219145. LowLevelGraphicsContext* createLowLevelContext()
  219146. {
  219147. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219148. }
  219149. SharedImage* clone()
  219150. {
  219151. jassertfalse;
  219152. return 0;
  219153. }
  219154. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219155. {
  219156. ScopedXLock xlock;
  219157. if (gc == None)
  219158. {
  219159. XGCValues gcvalues;
  219160. gcvalues.foreground = None;
  219161. gcvalues.background = None;
  219162. gcvalues.function = GXcopy;
  219163. gcvalues.plane_mask = AllPlanes;
  219164. gcvalues.clip_mask = None;
  219165. gcvalues.graphics_exposures = False;
  219166. gc = XCreateGC (display, window,
  219167. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219168. &gcvalues);
  219169. }
  219170. if (imageDepth == 16)
  219171. {
  219172. const uint32 rMask = xImage->red_mask;
  219173. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219174. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219175. const uint32 gMask = xImage->green_mask;
  219176. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219177. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219178. const uint32 bMask = xImage->blue_mask;
  219179. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219180. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219181. const Image::BitmapData srcData (Image (this), false);
  219182. for (int y = sy; y < sy + dh; ++y)
  219183. {
  219184. const uint8* p = srcData.getPixelPointer (sx, y);
  219185. for (int x = sx; x < sx + dw; ++x)
  219186. {
  219187. const PixelRGB* const pixel = (const PixelRGB*) p;
  219188. p += srcData.pixelStride;
  219189. XPutPixel (xImage, x, y,
  219190. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219191. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219192. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219193. }
  219194. }
  219195. }
  219196. // blit results to screen.
  219197. #if JUCE_USE_XSHM
  219198. if (usingXShm)
  219199. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219200. else
  219201. #endif
  219202. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219203. }
  219204. private:
  219205. XImage* xImage;
  219206. const int imageDepth;
  219207. HeapBlock <uint8> imageDataAllocated;
  219208. HeapBlock <char> imageData16Bit;
  219209. GC gc;
  219210. #if JUCE_USE_XSHM
  219211. XShmSegmentInfo segmentInfo;
  219212. bool usingXShm;
  219213. #endif
  219214. static int getShiftNeeded (const uint32 mask) throw()
  219215. {
  219216. for (int i = 32; --i >= 0;)
  219217. if (((mask >> i) & 1) != 0)
  219218. return i - 7;
  219219. jassertfalse;
  219220. return 0;
  219221. }
  219222. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219223. };
  219224. namespace PixmapHelpers
  219225. {
  219226. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219227. {
  219228. ScopedXLock xlock;
  219229. const int width = image.getWidth();
  219230. const int height = image.getHeight();
  219231. HeapBlock <uint32> colour (width * height);
  219232. int index = 0;
  219233. for (int y = 0; y < height; ++y)
  219234. for (int x = 0; x < width; ++x)
  219235. colour[index++] = image.getPixelAt (x, y).getARGB();
  219236. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219237. 0, reinterpret_cast<char*> (colour.getData()),
  219238. width, height, 32, 0);
  219239. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219240. width, height, 24);
  219241. GC gc = XCreateGC (display, pixmap, 0, 0);
  219242. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219243. XFreeGC (display, gc);
  219244. return pixmap;
  219245. }
  219246. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219247. {
  219248. ScopedXLock xlock;
  219249. const int width = image.getWidth();
  219250. const int height = image.getHeight();
  219251. const int stride = (width + 7) >> 3;
  219252. HeapBlock <char> mask;
  219253. mask.calloc (stride * height);
  219254. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219255. for (int y = 0; y < height; ++y)
  219256. {
  219257. for (int x = 0; x < width; ++x)
  219258. {
  219259. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219260. const int offset = y * stride + (x >> 3);
  219261. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219262. mask[offset] |= bit;
  219263. }
  219264. }
  219265. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219266. mask.getData(), width, height, 1, 0, 1);
  219267. }
  219268. }
  219269. class LinuxComponentPeer : public ComponentPeer
  219270. {
  219271. public:
  219272. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219273. : ComponentPeer (component, windowStyleFlags),
  219274. windowH (0),
  219275. parentWindow (0),
  219276. wx (0),
  219277. wy (0),
  219278. ww (0),
  219279. wh (0),
  219280. fullScreen (false),
  219281. mapped (false),
  219282. visual (0),
  219283. depth (0)
  219284. {
  219285. // it's dangerous to create a window on a thread other than the message thread..
  219286. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219287. repainter = new LinuxRepaintManager (this);
  219288. createWindow();
  219289. setTitle (component->getName());
  219290. }
  219291. ~LinuxComponentPeer()
  219292. {
  219293. // it's dangerous to delete a window on a thread other than the message thread..
  219294. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219295. deleteIconPixmaps();
  219296. destroyWindow();
  219297. windowH = 0;
  219298. }
  219299. void* getNativeHandle() const
  219300. {
  219301. return (void*) windowH;
  219302. }
  219303. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219304. {
  219305. XPointer peer = 0;
  219306. ScopedXLock xlock;
  219307. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219308. {
  219309. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219310. peer = 0;
  219311. }
  219312. return (LinuxComponentPeer*) peer;
  219313. }
  219314. void setVisible (bool shouldBeVisible)
  219315. {
  219316. ScopedXLock xlock;
  219317. if (shouldBeVisible)
  219318. XMapWindow (display, windowH);
  219319. else
  219320. XUnmapWindow (display, windowH);
  219321. }
  219322. void setTitle (const String& title)
  219323. {
  219324. XTextProperty nameProperty;
  219325. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  219326. ScopedXLock xlock;
  219327. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219328. {
  219329. XSetWMName (display, windowH, &nameProperty);
  219330. XSetWMIconName (display, windowH, &nameProperty);
  219331. XFree (nameProperty.value);
  219332. }
  219333. }
  219334. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219335. {
  219336. fullScreen = isNowFullScreen;
  219337. if (windowH != 0)
  219338. {
  219339. WeakReference<Component> deletionChecker (component);
  219340. wx = x;
  219341. wy = y;
  219342. ww = jmax (1, w);
  219343. wh = jmax (1, h);
  219344. ScopedXLock xlock;
  219345. // Make sure the Window manager does what we want
  219346. XSizeHints* hints = XAllocSizeHints();
  219347. hints->flags = USSize | USPosition;
  219348. hints->width = ww;
  219349. hints->height = wh;
  219350. hints->x = wx;
  219351. hints->y = wy;
  219352. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219353. {
  219354. hints->min_width = hints->max_width = hints->width;
  219355. hints->min_height = hints->max_height = hints->height;
  219356. hints->flags |= PMinSize | PMaxSize;
  219357. }
  219358. XSetWMNormalHints (display, windowH, hints);
  219359. XFree (hints);
  219360. XMoveResizeWindow (display, windowH,
  219361. wx - windowBorder.getLeft(),
  219362. wy - windowBorder.getTop(), ww, wh);
  219363. if (deletionChecker != 0)
  219364. {
  219365. updateBorderSize();
  219366. handleMovedOrResized();
  219367. }
  219368. }
  219369. }
  219370. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219371. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219372. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219373. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219374. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219375. {
  219376. return relativePosition + getScreenPosition();
  219377. }
  219378. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219379. {
  219380. return screenPosition - getScreenPosition();
  219381. }
  219382. void setAlpha (float newAlpha)
  219383. {
  219384. //xxx todo!
  219385. }
  219386. void setMinimised (bool shouldBeMinimised)
  219387. {
  219388. if (shouldBeMinimised)
  219389. {
  219390. Window root = RootWindow (display, DefaultScreen (display));
  219391. XClientMessageEvent clientMsg;
  219392. clientMsg.display = display;
  219393. clientMsg.window = windowH;
  219394. clientMsg.type = ClientMessage;
  219395. clientMsg.format = 32;
  219396. clientMsg.message_type = Atoms::ChangeState;
  219397. clientMsg.data.l[0] = IconicState;
  219398. ScopedXLock xlock;
  219399. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219400. }
  219401. else
  219402. {
  219403. setVisible (true);
  219404. }
  219405. }
  219406. bool isMinimised() const
  219407. {
  219408. bool minimised = false;
  219409. unsigned char* stateProp;
  219410. unsigned long nitems, bytesLeft;
  219411. Atom actualType;
  219412. int actualFormat;
  219413. ScopedXLock xlock;
  219414. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219415. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219416. &stateProp) == Success
  219417. && actualType == Atoms::State
  219418. && actualFormat == 32
  219419. && nitems > 0)
  219420. {
  219421. if (((unsigned long*) stateProp)[0] == IconicState)
  219422. minimised = true;
  219423. XFree (stateProp);
  219424. }
  219425. return minimised;
  219426. }
  219427. void setFullScreen (const bool shouldBeFullScreen)
  219428. {
  219429. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219430. setMinimised (false);
  219431. if (fullScreen != shouldBeFullScreen)
  219432. {
  219433. if (shouldBeFullScreen)
  219434. r = Desktop::getInstance().getMainMonitorArea();
  219435. if (! r.isEmpty())
  219436. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219437. getComponent()->repaint();
  219438. }
  219439. }
  219440. bool isFullScreen() const
  219441. {
  219442. return fullScreen;
  219443. }
  219444. bool isChildWindowOf (Window possibleParent) const
  219445. {
  219446. Window* windowList = 0;
  219447. uint32 windowListSize = 0;
  219448. Window parent, root;
  219449. ScopedXLock xlock;
  219450. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219451. {
  219452. if (windowList != 0)
  219453. XFree (windowList);
  219454. return parent == possibleParent;
  219455. }
  219456. return false;
  219457. }
  219458. bool isFrontWindow() const
  219459. {
  219460. Window* windowList = 0;
  219461. uint32 windowListSize = 0;
  219462. bool result = false;
  219463. ScopedXLock xlock;
  219464. Window parent, root = RootWindow (display, DefaultScreen (display));
  219465. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219466. {
  219467. for (int i = windowListSize; --i >= 0;)
  219468. {
  219469. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219470. if (peer != 0)
  219471. {
  219472. result = (peer == this);
  219473. break;
  219474. }
  219475. }
  219476. }
  219477. if (windowList != 0)
  219478. XFree (windowList);
  219479. return result;
  219480. }
  219481. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219482. {
  219483. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219484. return false;
  219485. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219486. {
  219487. Component* const c = Desktop::getInstance().getComponent (i);
  219488. if (c == getComponent())
  219489. break;
  219490. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219491. return false;
  219492. }
  219493. if (trueIfInAChildWindow)
  219494. return true;
  219495. ::Window root, child;
  219496. unsigned int bw, depth;
  219497. int wx, wy, w, h;
  219498. ScopedXLock xlock;
  219499. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219500. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219501. &bw, &depth))
  219502. {
  219503. return false;
  219504. }
  219505. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219506. return false;
  219507. return child == None;
  219508. }
  219509. const BorderSize<int> getFrameSize() const
  219510. {
  219511. return BorderSize<int>();
  219512. }
  219513. bool setAlwaysOnTop (bool alwaysOnTop)
  219514. {
  219515. return false;
  219516. }
  219517. void toFront (bool makeActive)
  219518. {
  219519. if (makeActive)
  219520. {
  219521. setVisible (true);
  219522. grabFocus();
  219523. }
  219524. XEvent ev;
  219525. ev.xclient.type = ClientMessage;
  219526. ev.xclient.serial = 0;
  219527. ev.xclient.send_event = True;
  219528. ev.xclient.message_type = Atoms::ActiveWin;
  219529. ev.xclient.window = windowH;
  219530. ev.xclient.format = 32;
  219531. ev.xclient.data.l[0] = 2;
  219532. ev.xclient.data.l[1] = CurrentTime;
  219533. ev.xclient.data.l[2] = 0;
  219534. ev.xclient.data.l[3] = 0;
  219535. ev.xclient.data.l[4] = 0;
  219536. {
  219537. ScopedXLock xlock;
  219538. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219539. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219540. XWindowAttributes attr;
  219541. XGetWindowAttributes (display, windowH, &attr);
  219542. if (component->isAlwaysOnTop())
  219543. XRaiseWindow (display, windowH);
  219544. XSync (display, False);
  219545. }
  219546. handleBroughtToFront();
  219547. }
  219548. void toBehind (ComponentPeer* other)
  219549. {
  219550. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219551. jassert (otherPeer != 0); // wrong type of window?
  219552. if (otherPeer != 0)
  219553. {
  219554. setMinimised (false);
  219555. Window newStack[] = { otherPeer->windowH, windowH };
  219556. ScopedXLock xlock;
  219557. XRestackWindows (display, newStack, 2);
  219558. }
  219559. }
  219560. bool isFocused() const
  219561. {
  219562. int revert = 0;
  219563. Window focusedWindow = 0;
  219564. ScopedXLock xlock;
  219565. XGetInputFocus (display, &focusedWindow, &revert);
  219566. return focusedWindow == windowH;
  219567. }
  219568. void grabFocus()
  219569. {
  219570. XWindowAttributes atts;
  219571. ScopedXLock xlock;
  219572. if (windowH != 0
  219573. && XGetWindowAttributes (display, windowH, &atts)
  219574. && atts.map_state == IsViewable
  219575. && ! isFocused())
  219576. {
  219577. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219578. isActiveApplication = true;
  219579. }
  219580. }
  219581. void textInputRequired (const Point<int>&)
  219582. {
  219583. }
  219584. void repaint (const Rectangle<int>& area)
  219585. {
  219586. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219587. }
  219588. void performAnyPendingRepaintsNow()
  219589. {
  219590. repainter->performAnyPendingRepaintsNow();
  219591. }
  219592. void setIcon (const Image& newIcon)
  219593. {
  219594. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219595. HeapBlock <unsigned long> data (dataSize);
  219596. int index = 0;
  219597. data[index++] = newIcon.getWidth();
  219598. data[index++] = newIcon.getHeight();
  219599. for (int y = 0; y < newIcon.getHeight(); ++y)
  219600. for (int x = 0; x < newIcon.getWidth(); ++x)
  219601. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219602. ScopedXLock xlock;
  219603. XChangeProperty (display, windowH,
  219604. XInternAtom (display, "_NET_WM_ICON", False),
  219605. XA_CARDINAL, 32, PropModeReplace,
  219606. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219607. deleteIconPixmaps();
  219608. XWMHints* wmHints = XGetWMHints (display, windowH);
  219609. if (wmHints == 0)
  219610. wmHints = XAllocWMHints();
  219611. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219612. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  219613. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  219614. XSetWMHints (display, windowH, wmHints);
  219615. XFree (wmHints);
  219616. XSync (display, False);
  219617. }
  219618. void deleteIconPixmaps()
  219619. {
  219620. ScopedXLock xlock;
  219621. XWMHints* wmHints = XGetWMHints (display, windowH);
  219622. if (wmHints != 0)
  219623. {
  219624. if ((wmHints->flags & IconPixmapHint) != 0)
  219625. {
  219626. wmHints->flags &= ~IconPixmapHint;
  219627. XFreePixmap (display, wmHints->icon_pixmap);
  219628. }
  219629. if ((wmHints->flags & IconMaskHint) != 0)
  219630. {
  219631. wmHints->flags &= ~IconMaskHint;
  219632. XFreePixmap (display, wmHints->icon_mask);
  219633. }
  219634. XSetWMHints (display, windowH, wmHints);
  219635. XFree (wmHints);
  219636. }
  219637. }
  219638. void handleWindowMessage (XEvent* event)
  219639. {
  219640. switch (event->xany.type)
  219641. {
  219642. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  219643. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  219644. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  219645. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  219646. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  219647. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  219648. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  219649. case FocusIn: handleFocusInEvent(); break;
  219650. case FocusOut: handleFocusOutEvent(); break;
  219651. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  219652. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  219653. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  219654. case SelectionNotify: handleDragAndDropSelection (event); break;
  219655. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  219656. case ReparentNotify: handleReparentNotifyEvent(); break;
  219657. case GravityNotify: handleGravityNotify(); break;
  219658. case CirculateNotify:
  219659. case CreateNotify:
  219660. case DestroyNotify:
  219661. // Think we can ignore these
  219662. break;
  219663. case MapNotify:
  219664. mapped = true;
  219665. handleBroughtToFront();
  219666. break;
  219667. case UnmapNotify:
  219668. mapped = false;
  219669. break;
  219670. case SelectionClear:
  219671. case SelectionRequest:
  219672. break;
  219673. default:
  219674. #if JUCE_USE_XSHM
  219675. {
  219676. ScopedXLock xlock;
  219677. if (event->xany.type == XShmGetEventBase (display))
  219678. repainter->notifyPaintCompleted();
  219679. }
  219680. #endif
  219681. break;
  219682. }
  219683. }
  219684. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  219685. {
  219686. char utf8 [64] = { 0 };
  219687. juce_wchar unicodeChar = 0;
  219688. int keyCode = 0;
  219689. bool keyDownChange = false;
  219690. KeySym sym;
  219691. {
  219692. ScopedXLock xlock;
  219693. updateKeyStates (keyEvent->keycode, true);
  219694. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219695. ::setlocale (LC_ALL, "");
  219696. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219697. ::setlocale (LC_ALL, oldLocale);
  219698. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219699. keyCode = (int) unicodeChar;
  219700. if (keyCode < 0x20)
  219701. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219702. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219703. }
  219704. const ModifierKeys oldMods (currentModifiers);
  219705. bool keyPressed = false;
  219706. if ((sym & 0xff00) == 0xff00)
  219707. {
  219708. switch (sym) // Translate keypad
  219709. {
  219710. case XK_KP_Divide: keyCode = XK_slash; break;
  219711. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  219712. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  219713. case XK_KP_Add: keyCode = XK_plus; break;
  219714. case XK_KP_Enter: keyCode = XK_Return; break;
  219715. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  219716. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  219717. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  219718. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  219719. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  219720. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  219721. case XK_KP_5: keyCode = XK_5; break;
  219722. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  219723. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  219724. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  219725. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  219726. default: break;
  219727. }
  219728. switch (sym)
  219729. {
  219730. case XK_Left:
  219731. case XK_Right:
  219732. case XK_Up:
  219733. case XK_Down:
  219734. case XK_Page_Up:
  219735. case XK_Page_Down:
  219736. case XK_End:
  219737. case XK_Home:
  219738. case XK_Delete:
  219739. case XK_Insert:
  219740. keyPressed = true;
  219741. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219742. break;
  219743. case XK_Tab:
  219744. case XK_Return:
  219745. case XK_Escape:
  219746. case XK_BackSpace:
  219747. keyPressed = true;
  219748. keyCode &= 0xff;
  219749. break;
  219750. default:
  219751. if (sym >= XK_F1 && sym <= XK_F16)
  219752. {
  219753. keyPressed = true;
  219754. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219755. }
  219756. break;
  219757. }
  219758. }
  219759. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219760. keyPressed = true;
  219761. if (oldMods != currentModifiers)
  219762. handleModifierKeysChange();
  219763. if (keyDownChange)
  219764. handleKeyUpOrDown (true);
  219765. if (keyPressed)
  219766. handleKeyPress (keyCode, unicodeChar);
  219767. }
  219768. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  219769. {
  219770. updateKeyStates (keyEvent->keycode, false);
  219771. KeySym sym;
  219772. {
  219773. ScopedXLock xlock;
  219774. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219775. }
  219776. const ModifierKeys oldMods (currentModifiers);
  219777. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219778. if (oldMods != currentModifiers)
  219779. handleModifierKeysChange();
  219780. if (keyDownChange)
  219781. handleKeyUpOrDown (false);
  219782. }
  219783. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  219784. {
  219785. updateKeyModifiers (buttonPressEvent->state);
  219786. bool buttonMsg = false;
  219787. const int map = pointerMap [buttonPressEvent->button - Button1];
  219788. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219789. {
  219790. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219791. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219792. }
  219793. if (map == Keys::LeftButton)
  219794. {
  219795. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219796. buttonMsg = true;
  219797. }
  219798. else if (map == Keys::RightButton)
  219799. {
  219800. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219801. buttonMsg = true;
  219802. }
  219803. else if (map == Keys::MiddleButton)
  219804. {
  219805. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219806. buttonMsg = true;
  219807. }
  219808. if (buttonMsg)
  219809. {
  219810. toFront (true);
  219811. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219812. getEventTime (buttonPressEvent->time));
  219813. }
  219814. clearLastMousePos();
  219815. }
  219816. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  219817. {
  219818. updateKeyModifiers (buttonRelEvent->state);
  219819. const int map = pointerMap [buttonRelEvent->button - Button1];
  219820. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219821. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219822. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219823. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219824. getEventTime (buttonRelEvent->time));
  219825. clearLastMousePos();
  219826. }
  219827. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  219828. {
  219829. updateKeyModifiers (movedEvent->state);
  219830. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  219831. if (lastMousePos != mousePos)
  219832. {
  219833. lastMousePos = mousePos;
  219834. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219835. {
  219836. Window wRoot = 0, wParent = 0;
  219837. {
  219838. ScopedXLock xlock;
  219839. unsigned int numChildren;
  219840. Window* wChild = 0;
  219841. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219842. }
  219843. if (wParent != 0
  219844. && wParent != windowH
  219845. && wParent != wRoot)
  219846. {
  219847. parentWindow = wParent;
  219848. updateBounds();
  219849. }
  219850. else
  219851. {
  219852. parentWindow = 0;
  219853. }
  219854. }
  219855. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219856. }
  219857. }
  219858. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  219859. {
  219860. clearLastMousePos();
  219861. if (! currentModifiers.isAnyMouseButtonDown())
  219862. {
  219863. updateKeyModifiers (enterEvent->state);
  219864. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219865. }
  219866. }
  219867. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  219868. {
  219869. // Suppress the normal leave if we've got a pointer grab, or if
  219870. // it's a bogus one caused by clicking a mouse button when running
  219871. // in a Window manager
  219872. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219873. || leaveEvent->mode == NotifyUngrab)
  219874. {
  219875. updateKeyModifiers (leaveEvent->state);
  219876. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219877. }
  219878. }
  219879. void handleFocusInEvent()
  219880. {
  219881. isActiveApplication = true;
  219882. if (isFocused())
  219883. handleFocusGain();
  219884. }
  219885. void handleFocusOutEvent()
  219886. {
  219887. isActiveApplication = false;
  219888. if (! isFocused())
  219889. handleFocusLoss();
  219890. }
  219891. void handleExposeEvent (XExposeEvent* exposeEvent)
  219892. {
  219893. // Batch together all pending expose events
  219894. XEvent nextEvent;
  219895. ScopedXLock xlock;
  219896. if (exposeEvent->window != windowH)
  219897. {
  219898. Window child;
  219899. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219900. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219901. &child);
  219902. }
  219903. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219904. exposeEvent->width, exposeEvent->height));
  219905. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219906. {
  219907. XPeekEvent (display, (XEvent*) &nextEvent);
  219908. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  219909. break;
  219910. XNextEvent (display, (XEvent*) &nextEvent);
  219911. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219912. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219913. nextExposeEvent->width, nextExposeEvent->height));
  219914. }
  219915. }
  219916. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  219917. {
  219918. updateBounds();
  219919. updateBorderSize();
  219920. handleMovedOrResized();
  219921. // if the native title bar is dragged, need to tell any active menus, etc.
  219922. if ((styleFlags & windowHasTitleBar) != 0
  219923. && component->isCurrentlyBlockedByAnotherModalComponent())
  219924. {
  219925. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219926. if (currentModalComp != 0)
  219927. currentModalComp->inputAttemptWhenModal();
  219928. }
  219929. if (confEvent->window == windowH
  219930. && confEvent->above != 0
  219931. && isFrontWindow())
  219932. {
  219933. handleBroughtToFront();
  219934. }
  219935. }
  219936. void handleReparentNotifyEvent()
  219937. {
  219938. parentWindow = 0;
  219939. Window wRoot = 0;
  219940. Window* wChild = 0;
  219941. unsigned int numChildren;
  219942. {
  219943. ScopedXLock xlock;
  219944. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219945. }
  219946. if (parentWindow == windowH || parentWindow == wRoot)
  219947. parentWindow = 0;
  219948. handleGravityNotify();
  219949. }
  219950. void handleGravityNotify()
  219951. {
  219952. updateBounds();
  219953. updateBorderSize();
  219954. handleMovedOrResized();
  219955. }
  219956. void handleMappingNotify (XMappingEvent* const mappingEvent)
  219957. {
  219958. if (mappingEvent->request != MappingPointer)
  219959. {
  219960. // Deal with modifier/keyboard mapping
  219961. ScopedXLock xlock;
  219962. XRefreshKeyboardMapping (mappingEvent);
  219963. updateModifierMappings();
  219964. }
  219965. }
  219966. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  219967. {
  219968. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219969. {
  219970. const Atom atom = (Atom) clientMsg->data.l[0];
  219971. if (atom == Atoms::ProtocolList [Atoms::PING])
  219972. {
  219973. Window root = RootWindow (display, DefaultScreen (display));
  219974. clientMsg->window = root;
  219975. XSendEvent (display, root, False, NoEventMask, event);
  219976. XFlush (display);
  219977. }
  219978. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219979. {
  219980. XWindowAttributes atts;
  219981. ScopedXLock xlock;
  219982. if (clientMsg->window != 0
  219983. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219984. {
  219985. if (atts.map_state == IsViewable)
  219986. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219987. }
  219988. }
  219989. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219990. {
  219991. handleUserClosingWindow();
  219992. }
  219993. }
  219994. else if (clientMsg->message_type == Atoms::XdndEnter)
  219995. {
  219996. handleDragAndDropEnter (clientMsg);
  219997. }
  219998. else if (clientMsg->message_type == Atoms::XdndLeave)
  219999. {
  220000. resetDragAndDrop();
  220001. }
  220002. else if (clientMsg->message_type == Atoms::XdndPosition)
  220003. {
  220004. handleDragAndDropPosition (clientMsg);
  220005. }
  220006. else if (clientMsg->message_type == Atoms::XdndDrop)
  220007. {
  220008. handleDragAndDropDrop (clientMsg);
  220009. }
  220010. else if (clientMsg->message_type == Atoms::XdndStatus)
  220011. {
  220012. handleDragAndDropStatus (clientMsg);
  220013. }
  220014. else if (clientMsg->message_type == Atoms::XdndFinished)
  220015. {
  220016. resetDragAndDrop();
  220017. }
  220018. }
  220019. void showMouseCursor (Cursor cursor) throw()
  220020. {
  220021. ScopedXLock xlock;
  220022. XDefineCursor (display, windowH, cursor);
  220023. }
  220024. void setTaskBarIcon (const Image& image)
  220025. {
  220026. ScopedXLock xlock;
  220027. taskbarImage = image;
  220028. Screen* const screen = XDefaultScreenOfDisplay (display);
  220029. const int screenNumber = XScreenNumberOfScreen (screen);
  220030. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220031. screenAtom << screenNumber;
  220032. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220033. XGrabServer (display);
  220034. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220035. if (managerWin != None)
  220036. XSelectInput (display, managerWin, StructureNotifyMask);
  220037. XUngrabServer (display);
  220038. XFlush (display);
  220039. if (managerWin != None)
  220040. {
  220041. XEvent ev;
  220042. zerostruct (ev);
  220043. ev.xclient.type = ClientMessage;
  220044. ev.xclient.window = managerWin;
  220045. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220046. ev.xclient.format = 32;
  220047. ev.xclient.data.l[0] = CurrentTime;
  220048. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220049. ev.xclient.data.l[2] = windowH;
  220050. ev.xclient.data.l[3] = 0;
  220051. ev.xclient.data.l[4] = 0;
  220052. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220053. XSync (display, False);
  220054. }
  220055. // For older KDE's ...
  220056. long atomData = 1;
  220057. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220058. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220059. // For more recent KDE's...
  220060. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220061. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220062. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220063. XSizeHints* hints = XAllocSizeHints();
  220064. hints->flags = PMinSize;
  220065. hints->min_width = 22;
  220066. hints->min_height = 22;
  220067. XSetWMNormalHints (display, windowH, hints);
  220068. XFree (hints);
  220069. }
  220070. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220071. bool dontRepaint;
  220072. static ModifierKeys currentModifiers;
  220073. static bool isActiveApplication;
  220074. private:
  220075. class LinuxRepaintManager : public Timer
  220076. {
  220077. public:
  220078. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220079. : peer (peer_),
  220080. lastTimeImageUsed (0)
  220081. {
  220082. #if JUCE_USE_XSHM
  220083. shmCompletedDrawing = true;
  220084. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220085. if (useARGBImagesForRendering)
  220086. {
  220087. ScopedXLock xlock;
  220088. XShmSegmentInfo segmentinfo;
  220089. XImage* const testImage
  220090. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220091. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220092. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220093. XDestroyImage (testImage);
  220094. }
  220095. #endif
  220096. }
  220097. void timerCallback()
  220098. {
  220099. #if JUCE_USE_XSHM
  220100. if (! shmCompletedDrawing)
  220101. return;
  220102. #endif
  220103. if (! regionsNeedingRepaint.isEmpty())
  220104. {
  220105. stopTimer();
  220106. performAnyPendingRepaintsNow();
  220107. }
  220108. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220109. {
  220110. stopTimer();
  220111. image = Image::null;
  220112. }
  220113. }
  220114. void repaint (const Rectangle<int>& area)
  220115. {
  220116. if (! isTimerRunning())
  220117. startTimer (repaintTimerPeriod);
  220118. regionsNeedingRepaint.add (area);
  220119. }
  220120. void performAnyPendingRepaintsNow()
  220121. {
  220122. #if JUCE_USE_XSHM
  220123. if (! shmCompletedDrawing)
  220124. {
  220125. startTimer (repaintTimerPeriod);
  220126. return;
  220127. }
  220128. #endif
  220129. peer->clearMaskedRegion();
  220130. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220131. regionsNeedingRepaint.clear();
  220132. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220133. if (! totalArea.isEmpty())
  220134. {
  220135. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220136. || image.getHeight() < totalArea.getHeight())
  220137. {
  220138. #if JUCE_USE_XSHM
  220139. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220140. : Image::RGB,
  220141. #else
  220142. image = Image (new XBitmapImage (Image::RGB,
  220143. #endif
  220144. (totalArea.getWidth() + 31) & ~31,
  220145. (totalArea.getHeight() + 31) & ~31,
  220146. false, peer->depth, peer->visual));
  220147. }
  220148. startTimer (repaintTimerPeriod);
  220149. RectangleList adjustedList (originalRepaintRegion);
  220150. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220151. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220152. if (peer->depth == 32)
  220153. {
  220154. RectangleList::Iterator i (originalRepaintRegion);
  220155. while (i.next())
  220156. image.clear (*i.getRectangle() - totalArea.getPosition());
  220157. }
  220158. peer->handlePaint (context);
  220159. if (! peer->maskedRegion.isEmpty())
  220160. originalRepaintRegion.subtract (peer->maskedRegion);
  220161. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220162. {
  220163. #if JUCE_USE_XSHM
  220164. shmCompletedDrawing = false;
  220165. #endif
  220166. const Rectangle<int>& r = *i.getRectangle();
  220167. static_cast<XBitmapImage*> (image.getSharedImage())
  220168. ->blitToWindow (peer->windowH,
  220169. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220170. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220171. }
  220172. }
  220173. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220174. startTimer (repaintTimerPeriod);
  220175. }
  220176. #if JUCE_USE_XSHM
  220177. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220178. #endif
  220179. private:
  220180. enum { repaintTimerPeriod = 1000 / 100 };
  220181. LinuxComponentPeer* const peer;
  220182. Image image;
  220183. uint32 lastTimeImageUsed;
  220184. RectangleList regionsNeedingRepaint;
  220185. #if JUCE_USE_XSHM
  220186. bool useARGBImagesForRendering, shmCompletedDrawing;
  220187. #endif
  220188. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220189. };
  220190. ScopedPointer <LinuxRepaintManager> repainter;
  220191. friend class LinuxRepaintManager;
  220192. Window windowH, parentWindow;
  220193. int wx, wy, ww, wh;
  220194. Image taskbarImage;
  220195. bool fullScreen, mapped;
  220196. Visual* visual;
  220197. int depth;
  220198. BorderSize<int> windowBorder;
  220199. struct MotifWmHints
  220200. {
  220201. unsigned long flags;
  220202. unsigned long functions;
  220203. unsigned long decorations;
  220204. long input_mode;
  220205. unsigned long status;
  220206. };
  220207. static void updateKeyStates (const int keycode, const bool press) throw()
  220208. {
  220209. const int keybyte = keycode >> 3;
  220210. const int keybit = (1 << (keycode & 7));
  220211. if (press)
  220212. Keys::keyStates [keybyte] |= keybit;
  220213. else
  220214. Keys::keyStates [keybyte] &= ~keybit;
  220215. }
  220216. static void updateKeyModifiers (const int status) throw()
  220217. {
  220218. int keyMods = 0;
  220219. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220220. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220221. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220222. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220223. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220224. Keys::capsLock = ((status & LockMask) != 0);
  220225. }
  220226. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220227. {
  220228. int modifier = 0;
  220229. bool isModifier = true;
  220230. switch (sym)
  220231. {
  220232. case XK_Shift_L:
  220233. case XK_Shift_R:
  220234. modifier = ModifierKeys::shiftModifier;
  220235. break;
  220236. case XK_Control_L:
  220237. case XK_Control_R:
  220238. modifier = ModifierKeys::ctrlModifier;
  220239. break;
  220240. case XK_Alt_L:
  220241. case XK_Alt_R:
  220242. modifier = ModifierKeys::altModifier;
  220243. break;
  220244. case XK_Num_Lock:
  220245. if (press)
  220246. Keys::numLock = ! Keys::numLock;
  220247. break;
  220248. case XK_Caps_Lock:
  220249. if (press)
  220250. Keys::capsLock = ! Keys::capsLock;
  220251. break;
  220252. case XK_Scroll_Lock:
  220253. break;
  220254. default:
  220255. isModifier = false;
  220256. break;
  220257. }
  220258. if (modifier != 0)
  220259. {
  220260. if (press)
  220261. currentModifiers = currentModifiers.withFlags (modifier);
  220262. else
  220263. currentModifiers = currentModifiers.withoutFlags (modifier);
  220264. }
  220265. return isModifier;
  220266. }
  220267. // Alt and Num lock are not defined by standard X
  220268. // modifier constants: check what they're mapped to
  220269. static void updateModifierMappings() throw()
  220270. {
  220271. ScopedXLock xlock;
  220272. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220273. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220274. Keys::AltMask = 0;
  220275. Keys::NumLockMask = 0;
  220276. XModifierKeymap* mapping = XGetModifierMapping (display);
  220277. if (mapping)
  220278. {
  220279. for (int i = 0; i < 8; i++)
  220280. {
  220281. if (mapping->modifiermap [i << 1] == altLeftCode)
  220282. Keys::AltMask = 1 << i;
  220283. else if (mapping->modifiermap [i << 1] == numLockCode)
  220284. Keys::NumLockMask = 1 << i;
  220285. }
  220286. XFreeModifiermap (mapping);
  220287. }
  220288. }
  220289. void removeWindowDecorations (Window wndH)
  220290. {
  220291. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220292. if (hints != None)
  220293. {
  220294. MotifWmHints motifHints;
  220295. zerostruct (motifHints);
  220296. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220297. motifHints.decorations = 0;
  220298. ScopedXLock xlock;
  220299. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220300. (unsigned char*) &motifHints, 4);
  220301. }
  220302. hints = XInternAtom (display, "_WIN_HINTS", True);
  220303. if (hints != None)
  220304. {
  220305. long gnomeHints = 0;
  220306. ScopedXLock xlock;
  220307. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220308. (unsigned char*) &gnomeHints, 1);
  220309. }
  220310. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220311. if (hints != None)
  220312. {
  220313. long kwmHints = 2; /*KDE_tinyDecoration*/
  220314. ScopedXLock xlock;
  220315. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220316. (unsigned char*) &kwmHints, 1);
  220317. }
  220318. }
  220319. void addWindowButtons (Window wndH)
  220320. {
  220321. ScopedXLock xlock;
  220322. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220323. if (hints != None)
  220324. {
  220325. MotifWmHints motifHints;
  220326. zerostruct (motifHints);
  220327. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220328. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220329. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220330. if ((styleFlags & windowHasCloseButton) != 0)
  220331. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220332. if ((styleFlags & windowHasMinimiseButton) != 0)
  220333. {
  220334. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220335. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220336. }
  220337. if ((styleFlags & windowHasMaximiseButton) != 0)
  220338. {
  220339. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220340. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220341. }
  220342. if ((styleFlags & windowIsResizable) != 0)
  220343. {
  220344. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220345. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220346. }
  220347. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220348. }
  220349. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220350. if (hints != None)
  220351. {
  220352. int netHints [6];
  220353. int num = 0;
  220354. if ((styleFlags & windowIsResizable) != 0)
  220355. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220356. if ((styleFlags & windowHasMaximiseButton) != 0)
  220357. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220358. if ((styleFlags & windowHasMinimiseButton) != 0)
  220359. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220360. if ((styleFlags & windowHasCloseButton) != 0)
  220361. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220362. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220363. }
  220364. }
  220365. void setWindowType()
  220366. {
  220367. int netHints [2];
  220368. int numHints = 0;
  220369. if ((styleFlags & windowIsTemporary) != 0
  220370. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220371. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220372. else
  220373. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220374. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220375. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220376. (unsigned char*) &netHints, numHints);
  220377. numHints = 0;
  220378. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220379. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220380. if (component->isAlwaysOnTop())
  220381. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220382. if (numHints > 0)
  220383. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220384. (unsigned char*) &netHints, numHints);
  220385. }
  220386. void createWindow()
  220387. {
  220388. ScopedXLock xlock;
  220389. Atoms::initialiseAtoms();
  220390. resetDragAndDrop();
  220391. // Get defaults for various properties
  220392. const int screen = DefaultScreen (display);
  220393. Window root = RootWindow (display, screen);
  220394. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220395. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220396. if (visual == 0)
  220397. {
  220398. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220399. Process::terminate();
  220400. }
  220401. // Create and install a colormap suitable fr our visual
  220402. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220403. XInstallColormap (display, colormap);
  220404. // Set up the window attributes
  220405. XSetWindowAttributes swa;
  220406. swa.border_pixel = 0;
  220407. swa.background_pixmap = None;
  220408. swa.colormap = colormap;
  220409. swa.event_mask = getAllEventsMask();
  220410. windowH = XCreateWindow (display, root,
  220411. 0, 0, 1, 1,
  220412. 0, depth, InputOutput, visual,
  220413. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220414. &swa);
  220415. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220416. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220417. GrabModeAsync, GrabModeAsync, None, None);
  220418. // Set the window context to identify the window handle object
  220419. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220420. {
  220421. // Failed
  220422. jassertfalse;
  220423. Logger::outputDebugString ("Failed to create context information for window.\n");
  220424. XDestroyWindow (display, windowH);
  220425. windowH = 0;
  220426. return;
  220427. }
  220428. // Set window manager hints
  220429. XWMHints* wmHints = XAllocWMHints();
  220430. wmHints->flags = InputHint | StateHint;
  220431. wmHints->input = True; // Locally active input model
  220432. wmHints->initial_state = NormalState;
  220433. XSetWMHints (display, windowH, wmHints);
  220434. XFree (wmHints);
  220435. // Set the window type
  220436. setWindowType();
  220437. // Define decoration
  220438. if ((styleFlags & windowHasTitleBar) == 0)
  220439. removeWindowDecorations (windowH);
  220440. else
  220441. addWindowButtons (windowH);
  220442. setTitle (getComponent()->getName());
  220443. // Associate the PID, allowing to be shut down when something goes wrong
  220444. unsigned long pid = getpid();
  220445. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220446. (unsigned char*) &pid, 1);
  220447. // Set window manager protocols
  220448. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220449. (unsigned char*) Atoms::ProtocolList, 2);
  220450. // Set drag and drop flags
  220451. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220452. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220453. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220454. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220455. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220456. (const unsigned char*) "", 0);
  220457. unsigned long dndVersion = Atoms::DndVersion;
  220458. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220459. (const unsigned char*) &dndVersion, 1);
  220460. // Initialise the pointer and keyboard mapping
  220461. // This is not the same as the logical pointer mapping the X server uses:
  220462. // we don't mess with this.
  220463. static bool mappingInitialised = false;
  220464. if (! mappingInitialised)
  220465. {
  220466. mappingInitialised = true;
  220467. const int numButtons = XGetPointerMapping (display, 0, 0);
  220468. if (numButtons == 2)
  220469. {
  220470. pointerMap[0] = Keys::LeftButton;
  220471. pointerMap[1] = Keys::RightButton;
  220472. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220473. }
  220474. else if (numButtons >= 3)
  220475. {
  220476. pointerMap[0] = Keys::LeftButton;
  220477. pointerMap[1] = Keys::MiddleButton;
  220478. pointerMap[2] = Keys::RightButton;
  220479. if (numButtons >= 5)
  220480. {
  220481. pointerMap[3] = Keys::WheelUp;
  220482. pointerMap[4] = Keys::WheelDown;
  220483. }
  220484. }
  220485. updateModifierMappings();
  220486. }
  220487. }
  220488. void destroyWindow()
  220489. {
  220490. ScopedXLock xlock;
  220491. XPointer handlePointer;
  220492. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220493. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220494. XDestroyWindow (display, windowH);
  220495. // Wait for it to complete and then remove any events for this
  220496. // window from the event queue.
  220497. XSync (display, false);
  220498. XEvent event;
  220499. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220500. {}
  220501. }
  220502. static int getAllEventsMask() throw()
  220503. {
  220504. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220505. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220506. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220507. }
  220508. static int64 getEventTime (::Time t)
  220509. {
  220510. static int64 eventTimeOffset = 0x12345678;
  220511. const int64 thisMessageTime = t;
  220512. if (eventTimeOffset == 0x12345678)
  220513. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220514. return eventTimeOffset + thisMessageTime;
  220515. }
  220516. void updateBorderSize()
  220517. {
  220518. if ((styleFlags & windowHasTitleBar) == 0)
  220519. {
  220520. windowBorder = BorderSize<int> (0);
  220521. }
  220522. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220523. {
  220524. ScopedXLock xlock;
  220525. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220526. if (hints != None)
  220527. {
  220528. unsigned char* data = 0;
  220529. unsigned long nitems, bytesLeft;
  220530. Atom actualType;
  220531. int actualFormat;
  220532. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220533. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220534. &data) == Success)
  220535. {
  220536. const unsigned long* const sizes = (const unsigned long*) data;
  220537. if (actualFormat == 32)
  220538. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  220539. (int) sizes[3], (int) sizes[1]);
  220540. XFree (data);
  220541. }
  220542. }
  220543. }
  220544. }
  220545. void updateBounds()
  220546. {
  220547. jassert (windowH != 0);
  220548. if (windowH != 0)
  220549. {
  220550. Window root, child;
  220551. unsigned int bw, depth;
  220552. ScopedXLock xlock;
  220553. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220554. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220555. &bw, &depth))
  220556. {
  220557. wx = wy = ww = wh = 0;
  220558. }
  220559. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220560. {
  220561. wx = wy = 0;
  220562. }
  220563. }
  220564. }
  220565. void resetDragAndDrop()
  220566. {
  220567. dragAndDropFiles.clear();
  220568. lastDropPos = Point<int> (-1, -1);
  220569. dragAndDropCurrentMimeType = 0;
  220570. dragAndDropSourceWindow = 0;
  220571. srcMimeTypeAtomList.clear();
  220572. }
  220573. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220574. {
  220575. msg.type = ClientMessage;
  220576. msg.display = display;
  220577. msg.window = dragAndDropSourceWindow;
  220578. msg.format = 32;
  220579. msg.data.l[0] = windowH;
  220580. ScopedXLock xlock;
  220581. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220582. }
  220583. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220584. {
  220585. XClientMessageEvent msg;
  220586. zerostruct (msg);
  220587. msg.message_type = Atoms::XdndStatus;
  220588. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220589. msg.data.l[4] = dropAction;
  220590. sendDragAndDropMessage (msg);
  220591. }
  220592. void sendDragAndDropLeave()
  220593. {
  220594. XClientMessageEvent msg;
  220595. zerostruct (msg);
  220596. msg.message_type = Atoms::XdndLeave;
  220597. sendDragAndDropMessage (msg);
  220598. }
  220599. void sendDragAndDropFinish()
  220600. {
  220601. XClientMessageEvent msg;
  220602. zerostruct (msg);
  220603. msg.message_type = Atoms::XdndFinished;
  220604. sendDragAndDropMessage (msg);
  220605. }
  220606. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220607. {
  220608. if ((clientMsg->data.l[1] & 1) == 0)
  220609. {
  220610. sendDragAndDropLeave();
  220611. if (dragAndDropFiles.size() > 0)
  220612. handleFileDragExit (dragAndDropFiles);
  220613. dragAndDropFiles.clear();
  220614. }
  220615. }
  220616. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220617. {
  220618. if (dragAndDropSourceWindow == 0)
  220619. return;
  220620. dragAndDropSourceWindow = clientMsg->data.l[0];
  220621. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220622. (int) clientMsg->data.l[2] & 0xffff);
  220623. dropPos -= getScreenPosition();
  220624. if (lastDropPos != dropPos)
  220625. {
  220626. lastDropPos = dropPos;
  220627. dragAndDropTimestamp = clientMsg->data.l[3];
  220628. Atom targetAction = Atoms::XdndActionCopy;
  220629. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220630. {
  220631. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220632. {
  220633. targetAction = Atoms::allowedActions[i];
  220634. break;
  220635. }
  220636. }
  220637. sendDragAndDropStatus (true, targetAction);
  220638. if (dragAndDropFiles.size() == 0)
  220639. updateDraggedFileList (clientMsg);
  220640. if (dragAndDropFiles.size() > 0)
  220641. handleFileDragMove (dragAndDropFiles, dropPos);
  220642. }
  220643. }
  220644. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220645. {
  220646. if (dragAndDropFiles.size() == 0)
  220647. updateDraggedFileList (clientMsg);
  220648. const StringArray files (dragAndDropFiles);
  220649. const Point<int> lastPos (lastDropPos);
  220650. sendDragAndDropFinish();
  220651. resetDragAndDrop();
  220652. if (files.size() > 0)
  220653. handleFileDragDrop (files, lastPos);
  220654. }
  220655. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220656. {
  220657. dragAndDropFiles.clear();
  220658. srcMimeTypeAtomList.clear();
  220659. dragAndDropCurrentMimeType = 0;
  220660. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220661. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220662. {
  220663. dragAndDropSourceWindow = 0;
  220664. return;
  220665. }
  220666. dragAndDropSourceWindow = clientMsg->data.l[0];
  220667. if ((clientMsg->data.l[1] & 1) != 0)
  220668. {
  220669. Atom actual;
  220670. int format;
  220671. unsigned long count = 0, remaining = 0;
  220672. unsigned char* data = 0;
  220673. ScopedXLock xlock;
  220674. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220675. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220676. &count, &remaining, &data);
  220677. if (data != 0)
  220678. {
  220679. if (actual == XA_ATOM && format == 32 && count != 0)
  220680. {
  220681. const unsigned long* const types = (const unsigned long*) data;
  220682. for (unsigned int i = 0; i < count; ++i)
  220683. if (types[i] != None)
  220684. srcMimeTypeAtomList.add (types[i]);
  220685. }
  220686. XFree (data);
  220687. }
  220688. }
  220689. if (srcMimeTypeAtomList.size() == 0)
  220690. {
  220691. for (int i = 2; i < 5; ++i)
  220692. if (clientMsg->data.l[i] != None)
  220693. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220694. if (srcMimeTypeAtomList.size() == 0)
  220695. {
  220696. dragAndDropSourceWindow = 0;
  220697. return;
  220698. }
  220699. }
  220700. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220701. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220702. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220703. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220704. handleDragAndDropPosition (clientMsg);
  220705. }
  220706. void handleDragAndDropSelection (const XEvent* const evt)
  220707. {
  220708. dragAndDropFiles.clear();
  220709. if (evt->xselection.property != 0)
  220710. {
  220711. StringArray lines;
  220712. {
  220713. MemoryBlock dropData;
  220714. for (;;)
  220715. {
  220716. Atom actual;
  220717. uint8* data = 0;
  220718. unsigned long count = 0, remaining = 0;
  220719. int format = 0;
  220720. ScopedXLock xlock;
  220721. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220722. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220723. &format, &count, &remaining, &data) == Success)
  220724. {
  220725. dropData.append (data, count * format / 8);
  220726. XFree (data);
  220727. if (remaining == 0)
  220728. break;
  220729. }
  220730. else
  220731. {
  220732. XFree (data);
  220733. break;
  220734. }
  220735. }
  220736. lines.addLines (dropData.toString());
  220737. }
  220738. for (int i = 0; i < lines.size(); ++i)
  220739. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220740. dragAndDropFiles.trim();
  220741. dragAndDropFiles.removeEmptyStrings();
  220742. }
  220743. }
  220744. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220745. {
  220746. dragAndDropFiles.clear();
  220747. if (dragAndDropSourceWindow != None
  220748. && dragAndDropCurrentMimeType != 0)
  220749. {
  220750. dragAndDropTimestamp = clientMsg->data.l[2];
  220751. ScopedXLock xlock;
  220752. XConvertSelection (display,
  220753. Atoms::XdndSelection,
  220754. dragAndDropCurrentMimeType,
  220755. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220756. windowH,
  220757. dragAndDropTimestamp);
  220758. }
  220759. }
  220760. StringArray dragAndDropFiles;
  220761. int dragAndDropTimestamp;
  220762. Point<int> lastDropPos;
  220763. Atom dragAndDropCurrentMimeType;
  220764. Window dragAndDropSourceWindow;
  220765. Array <Atom> srcMimeTypeAtomList;
  220766. static int pointerMap[5];
  220767. static Point<int> lastMousePos;
  220768. static void clearLastMousePos() throw()
  220769. {
  220770. lastMousePos = Point<int> (0x100000, 0x100000);
  220771. }
  220772. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  220773. };
  220774. ModifierKeys LinuxComponentPeer::currentModifiers;
  220775. bool LinuxComponentPeer::isActiveApplication = false;
  220776. int LinuxComponentPeer::pointerMap[5];
  220777. Point<int> LinuxComponentPeer::lastMousePos;
  220778. bool Process::isForegroundProcess()
  220779. {
  220780. return LinuxComponentPeer::isActiveApplication;
  220781. }
  220782. void ModifierKeys::updateCurrentModifiers() throw()
  220783. {
  220784. currentModifiers = LinuxComponentPeer::currentModifiers;
  220785. }
  220786. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220787. {
  220788. Window root, child;
  220789. int x, y, winx, winy;
  220790. unsigned int mask;
  220791. int mouseMods = 0;
  220792. ScopedXLock xlock;
  220793. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220794. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220795. {
  220796. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220797. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220798. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220799. }
  220800. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220801. return LinuxComponentPeer::currentModifiers;
  220802. }
  220803. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220804. {
  220805. if (enableOrDisable)
  220806. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220807. }
  220808. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220809. {
  220810. return new LinuxComponentPeer (this, styleFlags);
  220811. }
  220812. // (this callback is hooked up in the messaging code)
  220813. void juce_windowMessageReceive (XEvent* event)
  220814. {
  220815. if (event->xany.window != None)
  220816. {
  220817. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220818. if (ComponentPeer::isValidPeer (peer))
  220819. peer->handleWindowMessage (event);
  220820. }
  220821. else
  220822. {
  220823. switch (event->xany.type)
  220824. {
  220825. case KeymapNotify:
  220826. {
  220827. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220828. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220829. break;
  220830. }
  220831. default:
  220832. break;
  220833. }
  220834. }
  220835. }
  220836. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220837. {
  220838. if (display == 0)
  220839. return;
  220840. #if JUCE_USE_XINERAMA
  220841. int major_opcode, first_event, first_error;
  220842. ScopedXLock xlock;
  220843. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220844. {
  220845. typedef Bool (*tXineramaIsActive) (Display*);
  220846. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220847. static tXineramaIsActive xXineramaIsActive = 0;
  220848. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220849. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220850. {
  220851. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220852. if (h == 0)
  220853. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220854. if (h != 0)
  220855. {
  220856. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220857. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220858. }
  220859. }
  220860. if (xXineramaIsActive != 0
  220861. && xXineramaQueryScreens != 0
  220862. && xXineramaIsActive (display))
  220863. {
  220864. int numMonitors = 0;
  220865. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220866. if (screens != 0)
  220867. {
  220868. for (int i = numMonitors; --i >= 0;)
  220869. {
  220870. int index = screens[i].screen_number;
  220871. if (index >= 0)
  220872. {
  220873. while (monitorCoords.size() < index)
  220874. monitorCoords.add (Rectangle<int>());
  220875. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220876. screens[i].y_org,
  220877. screens[i].width,
  220878. screens[i].height));
  220879. }
  220880. }
  220881. XFree (screens);
  220882. }
  220883. }
  220884. }
  220885. if (monitorCoords.size() == 0)
  220886. #endif
  220887. {
  220888. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220889. if (hints != None)
  220890. {
  220891. const int numMonitors = ScreenCount (display);
  220892. for (int i = 0; i < numMonitors; ++i)
  220893. {
  220894. Window root = RootWindow (display, i);
  220895. unsigned long nitems, bytesLeft;
  220896. Atom actualType;
  220897. int actualFormat;
  220898. unsigned char* data = 0;
  220899. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220900. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220901. &data) == Success)
  220902. {
  220903. const long* const position = (const long*) data;
  220904. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220905. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220906. position[2], position[3]));
  220907. XFree (data);
  220908. }
  220909. }
  220910. }
  220911. if (monitorCoords.size() == 0)
  220912. {
  220913. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  220914. DisplayHeight (display, DefaultScreen (display))));
  220915. }
  220916. }
  220917. }
  220918. void Desktop::createMouseInputSources()
  220919. {
  220920. mouseSources.add (new MouseInputSource (0, true));
  220921. }
  220922. bool Desktop::canUseSemiTransparentWindows() throw()
  220923. {
  220924. int matchedDepth = 0;
  220925. const int desiredDepth = 32;
  220926. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220927. && (matchedDepth == desiredDepth);
  220928. }
  220929. const Point<int> MouseInputSource::getCurrentMousePosition()
  220930. {
  220931. Window root, child;
  220932. int x, y, winx, winy;
  220933. unsigned int mask;
  220934. ScopedXLock xlock;
  220935. if (XQueryPointer (display,
  220936. RootWindow (display, DefaultScreen (display)),
  220937. &root, &child,
  220938. &x, &y, &winx, &winy, &mask) == False)
  220939. {
  220940. // Pointer not on the default screen
  220941. x = y = -1;
  220942. }
  220943. return Point<int> (x, y);
  220944. }
  220945. void Desktop::setMousePosition (const Point<int>& newPosition)
  220946. {
  220947. ScopedXLock xlock;
  220948. Window root = RootWindow (display, DefaultScreen (display));
  220949. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220950. }
  220951. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  220952. {
  220953. return upright;
  220954. }
  220955. static bool screenSaverAllowed = true;
  220956. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220957. {
  220958. if (screenSaverAllowed != isEnabled)
  220959. {
  220960. screenSaverAllowed = isEnabled;
  220961. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220962. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220963. if (xScreenSaverSuspend == 0)
  220964. {
  220965. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220966. if (h != 0)
  220967. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220968. }
  220969. ScopedXLock xlock;
  220970. if (xScreenSaverSuspend != 0)
  220971. xScreenSaverSuspend (display, ! isEnabled);
  220972. }
  220973. }
  220974. bool Desktop::isScreenSaverEnabled()
  220975. {
  220976. return screenSaverAllowed;
  220977. }
  220978. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220979. {
  220980. ScopedXLock xlock;
  220981. const unsigned int imageW = image.getWidth();
  220982. const unsigned int imageH = image.getHeight();
  220983. #if JUCE_USE_XCURSOR
  220984. {
  220985. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220986. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220987. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220988. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220989. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220990. static tXcursorImageCreate xXcursorImageCreate = 0;
  220991. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220992. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220993. static bool hasBeenLoaded = false;
  220994. if (! hasBeenLoaded)
  220995. {
  220996. hasBeenLoaded = true;
  220997. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220998. if (h != 0)
  220999. {
  221000. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221001. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221002. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221003. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221004. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221005. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221006. || ! xXcursorSupportsARGB (display))
  221007. xXcursorSupportsARGB = 0;
  221008. }
  221009. }
  221010. if (xXcursorSupportsARGB != 0)
  221011. {
  221012. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221013. if (xcImage != 0)
  221014. {
  221015. xcImage->xhot = hotspotX;
  221016. xcImage->yhot = hotspotY;
  221017. XcursorPixel* dest = xcImage->pixels;
  221018. for (int y = 0; y < (int) imageH; ++y)
  221019. for (int x = 0; x < (int) imageW; ++x)
  221020. *dest++ = image.getPixelAt (x, y).getARGB();
  221021. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221022. xXcursorImageDestroy (xcImage);
  221023. if (result != 0)
  221024. return result;
  221025. }
  221026. }
  221027. }
  221028. #endif
  221029. Window root = RootWindow (display, DefaultScreen (display));
  221030. unsigned int cursorW, cursorH;
  221031. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221032. return 0;
  221033. Image im (Image::ARGB, cursorW, cursorH, true);
  221034. {
  221035. Graphics g (im);
  221036. if (imageW > cursorW || imageH > cursorH)
  221037. {
  221038. hotspotX = (hotspotX * cursorW) / imageW;
  221039. hotspotY = (hotspotY * cursorH) / imageH;
  221040. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221041. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221042. false);
  221043. }
  221044. else
  221045. {
  221046. g.drawImageAt (image, 0, 0);
  221047. }
  221048. }
  221049. const int stride = (cursorW + 7) >> 3;
  221050. HeapBlock <char> maskPlane, sourcePlane;
  221051. maskPlane.calloc (stride * cursorH);
  221052. sourcePlane.calloc (stride * cursorH);
  221053. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221054. for (int y = cursorH; --y >= 0;)
  221055. {
  221056. for (int x = cursorW; --x >= 0;)
  221057. {
  221058. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221059. const int offset = y * stride + (x >> 3);
  221060. const Colour c (im.getPixelAt (x, y));
  221061. if (c.getAlpha() >= 128)
  221062. maskPlane[offset] |= mask;
  221063. if (c.getBrightness() >= 0.5f)
  221064. sourcePlane[offset] |= mask;
  221065. }
  221066. }
  221067. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221068. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221069. XColor white, black;
  221070. black.red = black.green = black.blue = 0;
  221071. white.red = white.green = white.blue = 0xffff;
  221072. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221073. XFreePixmap (display, sourcePixmap);
  221074. XFreePixmap (display, maskPixmap);
  221075. return result;
  221076. }
  221077. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221078. {
  221079. ScopedXLock xlock;
  221080. if (cursorHandle != 0)
  221081. XFreeCursor (display, (Cursor) cursorHandle);
  221082. }
  221083. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221084. {
  221085. unsigned int shape;
  221086. switch (type)
  221087. {
  221088. case NormalCursor: return None; // Use parent cursor
  221089. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221090. case WaitCursor: shape = XC_watch; break;
  221091. case IBeamCursor: shape = XC_xterm; break;
  221092. case PointingHandCursor: shape = XC_hand2; break;
  221093. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221094. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221095. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221096. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221097. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221098. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221099. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221100. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221101. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221102. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221103. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221104. case CrosshairCursor: shape = XC_crosshair; break;
  221105. case DraggingHandCursor:
  221106. {
  221107. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221108. 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,
  221109. 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 };
  221110. const int dragHandDataSize = 99;
  221111. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221112. }
  221113. case CopyingCursor:
  221114. {
  221115. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221116. 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,
  221117. 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,
  221118. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221119. const int copyCursorSize = 119;
  221120. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221121. }
  221122. default:
  221123. jassertfalse;
  221124. return None;
  221125. }
  221126. ScopedXLock xlock;
  221127. return (void*) XCreateFontCursor (display, shape);
  221128. }
  221129. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221130. {
  221131. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221132. if (lp != 0)
  221133. lp->showMouseCursor ((Cursor) getHandle());
  221134. }
  221135. void MouseCursor::showInAllWindows() const
  221136. {
  221137. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221138. showInWindow (ComponentPeer::getPeer (i));
  221139. }
  221140. const Image juce_createIconForFile (const File& file)
  221141. {
  221142. return Image::null;
  221143. }
  221144. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221145. {
  221146. return createSoftwareImage (format, width, height, clearImage);
  221147. }
  221148. #if JUCE_OPENGL
  221149. class WindowedGLContext : public OpenGLContext
  221150. {
  221151. public:
  221152. WindowedGLContext (Component* const component,
  221153. const OpenGLPixelFormat& pixelFormat_,
  221154. GLXContext sharedContext)
  221155. : renderContext (0),
  221156. embeddedWindow (0),
  221157. pixelFormat (pixelFormat_),
  221158. swapInterval (0)
  221159. {
  221160. jassert (component != 0);
  221161. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221162. if (peer == 0)
  221163. return;
  221164. ScopedXLock xlock;
  221165. XSync (display, False);
  221166. GLint attribs [64];
  221167. int n = 0;
  221168. attribs[n++] = GLX_RGBA;
  221169. attribs[n++] = GLX_DOUBLEBUFFER;
  221170. attribs[n++] = GLX_RED_SIZE;
  221171. attribs[n++] = pixelFormat.redBits;
  221172. attribs[n++] = GLX_GREEN_SIZE;
  221173. attribs[n++] = pixelFormat.greenBits;
  221174. attribs[n++] = GLX_BLUE_SIZE;
  221175. attribs[n++] = pixelFormat.blueBits;
  221176. attribs[n++] = GLX_ALPHA_SIZE;
  221177. attribs[n++] = pixelFormat.alphaBits;
  221178. attribs[n++] = GLX_DEPTH_SIZE;
  221179. attribs[n++] = pixelFormat.depthBufferBits;
  221180. attribs[n++] = GLX_STENCIL_SIZE;
  221181. attribs[n++] = pixelFormat.stencilBufferBits;
  221182. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221183. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221184. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221185. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221186. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221187. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221188. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221189. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221190. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221191. attribs[n++] = None;
  221192. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221193. if (bestVisual == 0)
  221194. return;
  221195. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221196. Window windowH = (Window) peer->getNativeHandle();
  221197. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221198. XSetWindowAttributes swa;
  221199. swa.colormap = colourMap;
  221200. swa.border_pixel = 0;
  221201. swa.event_mask = ExposureMask | StructureNotifyMask;
  221202. embeddedWindow = XCreateWindow (display, windowH,
  221203. 0, 0, 1, 1, 0,
  221204. bestVisual->depth,
  221205. InputOutput,
  221206. bestVisual->visual,
  221207. CWBorderPixel | CWColormap | CWEventMask,
  221208. &swa);
  221209. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221210. XMapWindow (display, embeddedWindow);
  221211. XFreeColormap (display, colourMap);
  221212. XFree (bestVisual);
  221213. XSync (display, False);
  221214. }
  221215. ~WindowedGLContext()
  221216. {
  221217. ScopedXLock xlock;
  221218. deleteContext();
  221219. XUnmapWindow (display, embeddedWindow);
  221220. XDestroyWindow (display, embeddedWindow);
  221221. }
  221222. void deleteContext()
  221223. {
  221224. makeInactive();
  221225. if (renderContext != 0)
  221226. {
  221227. ScopedXLock xlock;
  221228. glXDestroyContext (display, renderContext);
  221229. renderContext = 0;
  221230. }
  221231. }
  221232. bool makeActive() const throw()
  221233. {
  221234. jassert (renderContext != 0);
  221235. ScopedXLock xlock;
  221236. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221237. && XSync (display, False);
  221238. }
  221239. bool makeInactive() const throw()
  221240. {
  221241. ScopedXLock xlock;
  221242. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221243. }
  221244. bool isActive() const throw()
  221245. {
  221246. ScopedXLock xlock;
  221247. return glXGetCurrentContext() == renderContext;
  221248. }
  221249. const OpenGLPixelFormat getPixelFormat() const
  221250. {
  221251. return pixelFormat;
  221252. }
  221253. void* getRawContext() const throw()
  221254. {
  221255. return renderContext;
  221256. }
  221257. void updateWindowPosition (int x, int y, int w, int h, int)
  221258. {
  221259. ScopedXLock xlock;
  221260. XMoveResizeWindow (display, embeddedWindow,
  221261. x, y, jmax (1, w), jmax (1, h));
  221262. }
  221263. void swapBuffers()
  221264. {
  221265. ScopedXLock xlock;
  221266. glXSwapBuffers (display, embeddedWindow);
  221267. }
  221268. bool setSwapInterval (const int numFramesPerSwap)
  221269. {
  221270. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221271. if (GLXSwapIntervalSGI != 0)
  221272. {
  221273. swapInterval = numFramesPerSwap;
  221274. GLXSwapIntervalSGI (numFramesPerSwap);
  221275. return true;
  221276. }
  221277. return false;
  221278. }
  221279. int getSwapInterval() const
  221280. {
  221281. return swapInterval;
  221282. }
  221283. void repaint()
  221284. {
  221285. }
  221286. GLXContext renderContext;
  221287. private:
  221288. Window embeddedWindow;
  221289. OpenGLPixelFormat pixelFormat;
  221290. int swapInterval;
  221291. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221292. };
  221293. OpenGLContext* OpenGLComponent::createContext()
  221294. {
  221295. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221296. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221297. return (c->renderContext != 0) ? c.release() : 0;
  221298. }
  221299. void juce_glViewport (const int w, const int h)
  221300. {
  221301. glViewport (0, 0, w, h);
  221302. }
  221303. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221304. OwnedArray <OpenGLPixelFormat>& results)
  221305. {
  221306. results.add (new OpenGLPixelFormat()); // xxx
  221307. }
  221308. #endif
  221309. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221310. {
  221311. jassertfalse; // not implemented!
  221312. return false;
  221313. }
  221314. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221315. {
  221316. jassertfalse; // not implemented!
  221317. return false;
  221318. }
  221319. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221320. {
  221321. if (! isOnDesktop ())
  221322. addToDesktop (0);
  221323. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221324. if (wp != 0)
  221325. {
  221326. wp->setTaskBarIcon (newImage);
  221327. setVisible (true);
  221328. toFront (false);
  221329. repaint();
  221330. }
  221331. }
  221332. void SystemTrayIconComponent::paint (Graphics& g)
  221333. {
  221334. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221335. if (wp != 0)
  221336. {
  221337. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221338. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221339. false);
  221340. }
  221341. }
  221342. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221343. {
  221344. // xxx not yet implemented!
  221345. }
  221346. void PlatformUtilities::beep()
  221347. {
  221348. std::cout << "\a" << std::flush;
  221349. }
  221350. bool AlertWindow::showNativeDialogBox (const String& title,
  221351. const String& bodyText,
  221352. bool isOkCancel)
  221353. {
  221354. // use a non-native one for the time being..
  221355. if (isOkCancel)
  221356. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221357. else
  221358. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221359. return true;
  221360. }
  221361. const int KeyPress::spaceKey = XK_space & 0xff;
  221362. const int KeyPress::returnKey = XK_Return & 0xff;
  221363. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221364. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221365. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221366. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221367. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221368. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221369. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221370. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221371. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221372. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221373. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221374. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221375. const int KeyPress::tabKey = XK_Tab & 0xff;
  221376. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221377. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221378. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221379. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221380. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221381. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221382. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221383. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221384. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221385. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221386. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221387. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221388. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221389. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221390. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221391. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221392. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221393. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221394. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221395. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221396. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221397. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221398. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221399. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221400. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221401. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221402. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221403. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221404. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221405. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221406. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221407. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221408. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221409. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221410. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221411. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221412. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221413. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221414. #endif
  221415. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221416. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221417. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221418. // compiled on its own).
  221419. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221420. namespace
  221421. {
  221422. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221423. {
  221424. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221425. snd_pcm_hw_params_t* hwParams;
  221426. snd_pcm_hw_params_alloca (&hwParams);
  221427. for (int i = 0; ratesToTry[i] != 0; ++i)
  221428. {
  221429. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221430. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221431. {
  221432. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221433. }
  221434. }
  221435. }
  221436. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221437. {
  221438. snd_pcm_hw_params_t *params;
  221439. snd_pcm_hw_params_alloca (&params);
  221440. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221441. {
  221442. snd_pcm_hw_params_get_channels_min (params, minChans);
  221443. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221444. }
  221445. }
  221446. void getDeviceProperties (const String& deviceID,
  221447. unsigned int& minChansOut,
  221448. unsigned int& maxChansOut,
  221449. unsigned int& minChansIn,
  221450. unsigned int& maxChansIn,
  221451. Array <int>& rates)
  221452. {
  221453. if (deviceID.isEmpty())
  221454. return;
  221455. snd_ctl_t* handle;
  221456. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221457. {
  221458. snd_pcm_info_t* info;
  221459. snd_pcm_info_alloca (&info);
  221460. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221461. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221462. snd_pcm_info_set_subdevice (info, 0);
  221463. if (snd_ctl_pcm_info (handle, info) >= 0)
  221464. {
  221465. snd_pcm_t* pcmHandle;
  221466. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221467. {
  221468. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221469. getDeviceSampleRates (pcmHandle, rates);
  221470. snd_pcm_close (pcmHandle);
  221471. }
  221472. }
  221473. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221474. if (snd_ctl_pcm_info (handle, info) >= 0)
  221475. {
  221476. snd_pcm_t* pcmHandle;
  221477. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221478. {
  221479. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221480. if (rates.size() == 0)
  221481. getDeviceSampleRates (pcmHandle, rates);
  221482. snd_pcm_close (pcmHandle);
  221483. }
  221484. }
  221485. snd_ctl_close (handle);
  221486. }
  221487. }
  221488. }
  221489. class ALSADevice
  221490. {
  221491. public:
  221492. ALSADevice (const String& deviceID, bool forInput)
  221493. : handle (0),
  221494. bitDepth (16),
  221495. numChannelsRunning (0),
  221496. latency (0),
  221497. isInput (forInput),
  221498. isInterleaved (true)
  221499. {
  221500. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221501. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221502. SND_PCM_ASYNC));
  221503. }
  221504. ~ALSADevice()
  221505. {
  221506. if (handle != 0)
  221507. snd_pcm_close (handle);
  221508. }
  221509. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221510. {
  221511. if (handle == 0)
  221512. return false;
  221513. snd_pcm_hw_params_t* hwParams;
  221514. snd_pcm_hw_params_alloca (&hwParams);
  221515. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221516. return false;
  221517. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221518. isInterleaved = false;
  221519. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221520. isInterleaved = true;
  221521. else
  221522. {
  221523. jassertfalse;
  221524. return false;
  221525. }
  221526. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  221527. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  221528. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  221529. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  221530. SND_PCM_FORMAT_S32_BE, 32,
  221531. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  221532. SND_PCM_FORMAT_S24_3BE, 24,
  221533. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  221534. SND_PCM_FORMAT_S16_BE, 16 };
  221535. bitDepth = 0;
  221536. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  221537. {
  221538. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221539. {
  221540. bitDepth = formatsToTry [i + 1] & 255;
  221541. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  221542. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  221543. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  221544. break;
  221545. }
  221546. }
  221547. if (bitDepth == 0)
  221548. {
  221549. error = "device doesn't support a compatible PCM format";
  221550. DBG ("ALSA error: " + error + "\n");
  221551. return false;
  221552. }
  221553. int dir = 0;
  221554. unsigned int periods = 4;
  221555. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221556. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221557. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221558. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221559. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221560. || failed (snd_pcm_hw_params (handle, hwParams)))
  221561. {
  221562. return false;
  221563. }
  221564. snd_pcm_uframes_t frames = 0;
  221565. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  221566. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  221567. latency = 0;
  221568. else
  221569. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  221570. snd_pcm_sw_params_t* swParams;
  221571. snd_pcm_sw_params_alloca (&swParams);
  221572. snd_pcm_uframes_t boundary;
  221573. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221574. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221575. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221576. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221577. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221578. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221579. || failed (snd_pcm_sw_params (handle, swParams)))
  221580. {
  221581. return false;
  221582. }
  221583. #if 0
  221584. // enable this to dump the config of the devices that get opened
  221585. snd_output_t* out;
  221586. snd_output_stdio_attach (&out, stderr, 0);
  221587. snd_pcm_hw_params_dump (hwParams, out);
  221588. snd_pcm_sw_params_dump (swParams, out);
  221589. #endif
  221590. numChannelsRunning = numChannels;
  221591. return true;
  221592. }
  221593. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221594. {
  221595. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221596. float** const data = outputChannelBuffer.getArrayOfChannels();
  221597. snd_pcm_sframes_t numDone = 0;
  221598. if (isInterleaved)
  221599. {
  221600. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221601. for (int i = 0; i < numChannelsRunning; ++i)
  221602. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  221603. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  221604. }
  221605. else
  221606. {
  221607. for (int i = 0; i < numChannelsRunning; ++i)
  221608. converter->convertSamples (data[i], data[i], numSamples);
  221609. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  221610. }
  221611. if (failed (numDone))
  221612. {
  221613. if (numDone == -EPIPE)
  221614. {
  221615. if (failed (snd_pcm_prepare (handle)))
  221616. return false;
  221617. }
  221618. else if (numDone != -ESTRPIPE)
  221619. return false;
  221620. }
  221621. return true;
  221622. }
  221623. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221624. {
  221625. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221626. float** const data = inputChannelBuffer.getArrayOfChannels();
  221627. if (isInterleaved)
  221628. {
  221629. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221630. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  221631. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  221632. if (failed (num))
  221633. {
  221634. if (num == -EPIPE)
  221635. {
  221636. if (failed (snd_pcm_prepare (handle)))
  221637. return false;
  221638. }
  221639. else if (num != -ESTRPIPE)
  221640. return false;
  221641. }
  221642. for (int i = 0; i < numChannelsRunning; ++i)
  221643. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  221644. }
  221645. else
  221646. {
  221647. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221648. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221649. return false;
  221650. for (int i = 0; i < numChannelsRunning; ++i)
  221651. converter->convertSamples (data[i], data[i], numSamples);
  221652. }
  221653. return true;
  221654. }
  221655. snd_pcm_t* handle;
  221656. String error;
  221657. int bitDepth, numChannelsRunning, latency;
  221658. private:
  221659. const bool isInput;
  221660. bool isInterleaved;
  221661. MemoryBlock scratch;
  221662. ScopedPointer<AudioData::Converter> converter;
  221663. template <class SampleType>
  221664. struct ConverterHelper
  221665. {
  221666. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  221667. {
  221668. if (forInput)
  221669. {
  221670. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  221671. if (isLittleEndian)
  221672. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221673. else
  221674. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221675. }
  221676. else
  221677. {
  221678. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  221679. if (isLittleEndian)
  221680. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221681. else
  221682. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221683. }
  221684. }
  221685. };
  221686. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  221687. {
  221688. switch (bitDepth)
  221689. {
  221690. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221691. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221692. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  221693. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221694. default: jassertfalse; break; // unsupported format!
  221695. }
  221696. return 0;
  221697. }
  221698. bool failed (const int errorNum)
  221699. {
  221700. if (errorNum >= 0)
  221701. return false;
  221702. error = snd_strerror (errorNum);
  221703. DBG ("ALSA error: " + error + "\n");
  221704. return true;
  221705. }
  221706. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  221707. };
  221708. class ALSAThread : public Thread
  221709. {
  221710. public:
  221711. ALSAThread (const String& inputId_,
  221712. const String& outputId_)
  221713. : Thread ("Juce ALSA"),
  221714. sampleRate (0),
  221715. bufferSize (0),
  221716. outputLatency (0),
  221717. inputLatency (0),
  221718. callback (0),
  221719. inputId (inputId_),
  221720. outputId (outputId_),
  221721. numCallbacks (0),
  221722. inputChannelBuffer (1, 1),
  221723. outputChannelBuffer (1, 1)
  221724. {
  221725. initialiseRatesAndChannels();
  221726. }
  221727. ~ALSAThread()
  221728. {
  221729. close();
  221730. }
  221731. void open (BigInteger inputChannels,
  221732. BigInteger outputChannels,
  221733. const double sampleRate_,
  221734. const int bufferSize_)
  221735. {
  221736. close();
  221737. error = String::empty;
  221738. sampleRate = sampleRate_;
  221739. bufferSize = bufferSize_;
  221740. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221741. inputChannelBuffer.clear();
  221742. inputChannelDataForCallback.clear();
  221743. currentInputChans.clear();
  221744. if (inputChannels.getHighestBit() >= 0)
  221745. {
  221746. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221747. {
  221748. if (inputChannels[i])
  221749. {
  221750. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221751. currentInputChans.setBit (i);
  221752. }
  221753. }
  221754. }
  221755. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221756. outputChannelBuffer.clear();
  221757. outputChannelDataForCallback.clear();
  221758. currentOutputChans.clear();
  221759. if (outputChannels.getHighestBit() >= 0)
  221760. {
  221761. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221762. {
  221763. if (outputChannels[i])
  221764. {
  221765. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221766. currentOutputChans.setBit (i);
  221767. }
  221768. }
  221769. }
  221770. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221771. {
  221772. outputDevice = new ALSADevice (outputId, false);
  221773. if (outputDevice->error.isNotEmpty())
  221774. {
  221775. error = outputDevice->error;
  221776. outputDevice = 0;
  221777. return;
  221778. }
  221779. currentOutputChans.setRange (0, minChansOut, true);
  221780. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221781. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221782. bufferSize))
  221783. {
  221784. error = outputDevice->error;
  221785. outputDevice = 0;
  221786. return;
  221787. }
  221788. outputLatency = outputDevice->latency;
  221789. }
  221790. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221791. {
  221792. inputDevice = new ALSADevice (inputId, true);
  221793. if (inputDevice->error.isNotEmpty())
  221794. {
  221795. error = inputDevice->error;
  221796. inputDevice = 0;
  221797. return;
  221798. }
  221799. currentInputChans.setRange (0, minChansIn, true);
  221800. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221801. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221802. bufferSize))
  221803. {
  221804. error = inputDevice->error;
  221805. inputDevice = 0;
  221806. return;
  221807. }
  221808. inputLatency = inputDevice->latency;
  221809. }
  221810. if (outputDevice == 0 && inputDevice == 0)
  221811. {
  221812. error = "no channels";
  221813. return;
  221814. }
  221815. if (outputDevice != 0 && inputDevice != 0)
  221816. {
  221817. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221818. }
  221819. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221820. return;
  221821. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221822. return;
  221823. startThread (9);
  221824. int count = 1000;
  221825. while (numCallbacks == 0)
  221826. {
  221827. sleep (5);
  221828. if (--count < 0 || ! isThreadRunning())
  221829. {
  221830. error = "device didn't start";
  221831. break;
  221832. }
  221833. }
  221834. }
  221835. void close()
  221836. {
  221837. stopThread (6000);
  221838. inputDevice = 0;
  221839. outputDevice = 0;
  221840. inputChannelBuffer.setSize (1, 1);
  221841. outputChannelBuffer.setSize (1, 1);
  221842. numCallbacks = 0;
  221843. }
  221844. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221845. {
  221846. const ScopedLock sl (callbackLock);
  221847. callback = newCallback;
  221848. }
  221849. void run()
  221850. {
  221851. while (! threadShouldExit())
  221852. {
  221853. if (inputDevice != 0)
  221854. {
  221855. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  221856. {
  221857. DBG ("ALSA: read failure");
  221858. break;
  221859. }
  221860. }
  221861. if (threadShouldExit())
  221862. break;
  221863. {
  221864. const ScopedLock sl (callbackLock);
  221865. ++numCallbacks;
  221866. if (callback != 0)
  221867. {
  221868. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221869. inputChannelDataForCallback.size(),
  221870. outputChannelDataForCallback.getRawDataPointer(),
  221871. outputChannelDataForCallback.size(),
  221872. bufferSize);
  221873. }
  221874. else
  221875. {
  221876. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221877. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221878. }
  221879. }
  221880. if (outputDevice != 0)
  221881. {
  221882. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221883. if (threadShouldExit())
  221884. break;
  221885. failed (snd_pcm_avail_update (outputDevice->handle));
  221886. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  221887. {
  221888. DBG ("ALSA: write failure");
  221889. break;
  221890. }
  221891. }
  221892. }
  221893. }
  221894. int getBitDepth() const throw()
  221895. {
  221896. if (outputDevice != 0)
  221897. return outputDevice->bitDepth;
  221898. if (inputDevice != 0)
  221899. return inputDevice->bitDepth;
  221900. return 16;
  221901. }
  221902. String error;
  221903. double sampleRate;
  221904. int bufferSize, outputLatency, inputLatency;
  221905. BigInteger currentInputChans, currentOutputChans;
  221906. Array <int> sampleRates;
  221907. StringArray channelNamesOut, channelNamesIn;
  221908. AudioIODeviceCallback* callback;
  221909. private:
  221910. const String inputId, outputId;
  221911. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  221912. int numCallbacks;
  221913. CriticalSection callbackLock;
  221914. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221915. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221916. unsigned int minChansOut, maxChansOut;
  221917. unsigned int minChansIn, maxChansIn;
  221918. bool failed (const int errorNum)
  221919. {
  221920. if (errorNum >= 0)
  221921. return false;
  221922. error = snd_strerror (errorNum);
  221923. DBG ("ALSA error: " + error + "\n");
  221924. return true;
  221925. }
  221926. void initialiseRatesAndChannels()
  221927. {
  221928. sampleRates.clear();
  221929. channelNamesOut.clear();
  221930. channelNamesIn.clear();
  221931. minChansOut = 0;
  221932. maxChansOut = 0;
  221933. minChansIn = 0;
  221934. maxChansIn = 0;
  221935. unsigned int dummy = 0;
  221936. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221937. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221938. unsigned int i;
  221939. for (i = 0; i < maxChansOut; ++i)
  221940. channelNamesOut.add ("channel " + String ((int) i + 1));
  221941. for (i = 0; i < maxChansIn; ++i)
  221942. channelNamesIn.add ("channel " + String ((int) i + 1));
  221943. }
  221944. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  221945. };
  221946. class ALSAAudioIODevice : public AudioIODevice
  221947. {
  221948. public:
  221949. ALSAAudioIODevice (const String& deviceName,
  221950. const String& inputId_,
  221951. const String& outputId_)
  221952. : AudioIODevice (deviceName, "ALSA"),
  221953. inputId (inputId_),
  221954. outputId (outputId_),
  221955. isOpen_ (false),
  221956. isStarted (false),
  221957. internal (inputId_, outputId_)
  221958. {
  221959. }
  221960. ~ALSAAudioIODevice()
  221961. {
  221962. }
  221963. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  221964. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  221965. int getNumSampleRates() { return internal.sampleRates.size(); }
  221966. double getSampleRate (int index) { return internal.sampleRates [index]; }
  221967. int getDefaultBufferSize() { return 512; }
  221968. int getNumBufferSizesAvailable() { return 50; }
  221969. int getBufferSizeSamples (int index)
  221970. {
  221971. int n = 16;
  221972. for (int i = 0; i < index; ++i)
  221973. n += n < 64 ? 16
  221974. : (n < 512 ? 32
  221975. : (n < 1024 ? 64
  221976. : (n < 2048 ? 128 : 256)));
  221977. return n;
  221978. }
  221979. const String open (const BigInteger& inputChannels,
  221980. const BigInteger& outputChannels,
  221981. double sampleRate,
  221982. int bufferSizeSamples)
  221983. {
  221984. close();
  221985. if (bufferSizeSamples <= 0)
  221986. bufferSizeSamples = getDefaultBufferSize();
  221987. if (sampleRate <= 0)
  221988. {
  221989. for (int i = 0; i < getNumSampleRates(); ++i)
  221990. {
  221991. if (getSampleRate (i) >= 44100)
  221992. {
  221993. sampleRate = getSampleRate (i);
  221994. break;
  221995. }
  221996. }
  221997. }
  221998. internal.open (inputChannels, outputChannels,
  221999. sampleRate, bufferSizeSamples);
  222000. isOpen_ = internal.error.isEmpty();
  222001. return internal.error;
  222002. }
  222003. void close()
  222004. {
  222005. stop();
  222006. internal.close();
  222007. isOpen_ = false;
  222008. }
  222009. bool isOpen() { return isOpen_; }
  222010. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222011. const String getLastError() { return internal.error; }
  222012. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222013. double getCurrentSampleRate() { return internal.sampleRate; }
  222014. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222015. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222016. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222017. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222018. int getInputLatencyInSamples() { return internal.inputLatency; }
  222019. void start (AudioIODeviceCallback* callback)
  222020. {
  222021. if (! isOpen_)
  222022. callback = 0;
  222023. if (callback != 0)
  222024. callback->audioDeviceAboutToStart (this);
  222025. internal.setCallback (callback);
  222026. isStarted = (callback != 0);
  222027. }
  222028. void stop()
  222029. {
  222030. AudioIODeviceCallback* const oldCallback = internal.callback;
  222031. start (0);
  222032. if (oldCallback != 0)
  222033. oldCallback->audioDeviceStopped();
  222034. }
  222035. String inputId, outputId;
  222036. private:
  222037. bool isOpen_, isStarted;
  222038. ALSAThread internal;
  222039. };
  222040. class ALSAAudioIODeviceType : public AudioIODeviceType
  222041. {
  222042. public:
  222043. ALSAAudioIODeviceType()
  222044. : AudioIODeviceType ("ALSA"),
  222045. hasScanned (false)
  222046. {
  222047. }
  222048. ~ALSAAudioIODeviceType()
  222049. {
  222050. }
  222051. void scanForDevices()
  222052. {
  222053. if (hasScanned)
  222054. return;
  222055. hasScanned = true;
  222056. inputNames.clear();
  222057. inputIds.clear();
  222058. outputNames.clear();
  222059. outputIds.clear();
  222060. /* void** hints = 0;
  222061. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222062. {
  222063. for (void** hint = hints; *hint != 0; ++hint)
  222064. {
  222065. const String name (getHint (*hint, "NAME"));
  222066. if (name.isNotEmpty())
  222067. {
  222068. const String ioid (getHint (*hint, "IOID"));
  222069. String desc (getHint (*hint, "DESC"));
  222070. if (desc.isEmpty())
  222071. desc = name;
  222072. desc = desc.replaceCharacters ("\n\r", " ");
  222073. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222074. if (ioid.isEmpty() || ioid == "Input")
  222075. {
  222076. inputNames.add (desc);
  222077. inputIds.add (name);
  222078. }
  222079. if (ioid.isEmpty() || ioid == "Output")
  222080. {
  222081. outputNames.add (desc);
  222082. outputIds.add (name);
  222083. }
  222084. }
  222085. }
  222086. snd_device_name_free_hint (hints);
  222087. }
  222088. */
  222089. snd_ctl_t* handle = 0;
  222090. snd_ctl_card_info_t* info = 0;
  222091. snd_ctl_card_info_alloca (&info);
  222092. int cardNum = -1;
  222093. while (outputIds.size() + inputIds.size() <= 32)
  222094. {
  222095. snd_card_next (&cardNum);
  222096. if (cardNum < 0)
  222097. break;
  222098. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222099. {
  222100. if (snd_ctl_card_info (handle, info) >= 0)
  222101. {
  222102. String cardId (snd_ctl_card_info_get_id (info));
  222103. if (cardId.removeCharacters ("0123456789").isEmpty())
  222104. cardId = String (cardNum);
  222105. int device = -1;
  222106. for (;;)
  222107. {
  222108. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222109. break;
  222110. String id, name;
  222111. id << "hw:" << cardId << ',' << device;
  222112. bool isInput, isOutput;
  222113. if (testDevice (id, isInput, isOutput))
  222114. {
  222115. name << snd_ctl_card_info_get_name (info);
  222116. if (name.isEmpty())
  222117. name = id;
  222118. if (isInput)
  222119. {
  222120. inputNames.add (name);
  222121. inputIds.add (id);
  222122. }
  222123. if (isOutput)
  222124. {
  222125. outputNames.add (name);
  222126. outputIds.add (id);
  222127. }
  222128. }
  222129. }
  222130. }
  222131. snd_ctl_close (handle);
  222132. }
  222133. }
  222134. inputNames.appendNumbersToDuplicates (false, true);
  222135. outputNames.appendNumbersToDuplicates (false, true);
  222136. }
  222137. const StringArray getDeviceNames (bool wantInputNames) const
  222138. {
  222139. jassert (hasScanned); // need to call scanForDevices() before doing this
  222140. return wantInputNames ? inputNames : outputNames;
  222141. }
  222142. int getDefaultDeviceIndex (bool forInput) const
  222143. {
  222144. jassert (hasScanned); // need to call scanForDevices() before doing this
  222145. return 0;
  222146. }
  222147. bool hasSeparateInputsAndOutputs() const { return true; }
  222148. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222149. {
  222150. jassert (hasScanned); // need to call scanForDevices() before doing this
  222151. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222152. if (d == 0)
  222153. return -1;
  222154. return asInput ? inputIds.indexOf (d->inputId)
  222155. : outputIds.indexOf (d->outputId);
  222156. }
  222157. AudioIODevice* createDevice (const String& outputDeviceName,
  222158. const String& inputDeviceName)
  222159. {
  222160. jassert (hasScanned); // need to call scanForDevices() before doing this
  222161. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222162. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222163. String deviceName (outputIndex >= 0 ? outputDeviceName
  222164. : inputDeviceName);
  222165. if (inputIndex >= 0 || outputIndex >= 0)
  222166. return new ALSAAudioIODevice (deviceName,
  222167. inputIds [inputIndex],
  222168. outputIds [outputIndex]);
  222169. return 0;
  222170. }
  222171. private:
  222172. StringArray inputNames, outputNames, inputIds, outputIds;
  222173. bool hasScanned;
  222174. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222175. {
  222176. unsigned int minChansOut = 0, maxChansOut = 0;
  222177. unsigned int minChansIn = 0, maxChansIn = 0;
  222178. Array <int> rates;
  222179. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222180. DBG ("ALSA device: " + id
  222181. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222182. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222183. + " rates=" + String (rates.size()));
  222184. isInput = maxChansIn > 0;
  222185. isOutput = maxChansOut > 0;
  222186. return (isInput || isOutput) && rates.size() > 0;
  222187. }
  222188. /*static const String getHint (void* hint, const char* type)
  222189. {
  222190. char* const n = snd_device_name_get_hint (hint, type);
  222191. const String s ((const char*) n);
  222192. free (n);
  222193. return s;
  222194. }*/
  222195. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222196. };
  222197. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222198. {
  222199. return new ALSAAudioIODeviceType();
  222200. }
  222201. #endif
  222202. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222203. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222204. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222205. // compiled on its own).
  222206. #ifdef JUCE_INCLUDED_FILE
  222207. #if JUCE_JACK
  222208. static void* juce_libjack_handle = 0;
  222209. void* juce_load_jack_function (const char* const name)
  222210. {
  222211. if (juce_libjack_handle == 0)
  222212. return 0;
  222213. return dlsym (juce_libjack_handle, name);
  222214. }
  222215. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222216. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222217. return_type fn_name argument_types { \
  222218. static fn_name##_ptr_t fn = 0; \
  222219. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222220. if (fn) return (*fn)arguments; \
  222221. else return 0; \
  222222. }
  222223. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222224. typedef void (*fn_name##_ptr_t)argument_types; \
  222225. void fn_name argument_types { \
  222226. static fn_name##_ptr_t fn = 0; \
  222227. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222228. if (fn) (*fn)arguments; \
  222229. }
  222230. 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));
  222231. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222232. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222233. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222234. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222235. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222236. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222237. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222238. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222239. 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));
  222240. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222241. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222242. 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));
  222243. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222244. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222245. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222246. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222247. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222248. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222249. #if JUCE_DEBUG
  222250. #define JACK_LOGGING_ENABLED 1
  222251. #endif
  222252. #if JACK_LOGGING_ENABLED
  222253. namespace
  222254. {
  222255. void jack_Log (const String& s)
  222256. {
  222257. std::cerr << s << std::endl;
  222258. }
  222259. void dumpJackErrorMessage (const jack_status_t status)
  222260. {
  222261. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222262. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222263. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222264. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222265. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222266. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222267. }
  222268. }
  222269. #else
  222270. #define dumpJackErrorMessage(a) {}
  222271. #define jack_Log(...) {}
  222272. #endif
  222273. #ifndef JUCE_JACK_CLIENT_NAME
  222274. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222275. #endif
  222276. class JackAudioIODevice : public AudioIODevice
  222277. {
  222278. public:
  222279. JackAudioIODevice (const String& deviceName,
  222280. const String& inputId_,
  222281. const String& outputId_)
  222282. : AudioIODevice (deviceName, "JACK"),
  222283. inputId (inputId_),
  222284. outputId (outputId_),
  222285. isOpen_ (false),
  222286. callback (0),
  222287. totalNumberOfInputChannels (0),
  222288. totalNumberOfOutputChannels (0)
  222289. {
  222290. jassert (deviceName.isNotEmpty());
  222291. jack_status_t status;
  222292. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222293. if (client == 0)
  222294. {
  222295. dumpJackErrorMessage (status);
  222296. }
  222297. else
  222298. {
  222299. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222300. // open input ports
  222301. const StringArray inputChannels (getInputChannelNames());
  222302. for (int i = 0; i < inputChannels.size(); i++)
  222303. {
  222304. String inputName;
  222305. inputName << "in_" << ++totalNumberOfInputChannels;
  222306. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222307. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222308. }
  222309. // open output ports
  222310. const StringArray outputChannels (getOutputChannelNames());
  222311. for (int i = 0; i < outputChannels.size (); i++)
  222312. {
  222313. String outputName;
  222314. outputName << "out_" << ++totalNumberOfOutputChannels;
  222315. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222316. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222317. }
  222318. inChans.calloc (totalNumberOfInputChannels + 2);
  222319. outChans.calloc (totalNumberOfOutputChannels + 2);
  222320. }
  222321. }
  222322. ~JackAudioIODevice()
  222323. {
  222324. close();
  222325. if (client != 0)
  222326. {
  222327. JUCE_NAMESPACE::jack_client_close (client);
  222328. client = 0;
  222329. }
  222330. }
  222331. const StringArray getChannelNames (bool forInput) const
  222332. {
  222333. StringArray names;
  222334. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222335. forInput ? JackPortIsInput : JackPortIsOutput);
  222336. if (ports != 0)
  222337. {
  222338. int j = 0;
  222339. while (ports[j] != 0)
  222340. {
  222341. const String portName (ports [j++]);
  222342. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222343. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222344. }
  222345. free (ports);
  222346. }
  222347. return names;
  222348. }
  222349. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222350. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222351. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222352. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222353. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222354. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222355. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222356. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222357. double sampleRate, int bufferSizeSamples)
  222358. {
  222359. if (client == 0)
  222360. {
  222361. lastError = "No JACK client running";
  222362. return lastError;
  222363. }
  222364. lastError = String::empty;
  222365. close();
  222366. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222367. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222368. JUCE_NAMESPACE::jack_activate (client);
  222369. isOpen_ = true;
  222370. if (! inputChannels.isZero())
  222371. {
  222372. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222373. if (ports != 0)
  222374. {
  222375. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222376. for (int i = 0; i < numInputChannels; ++i)
  222377. {
  222378. const String portName (ports[i]);
  222379. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222380. {
  222381. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222382. if (error != 0)
  222383. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222384. }
  222385. }
  222386. free (ports);
  222387. }
  222388. }
  222389. if (! outputChannels.isZero())
  222390. {
  222391. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222392. if (ports != 0)
  222393. {
  222394. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222395. for (int i = 0; i < numOutputChannels; ++i)
  222396. {
  222397. const String portName (ports[i]);
  222398. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222399. {
  222400. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222401. if (error != 0)
  222402. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222403. }
  222404. }
  222405. free (ports);
  222406. }
  222407. }
  222408. return lastError;
  222409. }
  222410. void close()
  222411. {
  222412. stop();
  222413. if (client != 0)
  222414. {
  222415. JUCE_NAMESPACE::jack_deactivate (client);
  222416. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222417. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222418. }
  222419. isOpen_ = false;
  222420. }
  222421. void start (AudioIODeviceCallback* newCallback)
  222422. {
  222423. if (isOpen_ && newCallback != callback)
  222424. {
  222425. if (newCallback != 0)
  222426. newCallback->audioDeviceAboutToStart (this);
  222427. AudioIODeviceCallback* const oldCallback = callback;
  222428. {
  222429. const ScopedLock sl (callbackLock);
  222430. callback = newCallback;
  222431. }
  222432. if (oldCallback != 0)
  222433. oldCallback->audioDeviceStopped();
  222434. }
  222435. }
  222436. void stop()
  222437. {
  222438. start (0);
  222439. }
  222440. bool isOpen() { return isOpen_; }
  222441. bool isPlaying() { return callback != 0; }
  222442. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222443. double getCurrentSampleRate() { return getSampleRate (0); }
  222444. int getCurrentBitDepth() { return 32; }
  222445. const String getLastError() { return lastError; }
  222446. const BigInteger getActiveOutputChannels() const
  222447. {
  222448. BigInteger outputBits;
  222449. for (int i = 0; i < outputPorts.size(); i++)
  222450. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222451. outputBits.setBit (i);
  222452. return outputBits;
  222453. }
  222454. const BigInteger getActiveInputChannels() const
  222455. {
  222456. BigInteger inputBits;
  222457. for (int i = 0; i < inputPorts.size(); i++)
  222458. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222459. inputBits.setBit (i);
  222460. return inputBits;
  222461. }
  222462. int getOutputLatencyInSamples()
  222463. {
  222464. int latency = 0;
  222465. for (int i = 0; i < outputPorts.size(); i++)
  222466. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222467. return latency;
  222468. }
  222469. int getInputLatencyInSamples()
  222470. {
  222471. int latency = 0;
  222472. for (int i = 0; i < inputPorts.size(); i++)
  222473. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222474. return latency;
  222475. }
  222476. String inputId, outputId;
  222477. private:
  222478. void process (const int numSamples)
  222479. {
  222480. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222481. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222482. {
  222483. jack_default_audio_sample_t* in
  222484. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222485. if (in != 0)
  222486. inChans [numActiveInChans++] = (float*) in;
  222487. }
  222488. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222489. {
  222490. jack_default_audio_sample_t* out
  222491. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222492. if (out != 0)
  222493. outChans [numActiveOutChans++] = (float*) out;
  222494. }
  222495. const ScopedLock sl (callbackLock);
  222496. if (callback != 0)
  222497. {
  222498. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222499. outChans, numActiveOutChans, numSamples);
  222500. }
  222501. else
  222502. {
  222503. for (i = 0; i < numActiveOutChans; ++i)
  222504. zeromem (outChans[i], sizeof (float) * numSamples);
  222505. }
  222506. }
  222507. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222508. {
  222509. if (callbackArgument != 0)
  222510. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222511. return 0;
  222512. }
  222513. static void threadInitCallback (void* callbackArgument)
  222514. {
  222515. jack_Log ("JackAudioIODevice::initialise");
  222516. }
  222517. static void shutdownCallback (void* callbackArgument)
  222518. {
  222519. jack_Log ("JackAudioIODevice::shutdown");
  222520. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222521. if (device != 0)
  222522. {
  222523. device->client = 0;
  222524. device->close();
  222525. }
  222526. }
  222527. static void errorCallback (const char* msg)
  222528. {
  222529. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222530. }
  222531. bool isOpen_;
  222532. jack_client_t* client;
  222533. String lastError;
  222534. AudioIODeviceCallback* callback;
  222535. CriticalSection callbackLock;
  222536. HeapBlock <float*> inChans, outChans;
  222537. int totalNumberOfInputChannels;
  222538. int totalNumberOfOutputChannels;
  222539. Array<void*> inputPorts, outputPorts;
  222540. };
  222541. class JackAudioIODeviceType : public AudioIODeviceType
  222542. {
  222543. public:
  222544. JackAudioIODeviceType()
  222545. : AudioIODeviceType ("JACK"),
  222546. hasScanned (false)
  222547. {
  222548. }
  222549. ~JackAudioIODeviceType()
  222550. {
  222551. }
  222552. void scanForDevices()
  222553. {
  222554. hasScanned = true;
  222555. inputNames.clear();
  222556. inputIds.clear();
  222557. outputNames.clear();
  222558. outputIds.clear();
  222559. if (juce_libjack_handle == 0)
  222560. {
  222561. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222562. if (juce_libjack_handle == 0)
  222563. return;
  222564. }
  222565. // open a dummy client
  222566. jack_status_t status;
  222567. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222568. if (client == 0)
  222569. {
  222570. dumpJackErrorMessage (status);
  222571. }
  222572. else
  222573. {
  222574. // scan for output devices
  222575. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222576. if (ports != 0)
  222577. {
  222578. int j = 0;
  222579. while (ports[j] != 0)
  222580. {
  222581. String clientName (ports[j]);
  222582. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222583. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222584. && ! inputNames.contains (clientName))
  222585. {
  222586. inputNames.add (clientName);
  222587. inputIds.add (ports [j]);
  222588. }
  222589. ++j;
  222590. }
  222591. free (ports);
  222592. }
  222593. // scan for input devices
  222594. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222595. if (ports != 0)
  222596. {
  222597. int j = 0;
  222598. while (ports[j] != 0)
  222599. {
  222600. String clientName (ports[j]);
  222601. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222602. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222603. && ! outputNames.contains (clientName))
  222604. {
  222605. outputNames.add (clientName);
  222606. outputIds.add (ports [j]);
  222607. }
  222608. ++j;
  222609. }
  222610. free (ports);
  222611. }
  222612. JUCE_NAMESPACE::jack_client_close (client);
  222613. }
  222614. }
  222615. const StringArray getDeviceNames (bool wantInputNames) const
  222616. {
  222617. jassert (hasScanned); // need to call scanForDevices() before doing this
  222618. return wantInputNames ? inputNames : outputNames;
  222619. }
  222620. int getDefaultDeviceIndex (bool forInput) const
  222621. {
  222622. jassert (hasScanned); // need to call scanForDevices() before doing this
  222623. return 0;
  222624. }
  222625. bool hasSeparateInputsAndOutputs() const { return true; }
  222626. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222627. {
  222628. jassert (hasScanned); // need to call scanForDevices() before doing this
  222629. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222630. if (d == 0)
  222631. return -1;
  222632. return asInput ? inputIds.indexOf (d->inputId)
  222633. : outputIds.indexOf (d->outputId);
  222634. }
  222635. AudioIODevice* createDevice (const String& outputDeviceName,
  222636. const String& inputDeviceName)
  222637. {
  222638. jassert (hasScanned); // need to call scanForDevices() before doing this
  222639. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222640. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222641. if (inputIndex >= 0 || outputIndex >= 0)
  222642. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222643. : inputDeviceName,
  222644. inputIds [inputIndex],
  222645. outputIds [outputIndex]);
  222646. return 0;
  222647. }
  222648. private:
  222649. StringArray inputNames, outputNames, inputIds, outputIds;
  222650. bool hasScanned;
  222651. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  222652. };
  222653. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222654. {
  222655. return new JackAudioIODeviceType();
  222656. }
  222657. #else // if JACK is turned off..
  222658. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222659. #endif
  222660. #endif
  222661. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222662. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222663. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222664. // compiled on its own).
  222665. #if JUCE_INCLUDED_FILE
  222666. #if JUCE_ALSA
  222667. namespace
  222668. {
  222669. snd_seq_t* iterateMidiDevices (const bool forInput,
  222670. StringArray& deviceNamesFound,
  222671. const int deviceIndexToOpen)
  222672. {
  222673. snd_seq_t* returnedHandle = 0;
  222674. snd_seq_t* seqHandle;
  222675. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222676. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222677. {
  222678. snd_seq_system_info_t* systemInfo;
  222679. snd_seq_client_info_t* clientInfo;
  222680. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222681. {
  222682. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222683. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222684. {
  222685. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222686. while (--numClients >= 0 && returnedHandle == 0)
  222687. {
  222688. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222689. {
  222690. snd_seq_port_info_t* portInfo;
  222691. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222692. {
  222693. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222694. const int client = snd_seq_client_info_get_client (clientInfo);
  222695. snd_seq_port_info_set_client (portInfo, client);
  222696. snd_seq_port_info_set_port (portInfo, -1);
  222697. while (--numPorts >= 0)
  222698. {
  222699. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222700. && (snd_seq_port_info_get_capability (portInfo)
  222701. & (forInput ? SND_SEQ_PORT_CAP_READ
  222702. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222703. {
  222704. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222705. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222706. {
  222707. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222708. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222709. if (sourcePort != -1)
  222710. {
  222711. snd_seq_set_client_name (seqHandle,
  222712. forInput ? "Juce Midi Input"
  222713. : "Juce Midi Output");
  222714. const int portId
  222715. = snd_seq_create_simple_port (seqHandle,
  222716. forInput ? "Juce Midi In Port"
  222717. : "Juce Midi Out Port",
  222718. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222719. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222720. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222721. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222722. returnedHandle = seqHandle;
  222723. }
  222724. }
  222725. }
  222726. }
  222727. snd_seq_port_info_free (portInfo);
  222728. }
  222729. }
  222730. }
  222731. snd_seq_client_info_free (clientInfo);
  222732. }
  222733. snd_seq_system_info_free (systemInfo);
  222734. }
  222735. if (returnedHandle == 0)
  222736. snd_seq_close (seqHandle);
  222737. }
  222738. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222739. return returnedHandle;
  222740. }
  222741. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  222742. {
  222743. snd_seq_t* seqHandle = 0;
  222744. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222745. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222746. {
  222747. snd_seq_set_client_name (seqHandle,
  222748. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222749. const int portId
  222750. = snd_seq_create_simple_port (seqHandle,
  222751. forInput ? "in"
  222752. : "out",
  222753. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222754. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222755. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222756. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222757. if (portId < 0)
  222758. {
  222759. snd_seq_close (seqHandle);
  222760. seqHandle = 0;
  222761. }
  222762. }
  222763. return seqHandle;
  222764. }
  222765. }
  222766. class MidiOutputDevice
  222767. {
  222768. public:
  222769. MidiOutputDevice (MidiOutput* const midiOutput_,
  222770. snd_seq_t* const seqHandle_)
  222771. :
  222772. midiOutput (midiOutput_),
  222773. seqHandle (seqHandle_),
  222774. maxEventSize (16 * 1024)
  222775. {
  222776. jassert (seqHandle != 0 && midiOutput != 0);
  222777. snd_midi_event_new (maxEventSize, &midiParser);
  222778. }
  222779. ~MidiOutputDevice()
  222780. {
  222781. snd_midi_event_free (midiParser);
  222782. snd_seq_close (seqHandle);
  222783. }
  222784. void sendMessageNow (const MidiMessage& message)
  222785. {
  222786. if (message.getRawDataSize() > maxEventSize)
  222787. {
  222788. maxEventSize = message.getRawDataSize();
  222789. snd_midi_event_free (midiParser);
  222790. snd_midi_event_new (maxEventSize, &midiParser);
  222791. }
  222792. snd_seq_event_t event;
  222793. snd_seq_ev_clear (&event);
  222794. snd_midi_event_encode (midiParser,
  222795. message.getRawData(),
  222796. message.getRawDataSize(),
  222797. &event);
  222798. snd_midi_event_reset_encode (midiParser);
  222799. snd_seq_ev_set_source (&event, 0);
  222800. snd_seq_ev_set_subs (&event);
  222801. snd_seq_ev_set_direct (&event);
  222802. snd_seq_event_output (seqHandle, &event);
  222803. snd_seq_drain_output (seqHandle);
  222804. }
  222805. private:
  222806. MidiOutput* const midiOutput;
  222807. snd_seq_t* const seqHandle;
  222808. snd_midi_event_t* midiParser;
  222809. int maxEventSize;
  222810. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  222811. };
  222812. const StringArray MidiOutput::getDevices()
  222813. {
  222814. StringArray devices;
  222815. iterateMidiDevices (false, devices, -1);
  222816. return devices;
  222817. }
  222818. int MidiOutput::getDefaultDeviceIndex()
  222819. {
  222820. return 0;
  222821. }
  222822. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222823. {
  222824. MidiOutput* newDevice = 0;
  222825. StringArray devices;
  222826. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  222827. if (handle != 0)
  222828. {
  222829. newDevice = new MidiOutput();
  222830. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222831. }
  222832. return newDevice;
  222833. }
  222834. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222835. {
  222836. MidiOutput* newDevice = 0;
  222837. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  222838. if (handle != 0)
  222839. {
  222840. newDevice = new MidiOutput();
  222841. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222842. }
  222843. return newDevice;
  222844. }
  222845. MidiOutput::~MidiOutput()
  222846. {
  222847. delete static_cast <MidiOutputDevice*> (internal);
  222848. }
  222849. void MidiOutput::reset()
  222850. {
  222851. }
  222852. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222853. {
  222854. return false;
  222855. }
  222856. void MidiOutput::setVolume (float leftVol, float rightVol)
  222857. {
  222858. }
  222859. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222860. {
  222861. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  222862. }
  222863. class MidiInputThread : public Thread
  222864. {
  222865. public:
  222866. MidiInputThread (MidiInput* const midiInput_,
  222867. snd_seq_t* const seqHandle_,
  222868. MidiInputCallback* const callback_)
  222869. : Thread ("Juce MIDI Input"),
  222870. midiInput (midiInput_),
  222871. seqHandle (seqHandle_),
  222872. callback (callback_)
  222873. {
  222874. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222875. }
  222876. ~MidiInputThread()
  222877. {
  222878. snd_seq_close (seqHandle);
  222879. }
  222880. void run()
  222881. {
  222882. const int maxEventSize = 16 * 1024;
  222883. snd_midi_event_t* midiParser;
  222884. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222885. {
  222886. HeapBlock <uint8> buffer (maxEventSize);
  222887. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222888. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222889. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222890. while (! threadShouldExit())
  222891. {
  222892. if (poll (pfd, numPfds, 500) > 0)
  222893. {
  222894. snd_seq_event_t* inputEvent = 0;
  222895. snd_seq_nonblock (seqHandle, 1);
  222896. do
  222897. {
  222898. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222899. {
  222900. // xxx what about SYSEXes that are too big for the buffer?
  222901. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222902. snd_midi_event_reset_decode (midiParser);
  222903. if (numBytes > 0)
  222904. {
  222905. const MidiMessage message ((const uint8*) buffer,
  222906. numBytes,
  222907. Time::getMillisecondCounter() * 0.001);
  222908. callback->handleIncomingMidiMessage (midiInput, message);
  222909. }
  222910. snd_seq_free_event (inputEvent);
  222911. }
  222912. }
  222913. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222914. snd_seq_free_event (inputEvent);
  222915. }
  222916. }
  222917. snd_midi_event_free (midiParser);
  222918. }
  222919. };
  222920. private:
  222921. MidiInput* const midiInput;
  222922. snd_seq_t* const seqHandle;
  222923. MidiInputCallback* const callback;
  222924. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  222925. };
  222926. MidiInput::MidiInput (const String& name_)
  222927. : name (name_),
  222928. internal (0)
  222929. {
  222930. }
  222931. MidiInput::~MidiInput()
  222932. {
  222933. stop();
  222934. delete static_cast <MidiInputThread*> (internal);
  222935. }
  222936. void MidiInput::start()
  222937. {
  222938. static_cast <MidiInputThread*> (internal)->startThread();
  222939. }
  222940. void MidiInput::stop()
  222941. {
  222942. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  222943. }
  222944. int MidiInput::getDefaultDeviceIndex()
  222945. {
  222946. return 0;
  222947. }
  222948. const StringArray MidiInput::getDevices()
  222949. {
  222950. StringArray devices;
  222951. iterateMidiDevices (true, devices, -1);
  222952. return devices;
  222953. }
  222954. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222955. {
  222956. MidiInput* newDevice = 0;
  222957. StringArray devices;
  222958. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  222959. if (handle != 0)
  222960. {
  222961. newDevice = new MidiInput (devices [deviceIndex]);
  222962. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222963. }
  222964. return newDevice;
  222965. }
  222966. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222967. {
  222968. MidiInput* newDevice = 0;
  222969. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  222970. if (handle != 0)
  222971. {
  222972. newDevice = new MidiInput (deviceName);
  222973. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222974. }
  222975. return newDevice;
  222976. }
  222977. #else
  222978. // (These are just stub functions if ALSA is unavailable...)
  222979. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222980. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222981. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222982. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222983. MidiOutput::~MidiOutput() {}
  222984. void MidiOutput::reset() {}
  222985. bool MidiOutput::getVolume (float&, float&) { return false; }
  222986. void MidiOutput::setVolume (float, float) {}
  222987. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222988. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222989. MidiInput::~MidiInput() {}
  222990. void MidiInput::start() {}
  222991. void MidiInput::stop() {}
  222992. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222993. const StringArray MidiInput::getDevices() { return StringArray(); }
  222994. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222995. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222996. #endif
  222997. #endif
  222998. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222999. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223000. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223001. // compiled on its own).
  223002. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223003. AudioCDReader::AudioCDReader()
  223004. : AudioFormatReader (0, "CD Audio")
  223005. {
  223006. }
  223007. const StringArray AudioCDReader::getAvailableCDNames()
  223008. {
  223009. StringArray names;
  223010. return names;
  223011. }
  223012. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223013. {
  223014. return 0;
  223015. }
  223016. AudioCDReader::~AudioCDReader()
  223017. {
  223018. }
  223019. void AudioCDReader::refreshTrackLengths()
  223020. {
  223021. }
  223022. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223023. int64 startSampleInFile, int numSamples)
  223024. {
  223025. return false;
  223026. }
  223027. bool AudioCDReader::isCDStillPresent() const
  223028. {
  223029. return false;
  223030. }
  223031. bool AudioCDReader::isTrackAudio (int trackNum) const
  223032. {
  223033. return false;
  223034. }
  223035. void AudioCDReader::enableIndexScanning (bool b)
  223036. {
  223037. }
  223038. int AudioCDReader::getLastIndex() const
  223039. {
  223040. return 0;
  223041. }
  223042. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223043. {
  223044. return Array<int>();
  223045. }
  223046. #endif
  223047. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223048. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223049. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223050. // compiled on its own).
  223051. #if JUCE_INCLUDED_FILE
  223052. void FileChooser::showPlatformDialog (Array<File>& results,
  223053. const String& title,
  223054. const File& file,
  223055. const String& filters,
  223056. bool isDirectory,
  223057. bool selectsFiles,
  223058. bool isSave,
  223059. bool warnAboutOverwritingExistingFiles,
  223060. bool selectMultipleFiles,
  223061. FilePreviewComponent* previewComponent)
  223062. {
  223063. const String separator (":");
  223064. String command ("zenity --file-selection");
  223065. if (title.isNotEmpty())
  223066. command << " --title=\"" << title << "\"";
  223067. if (file != File::nonexistent)
  223068. command << " --filename=\"" << file.getFullPathName () << "\"";
  223069. if (isDirectory)
  223070. command << " --directory";
  223071. if (isSave)
  223072. command << " --save";
  223073. if (selectMultipleFiles)
  223074. command << " --multiple --separator=\"" << separator << "\"";
  223075. command << " 2>&1";
  223076. MemoryOutputStream result;
  223077. int status = -1;
  223078. FILE* stream = popen (command.toUTF8(), "r");
  223079. if (stream != 0)
  223080. {
  223081. for (;;)
  223082. {
  223083. char buffer [1024];
  223084. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223085. if (bytesRead <= 0)
  223086. break;
  223087. result.write (buffer, bytesRead);
  223088. }
  223089. status = pclose (stream);
  223090. }
  223091. if (status == 0)
  223092. {
  223093. StringArray tokens;
  223094. if (selectMultipleFiles)
  223095. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223096. else
  223097. tokens.add (result.toUTF8());
  223098. for (int i = 0; i < tokens.size(); i++)
  223099. results.add (File (tokens[i]));
  223100. return;
  223101. }
  223102. //xxx ain't got one!
  223103. jassertfalse;
  223104. }
  223105. #endif
  223106. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223107. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223108. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223109. // compiled on its own).
  223110. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223111. /*
  223112. Sorry.. This class isn't implemented on Linux!
  223113. */
  223114. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223115. : browser (0),
  223116. blankPageShown (false),
  223117. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223118. {
  223119. setOpaque (true);
  223120. }
  223121. WebBrowserComponent::~WebBrowserComponent()
  223122. {
  223123. }
  223124. void WebBrowserComponent::goToURL (const String& url,
  223125. const StringArray* headers,
  223126. const MemoryBlock* postData)
  223127. {
  223128. lastURL = url;
  223129. lastHeaders.clear();
  223130. if (headers != 0)
  223131. lastHeaders = *headers;
  223132. lastPostData.setSize (0);
  223133. if (postData != 0)
  223134. lastPostData = *postData;
  223135. blankPageShown = false;
  223136. }
  223137. void WebBrowserComponent::stop()
  223138. {
  223139. }
  223140. void WebBrowserComponent::goBack()
  223141. {
  223142. lastURL = String::empty;
  223143. blankPageShown = false;
  223144. }
  223145. void WebBrowserComponent::goForward()
  223146. {
  223147. lastURL = String::empty;
  223148. }
  223149. void WebBrowserComponent::refresh()
  223150. {
  223151. }
  223152. void WebBrowserComponent::paint (Graphics& g)
  223153. {
  223154. g.fillAll (Colours::white);
  223155. }
  223156. void WebBrowserComponent::checkWindowAssociation()
  223157. {
  223158. }
  223159. void WebBrowserComponent::reloadLastURL()
  223160. {
  223161. if (lastURL.isNotEmpty())
  223162. {
  223163. goToURL (lastURL, &lastHeaders, &lastPostData);
  223164. lastURL = String::empty;
  223165. }
  223166. }
  223167. void WebBrowserComponent::parentHierarchyChanged()
  223168. {
  223169. checkWindowAssociation();
  223170. }
  223171. void WebBrowserComponent::resized()
  223172. {
  223173. }
  223174. void WebBrowserComponent::visibilityChanged()
  223175. {
  223176. checkWindowAssociation();
  223177. }
  223178. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223179. {
  223180. return true;
  223181. }
  223182. #endif
  223183. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223184. #endif
  223185. END_JUCE_NAMESPACE
  223186. #endif
  223187. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223188. #endif
  223189. #if JUCE_MAC || JUCE_IPHONE
  223190. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223191. /*
  223192. This file wraps together all the mac-specific code, so that
  223193. we can include all the native headers just once, and compile all our
  223194. platform-specific stuff in one big lump, keeping it out of the way of
  223195. the rest of the codebase.
  223196. */
  223197. #if JUCE_MAC || JUCE_IOS
  223198. #undef JUCE_BUILD_NATIVE
  223199. #define JUCE_BUILD_NATIVE 1
  223200. BEGIN_JUCE_NAMESPACE
  223201. #undef Point
  223202. namespace
  223203. {
  223204. template <class RectType>
  223205. const Rectangle<int> convertToRectInt (const RectType& r)
  223206. {
  223207. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223208. }
  223209. template <class RectType>
  223210. const Rectangle<float> convertToRectFloat (const RectType& r)
  223211. {
  223212. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223213. }
  223214. template <class RectType>
  223215. CGRect convertToCGRect (const RectType& r)
  223216. {
  223217. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223218. }
  223219. }
  223220. class MessageQueue
  223221. {
  223222. public:
  223223. MessageQueue()
  223224. {
  223225. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
  223226. runLoop = CFRunLoopGetMain();
  223227. #else
  223228. runLoop = CFRunLoopGetCurrent();
  223229. #endif
  223230. CFRunLoopSourceContext sourceContext;
  223231. zerostruct (sourceContext);
  223232. sourceContext.info = this;
  223233. sourceContext.perform = runLoopSourceCallback;
  223234. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223235. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223236. }
  223237. ~MessageQueue()
  223238. {
  223239. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223240. CFRunLoopSourceInvalidate (runLoopSource);
  223241. CFRelease (runLoopSource);
  223242. }
  223243. void post (Message* const message)
  223244. {
  223245. messages.add (message);
  223246. CFRunLoopSourceSignal (runLoopSource);
  223247. CFRunLoopWakeUp (runLoop);
  223248. }
  223249. private:
  223250. ReferenceCountedArray <Message, CriticalSection> messages;
  223251. CriticalSection lock;
  223252. CFRunLoopRef runLoop;
  223253. CFRunLoopSourceRef runLoopSource;
  223254. bool deliverNextMessage()
  223255. {
  223256. const Message::Ptr nextMessage (messages.removeAndReturn (0));
  223257. if (nextMessage == 0)
  223258. return false;
  223259. const ScopedAutoReleasePool pool;
  223260. MessageManager::getInstance()->deliverMessage (nextMessage);
  223261. return true;
  223262. }
  223263. void runLoopCallback()
  223264. {
  223265. for (int i = 4; --i >= 0;)
  223266. if (! deliverNextMessage())
  223267. return;
  223268. CFRunLoopSourceSignal (runLoopSource);
  223269. CFRunLoopWakeUp (runLoop);
  223270. }
  223271. static void runLoopSourceCallback (void* info)
  223272. {
  223273. static_cast <MessageQueue*> (info)->runLoopCallback();
  223274. }
  223275. };
  223276. #define JUCE_INCLUDED_FILE 1
  223277. // Now include the actual code files..
  223278. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223279. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223280. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223281. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223282. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223283. actually calling into a similarly named class in the other module's address space.
  223284. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223285. have unique names, and should avoid this problem.
  223286. If you're using the amalgamated version, you can just set this macro to something unique before
  223287. you include juce_amalgamated.cpp.
  223288. */
  223289. #ifndef JUCE_ObjCExtraSuffix
  223290. #define JUCE_ObjCExtraSuffix 3
  223291. #endif
  223292. #ifndef DOXYGEN
  223293. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223294. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223295. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223296. #endif
  223297. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223298. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223299. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223300. // compiled on its own).
  223301. #if JUCE_INCLUDED_FILE
  223302. namespace
  223303. {
  223304. const String nsStringToJuce (NSString* s)
  223305. {
  223306. return String::fromUTF8 ([s UTF8String]);
  223307. }
  223308. NSString* juceStringToNS (const String& s)
  223309. {
  223310. return [NSString stringWithUTF8String: s.toUTF8()];
  223311. }
  223312. const String convertUTF16ToString (const UniChar* utf16)
  223313. {
  223314. String s;
  223315. while (*utf16 != 0)
  223316. s += (juce_wchar) *utf16++;
  223317. return s;
  223318. }
  223319. }
  223320. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223321. {
  223322. String result;
  223323. if (cfString != 0)
  223324. {
  223325. CFRange range = { 0, CFStringGetLength (cfString) };
  223326. HeapBlock <UniChar> u (range.length + 1);
  223327. CFStringGetCharacters (cfString, range, u);
  223328. u[range.length] = 0;
  223329. result = convertUTF16ToString (u);
  223330. }
  223331. return result;
  223332. }
  223333. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223334. {
  223335. const int len = s.length();
  223336. HeapBlock <UniChar> temp (len + 2);
  223337. for (int i = 0; i <= len; ++i)
  223338. temp[i] = s[i];
  223339. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223340. }
  223341. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223342. {
  223343. #if JUCE_IOS
  223344. const ScopedAutoReleasePool pool;
  223345. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223346. #else
  223347. UnicodeMapping map;
  223348. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223349. kUnicodeNoSubset,
  223350. kTextEncodingDefaultFormat);
  223351. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223352. kUnicodeCanonicalCompVariant,
  223353. kTextEncodingDefaultFormat);
  223354. map.mappingVersion = kUnicodeUseLatestMapping;
  223355. UnicodeToTextInfo conversionInfo = 0;
  223356. String result;
  223357. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223358. {
  223359. const int len = s.length();
  223360. HeapBlock <UniChar> tempIn, tempOut;
  223361. tempIn.calloc (len + 2);
  223362. tempOut.calloc (len + 2);
  223363. for (int i = 0; i <= len; ++i)
  223364. tempIn[i] = s[i];
  223365. ByteCount bytesRead = 0;
  223366. ByteCount outputBufferSize = 0;
  223367. if (ConvertFromUnicodeToText (conversionInfo,
  223368. len * sizeof (UniChar), tempIn,
  223369. kUnicodeDefaultDirectionMask,
  223370. 0, 0, 0, 0,
  223371. len * sizeof (UniChar), &bytesRead,
  223372. &outputBufferSize, tempOut) == noErr)
  223373. {
  223374. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  223375. juce_wchar* t = result;
  223376. unsigned int i;
  223377. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  223378. t[i] = (juce_wchar) tempOut[i];
  223379. t[i] = 0;
  223380. }
  223381. DisposeUnicodeToTextInfo (&conversionInfo);
  223382. }
  223383. return result;
  223384. #endif
  223385. }
  223386. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223387. void SystemClipboard::copyTextToClipboard (const String& text)
  223388. {
  223389. #if JUCE_IOS
  223390. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223391. forPasteboardType: @"public.text"];
  223392. #else
  223393. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223394. owner: nil];
  223395. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223396. forType: NSStringPboardType];
  223397. #endif
  223398. }
  223399. const String SystemClipboard::getTextFromClipboard()
  223400. {
  223401. #if JUCE_IOS
  223402. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223403. #else
  223404. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223405. #endif
  223406. return text == 0 ? String::empty
  223407. : nsStringToJuce (text);
  223408. }
  223409. #endif
  223410. #endif
  223411. /*** End of inlined file: juce_mac_Strings.mm ***/
  223412. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223413. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223414. // compiled on its own).
  223415. #if JUCE_INCLUDED_FILE
  223416. namespace SystemStatsHelpers
  223417. {
  223418. static int64 highResTimerFrequency = 0;
  223419. static double highResTimerToMillisecRatio = 0;
  223420. #if JUCE_INTEL
  223421. void doCPUID (uint32& a, uint32& b, uint32& c, uint32& d, uint32 type)
  223422. {
  223423. uint32 la = a, lb = b, lc = c, ld = d;
  223424. asm ("mov %%ebx, %%esi \n\t"
  223425. "cpuid \n\t"
  223426. "xchg %%esi, %%ebx"
  223427. : "=a" (la), "=S" (lb), "=c" (lc), "=d" (ld) : "a" (type)
  223428. #if JUCE_64BIT
  223429. , "b" (lb), "c" (lc), "d" (ld)
  223430. #endif
  223431. );
  223432. a = la; b = lb; c = lc; d = ld;
  223433. }
  223434. #endif
  223435. }
  223436. void SystemStats::initialiseStats()
  223437. {
  223438. using namespace SystemStatsHelpers;
  223439. static bool initialised = false;
  223440. if (! initialised)
  223441. {
  223442. initialised = true;
  223443. #if JUCE_MAC
  223444. [NSApplication sharedApplication];
  223445. #endif
  223446. #if JUCE_INTEL
  223447. uint32 familyModel = 0, extFeatures = 0, features = 0, dummy = 0;
  223448. doCPUID (familyModel, extFeatures, dummy, features, 1);
  223449. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223450. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223451. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223452. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223453. #else
  223454. cpuFlags.hasMMX = false;
  223455. cpuFlags.hasSSE = false;
  223456. cpuFlags.hasSSE2 = false;
  223457. cpuFlags.has3DNow = false;
  223458. #endif
  223459. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223460. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223461. #else
  223462. cpuFlags.numCpus = (int) MPProcessors();
  223463. #endif
  223464. mach_timebase_info_data_t timebase;
  223465. (void) mach_timebase_info (&timebase);
  223466. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223467. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223468. String s (SystemStats::getJUCEVersion());
  223469. rlimit lim;
  223470. getrlimit (RLIMIT_NOFILE, &lim);
  223471. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223472. setrlimit (RLIMIT_NOFILE, &lim);
  223473. }
  223474. }
  223475. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223476. {
  223477. return MacOSX;
  223478. }
  223479. const String SystemStats::getOperatingSystemName()
  223480. {
  223481. return "Mac OS X";
  223482. }
  223483. #if ! JUCE_IOS
  223484. int PlatformUtilities::getOSXMinorVersionNumber()
  223485. {
  223486. SInt32 versionMinor = 0;
  223487. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223488. (void) err;
  223489. jassert (err == noErr);
  223490. return (int) versionMinor;
  223491. }
  223492. #endif
  223493. bool SystemStats::isOperatingSystem64Bit()
  223494. {
  223495. #if JUCE_IOS
  223496. return false;
  223497. #elif JUCE_64BIT
  223498. return true;
  223499. #else
  223500. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223501. #endif
  223502. }
  223503. int SystemStats::getMemorySizeInMegabytes()
  223504. {
  223505. uint64 mem = 0;
  223506. size_t memSize = sizeof (mem);
  223507. int mib[] = { CTL_HW, HW_MEMSIZE };
  223508. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223509. return (int) (mem / (1024 * 1024));
  223510. }
  223511. const String SystemStats::getCpuVendor()
  223512. {
  223513. #if JUCE_INTEL
  223514. uint32 dummy = 0;
  223515. uint32 vendor[4];
  223516. zerostruct (vendor);
  223517. SystemStatsHelpers::doCPUID (dummy, vendor[0], vendor[2], vendor[1], 0);
  223518. return String (reinterpret_cast <const char*> (vendor), 12);
  223519. #else
  223520. return String::empty;
  223521. #endif
  223522. }
  223523. int SystemStats::getCpuSpeedInMegaherz()
  223524. {
  223525. uint64 speedHz = 0;
  223526. size_t speedSize = sizeof (speedHz);
  223527. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223528. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223529. #if JUCE_BIG_ENDIAN
  223530. if (speedSize == 4)
  223531. speedHz >>= 32;
  223532. #endif
  223533. return (int) (speedHz / 1000000);
  223534. }
  223535. const String SystemStats::getLogonName()
  223536. {
  223537. return nsStringToJuce (NSUserName());
  223538. }
  223539. const String SystemStats::getFullUserName()
  223540. {
  223541. return nsStringToJuce (NSFullUserName());
  223542. }
  223543. uint32 juce_millisecondsSinceStartup() throw()
  223544. {
  223545. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223546. }
  223547. double Time::getMillisecondCounterHiRes() throw()
  223548. {
  223549. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223550. }
  223551. int64 Time::getHighResolutionTicks() throw()
  223552. {
  223553. return (int64) mach_absolute_time();
  223554. }
  223555. int64 Time::getHighResolutionTicksPerSecond() throw()
  223556. {
  223557. return SystemStatsHelpers::highResTimerFrequency;
  223558. }
  223559. bool Time::setSystemTimeToThisTime() const
  223560. {
  223561. jassertfalse;
  223562. return false;
  223563. }
  223564. int SystemStats::getPageSize()
  223565. {
  223566. return (int) NSPageSize();
  223567. }
  223568. void PlatformUtilities::fpuReset()
  223569. {
  223570. }
  223571. #endif
  223572. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223573. /*** Start of inlined file: juce_mac_Network.mm ***/
  223574. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223575. // compiled on its own).
  223576. #if JUCE_INCLUDED_FILE
  223577. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  223578. {
  223579. ifaddrs* addrs = 0;
  223580. if (getifaddrs (&addrs) == 0)
  223581. {
  223582. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  223583. {
  223584. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223585. if (sto->ss_family == AF_LINK)
  223586. {
  223587. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223588. #ifndef IFT_ETHER
  223589. #define IFT_ETHER 6
  223590. #endif
  223591. if (sadd->sdl_type == IFT_ETHER)
  223592. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  223593. }
  223594. }
  223595. freeifaddrs (addrs);
  223596. }
  223597. }
  223598. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223599. const String& emailSubject,
  223600. const String& bodyText,
  223601. const StringArray& filesToAttach)
  223602. {
  223603. #if JUCE_IOS
  223604. //xxx probably need to use MFMailComposeViewController
  223605. jassertfalse;
  223606. return false;
  223607. #else
  223608. const ScopedAutoReleasePool pool;
  223609. String script;
  223610. script << "tell application \"Mail\"\r\n"
  223611. "set newMessage to make new outgoing message with properties {subject:\""
  223612. << emailSubject.replace ("\"", "\\\"")
  223613. << "\", content:\""
  223614. << bodyText.replace ("\"", "\\\"")
  223615. << "\" & return & return}\r\n"
  223616. "tell newMessage\r\n"
  223617. "set visible to true\r\n"
  223618. "set sender to \"sdfsdfsdfewf\"\r\n"
  223619. "make new to recipient at end of to recipients with properties {address:\""
  223620. << targetEmailAddress
  223621. << "\"}\r\n";
  223622. for (int i = 0; i < filesToAttach.size(); ++i)
  223623. {
  223624. script << "tell content\r\n"
  223625. "make new attachment with properties {file name:\""
  223626. << filesToAttach[i].replace ("\"", "\\\"")
  223627. << "\"} at after the last paragraph\r\n"
  223628. "end tell\r\n";
  223629. }
  223630. script << "end tell\r\n"
  223631. "end tell\r\n";
  223632. NSAppleScript* s = [[NSAppleScript alloc]
  223633. initWithSource: juceStringToNS (script)];
  223634. NSDictionary* error = 0;
  223635. const bool ok = [s executeAndReturnError: &error] != nil;
  223636. [s release];
  223637. return ok;
  223638. #endif
  223639. }
  223640. END_JUCE_NAMESPACE
  223641. using namespace JUCE_NAMESPACE;
  223642. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223643. @interface JuceURLConnection : NSObject
  223644. {
  223645. @public
  223646. NSURLRequest* request;
  223647. NSURLConnection* connection;
  223648. NSMutableData* data;
  223649. Thread* runLoopThread;
  223650. bool initialised, hasFailed, hasFinished;
  223651. int position;
  223652. int64 contentLength;
  223653. NSDictionary* headers;
  223654. NSLock* dataLock;
  223655. }
  223656. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223657. - (void) dealloc;
  223658. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223659. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223660. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223661. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223662. - (BOOL) isOpen;
  223663. - (int) read: (char*) dest numBytes: (int) num;
  223664. - (int) readPosition;
  223665. - (void) stop;
  223666. - (void) createConnection;
  223667. @end
  223668. class JuceURLConnectionMessageThread : public Thread
  223669. {
  223670. public:
  223671. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223672. : Thread ("http connection"),
  223673. owner (owner_)
  223674. {
  223675. }
  223676. ~JuceURLConnectionMessageThread()
  223677. {
  223678. stopThread (10000);
  223679. }
  223680. void run()
  223681. {
  223682. [owner createConnection];
  223683. while (! threadShouldExit())
  223684. {
  223685. const ScopedAutoReleasePool pool;
  223686. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223687. }
  223688. }
  223689. private:
  223690. JuceURLConnection* owner;
  223691. };
  223692. @implementation JuceURLConnection
  223693. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223694. withCallback: (URL::OpenStreamProgressCallback*) callback
  223695. withContext: (void*) context;
  223696. {
  223697. [super init];
  223698. request = req;
  223699. [request retain];
  223700. data = [[NSMutableData data] retain];
  223701. dataLock = [[NSLock alloc] init];
  223702. connection = 0;
  223703. initialised = false;
  223704. hasFailed = false;
  223705. hasFinished = false;
  223706. contentLength = -1;
  223707. headers = 0;
  223708. runLoopThread = new JuceURLConnectionMessageThread (self);
  223709. runLoopThread->startThread();
  223710. while (runLoopThread->isThreadRunning() && ! initialised)
  223711. {
  223712. if (callback != 0)
  223713. callback (context, -1, (int) [[request HTTPBody] length]);
  223714. Thread::sleep (1);
  223715. }
  223716. return self;
  223717. }
  223718. - (void) dealloc
  223719. {
  223720. [self stop];
  223721. deleteAndZero (runLoopThread);
  223722. [connection release];
  223723. [data release];
  223724. [dataLock release];
  223725. [request release];
  223726. [headers release];
  223727. [super dealloc];
  223728. }
  223729. - (void) createConnection
  223730. {
  223731. NSUInteger oldRetainCount = [self retainCount];
  223732. connection = [[NSURLConnection alloc] initWithRequest: request
  223733. delegate: self];
  223734. if (oldRetainCount == [self retainCount])
  223735. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223736. if (connection == nil)
  223737. runLoopThread->signalThreadShouldExit();
  223738. }
  223739. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223740. {
  223741. (void) conn;
  223742. [dataLock lock];
  223743. [data setLength: 0];
  223744. [dataLock unlock];
  223745. initialised = true;
  223746. contentLength = [response expectedContentLength];
  223747. [headers release];
  223748. headers = 0;
  223749. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223750. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223751. }
  223752. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223753. {
  223754. (void) conn;
  223755. DBG (nsStringToJuce ([error description]));
  223756. hasFailed = true;
  223757. initialised = true;
  223758. if (runLoopThread != 0)
  223759. runLoopThread->signalThreadShouldExit();
  223760. }
  223761. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223762. {
  223763. (void) conn;
  223764. [dataLock lock];
  223765. [data appendData: newData];
  223766. [dataLock unlock];
  223767. initialised = true;
  223768. }
  223769. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223770. {
  223771. (void) conn;
  223772. hasFinished = true;
  223773. initialised = true;
  223774. if (runLoopThread != 0)
  223775. runLoopThread->signalThreadShouldExit();
  223776. }
  223777. - (BOOL) isOpen
  223778. {
  223779. return connection != 0 && ! hasFailed;
  223780. }
  223781. - (int) readPosition
  223782. {
  223783. return position;
  223784. }
  223785. - (int) read: (char*) dest numBytes: (int) numNeeded
  223786. {
  223787. int numDone = 0;
  223788. while (numNeeded > 0)
  223789. {
  223790. int available = jmin (numNeeded, (int) [data length]);
  223791. if (available > 0)
  223792. {
  223793. [dataLock lock];
  223794. [data getBytes: dest length: available];
  223795. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223796. [dataLock unlock];
  223797. numDone += available;
  223798. numNeeded -= available;
  223799. dest += available;
  223800. }
  223801. else
  223802. {
  223803. if (hasFailed || hasFinished)
  223804. break;
  223805. Thread::sleep (1);
  223806. }
  223807. }
  223808. position += numDone;
  223809. return numDone;
  223810. }
  223811. - (void) stop
  223812. {
  223813. [connection cancel];
  223814. if (runLoopThread != 0)
  223815. runLoopThread->stopThread (10000);
  223816. }
  223817. @end
  223818. BEGIN_JUCE_NAMESPACE
  223819. class WebInputStream : public InputStream
  223820. {
  223821. public:
  223822. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  223823. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223824. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  223825. : connection (nil),
  223826. address (address_), headers (headers_), postData (postData_), position (0),
  223827. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  223828. {
  223829. JUCE_AUTORELEASEPOOL
  223830. connection = createConnection (progressCallback, progressCallbackContext);
  223831. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  223832. {
  223833. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  223834. NSString* key;
  223835. while ((key = [enumerator nextObject]) != nil)
  223836. responseHeaders->set (nsStringToJuce (key),
  223837. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  223838. }
  223839. }
  223840. ~WebInputStream()
  223841. {
  223842. close();
  223843. }
  223844. bool isError() const { return connection == nil; }
  223845. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  223846. bool isExhausted() { return finished; }
  223847. int64 getPosition() { return position; }
  223848. int read (void* buffer, int bytesToRead)
  223849. {
  223850. if (finished || isError())
  223851. {
  223852. return 0;
  223853. }
  223854. else
  223855. {
  223856. JUCE_AUTORELEASEPOOL
  223857. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  223858. position += bytesRead;
  223859. if (bytesRead == 0)
  223860. finished = true;
  223861. return bytesRead;
  223862. }
  223863. }
  223864. bool setPosition (int64 wantedPos)
  223865. {
  223866. if (wantedPos != position)
  223867. {
  223868. finished = false;
  223869. if (wantedPos < position)
  223870. {
  223871. close();
  223872. position = 0;
  223873. connection = createConnection (0, 0);
  223874. }
  223875. skipNextBytes (wantedPos - position);
  223876. }
  223877. return true;
  223878. }
  223879. private:
  223880. JuceURLConnection* connection;
  223881. String address, headers;
  223882. MemoryBlock postData;
  223883. int64 position;
  223884. bool finished;
  223885. const bool isPost;
  223886. const int timeOutMs;
  223887. void close()
  223888. {
  223889. [connection stop];
  223890. [connection release];
  223891. connection = nil;
  223892. }
  223893. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  223894. void* progressCallbackContext)
  223895. {
  223896. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  223897. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223898. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223899. if (req == nil)
  223900. return 0;
  223901. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223902. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223903. StringArray headerLines;
  223904. headerLines.addLines (headers);
  223905. headerLines.removeEmptyStrings (true);
  223906. for (int i = 0; i < headerLines.size(); ++i)
  223907. {
  223908. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223909. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223910. if (key.isNotEmpty() && value.isNotEmpty())
  223911. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223912. }
  223913. if (isPost && postData.getSize() > 0)
  223914. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223915. length: postData.getSize()]];
  223916. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223917. withCallback: progressCallback
  223918. withContext: progressCallbackContext];
  223919. if ([s isOpen])
  223920. return s;
  223921. [s release];
  223922. return 0;
  223923. }
  223924. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  223925. };
  223926. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  223927. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223928. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  223929. {
  223930. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  223931. progressCallback, progressCallbackContext,
  223932. headers, timeOutMs, responseHeaders));
  223933. return wi->isError() ? 0 : wi.release();
  223934. }
  223935. #endif
  223936. /*** End of inlined file: juce_mac_Network.mm ***/
  223937. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223938. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223939. // compiled on its own).
  223940. #if JUCE_INCLUDED_FILE
  223941. struct NamedPipeInternal
  223942. {
  223943. String pipeInName, pipeOutName;
  223944. int pipeIn, pipeOut;
  223945. bool volatile createdPipe, blocked, stopReadOperation;
  223946. static void signalHandler (int) {}
  223947. };
  223948. void NamedPipe::cancelPendingReads()
  223949. {
  223950. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  223951. {
  223952. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223953. intern->stopReadOperation = true;
  223954. char buffer [1] = { 0 };
  223955. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223956. (void) bytesWritten;
  223957. int timeout = 2000;
  223958. while (intern->blocked && --timeout >= 0)
  223959. Thread::sleep (2);
  223960. intern->stopReadOperation = false;
  223961. }
  223962. }
  223963. void NamedPipe::close()
  223964. {
  223965. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223966. if (intern != 0)
  223967. {
  223968. internal = 0;
  223969. if (intern->pipeIn != -1)
  223970. ::close (intern->pipeIn);
  223971. if (intern->pipeOut != -1)
  223972. ::close (intern->pipeOut);
  223973. if (intern->createdPipe)
  223974. {
  223975. unlink (intern->pipeInName.toUTF8());
  223976. unlink (intern->pipeOutName.toUTF8());
  223977. }
  223978. delete intern;
  223979. }
  223980. }
  223981. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223982. {
  223983. close();
  223984. NamedPipeInternal* const intern = new NamedPipeInternal();
  223985. internal = intern;
  223986. intern->createdPipe = createPipe;
  223987. intern->blocked = false;
  223988. intern->stopReadOperation = false;
  223989. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223990. siginterrupt (SIGPIPE, 1);
  223991. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223992. intern->pipeInName = pipePath + "_in";
  223993. intern->pipeOutName = pipePath + "_out";
  223994. intern->pipeIn = -1;
  223995. intern->pipeOut = -1;
  223996. if (createPipe)
  223997. {
  223998. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223999. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224000. {
  224001. delete intern;
  224002. internal = 0;
  224003. return false;
  224004. }
  224005. }
  224006. return true;
  224007. }
  224008. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224009. {
  224010. int bytesRead = -1;
  224011. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224012. if (intern != 0)
  224013. {
  224014. intern->blocked = true;
  224015. if (intern->pipeIn == -1)
  224016. {
  224017. if (intern->createdPipe)
  224018. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224019. else
  224020. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224021. if (intern->pipeIn == -1)
  224022. {
  224023. intern->blocked = false;
  224024. return -1;
  224025. }
  224026. }
  224027. bytesRead = 0;
  224028. char* p = static_cast<char*> (destBuffer);
  224029. while (bytesRead < maxBytesToRead)
  224030. {
  224031. const int bytesThisTime = maxBytesToRead - bytesRead;
  224032. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224033. if (numRead <= 0 || intern->stopReadOperation)
  224034. {
  224035. bytesRead = -1;
  224036. break;
  224037. }
  224038. bytesRead += numRead;
  224039. p += bytesRead;
  224040. }
  224041. intern->blocked = false;
  224042. }
  224043. return bytesRead;
  224044. }
  224045. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224046. {
  224047. int bytesWritten = -1;
  224048. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224049. if (intern != 0)
  224050. {
  224051. if (intern->pipeOut == -1)
  224052. {
  224053. if (intern->createdPipe)
  224054. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224055. else
  224056. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224057. if (intern->pipeOut == -1)
  224058. {
  224059. return -1;
  224060. }
  224061. }
  224062. const char* p = static_cast<const char*> (sourceBuffer);
  224063. bytesWritten = 0;
  224064. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224065. while (bytesWritten < numBytesToWrite
  224066. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224067. {
  224068. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224069. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224070. if (numWritten <= 0)
  224071. {
  224072. bytesWritten = -1;
  224073. break;
  224074. }
  224075. bytesWritten += numWritten;
  224076. p += bytesWritten;
  224077. }
  224078. }
  224079. return bytesWritten;
  224080. }
  224081. #endif
  224082. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224083. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224084. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224085. // compiled on its own).
  224086. #if JUCE_INCLUDED_FILE
  224087. /*
  224088. Note that a lot of methods that you'd expect to find in this file actually
  224089. live in juce_posix_SharedCode.h!
  224090. */
  224091. bool Process::isForegroundProcess()
  224092. {
  224093. #if JUCE_MAC
  224094. return [NSApp isActive];
  224095. #else
  224096. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224097. #endif
  224098. }
  224099. void Process::raisePrivilege()
  224100. {
  224101. jassertfalse;
  224102. }
  224103. void Process::lowerPrivilege()
  224104. {
  224105. jassertfalse;
  224106. }
  224107. void Process::terminate()
  224108. {
  224109. exit (0);
  224110. }
  224111. void Process::setPriority (ProcessPriority)
  224112. {
  224113. // xxx
  224114. }
  224115. #endif
  224116. /*** End of inlined file: juce_mac_Threads.mm ***/
  224117. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224118. /*
  224119. This file contains posix routines that are common to both the Linux and Mac builds.
  224120. It gets included directly in the cpp files for these platforms.
  224121. */
  224122. CriticalSection::CriticalSection() throw()
  224123. {
  224124. pthread_mutexattr_t atts;
  224125. pthread_mutexattr_init (&atts);
  224126. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224127. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224128. pthread_mutex_init (&internal, &atts);
  224129. }
  224130. CriticalSection::~CriticalSection() throw()
  224131. {
  224132. pthread_mutex_destroy (&internal);
  224133. }
  224134. void CriticalSection::enter() const throw()
  224135. {
  224136. pthread_mutex_lock (&internal);
  224137. }
  224138. bool CriticalSection::tryEnter() const throw()
  224139. {
  224140. return pthread_mutex_trylock (&internal) == 0;
  224141. }
  224142. void CriticalSection::exit() const throw()
  224143. {
  224144. pthread_mutex_unlock (&internal);
  224145. }
  224146. class WaitableEventImpl
  224147. {
  224148. public:
  224149. WaitableEventImpl (const bool manualReset_)
  224150. : triggered (false),
  224151. manualReset (manualReset_)
  224152. {
  224153. pthread_cond_init (&condition, 0);
  224154. pthread_mutexattr_t atts;
  224155. pthread_mutexattr_init (&atts);
  224156. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224157. pthread_mutex_init (&mutex, &atts);
  224158. }
  224159. ~WaitableEventImpl()
  224160. {
  224161. pthread_cond_destroy (&condition);
  224162. pthread_mutex_destroy (&mutex);
  224163. }
  224164. bool wait (const int timeOutMillisecs) throw()
  224165. {
  224166. pthread_mutex_lock (&mutex);
  224167. if (! triggered)
  224168. {
  224169. if (timeOutMillisecs < 0)
  224170. {
  224171. do
  224172. {
  224173. pthread_cond_wait (&condition, &mutex);
  224174. }
  224175. while (! triggered);
  224176. }
  224177. else
  224178. {
  224179. struct timeval now;
  224180. gettimeofday (&now, 0);
  224181. struct timespec time;
  224182. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224183. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224184. if (time.tv_nsec >= 1000000000)
  224185. {
  224186. time.tv_nsec -= 1000000000;
  224187. time.tv_sec++;
  224188. }
  224189. do
  224190. {
  224191. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224192. {
  224193. pthread_mutex_unlock (&mutex);
  224194. return false;
  224195. }
  224196. }
  224197. while (! triggered);
  224198. }
  224199. }
  224200. if (! manualReset)
  224201. triggered = false;
  224202. pthread_mutex_unlock (&mutex);
  224203. return true;
  224204. }
  224205. void signal() throw()
  224206. {
  224207. pthread_mutex_lock (&mutex);
  224208. triggered = true;
  224209. pthread_cond_broadcast (&condition);
  224210. pthread_mutex_unlock (&mutex);
  224211. }
  224212. void reset() throw()
  224213. {
  224214. pthread_mutex_lock (&mutex);
  224215. triggered = false;
  224216. pthread_mutex_unlock (&mutex);
  224217. }
  224218. private:
  224219. pthread_cond_t condition;
  224220. pthread_mutex_t mutex;
  224221. bool triggered;
  224222. const bool manualReset;
  224223. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224224. };
  224225. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224226. : internal (new WaitableEventImpl (manualReset))
  224227. {
  224228. }
  224229. WaitableEvent::~WaitableEvent() throw()
  224230. {
  224231. delete static_cast <WaitableEventImpl*> (internal);
  224232. }
  224233. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224234. {
  224235. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224236. }
  224237. void WaitableEvent::signal() const throw()
  224238. {
  224239. static_cast <WaitableEventImpl*> (internal)->signal();
  224240. }
  224241. void WaitableEvent::reset() const throw()
  224242. {
  224243. static_cast <WaitableEventImpl*> (internal)->reset();
  224244. }
  224245. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224246. {
  224247. struct timespec time;
  224248. time.tv_sec = millisecs / 1000;
  224249. time.tv_nsec = (millisecs % 1000) * 1000000;
  224250. nanosleep (&time, 0);
  224251. }
  224252. const juce_wchar File::separator = '/';
  224253. const String File::separatorString ("/");
  224254. const File File::getCurrentWorkingDirectory()
  224255. {
  224256. HeapBlock<char> heapBuffer;
  224257. char localBuffer [1024];
  224258. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224259. int bufferSize = 4096;
  224260. while (cwd == 0 && errno == ERANGE)
  224261. {
  224262. heapBuffer.malloc (bufferSize);
  224263. cwd = getcwd (heapBuffer, bufferSize - 1);
  224264. bufferSize += 1024;
  224265. }
  224266. return File (String::fromUTF8 (cwd));
  224267. }
  224268. bool File::setAsCurrentWorkingDirectory() const
  224269. {
  224270. return chdir (getFullPathName().toUTF8()) == 0;
  224271. }
  224272. namespace
  224273. {
  224274. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224275. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224276. #else
  224277. typedef struct stat juce_statStruct;
  224278. #endif
  224279. bool juce_stat (const String& fileName, juce_statStruct& info)
  224280. {
  224281. return fileName.isNotEmpty()
  224282. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224283. && (stat64 (fileName.toUTF8(), &info) == 0);
  224284. #else
  224285. && (stat (fileName.toUTF8(), &info) == 0);
  224286. #endif
  224287. }
  224288. // if this file doesn't exist, find a parent of it that does..
  224289. bool juce_doStatFS (File f, struct statfs& result)
  224290. {
  224291. for (int i = 5; --i >= 0;)
  224292. {
  224293. if (f.exists())
  224294. break;
  224295. f = f.getParentDirectory();
  224296. }
  224297. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224298. }
  224299. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  224300. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224301. {
  224302. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224303. {
  224304. juce_statStruct info;
  224305. const bool statOk = juce_stat (path, info);
  224306. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224307. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224308. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  224309. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  224310. }
  224311. if (isReadOnly != 0)
  224312. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224313. }
  224314. }
  224315. bool File::isDirectory() const
  224316. {
  224317. juce_statStruct info;
  224318. return fullPath.isEmpty()
  224319. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224320. }
  224321. bool File::exists() const
  224322. {
  224323. juce_statStruct info;
  224324. return fullPath.isNotEmpty()
  224325. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224326. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224327. #else
  224328. && (lstat (fullPath.toUTF8(), &info) == 0);
  224329. #endif
  224330. }
  224331. bool File::existsAsFile() const
  224332. {
  224333. return exists() && ! isDirectory();
  224334. }
  224335. int64 File::getSize() const
  224336. {
  224337. juce_statStruct info;
  224338. return juce_stat (fullPath, info) ? info.st_size : 0;
  224339. }
  224340. bool File::hasWriteAccess() const
  224341. {
  224342. if (exists())
  224343. return access (fullPath.toUTF8(), W_OK) == 0;
  224344. if ((! isDirectory()) && fullPath.containsChar (separator))
  224345. return getParentDirectory().hasWriteAccess();
  224346. return false;
  224347. }
  224348. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224349. {
  224350. juce_statStruct info;
  224351. if (! juce_stat (fullPath, info))
  224352. return false;
  224353. info.st_mode &= 0777; // Just permissions
  224354. if (shouldBeReadOnly)
  224355. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224356. else
  224357. // Give everybody write permission?
  224358. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224359. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224360. }
  224361. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224362. {
  224363. modificationTime = 0;
  224364. accessTime = 0;
  224365. creationTime = 0;
  224366. juce_statStruct info;
  224367. if (juce_stat (fullPath, info))
  224368. {
  224369. modificationTime = (int64) info.st_mtime * 1000;
  224370. accessTime = (int64) info.st_atime * 1000;
  224371. creationTime = (int64) info.st_ctime * 1000;
  224372. }
  224373. }
  224374. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224375. {
  224376. struct utimbuf times;
  224377. times.actime = (time_t) (accessTime / 1000);
  224378. times.modtime = (time_t) (modificationTime / 1000);
  224379. return utime (fullPath.toUTF8(), &times) == 0;
  224380. }
  224381. bool File::deleteFile() const
  224382. {
  224383. if (! exists())
  224384. return true;
  224385. else if (isDirectory())
  224386. return rmdir (fullPath.toUTF8()) == 0;
  224387. else
  224388. return remove (fullPath.toUTF8()) == 0;
  224389. }
  224390. bool File::moveInternal (const File& dest) const
  224391. {
  224392. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224393. return true;
  224394. if (hasWriteAccess() && copyInternal (dest))
  224395. {
  224396. if (deleteFile())
  224397. return true;
  224398. dest.deleteFile();
  224399. }
  224400. return false;
  224401. }
  224402. void File::createDirectoryInternal (const String& fileName) const
  224403. {
  224404. mkdir (fileName.toUTF8(), 0777);
  224405. }
  224406. int64 juce_fileSetPosition (void* handle, int64 pos)
  224407. {
  224408. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224409. return pos;
  224410. return -1;
  224411. }
  224412. void FileInputStream::openHandle()
  224413. {
  224414. totalSize = file.getSize();
  224415. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224416. if (f != -1)
  224417. fileHandle = (void*) f;
  224418. }
  224419. void FileInputStream::closeHandle()
  224420. {
  224421. if (fileHandle != 0)
  224422. {
  224423. close ((int) (pointer_sized_int) fileHandle);
  224424. fileHandle = 0;
  224425. }
  224426. }
  224427. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224428. {
  224429. if (fileHandle != 0)
  224430. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224431. return 0;
  224432. }
  224433. void FileOutputStream::openHandle()
  224434. {
  224435. if (file.exists())
  224436. {
  224437. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224438. if (f != -1)
  224439. {
  224440. currentPosition = lseek (f, 0, SEEK_END);
  224441. if (currentPosition >= 0)
  224442. fileHandle = (void*) f;
  224443. else
  224444. close (f);
  224445. }
  224446. }
  224447. else
  224448. {
  224449. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224450. if (f != -1)
  224451. fileHandle = (void*) f;
  224452. }
  224453. }
  224454. void FileOutputStream::closeHandle()
  224455. {
  224456. if (fileHandle != 0)
  224457. {
  224458. close ((int) (pointer_sized_int) fileHandle);
  224459. fileHandle = 0;
  224460. }
  224461. }
  224462. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224463. {
  224464. if (fileHandle != 0)
  224465. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224466. return 0;
  224467. }
  224468. void FileOutputStream::flushInternal()
  224469. {
  224470. if (fileHandle != 0)
  224471. fsync ((int) (pointer_sized_int) fileHandle);
  224472. }
  224473. const File juce_getExecutableFile()
  224474. {
  224475. Dl_info exeInfo;
  224476. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  224477. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224478. }
  224479. int64 File::getBytesFreeOnVolume() const
  224480. {
  224481. struct statfs buf;
  224482. if (juce_doStatFS (*this, buf))
  224483. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224484. return 0;
  224485. }
  224486. int64 File::getVolumeTotalSize() const
  224487. {
  224488. struct statfs buf;
  224489. if (juce_doStatFS (*this, buf))
  224490. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224491. return 0;
  224492. }
  224493. const String File::getVolumeLabel() const
  224494. {
  224495. #if JUCE_MAC
  224496. struct VolAttrBuf
  224497. {
  224498. u_int32_t length;
  224499. attrreference_t mountPointRef;
  224500. char mountPointSpace [MAXPATHLEN];
  224501. } attrBuf;
  224502. struct attrlist attrList;
  224503. zerostruct (attrList);
  224504. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224505. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224506. File f (*this);
  224507. for (;;)
  224508. {
  224509. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224510. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224511. (int) attrBuf.mountPointRef.attr_length);
  224512. const File parent (f.getParentDirectory());
  224513. if (f == parent)
  224514. break;
  224515. f = parent;
  224516. }
  224517. #endif
  224518. return String::empty;
  224519. }
  224520. int File::getVolumeSerialNumber() const
  224521. {
  224522. return 0; // xxx
  224523. }
  224524. void juce_runSystemCommand (const String& command)
  224525. {
  224526. int result = system (command.toUTF8());
  224527. (void) result;
  224528. }
  224529. const String juce_getOutputFromCommand (const String& command)
  224530. {
  224531. // slight bodge here, as we just pipe the output into a temp file and read it...
  224532. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224533. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224534. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224535. String result (tempFile.loadFileAsString());
  224536. tempFile.deleteFile();
  224537. return result;
  224538. }
  224539. class InterProcessLock::Pimpl
  224540. {
  224541. public:
  224542. Pimpl (const String& name, const int timeOutMillisecs)
  224543. : handle (0), refCount (1)
  224544. {
  224545. #if JUCE_MAC
  224546. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224547. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224548. #else
  224549. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224550. #endif
  224551. temp.create();
  224552. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224553. if (handle != 0)
  224554. {
  224555. struct flock fl;
  224556. zerostruct (fl);
  224557. fl.l_whence = SEEK_SET;
  224558. fl.l_type = F_WRLCK;
  224559. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224560. for (;;)
  224561. {
  224562. const int result = fcntl (handle, F_SETLK, &fl);
  224563. if (result >= 0)
  224564. return;
  224565. if (errno != EINTR)
  224566. {
  224567. if (timeOutMillisecs == 0
  224568. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224569. break;
  224570. Thread::sleep (10);
  224571. }
  224572. }
  224573. }
  224574. closeFile();
  224575. }
  224576. ~Pimpl()
  224577. {
  224578. closeFile();
  224579. }
  224580. void closeFile()
  224581. {
  224582. if (handle != 0)
  224583. {
  224584. struct flock fl;
  224585. zerostruct (fl);
  224586. fl.l_whence = SEEK_SET;
  224587. fl.l_type = F_UNLCK;
  224588. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224589. {}
  224590. close (handle);
  224591. handle = 0;
  224592. }
  224593. }
  224594. int handle, refCount;
  224595. };
  224596. InterProcessLock::InterProcessLock (const String& name_)
  224597. : name (name_)
  224598. {
  224599. }
  224600. InterProcessLock::~InterProcessLock()
  224601. {
  224602. }
  224603. bool InterProcessLock::enter (const int timeOutMillisecs)
  224604. {
  224605. const ScopedLock sl (lock);
  224606. if (pimpl == 0)
  224607. {
  224608. pimpl = new Pimpl (name, timeOutMillisecs);
  224609. if (pimpl->handle == 0)
  224610. pimpl = 0;
  224611. }
  224612. else
  224613. {
  224614. pimpl->refCount++;
  224615. }
  224616. return pimpl != 0;
  224617. }
  224618. void InterProcessLock::exit()
  224619. {
  224620. const ScopedLock sl (lock);
  224621. // Trying to release the lock too many times!
  224622. jassert (pimpl != 0);
  224623. if (pimpl != 0 && --(pimpl->refCount) == 0)
  224624. pimpl = 0;
  224625. }
  224626. void JUCE_API juce_threadEntryPoint (void*);
  224627. void* threadEntryProc (void* userData)
  224628. {
  224629. JUCE_AUTORELEASEPOOL
  224630. juce_threadEntryPoint (userData);
  224631. return 0;
  224632. }
  224633. void Thread::launchThread()
  224634. {
  224635. threadHandle_ = 0;
  224636. pthread_t handle = 0;
  224637. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  224638. {
  224639. pthread_detach (handle);
  224640. threadHandle_ = (void*) handle;
  224641. threadId_ = (ThreadID) threadHandle_;
  224642. }
  224643. }
  224644. void Thread::closeThreadHandle()
  224645. {
  224646. threadId_ = 0;
  224647. threadHandle_ = 0;
  224648. }
  224649. void Thread::killThread()
  224650. {
  224651. if (threadHandle_ != 0)
  224652. pthread_cancel ((pthread_t) threadHandle_);
  224653. }
  224654. void Thread::setCurrentThreadName (const String& /*name*/)
  224655. {
  224656. }
  224657. bool Thread::setThreadPriority (void* handle, int priority)
  224658. {
  224659. struct sched_param param;
  224660. int policy;
  224661. priority = jlimit (0, 10, priority);
  224662. if (handle == 0)
  224663. handle = (void*) pthread_self();
  224664. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  224665. return false;
  224666. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  224667. const int minPriority = sched_get_priority_min (policy);
  224668. const int maxPriority = sched_get_priority_max (policy);
  224669. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  224670. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  224671. }
  224672. Thread::ThreadID Thread::getCurrentThreadId()
  224673. {
  224674. return (ThreadID) pthread_self();
  224675. }
  224676. void Thread::yield()
  224677. {
  224678. sched_yield();
  224679. }
  224680. /* Remove this macro if you're having problems compiling the cpu affinity
  224681. calls (the API for these has changed about quite a bit in various Linux
  224682. versions, and a lot of distros seem to ship with obsolete versions)
  224683. */
  224684. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  224685. #define SUPPORT_AFFINITIES 1
  224686. #endif
  224687. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  224688. {
  224689. #if SUPPORT_AFFINITIES
  224690. cpu_set_t affinity;
  224691. CPU_ZERO (&affinity);
  224692. for (int i = 0; i < 32; ++i)
  224693. if ((affinityMask & (1 << i)) != 0)
  224694. CPU_SET (i, &affinity);
  224695. /*
  224696. N.B. If this line causes a compile error, then you've probably not got the latest
  224697. version of glibc installed.
  224698. If you don't want to update your copy of glibc and don't care about cpu affinities,
  224699. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  224700. */
  224701. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  224702. sched_yield();
  224703. #else
  224704. /* affinities aren't supported because either the appropriate header files weren't found,
  224705. or the SUPPORT_AFFINITIES macro was turned off
  224706. */
  224707. jassertfalse;
  224708. (void) affinityMask;
  224709. #endif
  224710. }
  224711. /*** End of inlined file: juce_posix_SharedCode.h ***/
  224712. /*** Start of inlined file: juce_mac_Files.mm ***/
  224713. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224714. // compiled on its own).
  224715. #if JUCE_INCLUDED_FILE
  224716. /*
  224717. Note that a lot of methods that you'd expect to find in this file actually
  224718. live in juce_posix_SharedCode.h!
  224719. */
  224720. bool File::copyInternal (const File& dest) const
  224721. {
  224722. const ScopedAutoReleasePool pool;
  224723. NSFileManager* fm = [NSFileManager defaultManager];
  224724. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  224725. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224726. && [fm copyItemAtPath: juceStringToNS (fullPath)
  224727. toPath: juceStringToNS (dest.getFullPathName())
  224728. error: nil];
  224729. #else
  224730. && [fm copyPath: juceStringToNS (fullPath)
  224731. toPath: juceStringToNS (dest.getFullPathName())
  224732. handler: nil];
  224733. #endif
  224734. }
  224735. void File::findFileSystemRoots (Array<File>& destArray)
  224736. {
  224737. destArray.add (File ("/"));
  224738. }
  224739. namespace FileHelpers
  224740. {
  224741. bool isFileOnDriveType (const File& f, const char* const* types)
  224742. {
  224743. struct statfs buf;
  224744. if (juce_doStatFS (f, buf))
  224745. {
  224746. const String type (buf.f_fstypename);
  224747. while (*types != 0)
  224748. if (type.equalsIgnoreCase (*types++))
  224749. return true;
  224750. }
  224751. return false;
  224752. }
  224753. bool isHiddenFile (const String& path)
  224754. {
  224755. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  224756. const ScopedAutoReleasePool pool;
  224757. NSNumber* hidden = nil;
  224758. NSError* err = nil;
  224759. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  224760. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  224761. && [hidden boolValue];
  224762. #else
  224763. #if JUCE_IOS
  224764. return File (path).getFileName().startsWithChar ('.');
  224765. #else
  224766. FSRef ref;
  224767. LSItemInfoRecord info;
  224768. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  224769. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  224770. && (info.flags & kLSItemInfoIsInvisible) != 0;
  224771. #endif
  224772. #endif
  224773. }
  224774. #if JUCE_IOS
  224775. const String getIOSSystemLocation (NSSearchPathDirectory type)
  224776. {
  224777. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  224778. objectAtIndex: 0]);
  224779. }
  224780. #endif
  224781. bool launchExecutable (const String& pathAndArguments)
  224782. {
  224783. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224784. const int cpid = fork();
  224785. if (cpid == 0)
  224786. {
  224787. // Child process
  224788. if (execve (argv[0], (char**) argv, 0) < 0)
  224789. exit (0);
  224790. }
  224791. else
  224792. {
  224793. if (cpid < 0)
  224794. return false;
  224795. }
  224796. return true;
  224797. }
  224798. }
  224799. bool File::isOnCDRomDrive() const
  224800. {
  224801. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224802. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  224803. }
  224804. bool File::isOnHardDisk() const
  224805. {
  224806. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224807. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  224808. }
  224809. bool File::isOnRemovableDrive() const
  224810. {
  224811. #if JUCE_IOS
  224812. return false; // xxx is this possible?
  224813. #else
  224814. const ScopedAutoReleasePool pool;
  224815. BOOL removable = false;
  224816. [[NSWorkspace sharedWorkspace]
  224817. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224818. isRemovable: &removable
  224819. isWritable: nil
  224820. isUnmountable: nil
  224821. description: nil
  224822. type: nil];
  224823. return removable;
  224824. #endif
  224825. }
  224826. bool File::isHidden() const
  224827. {
  224828. return FileHelpers::isHiddenFile (getFullPathName());
  224829. }
  224830. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224831. const File File::getSpecialLocation (const SpecialLocationType type)
  224832. {
  224833. const ScopedAutoReleasePool pool;
  224834. String resultPath;
  224835. switch (type)
  224836. {
  224837. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  224838. #if JUCE_IOS
  224839. case userDocumentsDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDocumentDirectory); break;
  224840. case userDesktopDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDesktopDirectory); break;
  224841. case tempDirectory:
  224842. {
  224843. File tmp (FileHelpers::getIOSSystemLocation (NSCachesDirectory));
  224844. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  224845. tmp.createDirectory();
  224846. return tmp.getFullPathName();
  224847. }
  224848. #else
  224849. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  224850. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  224851. case tempDirectory:
  224852. {
  224853. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224854. tmp.createDirectory();
  224855. return tmp.getFullPathName();
  224856. }
  224857. #endif
  224858. case userMusicDirectory: resultPath = "~/Music"; break;
  224859. case userMoviesDirectory: resultPath = "~/Movies"; break;
  224860. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  224861. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  224862. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  224863. case invokedExecutableFile:
  224864. if (juce_Argv0 != 0)
  224865. return File (String::fromUTF8 (juce_Argv0));
  224866. // deliberate fall-through...
  224867. case currentExecutableFile:
  224868. return juce_getExecutableFile();
  224869. case currentApplicationFile:
  224870. {
  224871. const File exe (juce_getExecutableFile());
  224872. const File parent (exe.getParentDirectory());
  224873. #if JUCE_IOS
  224874. return parent;
  224875. #else
  224876. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  224877. ? parent.getParentDirectory().getParentDirectory()
  224878. : exe;
  224879. #endif
  224880. }
  224881. case hostApplicationPath:
  224882. {
  224883. unsigned int size = 8192;
  224884. HeapBlock<char> buffer;
  224885. buffer.calloc (size + 8);
  224886. _NSGetExecutablePath (buffer.getData(), &size);
  224887. return String::fromUTF8 (buffer, size);
  224888. }
  224889. default:
  224890. jassertfalse; // unknown type?
  224891. break;
  224892. }
  224893. if (resultPath.isNotEmpty())
  224894. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224895. return File::nonexistent;
  224896. }
  224897. const String File::getVersion() const
  224898. {
  224899. const ScopedAutoReleasePool pool;
  224900. String result;
  224901. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  224902. if (bundle != 0)
  224903. {
  224904. NSDictionary* info = [bundle infoDictionary];
  224905. if (info != 0)
  224906. {
  224907. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  224908. if (name != nil)
  224909. result = nsStringToJuce (name);
  224910. }
  224911. }
  224912. return result;
  224913. }
  224914. const File File::getLinkedTarget() const
  224915. {
  224916. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224917. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224918. #else
  224919. // (the cast here avoids a deprecation warning)
  224920. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224921. #endif
  224922. if (dest != nil)
  224923. return File (nsStringToJuce (dest));
  224924. return *this;
  224925. }
  224926. bool File::moveToTrash() const
  224927. {
  224928. if (! exists())
  224929. return true;
  224930. #if JUCE_IOS
  224931. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224932. #else
  224933. const ScopedAutoReleasePool pool;
  224934. NSString* p = juceStringToNS (getFullPathName());
  224935. return [[NSWorkspace sharedWorkspace]
  224936. performFileOperation: NSWorkspaceRecycleOperation
  224937. source: [p stringByDeletingLastPathComponent]
  224938. destination: @""
  224939. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224940. tag: nil ];
  224941. #endif
  224942. }
  224943. class DirectoryIterator::NativeIterator::Pimpl
  224944. {
  224945. public:
  224946. Pimpl (const File& directory, const String& wildCard_)
  224947. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224948. wildCard (wildCard_),
  224949. enumerator (0)
  224950. {
  224951. const ScopedAutoReleasePool pool;
  224952. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224953. wildcardUTF8 = wildCard.toUTF8();
  224954. }
  224955. ~Pimpl()
  224956. {
  224957. [enumerator release];
  224958. }
  224959. bool next (String& filenameFound,
  224960. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224961. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224962. {
  224963. const ScopedAutoReleasePool pool;
  224964. for (;;)
  224965. {
  224966. NSString* file;
  224967. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224968. return false;
  224969. [enumerator skipDescendents];
  224970. filenameFound = nsStringToJuce (file);
  224971. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224972. continue;
  224973. const String path (parentDir + filenameFound);
  224974. updateStatInfoForFile (path, isDir, fileSize, modTime, creationTime, isReadOnly);
  224975. if (isHidden != 0)
  224976. *isHidden = FileHelpers::isHiddenFile (path);
  224977. return true;
  224978. }
  224979. }
  224980. private:
  224981. String parentDir, wildCard;
  224982. const char* wildcardUTF8;
  224983. NSDirectoryEnumerator* enumerator;
  224984. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  224985. };
  224986. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224987. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224988. {
  224989. }
  224990. DirectoryIterator::NativeIterator::~NativeIterator()
  224991. {
  224992. }
  224993. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224994. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224995. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224996. {
  224997. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224998. }
  224999. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225000. {
  225001. #if JUCE_IOS
  225002. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225003. #else
  225004. const ScopedAutoReleasePool pool;
  225005. if (parameters.isEmpty())
  225006. {
  225007. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225008. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225009. }
  225010. bool ok = false;
  225011. if (PlatformUtilities::isBundle (fileName))
  225012. {
  225013. NSMutableArray* urls = [NSMutableArray array];
  225014. StringArray docs;
  225015. docs.addTokens (parameters, true);
  225016. for (int i = 0; i < docs.size(); ++i)
  225017. [urls addObject: juceStringToNS (docs[i])];
  225018. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225019. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225020. options: 0
  225021. additionalEventParamDescriptor: nil
  225022. launchIdentifiers: nil];
  225023. }
  225024. else if (File (fileName).exists())
  225025. {
  225026. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  225027. }
  225028. return ok;
  225029. #endif
  225030. }
  225031. void File::revealToUser() const
  225032. {
  225033. #if ! JUCE_IOS
  225034. if (exists())
  225035. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225036. else if (getParentDirectory().exists())
  225037. getParentDirectory().revealToUser();
  225038. #endif
  225039. }
  225040. #if ! JUCE_IOS
  225041. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225042. {
  225043. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225044. }
  225045. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225046. {
  225047. char path [2048];
  225048. zerostruct (path);
  225049. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225050. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225051. return String::empty;
  225052. }
  225053. #endif
  225054. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225055. {
  225056. const ScopedAutoReleasePool pool;
  225057. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225058. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225059. #else
  225060. // (the cast here avoids a deprecation warning)
  225061. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225062. #endif
  225063. return [fileDict fileHFSTypeCode];
  225064. }
  225065. bool PlatformUtilities::isBundle (const String& filename)
  225066. {
  225067. #if JUCE_IOS
  225068. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225069. #else
  225070. const ScopedAutoReleasePool pool;
  225071. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225072. #endif
  225073. }
  225074. #endif
  225075. /*** End of inlined file: juce_mac_Files.mm ***/
  225076. #if JUCE_IOS
  225077. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225078. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225079. // compiled on its own).
  225080. #if JUCE_INCLUDED_FILE
  225081. END_JUCE_NAMESPACE
  225082. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225083. {
  225084. }
  225085. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225086. - (void) applicationWillTerminate: (UIApplication*) application;
  225087. @end
  225088. @implementation JuceAppStartupDelegate
  225089. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225090. {
  225091. initialiseJuce_GUI();
  225092. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225093. exit (0);
  225094. }
  225095. - (void) applicationWillTerminate: (UIApplication*) application
  225096. {
  225097. JUCEApplication::appWillTerminateByForce();
  225098. }
  225099. @end
  225100. BEGIN_JUCE_NAMESPACE
  225101. int juce_iOSMain (int argc, const char* argv[])
  225102. {
  225103. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225104. }
  225105. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225106. {
  225107. pool = [[NSAutoreleasePool alloc] init];
  225108. }
  225109. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225110. {
  225111. [((NSAutoreleasePool*) pool) release];
  225112. }
  225113. void PlatformUtilities::beep()
  225114. {
  225115. //xxx
  225116. //AudioServicesPlaySystemSound ();
  225117. }
  225118. void PlatformUtilities::addItemToDock (const File& file)
  225119. {
  225120. }
  225121. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225122. END_JUCE_NAMESPACE
  225123. @interface JuceAlertBoxDelegate : NSObject
  225124. {
  225125. @public
  225126. bool clickedOk;
  225127. }
  225128. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225129. @end
  225130. @implementation JuceAlertBoxDelegate
  225131. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225132. {
  225133. clickedOk = (buttonIndex == 0);
  225134. alertView.hidden = true;
  225135. }
  225136. @end
  225137. BEGIN_JUCE_NAMESPACE
  225138. // (This function is used directly by other bits of code)
  225139. bool juce_iPhoneShowModalAlert (const String& title,
  225140. const String& bodyText,
  225141. NSString* okButtonText,
  225142. NSString* cancelButtonText)
  225143. {
  225144. const ScopedAutoReleasePool pool;
  225145. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225146. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225147. message: juceStringToNS (bodyText)
  225148. delegate: callback
  225149. cancelButtonTitle: okButtonText
  225150. otherButtonTitles: cancelButtonText, nil];
  225151. [alert retain];
  225152. [alert show];
  225153. while (! alert.hidden && alert.superview != nil)
  225154. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225155. const bool result = callback->clickedOk;
  225156. [alert release];
  225157. [callback release];
  225158. return result;
  225159. }
  225160. bool AlertWindow::showNativeDialogBox (const String& title,
  225161. const String& bodyText,
  225162. bool isOkCancel)
  225163. {
  225164. return juce_iPhoneShowModalAlert (title, bodyText,
  225165. @"OK",
  225166. isOkCancel ? @"Cancel" : nil);
  225167. }
  225168. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225169. {
  225170. jassertfalse; // no such thing on the iphone!
  225171. return false;
  225172. }
  225173. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225174. {
  225175. jassertfalse; // no such thing on the iphone!
  225176. return false;
  225177. }
  225178. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225179. {
  225180. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225181. }
  225182. bool Desktop::isScreenSaverEnabled()
  225183. {
  225184. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225185. }
  225186. #endif
  225187. #endif
  225188. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225189. #else
  225190. /*** Start of inlined file: juce_mac_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. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225195. {
  225196. pool = [[NSAutoreleasePool alloc] init];
  225197. }
  225198. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225199. {
  225200. [((NSAutoreleasePool*) pool) release];
  225201. }
  225202. void PlatformUtilities::beep()
  225203. {
  225204. NSBeep();
  225205. }
  225206. void PlatformUtilities::addItemToDock (const File& file)
  225207. {
  225208. // check that it's not already there...
  225209. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225210. .containsIgnoreCase (file.getFullPathName()))
  225211. {
  225212. 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>"
  225213. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225214. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225215. }
  225216. }
  225217. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225218. bool AlertWindow::showNativeDialogBox (const String& title,
  225219. const String& bodyText,
  225220. bool isOkCancel)
  225221. {
  225222. const ScopedAutoReleasePool pool;
  225223. return NSRunAlertPanel (juceStringToNS (title),
  225224. juceStringToNS (bodyText),
  225225. @"Ok",
  225226. isOkCancel ? @"Cancel" : nil,
  225227. nil) == NSAlertDefaultReturn;
  225228. }
  225229. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225230. {
  225231. if (files.size() == 0)
  225232. return false;
  225233. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225234. if (draggingSource == 0)
  225235. {
  225236. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225237. return false;
  225238. }
  225239. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225240. if (sourceComp == 0)
  225241. {
  225242. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225243. return false;
  225244. }
  225245. const ScopedAutoReleasePool pool;
  225246. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225247. if (view == 0)
  225248. return false;
  225249. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225250. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225251. owner: nil];
  225252. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225253. for (int i = 0; i < files.size(); ++i)
  225254. [filesArray addObject: juceStringToNS (files[i])];
  225255. [pboard setPropertyList: filesArray
  225256. forType: NSFilenamesPboardType];
  225257. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225258. fromView: nil];
  225259. dragPosition.x -= 16;
  225260. dragPosition.y -= 16;
  225261. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225262. at: dragPosition
  225263. offset: NSMakeSize (0, 0)
  225264. event: [[view window] currentEvent]
  225265. pasteboard: pboard
  225266. source: view
  225267. slideBack: YES];
  225268. return true;
  225269. }
  225270. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225271. {
  225272. jassertfalse; // not implemented!
  225273. return false;
  225274. }
  225275. bool Desktop::canUseSemiTransparentWindows() throw()
  225276. {
  225277. return true;
  225278. }
  225279. const Point<int> MouseInputSource::getCurrentMousePosition()
  225280. {
  225281. const ScopedAutoReleasePool pool;
  225282. const NSPoint p ([NSEvent mouseLocation]);
  225283. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225284. }
  225285. void Desktop::setMousePosition (const Point<int>& newPosition)
  225286. {
  225287. // this rubbish needs to be done around the warp call, to avoid causing a
  225288. // bizarre glitch..
  225289. CGAssociateMouseAndMouseCursorPosition (false);
  225290. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225291. CGAssociateMouseAndMouseCursorPosition (true);
  225292. }
  225293. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225294. {
  225295. return upright;
  225296. }
  225297. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225298. class ScreenSaverDefeater : public Timer,
  225299. public DeletedAtShutdown
  225300. {
  225301. public:
  225302. ScreenSaverDefeater()
  225303. {
  225304. startTimer (10000);
  225305. timerCallback();
  225306. }
  225307. ~ScreenSaverDefeater() {}
  225308. void timerCallback()
  225309. {
  225310. if (Process::isForegroundProcess())
  225311. UpdateSystemActivity (UsrActivity);
  225312. }
  225313. };
  225314. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225315. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225316. {
  225317. if (isEnabled)
  225318. deleteAndZero (screenSaverDefeater);
  225319. else if (screenSaverDefeater == 0)
  225320. screenSaverDefeater = new ScreenSaverDefeater();
  225321. }
  225322. bool Desktop::isScreenSaverEnabled()
  225323. {
  225324. return screenSaverDefeater == 0;
  225325. }
  225326. #else
  225327. static IOPMAssertionID screenSaverDisablerID = 0;
  225328. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225329. {
  225330. if (isEnabled)
  225331. {
  225332. if (screenSaverDisablerID != 0)
  225333. {
  225334. IOPMAssertionRelease (screenSaverDisablerID);
  225335. screenSaverDisablerID = 0;
  225336. }
  225337. }
  225338. else
  225339. {
  225340. if (screenSaverDisablerID == 0)
  225341. {
  225342. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225343. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225344. CFSTR ("Juce"), &screenSaverDisablerID);
  225345. #else
  225346. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225347. &screenSaverDisablerID);
  225348. #endif
  225349. }
  225350. }
  225351. }
  225352. bool Desktop::isScreenSaverEnabled()
  225353. {
  225354. return screenSaverDisablerID == 0;
  225355. }
  225356. #endif
  225357. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225358. {
  225359. const ScopedAutoReleasePool pool;
  225360. monitorCoords.clear();
  225361. NSArray* screens = [NSScreen screens];
  225362. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225363. for (unsigned int i = 0; i < [screens count]; ++i)
  225364. {
  225365. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225366. NSRect r = clipToWorkArea ? [s visibleFrame]
  225367. : [s frame];
  225368. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225369. monitorCoords.add (convertToRectInt (r));
  225370. }
  225371. jassert (monitorCoords.size() > 0);
  225372. }
  225373. #endif
  225374. #endif
  225375. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225376. #endif
  225377. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225378. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225379. // compiled on its own).
  225380. #if JUCE_INCLUDED_FILE
  225381. void Logger::outputDebugString (const String& text)
  225382. {
  225383. std::cerr << text << std::endl;
  225384. }
  225385. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225386. {
  225387. static char testResult = 0;
  225388. if (testResult == 0)
  225389. {
  225390. struct kinfo_proc info;
  225391. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225392. size_t sz = sizeof (info);
  225393. sysctl (m, 4, &info, &sz, 0, 0);
  225394. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225395. }
  225396. return testResult > 0;
  225397. }
  225398. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225399. {
  225400. return juce_isRunningUnderDebugger();
  225401. }
  225402. #endif
  225403. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225404. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225405. #if JUCE_IOS
  225406. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225407. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225408. // compiled on its own).
  225409. #if JUCE_INCLUDED_FILE
  225410. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225411. #define SUPPORT_10_4_FONTS 1
  225412. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225413. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225414. #define SUPPORT_ONLY_10_4_FONTS 1
  225415. #endif
  225416. END_JUCE_NAMESPACE
  225417. @interface NSFont (PrivateHack)
  225418. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225419. @end
  225420. BEGIN_JUCE_NAMESPACE
  225421. #endif
  225422. class MacTypeface : public Typeface
  225423. {
  225424. public:
  225425. MacTypeface (const Font& font)
  225426. : Typeface (font.getTypefaceName())
  225427. {
  225428. const ScopedAutoReleasePool pool;
  225429. renderingTransform = CGAffineTransformIdentity;
  225430. bool needsItalicTransform = false;
  225431. #if JUCE_IOS
  225432. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225433. if (font.isItalic() || font.isBold())
  225434. {
  225435. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225436. for (NSString* i in familyFonts)
  225437. {
  225438. const String fn (nsStringToJuce (i));
  225439. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225440. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225441. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225442. || afterDash.containsIgnoreCase ("italic")
  225443. || fn.endsWithIgnoreCase ("oblique")
  225444. || fn.endsWithIgnoreCase ("italic");
  225445. if (probablyBold == font.isBold()
  225446. && probablyItalic == font.isItalic())
  225447. {
  225448. fontName = i;
  225449. needsItalicTransform = false;
  225450. break;
  225451. }
  225452. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225453. {
  225454. fontName = i;
  225455. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225456. }
  225457. }
  225458. if (needsItalicTransform)
  225459. renderingTransform.c = 0.15f;
  225460. }
  225461. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225462. const int ascender = abs (CGFontGetAscent (fontRef));
  225463. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225464. ascent = ascender / totalHeight;
  225465. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225466. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225467. #else
  225468. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225469. if (font.isItalic())
  225470. {
  225471. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225472. toHaveTrait: NSItalicFontMask];
  225473. if (newFont == nsFont)
  225474. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225475. nsFont = newFont;
  225476. }
  225477. if (font.isBold())
  225478. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225479. [nsFont retain];
  225480. ascent = std::abs ((float) [nsFont ascender]);
  225481. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225482. ascent /= totalSize;
  225483. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225484. if (needsItalicTransform)
  225485. {
  225486. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225487. renderingTransform.c = 0.15f;
  225488. }
  225489. #if SUPPORT_ONLY_10_4_FONTS
  225490. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225491. if (atsFont == 0)
  225492. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225493. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225494. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225495. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225496. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225497. #else
  225498. #if SUPPORT_10_4_FONTS
  225499. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225500. {
  225501. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225502. if (atsFont == 0)
  225503. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225504. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225505. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225506. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225507. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225508. }
  225509. else
  225510. #endif
  225511. {
  225512. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225513. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225514. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225515. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225516. }
  225517. #endif
  225518. #endif
  225519. }
  225520. ~MacTypeface()
  225521. {
  225522. #if ! JUCE_IOS
  225523. [nsFont release];
  225524. #endif
  225525. if (fontRef != 0)
  225526. CGFontRelease (fontRef);
  225527. }
  225528. float getAscent() const
  225529. {
  225530. return ascent;
  225531. }
  225532. float getDescent() const
  225533. {
  225534. return 1.0f - ascent;
  225535. }
  225536. float getStringWidth (const String& text)
  225537. {
  225538. if (fontRef == 0 || text.isEmpty())
  225539. return 0;
  225540. const int length = text.length();
  225541. HeapBlock <CGGlyph> glyphs;
  225542. createGlyphsForString (text, length, glyphs);
  225543. float x = 0;
  225544. #if SUPPORT_ONLY_10_4_FONTS
  225545. HeapBlock <NSSize> advances (length);
  225546. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225547. for (int i = 0; i < length; ++i)
  225548. x += advances[i].width;
  225549. #else
  225550. #if SUPPORT_10_4_FONTS
  225551. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225552. {
  225553. HeapBlock <NSSize> advances (length);
  225554. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225555. for (int i = 0; i < length; ++i)
  225556. x += advances[i].width;
  225557. }
  225558. else
  225559. #endif
  225560. {
  225561. HeapBlock <int> advances (length);
  225562. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225563. for (int i = 0; i < length; ++i)
  225564. x += advances[i];
  225565. }
  225566. #endif
  225567. return x * unitsToHeightScaleFactor;
  225568. }
  225569. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225570. {
  225571. xOffsets.add (0);
  225572. if (fontRef == 0 || text.isEmpty())
  225573. return;
  225574. const int length = text.length();
  225575. HeapBlock <CGGlyph> glyphs;
  225576. createGlyphsForString (text, length, glyphs);
  225577. #if SUPPORT_ONLY_10_4_FONTS
  225578. HeapBlock <NSSize> advances (length);
  225579. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225580. int x = 0;
  225581. for (int i = 0; i < length; ++i)
  225582. {
  225583. x += advances[i].width;
  225584. xOffsets.add (x * unitsToHeightScaleFactor);
  225585. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225586. }
  225587. #else
  225588. #if SUPPORT_10_4_FONTS
  225589. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225590. {
  225591. HeapBlock <NSSize> advances (length);
  225592. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225593. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225594. float x = 0;
  225595. for (int i = 0; i < length; ++i)
  225596. {
  225597. x += advances[i].width;
  225598. xOffsets.add (x * unitsToHeightScaleFactor);
  225599. resultGlyphs.add (nsGlyphs[i]);
  225600. }
  225601. }
  225602. else
  225603. #endif
  225604. {
  225605. HeapBlock <int> advances (length);
  225606. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225607. {
  225608. int x = 0;
  225609. for (int i = 0; i < length; ++i)
  225610. {
  225611. x += advances [i];
  225612. xOffsets.add (x * unitsToHeightScaleFactor);
  225613. resultGlyphs.add (glyphs[i]);
  225614. }
  225615. }
  225616. }
  225617. #endif
  225618. }
  225619. bool getOutlineForGlyph (int glyphNumber, Path& path)
  225620. {
  225621. #if JUCE_IOS
  225622. return false;
  225623. #else
  225624. if (nsFont == 0)
  225625. return false;
  225626. // we might need to apply a transform to the path, so it mustn't have anything else in it
  225627. jassert (path.isEmpty());
  225628. const ScopedAutoReleasePool pool;
  225629. NSBezierPath* bez = [NSBezierPath bezierPath];
  225630. [bez moveToPoint: NSMakePoint (0, 0)];
  225631. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  225632. inFont: nsFont];
  225633. for (int i = 0; i < [bez elementCount]; ++i)
  225634. {
  225635. NSPoint p[3];
  225636. switch ([bez elementAtIndex: i associatedPoints: p])
  225637. {
  225638. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  225639. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  225640. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  225641. (float) p[1].x, (float) -p[1].y,
  225642. (float) p[2].x, (float) -p[2].y); break;
  225643. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  225644. default: jassertfalse; break;
  225645. }
  225646. }
  225647. path.applyTransform (pathTransform);
  225648. return true;
  225649. #endif
  225650. }
  225651. CGFontRef fontRef;
  225652. float fontHeightToCGSizeFactor;
  225653. CGAffineTransform renderingTransform;
  225654. private:
  225655. float ascent, unitsToHeightScaleFactor;
  225656. #if JUCE_IOS
  225657. #else
  225658. NSFont* nsFont;
  225659. AffineTransform pathTransform;
  225660. #endif
  225661. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  225662. {
  225663. #if SUPPORT_10_4_FONTS
  225664. #if ! SUPPORT_ONLY_10_4_FONTS
  225665. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225666. #endif
  225667. {
  225668. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  225669. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225670. for (int i = 0; i < length; ++i)
  225671. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  225672. return;
  225673. }
  225674. #endif
  225675. #if ! SUPPORT_ONLY_10_4_FONTS
  225676. if (charToGlyphMapper == 0)
  225677. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  225678. glyphs.malloc (length);
  225679. for (int i = 0; i < length; ++i)
  225680. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  225681. #endif
  225682. }
  225683. #if ! SUPPORT_ONLY_10_4_FONTS
  225684. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  225685. class CharToGlyphMapper
  225686. {
  225687. public:
  225688. CharToGlyphMapper (CGFontRef fontRef)
  225689. : segCount (0), endCode (0), startCode (0), idDelta (0),
  225690. idRangeOffset (0), glyphIndexes (0)
  225691. {
  225692. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  225693. if (cmapTable != 0)
  225694. {
  225695. const int numSubtables = getValue16 (cmapTable, 2);
  225696. for (int i = 0; i < numSubtables; ++i)
  225697. {
  225698. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  225699. {
  225700. const int offset = getValue32 (cmapTable, i * 8 + 8);
  225701. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  225702. {
  225703. const int length = getValue16 (cmapTable, offset + 2);
  225704. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  225705. segCount = segCountX2 / 2;
  225706. const int endCodeOffset = offset + 14;
  225707. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  225708. const int idDeltaOffset = startCodeOffset + segCountX2;
  225709. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  225710. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  225711. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  225712. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  225713. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  225714. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  225715. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  225716. }
  225717. break;
  225718. }
  225719. }
  225720. CFRelease (cmapTable);
  225721. }
  225722. }
  225723. ~CharToGlyphMapper()
  225724. {
  225725. if (endCode != 0)
  225726. {
  225727. CFRelease (endCode);
  225728. CFRelease (startCode);
  225729. CFRelease (idDelta);
  225730. CFRelease (idRangeOffset);
  225731. CFRelease (glyphIndexes);
  225732. }
  225733. }
  225734. int getGlyphForCharacter (const juce_wchar c) const
  225735. {
  225736. for (int i = 0; i < segCount; ++i)
  225737. {
  225738. if (getValue16 (endCode, i * 2) >= c)
  225739. {
  225740. const int start = getValue16 (startCode, i * 2);
  225741. if (start > c)
  225742. break;
  225743. const int delta = getValue16 (idDelta, i * 2);
  225744. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225745. if (rangeOffset == 0)
  225746. return delta + c;
  225747. else
  225748. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225749. }
  225750. }
  225751. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225752. return jmax (-1, (int) c - 29);
  225753. }
  225754. private:
  225755. int segCount;
  225756. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225757. static uint16 getValue16 (CFDataRef data, const int index)
  225758. {
  225759. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225760. }
  225761. static uint32 getValue32 (CFDataRef data, const int index)
  225762. {
  225763. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225764. }
  225765. };
  225766. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225767. #endif
  225768. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  225769. };
  225770. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225771. {
  225772. return new MacTypeface (font);
  225773. }
  225774. const StringArray Font::findAllTypefaceNames()
  225775. {
  225776. StringArray names;
  225777. const ScopedAutoReleasePool pool;
  225778. #if JUCE_IOS
  225779. NSArray* fonts = [UIFont familyNames];
  225780. #else
  225781. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225782. #endif
  225783. for (unsigned int i = 0; i < [fonts count]; ++i)
  225784. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225785. names.sort (true);
  225786. return names;
  225787. }
  225788. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  225789. {
  225790. #if JUCE_IOS
  225791. defaultSans = "Helvetica";
  225792. defaultSerif = "Times New Roman";
  225793. defaultFixed = "Courier New";
  225794. #else
  225795. defaultSans = "Lucida Grande";
  225796. defaultSerif = "Times New Roman";
  225797. defaultFixed = "Monaco";
  225798. #endif
  225799. defaultFallback = "Arial Unicode MS";
  225800. }
  225801. #endif
  225802. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225803. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225804. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225805. // compiled on its own).
  225806. #if JUCE_INCLUDED_FILE
  225807. class CoreGraphicsImage : public Image::SharedImage
  225808. {
  225809. public:
  225810. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225811. : Image::SharedImage (format_, width_, height_)
  225812. {
  225813. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225814. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225815. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225816. imageData = imageDataAllocated;
  225817. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225818. : CGColorSpaceCreateDeviceRGB();
  225819. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225820. colourSpace, getCGImageFlags (format_));
  225821. CGColorSpaceRelease (colourSpace);
  225822. }
  225823. ~CoreGraphicsImage()
  225824. {
  225825. CGContextRelease (context);
  225826. }
  225827. Image::ImageType getType() const { return Image::NativeImage; }
  225828. LowLevelGraphicsContext* createLowLevelContext();
  225829. SharedImage* clone()
  225830. {
  225831. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225832. memcpy (im->imageData, imageData, lineStride * height);
  225833. return im;
  225834. }
  225835. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  225836. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  225837. {
  225838. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225839. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225840. {
  225841. return CGBitmapContextCreateImage (nativeImage->context);
  225842. }
  225843. else
  225844. {
  225845. const Image::BitmapData srcData (juceImage, false);
  225846. CGDataProviderRef provider;
  225847. if (mustOutliveSource)
  225848. {
  225849. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  225850. provider = CGDataProviderCreateWithCFData (data);
  225851. CFRelease (data);
  225852. }
  225853. else
  225854. {
  225855. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225856. }
  225857. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225858. 8, srcData.pixelStride * 8, srcData.lineStride,
  225859. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225860. 0, true, kCGRenderingIntentDefault);
  225861. CGDataProviderRelease (provider);
  225862. return imageRef;
  225863. }
  225864. }
  225865. #if JUCE_MAC
  225866. static NSImage* createNSImage (const Image& image)
  225867. {
  225868. const ScopedAutoReleasePool pool;
  225869. NSImage* im = [[NSImage alloc] init];
  225870. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225871. [im lockFocus];
  225872. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225873. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  225874. CGColorSpaceRelease (colourSpace);
  225875. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225876. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225877. CGImageRelease (imageRef);
  225878. [im unlockFocus];
  225879. return im;
  225880. }
  225881. #endif
  225882. CGContextRef context;
  225883. HeapBlock<uint8> imageDataAllocated;
  225884. private:
  225885. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225886. {
  225887. #if JUCE_BIG_ENDIAN
  225888. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225889. #else
  225890. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225891. #endif
  225892. }
  225893. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  225894. };
  225895. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225896. {
  225897. #if USE_COREGRAPHICS_RENDERING
  225898. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225899. #else
  225900. return createSoftwareImage (format, width, height, clearImage);
  225901. #endif
  225902. }
  225903. class CoreGraphicsContext : public LowLevelGraphicsContext
  225904. {
  225905. public:
  225906. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225907. : context (context_),
  225908. flipHeight (flipHeight_),
  225909. lastClipRectIsValid (false),
  225910. state (new SavedState()),
  225911. numGradientLookupEntries (0)
  225912. {
  225913. CGContextRetain (context);
  225914. CGContextSaveGState(context);
  225915. CGContextSetShouldSmoothFonts (context, true);
  225916. CGContextSetShouldAntialias (context, true);
  225917. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225918. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225919. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225920. gradientCallbacks.version = 0;
  225921. gradientCallbacks.evaluate = gradientCallback;
  225922. gradientCallbacks.releaseInfo = 0;
  225923. setFont (Font());
  225924. }
  225925. ~CoreGraphicsContext()
  225926. {
  225927. CGContextRestoreGState (context);
  225928. CGContextRelease (context);
  225929. CGColorSpaceRelease (rgbColourSpace);
  225930. CGColorSpaceRelease (greyColourSpace);
  225931. }
  225932. bool isVectorDevice() const { return false; }
  225933. void setOrigin (int x, int y)
  225934. {
  225935. CGContextTranslateCTM (context, x, -y);
  225936. if (lastClipRectIsValid)
  225937. lastClipRect.translate (-x, -y);
  225938. }
  225939. void addTransform (const AffineTransform& transform)
  225940. {
  225941. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  225942. .translated (0, flipHeight)
  225943. .followedBy (transform)
  225944. .translated (0, -flipHeight)
  225945. .scaled (1.0f, -1.0f));
  225946. lastClipRectIsValid = false;
  225947. }
  225948. float getScaleFactor()
  225949. {
  225950. CGAffineTransform t = CGContextGetCTM (context);
  225951. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  225952. }
  225953. bool clipToRectangle (const Rectangle<int>& r)
  225954. {
  225955. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225956. if (lastClipRectIsValid)
  225957. {
  225958. // This is actually incorrect, because the actual clip region may be complex, and
  225959. // clipping its bounds to a rect may not be right... But, removing this shortcut
  225960. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  225961. // when calculating the resultant clip bounds, and makes the same mistake!
  225962. lastClipRect = lastClipRect.getIntersection (r);
  225963. return ! lastClipRect.isEmpty();
  225964. }
  225965. return ! isClipEmpty();
  225966. }
  225967. bool clipToRectangleList (const RectangleList& clipRegion)
  225968. {
  225969. if (clipRegion.isEmpty())
  225970. {
  225971. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225972. lastClipRectIsValid = true;
  225973. lastClipRect = Rectangle<int>();
  225974. return false;
  225975. }
  225976. else
  225977. {
  225978. const int numRects = clipRegion.getNumRectangles();
  225979. HeapBlock <CGRect> rects (numRects);
  225980. for (int i = 0; i < numRects; ++i)
  225981. {
  225982. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225983. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225984. }
  225985. CGContextClipToRects (context, rects, numRects);
  225986. lastClipRectIsValid = false;
  225987. return ! isClipEmpty();
  225988. }
  225989. }
  225990. void excludeClipRectangle (const Rectangle<int>& r)
  225991. {
  225992. RectangleList remaining (getClipBounds());
  225993. remaining.subtract (r);
  225994. clipToRectangleList (remaining);
  225995. lastClipRectIsValid = false;
  225996. }
  225997. void clipToPath (const Path& path, const AffineTransform& transform)
  225998. {
  225999. createPath (path, transform);
  226000. CGContextClip (context);
  226001. lastClipRectIsValid = false;
  226002. }
  226003. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226004. {
  226005. if (! transform.isSingularity())
  226006. {
  226007. Image singleChannelImage (sourceImage);
  226008. if (sourceImage.getFormat() != Image::SingleChannel)
  226009. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226010. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  226011. flip();
  226012. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226013. applyTransform (t);
  226014. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226015. CGContextClipToMask (context, r, image);
  226016. applyTransform (t.inverted());
  226017. flip();
  226018. CGImageRelease (image);
  226019. lastClipRectIsValid = false;
  226020. }
  226021. }
  226022. bool clipRegionIntersects (const Rectangle<int>& r)
  226023. {
  226024. return getClipBounds().intersects (r);
  226025. }
  226026. const Rectangle<int> getClipBounds() const
  226027. {
  226028. if (! lastClipRectIsValid)
  226029. {
  226030. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226031. lastClipRectIsValid = true;
  226032. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226033. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226034. roundToInt (bounds.size.width),
  226035. roundToInt (bounds.size.height));
  226036. }
  226037. return lastClipRect;
  226038. }
  226039. bool isClipEmpty() const
  226040. {
  226041. return getClipBounds().isEmpty();
  226042. }
  226043. void saveState()
  226044. {
  226045. CGContextSaveGState (context);
  226046. stateStack.add (new SavedState (*state));
  226047. }
  226048. void restoreState()
  226049. {
  226050. CGContextRestoreGState (context);
  226051. SavedState* const top = stateStack.getLast();
  226052. if (top != 0)
  226053. {
  226054. state = top;
  226055. stateStack.removeLast (1, false);
  226056. lastClipRectIsValid = false;
  226057. }
  226058. else
  226059. {
  226060. jassertfalse; // trying to pop with an empty stack!
  226061. }
  226062. }
  226063. void beginTransparencyLayer (float opacity)
  226064. {
  226065. saveState();
  226066. CGContextSetAlpha (context, opacity);
  226067. CGContextBeginTransparencyLayer (context, 0);
  226068. }
  226069. void endTransparencyLayer()
  226070. {
  226071. CGContextEndTransparencyLayer (context);
  226072. restoreState();
  226073. }
  226074. void setFill (const FillType& fillType)
  226075. {
  226076. state->fillType = fillType;
  226077. if (fillType.isColour())
  226078. {
  226079. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226080. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226081. CGContextSetAlpha (context, 1.0f);
  226082. }
  226083. }
  226084. void setOpacity (float newOpacity)
  226085. {
  226086. state->fillType.setOpacity (newOpacity);
  226087. setFill (state->fillType);
  226088. }
  226089. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226090. {
  226091. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226092. ? kCGInterpolationLow
  226093. : kCGInterpolationHigh);
  226094. }
  226095. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226096. {
  226097. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226098. }
  226099. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226100. {
  226101. if (replaceExistingContents)
  226102. {
  226103. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226104. CGContextClearRect (context, cgRect);
  226105. #else
  226106. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226107. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226108. CGContextClearRect (context, cgRect);
  226109. else
  226110. #endif
  226111. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226112. #endif
  226113. fillCGRect (cgRect, false);
  226114. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226115. }
  226116. else
  226117. {
  226118. if (state->fillType.isColour())
  226119. {
  226120. CGContextFillRect (context, cgRect);
  226121. }
  226122. else if (state->fillType.isGradient())
  226123. {
  226124. CGContextSaveGState (context);
  226125. CGContextClipToRect (context, cgRect);
  226126. drawGradient();
  226127. CGContextRestoreGState (context);
  226128. }
  226129. else
  226130. {
  226131. CGContextSaveGState (context);
  226132. CGContextClipToRect (context, cgRect);
  226133. drawImage (state->fillType.image, state->fillType.transform, true);
  226134. CGContextRestoreGState (context);
  226135. }
  226136. }
  226137. }
  226138. void fillPath (const Path& path, const AffineTransform& transform)
  226139. {
  226140. CGContextSaveGState (context);
  226141. if (state->fillType.isColour())
  226142. {
  226143. flip();
  226144. applyTransform (transform);
  226145. createPath (path);
  226146. if (path.isUsingNonZeroWinding())
  226147. CGContextFillPath (context);
  226148. else
  226149. CGContextEOFillPath (context);
  226150. }
  226151. else
  226152. {
  226153. createPath (path, transform);
  226154. if (path.isUsingNonZeroWinding())
  226155. CGContextClip (context);
  226156. else
  226157. CGContextEOClip (context);
  226158. if (state->fillType.isGradient())
  226159. drawGradient();
  226160. else
  226161. drawImage (state->fillType.image, state->fillType.transform, true);
  226162. }
  226163. CGContextRestoreGState (context);
  226164. }
  226165. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226166. {
  226167. const int iw = sourceImage.getWidth();
  226168. const int ih = sourceImage.getHeight();
  226169. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  226170. CGContextSaveGState (context);
  226171. CGContextSetAlpha (context, state->fillType.getOpacity());
  226172. flip();
  226173. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226174. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226175. if (fillEntireClipAsTiles)
  226176. {
  226177. #if JUCE_IOS
  226178. CGContextDrawTiledImage (context, imageRect, image);
  226179. #else
  226180. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226181. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226182. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226183. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226184. CGContextDrawTiledImage (context, imageRect, image);
  226185. else
  226186. #endif
  226187. {
  226188. // Fallback to manually doing a tiled fill on 10.4
  226189. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226190. int x = 0, y = 0;
  226191. while (x > clip.origin.x) x -= iw;
  226192. while (y > clip.origin.y) y -= ih;
  226193. const int right = (int) (clip.origin.x + clip.size.width);
  226194. const int bottom = (int) (clip.origin.y + clip.size.height);
  226195. while (y < bottom)
  226196. {
  226197. for (int x2 = x; x2 < right; x2 += iw)
  226198. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226199. y += ih;
  226200. }
  226201. }
  226202. #endif
  226203. }
  226204. else
  226205. {
  226206. CGContextDrawImage (context, imageRect, image);
  226207. }
  226208. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226209. CGContextRestoreGState (context);
  226210. }
  226211. void drawLine (const Line<float>& line)
  226212. {
  226213. if (state->fillType.isColour())
  226214. {
  226215. CGContextSetLineCap (context, kCGLineCapSquare);
  226216. CGContextSetLineWidth (context, 1.0f);
  226217. CGContextSetRGBStrokeColor (context,
  226218. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226219. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226220. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226221. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226222. CGContextStrokeLineSegments (context, cgLine, 1);
  226223. }
  226224. else
  226225. {
  226226. Path p;
  226227. p.addLineSegment (line, 1.0f);
  226228. fillPath (p, AffineTransform::identity);
  226229. }
  226230. }
  226231. void drawVerticalLine (const int x, float top, float bottom)
  226232. {
  226233. if (state->fillType.isColour())
  226234. {
  226235. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226236. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226237. #else
  226238. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226239. // the x co-ord slightly to trick it..
  226240. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226241. #endif
  226242. }
  226243. else
  226244. {
  226245. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226246. }
  226247. }
  226248. void drawHorizontalLine (const int y, float left, float right)
  226249. {
  226250. if (state->fillType.isColour())
  226251. {
  226252. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226253. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226254. #else
  226255. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226256. // the x co-ord slightly to trick it..
  226257. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226258. #endif
  226259. }
  226260. else
  226261. {
  226262. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226263. }
  226264. }
  226265. void setFont (const Font& newFont)
  226266. {
  226267. if (state->font != newFont)
  226268. {
  226269. state->fontRef = 0;
  226270. state->font = newFont;
  226271. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226272. if (mf != 0)
  226273. {
  226274. state->fontRef = mf->fontRef;
  226275. CGContextSetFont (context, state->fontRef);
  226276. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226277. state->fontTransform = mf->renderingTransform;
  226278. state->fontTransform.a *= state->font.getHorizontalScale();
  226279. CGContextSetTextMatrix (context, state->fontTransform);
  226280. }
  226281. }
  226282. }
  226283. const Font getFont()
  226284. {
  226285. return state->font;
  226286. }
  226287. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226288. {
  226289. if (state->fontRef != 0 && state->fillType.isColour())
  226290. {
  226291. if (transform.isOnlyTranslation())
  226292. {
  226293. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226294. CGGlyph g = glyphNumber;
  226295. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226296. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226297. }
  226298. else
  226299. {
  226300. CGContextSaveGState (context);
  226301. flip();
  226302. applyTransform (transform);
  226303. CGAffineTransform t = state->fontTransform;
  226304. t.d = -t.d;
  226305. CGContextSetTextMatrix (context, t);
  226306. CGGlyph g = glyphNumber;
  226307. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226308. CGContextRestoreGState (context);
  226309. }
  226310. }
  226311. else
  226312. {
  226313. Path p;
  226314. Font& f = state->font;
  226315. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226316. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226317. .followedBy (transform));
  226318. }
  226319. }
  226320. private:
  226321. CGContextRef context;
  226322. const CGFloat flipHeight;
  226323. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226324. CGFunctionCallbacks gradientCallbacks;
  226325. mutable Rectangle<int> lastClipRect;
  226326. mutable bool lastClipRectIsValid;
  226327. struct SavedState
  226328. {
  226329. SavedState()
  226330. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226331. {
  226332. }
  226333. SavedState (const SavedState& other)
  226334. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226335. fontTransform (other.fontTransform)
  226336. {
  226337. }
  226338. FillType fillType;
  226339. Font font;
  226340. CGFontRef fontRef;
  226341. CGAffineTransform fontTransform;
  226342. };
  226343. ScopedPointer <SavedState> state;
  226344. OwnedArray <SavedState> stateStack;
  226345. HeapBlock <PixelARGB> gradientLookupTable;
  226346. int numGradientLookupEntries;
  226347. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226348. {
  226349. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226350. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226351. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226352. colour.unpremultiply();
  226353. outData[0] = colour.getRed() / 255.0f;
  226354. outData[1] = colour.getGreen() / 255.0f;
  226355. outData[2] = colour.getBlue() / 255.0f;
  226356. outData[3] = colour.getAlpha() / 255.0f;
  226357. }
  226358. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226359. {
  226360. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  226361. CGShadingRef result = 0;
  226362. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226363. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226364. if (gradient.isRadial)
  226365. {
  226366. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226367. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226368. function, true, true);
  226369. }
  226370. else
  226371. {
  226372. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226373. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226374. function, true, true);
  226375. }
  226376. CGFunctionRelease (function);
  226377. return result;
  226378. }
  226379. void drawGradient()
  226380. {
  226381. flip();
  226382. applyTransform (state->fillType.transform);
  226383. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226384. // you draw a gradient with high quality interp enabled).
  226385. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226386. CGContextSetAlpha (context, state->fillType.getOpacity());
  226387. CGContextDrawShading (context, shading);
  226388. CGShadingRelease (shading);
  226389. }
  226390. void createPath (const Path& path) const
  226391. {
  226392. CGContextBeginPath (context);
  226393. Path::Iterator i (path);
  226394. while (i.next())
  226395. {
  226396. switch (i.elementType)
  226397. {
  226398. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226399. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226400. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226401. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226402. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226403. default: jassertfalse; break;
  226404. }
  226405. }
  226406. }
  226407. void createPath (const Path& path, const AffineTransform& transform) const
  226408. {
  226409. CGContextBeginPath (context);
  226410. Path::Iterator i (path);
  226411. while (i.next())
  226412. {
  226413. switch (i.elementType)
  226414. {
  226415. case Path::Iterator::startNewSubPath:
  226416. transform.transformPoint (i.x1, i.y1);
  226417. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226418. break;
  226419. case Path::Iterator::lineTo:
  226420. transform.transformPoint (i.x1, i.y1);
  226421. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226422. break;
  226423. case Path::Iterator::quadraticTo:
  226424. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226425. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226426. break;
  226427. case Path::Iterator::cubicTo:
  226428. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226429. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226430. break;
  226431. case Path::Iterator::closePath:
  226432. CGContextClosePath (context); break;
  226433. default:
  226434. jassertfalse;
  226435. break;
  226436. }
  226437. }
  226438. }
  226439. void flip() const
  226440. {
  226441. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226442. }
  226443. void applyTransform (const AffineTransform& transform) const
  226444. {
  226445. CGAffineTransform t;
  226446. t.a = transform.mat00;
  226447. t.b = transform.mat10;
  226448. t.c = transform.mat01;
  226449. t.d = transform.mat11;
  226450. t.tx = transform.mat02;
  226451. t.ty = transform.mat12;
  226452. CGContextConcatCTM (context, t);
  226453. }
  226454. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226455. };
  226456. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226457. {
  226458. return new CoreGraphicsContext (context, height);
  226459. }
  226460. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226461. const Image juce_loadWithCoreImage (InputStream& input)
  226462. {
  226463. MemoryBlock data;
  226464. input.readIntoMemoryBlock (data, -1);
  226465. #if JUCE_IOS
  226466. JUCE_AUTORELEASEPOOL
  226467. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226468. length: data.getSize()
  226469. freeWhenDone: NO]];
  226470. if (image != nil)
  226471. {
  226472. CGImageRef loadedImage = image.CGImage;
  226473. #else
  226474. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226475. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  226476. CGDataProviderRelease (provider);
  226477. if (imageSource != 0)
  226478. {
  226479. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  226480. CFRelease (imageSource);
  226481. #endif
  226482. if (loadedImage != 0)
  226483. {
  226484. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  226485. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  226486. && alphaInfo != kCGImageAlphaNoneSkipLast
  226487. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  226488. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  226489. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  226490. hasAlphaChan, Image::NativeImage);
  226491. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  226492. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  226493. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  226494. CGContextFlush (cgImage->context);
  226495. #if ! JUCE_IOS
  226496. CFRelease (loadedImage);
  226497. #endif
  226498. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  226499. // to find out whether the file they just loaded the image from had an alpha channel or not.
  226500. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  226501. return image;
  226502. }
  226503. }
  226504. return Image::null;
  226505. }
  226506. #endif
  226507. #endif
  226508. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226509. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226510. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226511. // compiled on its own).
  226512. #if JUCE_INCLUDED_FILE
  226513. class UIViewComponentPeer;
  226514. END_JUCE_NAMESPACE
  226515. #define JuceUIView MakeObjCClassName(JuceUIView)
  226516. @interface JuceUIView : UIView <UITextViewDelegate>
  226517. {
  226518. @public
  226519. UIViewComponentPeer* owner;
  226520. UITextView* hiddenTextView;
  226521. }
  226522. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  226523. - (void) dealloc;
  226524. - (void) drawRect: (CGRect) r;
  226525. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  226526. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  226527. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  226528. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  226529. - (BOOL) becomeFirstResponder;
  226530. - (BOOL) resignFirstResponder;
  226531. - (BOOL) canBecomeFirstResponder;
  226532. - (void) asyncRepaint: (id) rect;
  226533. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  226534. @end
  226535. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  226536. @interface JuceUIViewController : UIViewController
  226537. {
  226538. }
  226539. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  226540. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  226541. @end
  226542. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  226543. @interface JuceUIWindow : UIWindow
  226544. {
  226545. @private
  226546. UIViewComponentPeer* owner;
  226547. bool isZooming;
  226548. }
  226549. - (void) setOwner: (UIViewComponentPeer*) owner;
  226550. - (void) becomeKeyWindow;
  226551. @end
  226552. BEGIN_JUCE_NAMESPACE
  226553. class UIViewComponentPeer : public ComponentPeer,
  226554. public FocusChangeListener
  226555. {
  226556. public:
  226557. UIViewComponentPeer (Component* const component,
  226558. const int windowStyleFlags,
  226559. UIView* viewToAttachTo);
  226560. ~UIViewComponentPeer();
  226561. void* getNativeHandle() const;
  226562. void setVisible (bool shouldBeVisible);
  226563. void setTitle (const String& title);
  226564. void setPosition (int x, int y);
  226565. void setSize (int w, int h);
  226566. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  226567. const Rectangle<int> getBounds() const;
  226568. const Rectangle<int> getBounds (const bool global) const;
  226569. const Point<int> getScreenPosition() const;
  226570. const Point<int> localToGlobal (const Point<int>& relativePosition);
  226571. const Point<int> globalToLocal (const Point<int>& screenPosition);
  226572. void setAlpha (float newAlpha);
  226573. void setMinimised (bool shouldBeMinimised);
  226574. bool isMinimised() const;
  226575. void setFullScreen (bool shouldBeFullScreen);
  226576. bool isFullScreen() const;
  226577. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226578. const BorderSize<int> getFrameSize() const;
  226579. bool setAlwaysOnTop (bool alwaysOnTop);
  226580. void toFront (bool makeActiveWindow);
  226581. void toBehind (ComponentPeer* other);
  226582. void setIcon (const Image& newIcon);
  226583. virtual void drawRect (CGRect r);
  226584. virtual bool canBecomeKeyWindow();
  226585. virtual bool windowShouldClose();
  226586. virtual void redirectMovedOrResized();
  226587. virtual CGRect constrainRect (CGRect r);
  226588. virtual void viewFocusGain();
  226589. virtual void viewFocusLoss();
  226590. bool isFocused() const;
  226591. void grabFocus();
  226592. void textInputRequired (const Point<int>& position);
  226593. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  226594. void updateHiddenTextContent (TextInputTarget* target);
  226595. void globalFocusChanged (Component*);
  226596. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  226597. virtual void displayRotated();
  226598. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  226599. void repaint (const Rectangle<int>& area);
  226600. void performAnyPendingRepaintsNow();
  226601. UIWindow* window;
  226602. JuceUIView* view;
  226603. JuceUIViewController* controller;
  226604. bool isSharedWindow, fullScreen, insideDrawRect;
  226605. static ModifierKeys currentModifiers;
  226606. static int64 getMouseTime (UIEvent* e)
  226607. {
  226608. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  226609. + (int64) ([e timestamp] * 1000.0);
  226610. }
  226611. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  226612. {
  226613. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226614. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226615. {
  226616. case UIInterfaceOrientationPortrait:
  226617. return r;
  226618. case UIInterfaceOrientationPortraitUpsideDown:
  226619. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226620. r.getWidth(), r.getHeight());
  226621. case UIInterfaceOrientationLandscapeLeft:
  226622. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  226623. r.getHeight(), r.getWidth());
  226624. case UIInterfaceOrientationLandscapeRight:
  226625. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  226626. r.getHeight(), r.getWidth());
  226627. default: jassertfalse; // unknown orientation!
  226628. }
  226629. return r;
  226630. }
  226631. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  226632. {
  226633. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226634. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226635. {
  226636. case UIInterfaceOrientationPortrait:
  226637. return r;
  226638. case UIInterfaceOrientationPortraitUpsideDown:
  226639. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226640. r.getWidth(), r.getHeight());
  226641. case UIInterfaceOrientationLandscapeLeft:
  226642. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  226643. r.getHeight(), r.getWidth());
  226644. case UIInterfaceOrientationLandscapeRight:
  226645. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  226646. r.getHeight(), r.getWidth());
  226647. default: jassertfalse; // unknown orientation!
  226648. }
  226649. return r;
  226650. }
  226651. Array <UITouch*> currentTouches;
  226652. private:
  226653. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  226654. };
  226655. END_JUCE_NAMESPACE
  226656. @implementation JuceUIViewController
  226657. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  226658. {
  226659. JuceUIView* juceView = (JuceUIView*) [self view];
  226660. jassert (juceView != 0 && juceView->owner != 0);
  226661. return juceView->owner->shouldRotate (interfaceOrientation);
  226662. }
  226663. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  226664. {
  226665. JuceUIView* juceView = (JuceUIView*) [self view];
  226666. jassert (juceView != 0 && juceView->owner != 0);
  226667. juceView->owner->displayRotated();
  226668. }
  226669. @end
  226670. @implementation JuceUIView
  226671. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  226672. withFrame: (CGRect) frame
  226673. {
  226674. [super initWithFrame: frame];
  226675. owner = owner_;
  226676. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  226677. [self addSubview: hiddenTextView];
  226678. hiddenTextView.delegate = self;
  226679. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  226680. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  226681. return self;
  226682. }
  226683. - (void) dealloc
  226684. {
  226685. [hiddenTextView removeFromSuperview];
  226686. [hiddenTextView release];
  226687. [super dealloc];
  226688. }
  226689. - (void) drawRect: (CGRect) r
  226690. {
  226691. if (owner != 0)
  226692. owner->drawRect (r);
  226693. }
  226694. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  226695. {
  226696. return false;
  226697. }
  226698. ModifierKeys UIViewComponentPeer::currentModifiers;
  226699. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  226700. {
  226701. return UIViewComponentPeer::currentModifiers;
  226702. }
  226703. void ModifierKeys::updateCurrentModifiers() throw()
  226704. {
  226705. currentModifiers = UIViewComponentPeer::currentModifiers;
  226706. }
  226707. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  226708. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  226709. {
  226710. if (owner != 0)
  226711. owner->handleTouches (event, true, false, false);
  226712. }
  226713. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  226714. {
  226715. if (owner != 0)
  226716. owner->handleTouches (event, false, false, false);
  226717. }
  226718. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  226719. {
  226720. if (owner != 0)
  226721. owner->handleTouches (event, false, true, false);
  226722. }
  226723. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  226724. {
  226725. if (owner != 0)
  226726. owner->handleTouches (event, false, true, true);
  226727. [self touchesEnded: touches withEvent: event];
  226728. }
  226729. - (BOOL) becomeFirstResponder
  226730. {
  226731. if (owner != 0)
  226732. owner->viewFocusGain();
  226733. return true;
  226734. }
  226735. - (BOOL) resignFirstResponder
  226736. {
  226737. if (owner != 0)
  226738. owner->viewFocusLoss();
  226739. return true;
  226740. }
  226741. - (BOOL) canBecomeFirstResponder
  226742. {
  226743. return owner != 0 && owner->canBecomeKeyWindow();
  226744. }
  226745. - (void) asyncRepaint: (id) rect
  226746. {
  226747. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  226748. [self setNeedsDisplayInRect: *r];
  226749. }
  226750. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  226751. {
  226752. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  226753. nsStringToJuce (text));
  226754. }
  226755. @end
  226756. @implementation JuceUIWindow
  226757. - (void) setOwner: (UIViewComponentPeer*) owner_
  226758. {
  226759. owner = owner_;
  226760. isZooming = false;
  226761. }
  226762. - (void) becomeKeyWindow
  226763. {
  226764. [super becomeKeyWindow];
  226765. if (owner != 0)
  226766. owner->grabFocus();
  226767. }
  226768. @end
  226769. BEGIN_JUCE_NAMESPACE
  226770. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  226771. const int windowStyleFlags,
  226772. UIView* viewToAttachTo)
  226773. : ComponentPeer (component, windowStyleFlags),
  226774. window (0),
  226775. view (0), controller (0),
  226776. isSharedWindow (viewToAttachTo != 0),
  226777. fullScreen (false),
  226778. insideDrawRect (false)
  226779. {
  226780. CGRect r = convertToCGRect (component->getLocalBounds());
  226781. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  226782. if (isSharedWindow)
  226783. {
  226784. window = [viewToAttachTo window];
  226785. [viewToAttachTo addSubview: view];
  226786. setVisible (component->isVisible());
  226787. }
  226788. else
  226789. {
  226790. controller = [[JuceUIViewController alloc] init];
  226791. controller.view = view;
  226792. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  226793. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  226794. window = [[JuceUIWindow alloc] init];
  226795. window.frame = r;
  226796. window.opaque = component->isOpaque();
  226797. view.opaque = component->isOpaque();
  226798. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226799. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226800. [((JuceUIWindow*) window) setOwner: this];
  226801. if (component->isAlwaysOnTop())
  226802. window.windowLevel = UIWindowLevelAlert;
  226803. [window addSubview: view];
  226804. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226805. view.hidden = ! component->isVisible();
  226806. window.hidden = ! component->isVisible();
  226807. view.multipleTouchEnabled = YES;
  226808. }
  226809. setTitle (component->getName());
  226810. Desktop::getInstance().addFocusChangeListener (this);
  226811. }
  226812. UIViewComponentPeer::~UIViewComponentPeer()
  226813. {
  226814. Desktop::getInstance().removeFocusChangeListener (this);
  226815. view->owner = 0;
  226816. [view removeFromSuperview];
  226817. [view release];
  226818. [controller release];
  226819. if (! isSharedWindow)
  226820. {
  226821. [((JuceUIWindow*) window) setOwner: 0];
  226822. [window release];
  226823. }
  226824. }
  226825. void* UIViewComponentPeer::getNativeHandle() const
  226826. {
  226827. return view;
  226828. }
  226829. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  226830. {
  226831. view.hidden = ! shouldBeVisible;
  226832. if (! isSharedWindow)
  226833. window.hidden = ! shouldBeVisible;
  226834. }
  226835. void UIViewComponentPeer::setTitle (const String& title)
  226836. {
  226837. // xxx is this possible?
  226838. }
  226839. void UIViewComponentPeer::setPosition (int x, int y)
  226840. {
  226841. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  226842. }
  226843. void UIViewComponentPeer::setSize (int w, int h)
  226844. {
  226845. setBounds (component->getX(), component->getY(), w, h, false);
  226846. }
  226847. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  226848. {
  226849. fullScreen = isNowFullScreen;
  226850. w = jmax (0, w);
  226851. h = jmax (0, h);
  226852. if (isSharedWindow)
  226853. {
  226854. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  226855. if ([view frame].size.width != r.size.width
  226856. || [view frame].size.height != r.size.height)
  226857. [view setNeedsDisplay];
  226858. view.frame = r;
  226859. }
  226860. else
  226861. {
  226862. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  226863. window.frame = convertToCGRect (bounds);
  226864. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  226865. handleMovedOrResized();
  226866. }
  226867. }
  226868. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  226869. {
  226870. CGRect r = [view frame];
  226871. if (global && [view window] != 0)
  226872. {
  226873. r = [view convertRect: r toView: nil];
  226874. CGRect wr = [[view window] frame];
  226875. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  226876. r.origin.x = windowBounds.getX();
  226877. r.origin.y = windowBounds.getY();
  226878. }
  226879. return convertToRectInt (r);
  226880. }
  226881. const Rectangle<int> UIViewComponentPeer::getBounds() const
  226882. {
  226883. return getBounds (! isSharedWindow);
  226884. }
  226885. const Point<int> UIViewComponentPeer::getScreenPosition() const
  226886. {
  226887. return getBounds (true).getPosition();
  226888. }
  226889. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  226890. {
  226891. return relativePosition + getScreenPosition();
  226892. }
  226893. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  226894. {
  226895. return screenPosition - getScreenPosition();
  226896. }
  226897. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  226898. {
  226899. if (constrainer != 0)
  226900. {
  226901. CGRect current = [window frame];
  226902. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  226903. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  226904. Rectangle<int> pos (convertToRectInt (r));
  226905. Rectangle<int> original (convertToRectInt (current));
  226906. constrainer->checkBounds (pos, original,
  226907. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  226908. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  226909. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  226910. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  226911. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  226912. r.origin.x = pos.getX();
  226913. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  226914. r.size.width = pos.getWidth();
  226915. r.size.height = pos.getHeight();
  226916. }
  226917. return r;
  226918. }
  226919. void UIViewComponentPeer::setAlpha (float newAlpha)
  226920. {
  226921. [[view window] setAlpha: (CGFloat) newAlpha];
  226922. }
  226923. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  226924. {
  226925. }
  226926. bool UIViewComponentPeer::isMinimised() const
  226927. {
  226928. return false;
  226929. }
  226930. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  226931. {
  226932. if (! isSharedWindow)
  226933. {
  226934. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  226935. : lastNonFullscreenBounds);
  226936. if ((! shouldBeFullScreen) && r.isEmpty())
  226937. r = getBounds();
  226938. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  226939. if (! r.isEmpty())
  226940. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  226941. component->repaint();
  226942. }
  226943. }
  226944. bool UIViewComponentPeer::isFullScreen() const
  226945. {
  226946. return fullScreen;
  226947. }
  226948. namespace
  226949. {
  226950. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  226951. {
  226952. switch (interfaceOrientation)
  226953. {
  226954. case UIInterfaceOrientationPortrait: return Desktop::upright;
  226955. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  226956. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  226957. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  226958. default: jassertfalse; // unknown orientation!
  226959. }
  226960. return Desktop::upright;
  226961. }
  226962. }
  226963. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  226964. {
  226965. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  226966. }
  226967. void UIViewComponentPeer::displayRotated()
  226968. {
  226969. const Rectangle<int> oldArea (component->getBounds());
  226970. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  226971. Desktop::getInstance().refreshMonitorSizes();
  226972. if (fullScreen)
  226973. {
  226974. fullScreen = false;
  226975. setFullScreen (true);
  226976. }
  226977. else
  226978. {
  226979. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  226980. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  226981. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  226982. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  226983. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  226984. setBounds ((int) (l * newDesktop.getWidth()),
  226985. (int) (t * newDesktop.getHeight()),
  226986. (int) ((r - l) * newDesktop.getWidth()),
  226987. (int) ((b - t) * newDesktop.getHeight()),
  226988. false);
  226989. }
  226990. }
  226991. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  226992. {
  226993. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  226994. && isPositiveAndBelow (position.getY(), component->getHeight())))
  226995. return false;
  226996. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  226997. withEvent: nil];
  226998. if (trueIfInAChildWindow)
  226999. return v != nil;
  227000. return v == view;
  227001. }
  227002. const BorderSize<int> UIViewComponentPeer::getFrameSize() const
  227003. {
  227004. return BorderSize<int>();
  227005. }
  227006. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227007. {
  227008. if (! isSharedWindow)
  227009. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227010. return true;
  227011. }
  227012. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227013. {
  227014. if (isSharedWindow)
  227015. [[view superview] bringSubviewToFront: view];
  227016. if (window != 0 && component->isVisible())
  227017. [window makeKeyAndVisible];
  227018. }
  227019. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227020. {
  227021. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227022. jassert (otherPeer != 0); // wrong type of window?
  227023. if (otherPeer != 0)
  227024. {
  227025. if (isSharedWindow)
  227026. {
  227027. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227028. }
  227029. else
  227030. {
  227031. jassertfalse; // don't know how to do this
  227032. }
  227033. }
  227034. }
  227035. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227036. {
  227037. // to do..
  227038. }
  227039. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227040. {
  227041. NSArray* touches = [[event touchesForView: view] allObjects];
  227042. for (unsigned int i = 0; i < [touches count]; ++i)
  227043. {
  227044. UITouch* touch = [touches objectAtIndex: i];
  227045. CGPoint p = [touch locationInView: view];
  227046. const Point<int> pos ((int) p.x, (int) p.y);
  227047. juce_lastMousePos = pos + getScreenPosition();
  227048. const int64 time = getMouseTime (event);
  227049. int touchIndex = currentTouches.indexOf (touch);
  227050. if (touchIndex < 0)
  227051. {
  227052. touchIndex = currentTouches.size();
  227053. currentTouches.add (touch);
  227054. }
  227055. if (isDown)
  227056. {
  227057. currentModifiers = currentModifiers.withoutMouseButtons();
  227058. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227059. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227060. }
  227061. else if (isUp)
  227062. {
  227063. currentModifiers = currentModifiers.withoutMouseButtons();
  227064. currentTouches.remove (touchIndex);
  227065. }
  227066. if (isCancel)
  227067. currentTouches.clear();
  227068. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227069. }
  227070. }
  227071. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227072. void UIViewComponentPeer::viewFocusGain()
  227073. {
  227074. if (currentlyFocusedPeer != this)
  227075. {
  227076. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227077. currentlyFocusedPeer->handleFocusLoss();
  227078. currentlyFocusedPeer = this;
  227079. handleFocusGain();
  227080. }
  227081. }
  227082. void UIViewComponentPeer::viewFocusLoss()
  227083. {
  227084. if (currentlyFocusedPeer == this)
  227085. {
  227086. currentlyFocusedPeer = 0;
  227087. handleFocusLoss();
  227088. }
  227089. }
  227090. void juce_HandleProcessFocusChange()
  227091. {
  227092. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227093. {
  227094. if (Process::isForegroundProcess())
  227095. {
  227096. currentlyFocusedPeer->handleFocusGain();
  227097. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227098. }
  227099. else
  227100. {
  227101. currentlyFocusedPeer->handleFocusLoss();
  227102. // turn kiosk mode off if we lose focus..
  227103. Desktop::getInstance().setKioskModeComponent (0);
  227104. }
  227105. }
  227106. }
  227107. bool UIViewComponentPeer::isFocused() const
  227108. {
  227109. return isSharedWindow ? this == currentlyFocusedPeer
  227110. : (window != 0 && [window isKeyWindow]);
  227111. }
  227112. void UIViewComponentPeer::grabFocus()
  227113. {
  227114. if (window != 0)
  227115. {
  227116. [window makeKeyWindow];
  227117. viewFocusGain();
  227118. }
  227119. }
  227120. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227121. {
  227122. }
  227123. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227124. {
  227125. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227126. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227127. }
  227128. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227129. {
  227130. TextInputTarget* const target = findCurrentTextInputTarget();
  227131. if (target != 0)
  227132. {
  227133. const Range<int> currentSelection (target->getHighlightedRegion());
  227134. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227135. if (currentSelection.isEmpty())
  227136. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227137. target->insertTextAtCaret (text);
  227138. updateHiddenTextContent (target);
  227139. }
  227140. return NO;
  227141. }
  227142. void UIViewComponentPeer::globalFocusChanged (Component*)
  227143. {
  227144. TextInputTarget* const target = findCurrentTextInputTarget();
  227145. if (target != 0)
  227146. {
  227147. Component* comp = dynamic_cast<Component*> (target);
  227148. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227149. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227150. updateHiddenTextContent (target);
  227151. [view->hiddenTextView becomeFirstResponder];
  227152. }
  227153. else
  227154. {
  227155. [view->hiddenTextView resignFirstResponder];
  227156. }
  227157. }
  227158. void UIViewComponentPeer::drawRect (CGRect r)
  227159. {
  227160. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227161. return;
  227162. CGContextRef cg = UIGraphicsGetCurrentContext();
  227163. if (! component->isOpaque())
  227164. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227165. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227166. CoreGraphicsContext g (cg, view.bounds.size.height);
  227167. insideDrawRect = true;
  227168. handlePaint (g);
  227169. insideDrawRect = false;
  227170. }
  227171. bool UIViewComponentPeer::canBecomeKeyWindow()
  227172. {
  227173. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227174. }
  227175. bool UIViewComponentPeer::windowShouldClose()
  227176. {
  227177. if (! isValidPeer (this))
  227178. return YES;
  227179. handleUserClosingWindow();
  227180. return NO;
  227181. }
  227182. void UIViewComponentPeer::redirectMovedOrResized()
  227183. {
  227184. handleMovedOrResized();
  227185. }
  227186. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227187. {
  227188. }
  227189. class AsyncRepaintMessage : public CallbackMessage
  227190. {
  227191. public:
  227192. UIViewComponentPeer* const peer;
  227193. const Rectangle<int> rect;
  227194. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227195. : peer (peer_), rect (rect_)
  227196. {
  227197. }
  227198. void messageCallback()
  227199. {
  227200. if (ComponentPeer::isValidPeer (peer))
  227201. peer->repaint (rect);
  227202. }
  227203. };
  227204. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227205. {
  227206. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227207. {
  227208. (new AsyncRepaintMessage (this, area))->post();
  227209. }
  227210. else
  227211. {
  227212. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227213. }
  227214. }
  227215. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227216. {
  227217. }
  227218. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227219. {
  227220. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227221. }
  227222. const Image juce_createIconForFile (const File& file)
  227223. {
  227224. return Image::null;
  227225. }
  227226. void Desktop::createMouseInputSources()
  227227. {
  227228. for (int i = 0; i < 10; ++i)
  227229. mouseSources.add (new MouseInputSource (i, false));
  227230. }
  227231. bool Desktop::canUseSemiTransparentWindows() throw()
  227232. {
  227233. return true;
  227234. }
  227235. const Point<int> MouseInputSource::getCurrentMousePosition()
  227236. {
  227237. return juce_lastMousePos;
  227238. }
  227239. void Desktop::setMousePosition (const Point<int>&)
  227240. {
  227241. }
  227242. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227243. {
  227244. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227245. }
  227246. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227247. {
  227248. const ScopedAutoReleasePool pool;
  227249. monitorCoords.clear();
  227250. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227251. : [[UIScreen mainScreen] bounds];
  227252. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227253. }
  227254. const int KeyPress::spaceKey = ' ';
  227255. const int KeyPress::returnKey = 0x0d;
  227256. const int KeyPress::escapeKey = 0x1b;
  227257. const int KeyPress::backspaceKey = 0x7f;
  227258. const int KeyPress::leftKey = 0x1000;
  227259. const int KeyPress::rightKey = 0x1001;
  227260. const int KeyPress::upKey = 0x1002;
  227261. const int KeyPress::downKey = 0x1003;
  227262. const int KeyPress::pageUpKey = 0x1004;
  227263. const int KeyPress::pageDownKey = 0x1005;
  227264. const int KeyPress::endKey = 0x1006;
  227265. const int KeyPress::homeKey = 0x1007;
  227266. const int KeyPress::deleteKey = 0x1008;
  227267. const int KeyPress::insertKey = -1;
  227268. const int KeyPress::tabKey = 9;
  227269. const int KeyPress::F1Key = 0x2001;
  227270. const int KeyPress::F2Key = 0x2002;
  227271. const int KeyPress::F3Key = 0x2003;
  227272. const int KeyPress::F4Key = 0x2004;
  227273. const int KeyPress::F5Key = 0x2005;
  227274. const int KeyPress::F6Key = 0x2006;
  227275. const int KeyPress::F7Key = 0x2007;
  227276. const int KeyPress::F8Key = 0x2008;
  227277. const int KeyPress::F9Key = 0x2009;
  227278. const int KeyPress::F10Key = 0x200a;
  227279. const int KeyPress::F11Key = 0x200b;
  227280. const int KeyPress::F12Key = 0x200c;
  227281. const int KeyPress::F13Key = 0x200d;
  227282. const int KeyPress::F14Key = 0x200e;
  227283. const int KeyPress::F15Key = 0x200f;
  227284. const int KeyPress::F16Key = 0x2010;
  227285. const int KeyPress::numberPad0 = 0x30020;
  227286. const int KeyPress::numberPad1 = 0x30021;
  227287. const int KeyPress::numberPad2 = 0x30022;
  227288. const int KeyPress::numberPad3 = 0x30023;
  227289. const int KeyPress::numberPad4 = 0x30024;
  227290. const int KeyPress::numberPad5 = 0x30025;
  227291. const int KeyPress::numberPad6 = 0x30026;
  227292. const int KeyPress::numberPad7 = 0x30027;
  227293. const int KeyPress::numberPad8 = 0x30028;
  227294. const int KeyPress::numberPad9 = 0x30029;
  227295. const int KeyPress::numberPadAdd = 0x3002a;
  227296. const int KeyPress::numberPadSubtract = 0x3002b;
  227297. const int KeyPress::numberPadMultiply = 0x3002c;
  227298. const int KeyPress::numberPadDivide = 0x3002d;
  227299. const int KeyPress::numberPadSeparator = 0x3002e;
  227300. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227301. const int KeyPress::numberPadEquals = 0x30030;
  227302. const int KeyPress::numberPadDelete = 0x30031;
  227303. const int KeyPress::playKey = 0x30000;
  227304. const int KeyPress::stopKey = 0x30001;
  227305. const int KeyPress::fastForwardKey = 0x30002;
  227306. const int KeyPress::rewindKey = 0x30003;
  227307. #endif
  227308. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227309. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  227310. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227311. // compiled on its own).
  227312. #if JUCE_INCLUDED_FILE
  227313. struct CallbackMessagePayload
  227314. {
  227315. MessageCallbackFunction* function;
  227316. void* parameter;
  227317. void* volatile result;
  227318. bool volatile hasBeenExecuted;
  227319. };
  227320. END_JUCE_NAMESPACE
  227321. @interface JuceCustomMessageHandler : NSObject
  227322. {
  227323. }
  227324. - (void) performCallback: (id) info;
  227325. @end
  227326. @implementation JuceCustomMessageHandler
  227327. - (void) performCallback: (id) info
  227328. {
  227329. if ([info isKindOfClass: [NSData class]])
  227330. {
  227331. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227332. if (pl != 0)
  227333. {
  227334. pl->result = (*pl->function) (pl->parameter);
  227335. pl->hasBeenExecuted = true;
  227336. }
  227337. }
  227338. else
  227339. {
  227340. jassertfalse; // should never get here!
  227341. }
  227342. }
  227343. @end
  227344. BEGIN_JUCE_NAMESPACE
  227345. void MessageManager::runDispatchLoop()
  227346. {
  227347. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227348. runDispatchLoopUntil (-1);
  227349. }
  227350. void MessageManager::stopDispatchLoop()
  227351. {
  227352. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227353. exit (0); // iPhone apps get no mercy..
  227354. }
  227355. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227356. {
  227357. const ScopedAutoReleasePool pool;
  227358. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227359. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227360. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227361. while (! quitMessagePosted)
  227362. {
  227363. const ScopedAutoReleasePool pool;
  227364. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227365. beforeDate: endDate];
  227366. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227367. break;
  227368. }
  227369. return ! quitMessagePosted;
  227370. }
  227371. struct MessageDispatchSystem
  227372. {
  227373. MessageDispatchSystem()
  227374. : juceCustomMessageHandler (0)
  227375. {
  227376. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227377. }
  227378. ~MessageDispatchSystem()
  227379. {
  227380. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227381. [juceCustomMessageHandler release];
  227382. }
  227383. JuceCustomMessageHandler* juceCustomMessageHandler;
  227384. MessageQueue messageQueue;
  227385. };
  227386. static MessageDispatchSystem* dispatcher = 0;
  227387. void MessageManager::doPlatformSpecificInitialisation()
  227388. {
  227389. if (dispatcher == 0)
  227390. dispatcher = new MessageDispatchSystem();
  227391. }
  227392. void MessageManager::doPlatformSpecificShutdown()
  227393. {
  227394. deleteAndZero (dispatcher);
  227395. }
  227396. bool juce_postMessageToSystemQueue (Message* message)
  227397. {
  227398. if (dispatcher != 0)
  227399. dispatcher->messageQueue.post (message);
  227400. return true;
  227401. }
  227402. void MessageManager::broadcastMessage (const String& value)
  227403. {
  227404. }
  227405. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227406. {
  227407. if (isThisTheMessageThread())
  227408. {
  227409. return (*callback) (data);
  227410. }
  227411. else
  227412. {
  227413. jassert (dispatcher != 0); // trying to call this when the juce system isn't initialised..
  227414. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227415. // deadlock because the message manager is blocked from running, so can never
  227416. // call your function..
  227417. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227418. const ScopedAutoReleasePool pool;
  227419. CallbackMessagePayload cmp;
  227420. cmp.function = callback;
  227421. cmp.parameter = data;
  227422. cmp.result = 0;
  227423. cmp.hasBeenExecuted = false;
  227424. [dispatcher->juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227425. withObject: [NSData dataWithBytesNoCopy: &cmp
  227426. length: sizeof (cmp)
  227427. freeWhenDone: NO]
  227428. waitUntilDone: YES];
  227429. return cmp.result;
  227430. }
  227431. }
  227432. #endif
  227433. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  227434. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227435. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227436. // compiled on its own).
  227437. #if JUCE_INCLUDED_FILE
  227438. #if JUCE_MAC
  227439. END_JUCE_NAMESPACE
  227440. using namespace JUCE_NAMESPACE;
  227441. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227442. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227443. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227444. #else
  227445. @interface JuceFileChooserDelegate : NSObject
  227446. #endif
  227447. {
  227448. StringArray* filters;
  227449. }
  227450. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227451. - (void) dealloc;
  227452. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227453. @end
  227454. @implementation JuceFileChooserDelegate
  227455. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227456. {
  227457. [super init];
  227458. filters = filters_;
  227459. return self;
  227460. }
  227461. - (void) dealloc
  227462. {
  227463. delete filters;
  227464. [super dealloc];
  227465. }
  227466. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227467. {
  227468. (void) sender;
  227469. const File f (nsStringToJuce (filename));
  227470. for (int i = filters->size(); --i >= 0;)
  227471. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227472. return true;
  227473. return f.isDirectory();
  227474. }
  227475. @end
  227476. BEGIN_JUCE_NAMESPACE
  227477. void FileChooser::showPlatformDialog (Array<File>& results,
  227478. const String& title,
  227479. const File& currentFileOrDirectory,
  227480. const String& filter,
  227481. bool selectsDirectory,
  227482. bool selectsFiles,
  227483. bool isSaveDialogue,
  227484. bool /*warnAboutOverwritingExistingFiles*/,
  227485. bool selectMultipleFiles,
  227486. FilePreviewComponent* /*extraInfoComponent*/)
  227487. {
  227488. const ScopedAutoReleasePool pool;
  227489. StringArray* filters = new StringArray();
  227490. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  227491. filters->trim();
  227492. filters->removeEmptyStrings();
  227493. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  227494. [delegate autorelease];
  227495. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  227496. : [NSOpenPanel openPanel];
  227497. [panel setTitle: juceStringToNS (title)];
  227498. if (! isSaveDialogue)
  227499. {
  227500. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227501. [openPanel setCanChooseDirectories: selectsDirectory];
  227502. [openPanel setCanChooseFiles: selectsFiles];
  227503. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  227504. }
  227505. [panel setDelegate: delegate];
  227506. if (isSaveDialogue || selectsDirectory)
  227507. [panel setCanCreateDirectories: YES];
  227508. String directory, filename;
  227509. if (currentFileOrDirectory.isDirectory())
  227510. {
  227511. directory = currentFileOrDirectory.getFullPathName();
  227512. }
  227513. else
  227514. {
  227515. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  227516. filename = currentFileOrDirectory.getFileName();
  227517. }
  227518. if ([panel runModalForDirectory: juceStringToNS (directory)
  227519. file: juceStringToNS (filename)]
  227520. == NSOKButton)
  227521. {
  227522. if (isSaveDialogue)
  227523. {
  227524. results.add (File (nsStringToJuce ([panel filename])));
  227525. }
  227526. else
  227527. {
  227528. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227529. NSArray* urls = [openPanel filenames];
  227530. for (unsigned int i = 0; i < [urls count]; ++i)
  227531. {
  227532. NSString* f = [urls objectAtIndex: i];
  227533. results.add (File (nsStringToJuce (f)));
  227534. }
  227535. }
  227536. }
  227537. [panel setDelegate: nil];
  227538. }
  227539. #else
  227540. void FileChooser::showPlatformDialog (Array<File>& results,
  227541. const String& title,
  227542. const File& currentFileOrDirectory,
  227543. const String& filter,
  227544. bool selectsDirectory,
  227545. bool selectsFiles,
  227546. bool isSaveDialogue,
  227547. bool warnAboutOverwritingExistingFiles,
  227548. bool selectMultipleFiles,
  227549. FilePreviewComponent* extraInfoComponent)
  227550. {
  227551. const ScopedAutoReleasePool pool;
  227552. jassertfalse; //xxx to do
  227553. }
  227554. #endif
  227555. #endif
  227556. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  227557. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  227558. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227559. // compiled on its own).
  227560. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  227561. #if JUCE_MAC
  227562. END_JUCE_NAMESPACE
  227563. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  227564. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  227565. {
  227566. CriticalSection* contextLock;
  227567. bool needsUpdate;
  227568. }
  227569. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  227570. - (bool) makeActive;
  227571. - (void) makeInactive;
  227572. - (void) reshape;
  227573. @end
  227574. @implementation ThreadSafeNSOpenGLView
  227575. - (id) initWithFrame: (NSRect) frameRect
  227576. pixelFormat: (NSOpenGLPixelFormat*) format
  227577. {
  227578. contextLock = new CriticalSection();
  227579. self = [super initWithFrame: frameRect pixelFormat: format];
  227580. if (self != nil)
  227581. [[NSNotificationCenter defaultCenter] addObserver: self
  227582. selector: @selector (_surfaceNeedsUpdate:)
  227583. name: NSViewGlobalFrameDidChangeNotification
  227584. object: self];
  227585. return self;
  227586. }
  227587. - (void) dealloc
  227588. {
  227589. [[NSNotificationCenter defaultCenter] removeObserver: self];
  227590. delete contextLock;
  227591. [super dealloc];
  227592. }
  227593. - (bool) makeActive
  227594. {
  227595. const ScopedLock sl (*contextLock);
  227596. if ([self openGLContext] == 0)
  227597. return false;
  227598. [[self openGLContext] makeCurrentContext];
  227599. if (needsUpdate)
  227600. {
  227601. [super update];
  227602. needsUpdate = false;
  227603. }
  227604. return true;
  227605. }
  227606. - (void) makeInactive
  227607. {
  227608. const ScopedLock sl (*contextLock);
  227609. [NSOpenGLContext clearCurrentContext];
  227610. }
  227611. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  227612. {
  227613. (void) notification;
  227614. const ScopedLock sl (*contextLock);
  227615. needsUpdate = true;
  227616. }
  227617. - (void) update
  227618. {
  227619. const ScopedLock sl (*contextLock);
  227620. needsUpdate = true;
  227621. }
  227622. - (void) reshape
  227623. {
  227624. const ScopedLock sl (*contextLock);
  227625. needsUpdate = true;
  227626. }
  227627. @end
  227628. BEGIN_JUCE_NAMESPACE
  227629. class WindowedGLContext : public OpenGLContext
  227630. {
  227631. public:
  227632. WindowedGLContext (Component& component,
  227633. const OpenGLPixelFormat& pixelFormat_,
  227634. NSOpenGLContext* sharedContext)
  227635. : renderContext (0),
  227636. pixelFormat (pixelFormat_)
  227637. {
  227638. NSOpenGLPixelFormatAttribute attribs [64];
  227639. int n = 0;
  227640. attribs[n++] = NSOpenGLPFADoubleBuffer;
  227641. attribs[n++] = NSOpenGLPFAAccelerated;
  227642. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  227643. attribs[n++] = NSOpenGLPFAColorSize;
  227644. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  227645. pixelFormat.greenBits,
  227646. pixelFormat.blueBits);
  227647. attribs[n++] = NSOpenGLPFAAlphaSize;
  227648. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  227649. attribs[n++] = NSOpenGLPFADepthSize;
  227650. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  227651. attribs[n++] = NSOpenGLPFAStencilSize;
  227652. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  227653. attribs[n++] = NSOpenGLPFAAccumSize;
  227654. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  227655. pixelFormat.accumulationBufferGreenBits,
  227656. pixelFormat.accumulationBufferBlueBits,
  227657. pixelFormat.accumulationBufferAlphaBits);
  227658. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  227659. attribs[n++] = NSOpenGLPFASampleBuffers;
  227660. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  227661. attribs[n++] = NSOpenGLPFAClosestPolicy;
  227662. attribs[n++] = NSOpenGLPFANoRecovery;
  227663. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  227664. NSOpenGLPixelFormat* format
  227665. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  227666. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227667. pixelFormat: format];
  227668. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  227669. shareContext: sharedContext] autorelease];
  227670. const GLint swapInterval = 1;
  227671. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  227672. [view setOpenGLContext: renderContext];
  227673. [format release];
  227674. viewHolder = new NSViewComponentInternal (view, component);
  227675. }
  227676. ~WindowedGLContext()
  227677. {
  227678. deleteContext();
  227679. viewHolder = 0;
  227680. }
  227681. void deleteContext()
  227682. {
  227683. makeInactive();
  227684. [renderContext clearDrawable];
  227685. [renderContext setView: nil];
  227686. [view setOpenGLContext: nil];
  227687. renderContext = nil;
  227688. }
  227689. bool makeActive() const throw()
  227690. {
  227691. jassert (renderContext != 0);
  227692. if ([renderContext view] != view)
  227693. [renderContext setView: view];
  227694. [view makeActive];
  227695. return isActive();
  227696. }
  227697. bool makeInactive() const throw()
  227698. {
  227699. [view makeInactive];
  227700. return true;
  227701. }
  227702. bool isActive() const throw()
  227703. {
  227704. return [NSOpenGLContext currentContext] == renderContext;
  227705. }
  227706. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227707. void* getRawContext() const throw() { return renderContext; }
  227708. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  227709. {
  227710. }
  227711. void swapBuffers()
  227712. {
  227713. [renderContext flushBuffer];
  227714. }
  227715. bool setSwapInterval (const int numFramesPerSwap)
  227716. {
  227717. [renderContext setValues: (const GLint*) &numFramesPerSwap
  227718. forParameter: NSOpenGLCPSwapInterval];
  227719. return true;
  227720. }
  227721. int getSwapInterval() const
  227722. {
  227723. GLint numFrames = 0;
  227724. [renderContext getValues: &numFrames
  227725. forParameter: NSOpenGLCPSwapInterval];
  227726. return numFrames;
  227727. }
  227728. void repaint()
  227729. {
  227730. // we need to invalidate the juce view that holds this gl view, to make it
  227731. // cause a repaint callback
  227732. NSView* v = (NSView*) viewHolder->view;
  227733. NSRect r = [v frame];
  227734. // bit of a bodge here.. if we only invalidate the area of the gl component,
  227735. // it's completely covered by the NSOpenGLView, so the OS throws away the
  227736. // repaint message, thus never causing our paint() callback, and never repainting
  227737. // the comp. So invalidating just a little bit around the edge helps..
  227738. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  227739. }
  227740. void* getNativeWindowHandle() const { return viewHolder->view; }
  227741. NSOpenGLContext* renderContext;
  227742. ThreadSafeNSOpenGLView* view;
  227743. private:
  227744. OpenGLPixelFormat pixelFormat;
  227745. ScopedPointer <NSViewComponentInternal> viewHolder;
  227746. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  227747. };
  227748. OpenGLContext* OpenGLComponent::createContext()
  227749. {
  227750. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  227751. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  227752. return (c->renderContext != 0) ? c.release() : 0;
  227753. }
  227754. void* OpenGLComponent::getNativeWindowHandle() const
  227755. {
  227756. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  227757. : 0;
  227758. }
  227759. void juce_glViewport (const int w, const int h)
  227760. {
  227761. glViewport (0, 0, w, h);
  227762. }
  227763. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227764. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227765. {
  227766. /* GLint attribs [64];
  227767. int n = 0;
  227768. attribs[n++] = AGL_RGBA;
  227769. attribs[n++] = AGL_DOUBLEBUFFER;
  227770. attribs[n++] = AGL_ACCELERATED;
  227771. attribs[n++] = AGL_NO_RECOVERY;
  227772. attribs[n++] = AGL_NONE;
  227773. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  227774. while (p != 0)
  227775. {
  227776. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  227777. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  227778. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  227779. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  227780. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  227781. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  227782. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  227783. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  227784. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  227785. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  227786. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  227787. results.add (pf);
  227788. p = aglNextPixelFormat (p);
  227789. }*/
  227790. //jassertfalse // can't see how you do this in cocoa!
  227791. }
  227792. #else
  227793. END_JUCE_NAMESPACE
  227794. @interface JuceGLView : UIView
  227795. {
  227796. }
  227797. + (Class) layerClass;
  227798. @end
  227799. @implementation JuceGLView
  227800. + (Class) layerClass
  227801. {
  227802. return [CAEAGLLayer class];
  227803. }
  227804. @end
  227805. BEGIN_JUCE_NAMESPACE
  227806. class GLESContext : public OpenGLContext
  227807. {
  227808. public:
  227809. GLESContext (UIViewComponentPeer* peer,
  227810. Component* const component_,
  227811. const OpenGLPixelFormat& pixelFormat_,
  227812. const GLESContext* const sharedContext,
  227813. NSUInteger apiType)
  227814. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  227815. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  227816. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  227817. {
  227818. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  227819. view.opaque = YES;
  227820. view.hidden = NO;
  227821. view.backgroundColor = [UIColor blackColor];
  227822. view.userInteractionEnabled = NO;
  227823. glLayer = (CAEAGLLayer*) [view layer];
  227824. [peer->view addSubview: view];
  227825. if (sharedContext != 0)
  227826. context = [[EAGLContext alloc] initWithAPI: apiType
  227827. sharegroup: [sharedContext->context sharegroup]];
  227828. else
  227829. context = [[EAGLContext alloc] initWithAPI: apiType];
  227830. createGLBuffers();
  227831. }
  227832. ~GLESContext()
  227833. {
  227834. deleteContext();
  227835. [view removeFromSuperview];
  227836. [view release];
  227837. freeGLBuffers();
  227838. }
  227839. void deleteContext()
  227840. {
  227841. makeInactive();
  227842. [context release];
  227843. context = nil;
  227844. }
  227845. bool makeActive() const throw()
  227846. {
  227847. jassert (context != 0);
  227848. [EAGLContext setCurrentContext: context];
  227849. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227850. return true;
  227851. }
  227852. void swapBuffers()
  227853. {
  227854. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227855. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  227856. }
  227857. bool makeInactive() const throw()
  227858. {
  227859. return [EAGLContext setCurrentContext: nil];
  227860. }
  227861. bool isActive() const throw()
  227862. {
  227863. return [EAGLContext currentContext] == context;
  227864. }
  227865. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227866. void* getRawContext() const throw() { return glLayer; }
  227867. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227868. {
  227869. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  227870. if (lastWidth != w || lastHeight != h)
  227871. {
  227872. lastWidth = w;
  227873. lastHeight = h;
  227874. freeGLBuffers();
  227875. createGLBuffers();
  227876. }
  227877. }
  227878. bool setSwapInterval (const int numFramesPerSwap)
  227879. {
  227880. numFrames = numFramesPerSwap;
  227881. return true;
  227882. }
  227883. int getSwapInterval() const
  227884. {
  227885. return numFrames;
  227886. }
  227887. void repaint()
  227888. {
  227889. }
  227890. void createGLBuffers()
  227891. {
  227892. makeActive();
  227893. glGenFramebuffersOES (1, &frameBufferHandle);
  227894. glGenRenderbuffersOES (1, &colorBufferHandle);
  227895. glGenRenderbuffersOES (1, &depthBufferHandle);
  227896. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227897. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  227898. GLint width, height;
  227899. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  227900. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  227901. if (useDepthBuffer)
  227902. {
  227903. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  227904. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  227905. }
  227906. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227907. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227908. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  227909. if (useDepthBuffer)
  227910. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  227911. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  227912. }
  227913. void freeGLBuffers()
  227914. {
  227915. if (frameBufferHandle != 0)
  227916. {
  227917. glDeleteFramebuffersOES (1, &frameBufferHandle);
  227918. frameBufferHandle = 0;
  227919. }
  227920. if (colorBufferHandle != 0)
  227921. {
  227922. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  227923. colorBufferHandle = 0;
  227924. }
  227925. if (depthBufferHandle != 0)
  227926. {
  227927. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  227928. depthBufferHandle = 0;
  227929. }
  227930. }
  227931. private:
  227932. WeakReference<Component> component;
  227933. OpenGLPixelFormat pixelFormat;
  227934. JuceGLView* view;
  227935. CAEAGLLayer* glLayer;
  227936. EAGLContext* context;
  227937. bool useDepthBuffer;
  227938. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  227939. int numFrames;
  227940. int lastWidth, lastHeight;
  227941. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  227942. };
  227943. OpenGLContext* OpenGLComponent::createContext()
  227944. {
  227945. ScopedAutoReleasePool pool;
  227946. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  227947. if (peer != 0)
  227948. return new GLESContext (peer, this, preferredPixelFormat,
  227949. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  227950. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  227951. return 0;
  227952. }
  227953. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227954. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227955. {
  227956. }
  227957. void juce_glViewport (const int w, const int h)
  227958. {
  227959. glViewport (0, 0, w, h);
  227960. }
  227961. #endif
  227962. #endif
  227963. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  227964. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  227965. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227966. // compiled on its own).
  227967. #if JUCE_INCLUDED_FILE
  227968. #if JUCE_MAC
  227969. namespace MouseCursorHelpers
  227970. {
  227971. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  227972. {
  227973. NSImage* im = CoreGraphicsImage::createNSImage (image);
  227974. NSCursor* c = [[NSCursor alloc] initWithImage: im
  227975. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  227976. [im release];
  227977. return c;
  227978. }
  227979. static void* fromWebKitFile (const char* filename, float hx, float hy)
  227980. {
  227981. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  227982. BufferedInputStream buf (fileStream, 4096);
  227983. PNGImageFormat pngFormat;
  227984. Image im (pngFormat.decodeImage (buf));
  227985. if (im.isValid())
  227986. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  227987. jassertfalse;
  227988. return 0;
  227989. }
  227990. }
  227991. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  227992. {
  227993. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  227994. }
  227995. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  227996. {
  227997. const ScopedAutoReleasePool pool;
  227998. NSCursor* c = 0;
  227999. switch (type)
  228000. {
  228001. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228002. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228003. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228004. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228005. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228006. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228007. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228008. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228009. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228010. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228011. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228012. case UpDownResizeCursor:
  228013. case TopEdgeResizeCursor:
  228014. case BottomEdgeResizeCursor:
  228015. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228016. case TopLeftCornerResizeCursor:
  228017. case BottomRightCornerResizeCursor:
  228018. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228019. case TopRightCornerResizeCursor:
  228020. case BottomLeftCornerResizeCursor:
  228021. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228022. case UpDownLeftRightResizeCursor:
  228023. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228024. default:
  228025. jassertfalse;
  228026. break;
  228027. }
  228028. [c retain];
  228029. return c;
  228030. }
  228031. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228032. {
  228033. [((NSCursor*) cursorHandle) release];
  228034. }
  228035. void MouseCursor::showInAllWindows() const
  228036. {
  228037. showInWindow (0);
  228038. }
  228039. void MouseCursor::showInWindow (ComponentPeer*) const
  228040. {
  228041. NSCursor* c = (NSCursor*) getHandle();
  228042. if (c == 0)
  228043. c = [NSCursor arrowCursor];
  228044. [c set];
  228045. }
  228046. #else
  228047. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228048. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228049. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228050. void MouseCursor::showInAllWindows() const {}
  228051. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228052. #endif
  228053. #endif
  228054. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228055. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228056. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228057. // compiled on its own).
  228058. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228059. #if JUCE_MAC
  228060. END_JUCE_NAMESPACE
  228061. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228062. @interface DownloadClickDetector : NSObject
  228063. {
  228064. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228065. }
  228066. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228067. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228068. request: (NSURLRequest*) request
  228069. frame: (WebFrame*) frame
  228070. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228071. @end
  228072. @implementation DownloadClickDetector
  228073. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228074. {
  228075. [super init];
  228076. ownerComponent = ownerComponent_;
  228077. return self;
  228078. }
  228079. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228080. request: (NSURLRequest*) request
  228081. frame: (WebFrame*) frame
  228082. decisionListener: (id <WebPolicyDecisionListener>) listener
  228083. {
  228084. (void) sender;
  228085. (void) request;
  228086. (void) frame;
  228087. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228088. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228089. [listener use];
  228090. else
  228091. [listener ignore];
  228092. }
  228093. @end
  228094. BEGIN_JUCE_NAMESPACE
  228095. class WebBrowserComponentInternal : public NSViewComponent
  228096. {
  228097. public:
  228098. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228099. {
  228100. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228101. frameName: @""
  228102. groupName: @""];
  228103. setView (webView);
  228104. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228105. [webView setPolicyDelegate: clickListener];
  228106. }
  228107. ~WebBrowserComponentInternal()
  228108. {
  228109. [webView setPolicyDelegate: nil];
  228110. [clickListener release];
  228111. setView (0);
  228112. }
  228113. void goToURL (const String& url,
  228114. const StringArray* headers,
  228115. const MemoryBlock* postData)
  228116. {
  228117. NSMutableURLRequest* r
  228118. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228119. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228120. timeoutInterval: 30.0];
  228121. if (postData != 0 && postData->getSize() > 0)
  228122. {
  228123. [r setHTTPMethod: @"POST"];
  228124. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228125. length: postData->getSize()]];
  228126. }
  228127. if (headers != 0)
  228128. {
  228129. for (int i = 0; i < headers->size(); ++i)
  228130. {
  228131. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228132. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228133. [r setValue: juceStringToNS (headerValue)
  228134. forHTTPHeaderField: juceStringToNS (headerName)];
  228135. }
  228136. }
  228137. stop();
  228138. [[webView mainFrame] loadRequest: r];
  228139. }
  228140. void goBack()
  228141. {
  228142. [webView goBack];
  228143. }
  228144. void goForward()
  228145. {
  228146. [webView goForward];
  228147. }
  228148. void stop()
  228149. {
  228150. [webView stopLoading: nil];
  228151. }
  228152. void refresh()
  228153. {
  228154. [webView reload: nil];
  228155. }
  228156. void mouseMove (const MouseEvent&)
  228157. {
  228158. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228159. // them work is to push them via this non-public method..
  228160. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228161. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228162. }
  228163. private:
  228164. WebView* webView;
  228165. DownloadClickDetector* clickListener;
  228166. };
  228167. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228168. : browser (0),
  228169. blankPageShown (false),
  228170. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228171. {
  228172. setOpaque (true);
  228173. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228174. }
  228175. WebBrowserComponent::~WebBrowserComponent()
  228176. {
  228177. deleteAndZero (browser);
  228178. }
  228179. void WebBrowserComponent::goToURL (const String& url,
  228180. const StringArray* headers,
  228181. const MemoryBlock* postData)
  228182. {
  228183. lastURL = url;
  228184. lastHeaders.clear();
  228185. if (headers != 0)
  228186. lastHeaders = *headers;
  228187. lastPostData.setSize (0);
  228188. if (postData != 0)
  228189. lastPostData = *postData;
  228190. blankPageShown = false;
  228191. browser->goToURL (url, headers, postData);
  228192. }
  228193. void WebBrowserComponent::stop()
  228194. {
  228195. browser->stop();
  228196. }
  228197. void WebBrowserComponent::goBack()
  228198. {
  228199. lastURL = String::empty;
  228200. blankPageShown = false;
  228201. browser->goBack();
  228202. }
  228203. void WebBrowserComponent::goForward()
  228204. {
  228205. lastURL = String::empty;
  228206. browser->goForward();
  228207. }
  228208. void WebBrowserComponent::refresh()
  228209. {
  228210. browser->refresh();
  228211. }
  228212. void WebBrowserComponent::paint (Graphics&)
  228213. {
  228214. }
  228215. void WebBrowserComponent::checkWindowAssociation()
  228216. {
  228217. if (isShowing())
  228218. {
  228219. if (blankPageShown)
  228220. goBack();
  228221. }
  228222. else
  228223. {
  228224. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228225. {
  228226. // when the component becomes invisible, some stuff like flash
  228227. // carries on playing audio, so we need to force it onto a blank
  228228. // page to avoid this, (and send it back when it's made visible again).
  228229. blankPageShown = true;
  228230. browser->goToURL ("about:blank", 0, 0);
  228231. }
  228232. }
  228233. }
  228234. void WebBrowserComponent::reloadLastURL()
  228235. {
  228236. if (lastURL.isNotEmpty())
  228237. {
  228238. goToURL (lastURL, &lastHeaders, &lastPostData);
  228239. lastURL = String::empty;
  228240. }
  228241. }
  228242. void WebBrowserComponent::parentHierarchyChanged()
  228243. {
  228244. checkWindowAssociation();
  228245. }
  228246. void WebBrowserComponent::resized()
  228247. {
  228248. browser->setSize (getWidth(), getHeight());
  228249. }
  228250. void WebBrowserComponent::visibilityChanged()
  228251. {
  228252. checkWindowAssociation();
  228253. }
  228254. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228255. {
  228256. return true;
  228257. }
  228258. #else
  228259. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228260. {
  228261. }
  228262. WebBrowserComponent::~WebBrowserComponent()
  228263. {
  228264. }
  228265. void WebBrowserComponent::goToURL (const String& url,
  228266. const StringArray* headers,
  228267. const MemoryBlock* postData)
  228268. {
  228269. }
  228270. void WebBrowserComponent::stop()
  228271. {
  228272. }
  228273. void WebBrowserComponent::goBack()
  228274. {
  228275. }
  228276. void WebBrowserComponent::goForward()
  228277. {
  228278. }
  228279. void WebBrowserComponent::refresh()
  228280. {
  228281. }
  228282. void WebBrowserComponent::paint (Graphics& g)
  228283. {
  228284. }
  228285. void WebBrowserComponent::checkWindowAssociation()
  228286. {
  228287. }
  228288. void WebBrowserComponent::reloadLastURL()
  228289. {
  228290. }
  228291. void WebBrowserComponent::parentHierarchyChanged()
  228292. {
  228293. }
  228294. void WebBrowserComponent::resized()
  228295. {
  228296. }
  228297. void WebBrowserComponent::visibilityChanged()
  228298. {
  228299. }
  228300. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228301. {
  228302. return true;
  228303. }
  228304. #endif
  228305. #endif
  228306. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228307. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  228308. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228309. // compiled on its own).
  228310. #if JUCE_INCLUDED_FILE
  228311. class IPhoneAudioIODevice : public AudioIODevice
  228312. {
  228313. public:
  228314. IPhoneAudioIODevice (const String& deviceName)
  228315. : AudioIODevice (deviceName, "Audio"),
  228316. actualBufferSize (0),
  228317. isRunning (false),
  228318. audioUnit (0),
  228319. callback (0),
  228320. floatData (1, 2)
  228321. {
  228322. numInputChannels = 2;
  228323. numOutputChannels = 2;
  228324. preferredBufferSize = 0;
  228325. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228326. updateDeviceInfo();
  228327. }
  228328. ~IPhoneAudioIODevice()
  228329. {
  228330. close();
  228331. }
  228332. const StringArray getOutputChannelNames()
  228333. {
  228334. StringArray s;
  228335. s.add ("Left");
  228336. s.add ("Right");
  228337. return s;
  228338. }
  228339. const StringArray getInputChannelNames()
  228340. {
  228341. StringArray s;
  228342. if (audioInputIsAvailable)
  228343. {
  228344. s.add ("Left");
  228345. s.add ("Right");
  228346. }
  228347. return s;
  228348. }
  228349. int getNumSampleRates()
  228350. {
  228351. return 1;
  228352. }
  228353. double getSampleRate (int index)
  228354. {
  228355. return sampleRate;
  228356. }
  228357. int getNumBufferSizesAvailable()
  228358. {
  228359. return 1;
  228360. }
  228361. int getBufferSizeSamples (int index)
  228362. {
  228363. return getDefaultBufferSize();
  228364. }
  228365. int getDefaultBufferSize()
  228366. {
  228367. return 1024;
  228368. }
  228369. const String open (const BigInteger& inputChannels,
  228370. const BigInteger& outputChannels,
  228371. double sampleRate,
  228372. int bufferSize)
  228373. {
  228374. close();
  228375. lastError = String::empty;
  228376. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228377. // xxx set up channel mapping
  228378. activeOutputChans = outputChannels;
  228379. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228380. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228381. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228382. activeInputChans = inputChannels;
  228383. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228384. numInputChannels = activeInputChans.countNumberOfSetBits();
  228385. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228386. AudioSessionSetActive (true);
  228387. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228388. : kAudioSessionCategory_MediaPlayback;
  228389. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228390. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228391. fixAudioRouteIfSetToReceiver();
  228392. updateDeviceInfo();
  228393. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228394. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228395. actualBufferSize = preferredBufferSize;
  228396. prepareFloatBuffers();
  228397. isRunning = true;
  228398. propertyChanged (0, 0, 0); // creates and starts the AU
  228399. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228400. return lastError;
  228401. }
  228402. void close()
  228403. {
  228404. if (isRunning)
  228405. {
  228406. isRunning = false;
  228407. AudioSessionSetActive (false);
  228408. if (audioUnit != 0)
  228409. {
  228410. AudioComponentInstanceDispose (audioUnit);
  228411. audioUnit = 0;
  228412. }
  228413. }
  228414. }
  228415. bool isOpen()
  228416. {
  228417. return isRunning;
  228418. }
  228419. int getCurrentBufferSizeSamples()
  228420. {
  228421. return actualBufferSize;
  228422. }
  228423. double getCurrentSampleRate()
  228424. {
  228425. return sampleRate;
  228426. }
  228427. int getCurrentBitDepth()
  228428. {
  228429. return 16;
  228430. }
  228431. const BigInteger getActiveOutputChannels() const
  228432. {
  228433. return activeOutputChans;
  228434. }
  228435. const BigInteger getActiveInputChannels() const
  228436. {
  228437. return activeInputChans;
  228438. }
  228439. int getOutputLatencyInSamples()
  228440. {
  228441. return 0; //xxx
  228442. }
  228443. int getInputLatencyInSamples()
  228444. {
  228445. return 0; //xxx
  228446. }
  228447. void start (AudioIODeviceCallback* callback_)
  228448. {
  228449. if (isRunning && callback != callback_)
  228450. {
  228451. if (callback_ != 0)
  228452. callback_->audioDeviceAboutToStart (this);
  228453. const ScopedLock sl (callbackLock);
  228454. callback = callback_;
  228455. }
  228456. }
  228457. void stop()
  228458. {
  228459. if (isRunning)
  228460. {
  228461. AudioIODeviceCallback* lastCallback;
  228462. {
  228463. const ScopedLock sl (callbackLock);
  228464. lastCallback = callback;
  228465. callback = 0;
  228466. }
  228467. if (lastCallback != 0)
  228468. lastCallback->audioDeviceStopped();
  228469. }
  228470. }
  228471. bool isPlaying()
  228472. {
  228473. return isRunning && callback != 0;
  228474. }
  228475. const String getLastError()
  228476. {
  228477. return lastError;
  228478. }
  228479. private:
  228480. CriticalSection callbackLock;
  228481. Float64 sampleRate;
  228482. int numInputChannels, numOutputChannels;
  228483. int preferredBufferSize;
  228484. int actualBufferSize;
  228485. bool isRunning;
  228486. String lastError;
  228487. AudioStreamBasicDescription format;
  228488. AudioUnit audioUnit;
  228489. UInt32 audioInputIsAvailable;
  228490. AudioIODeviceCallback* callback;
  228491. BigInteger activeOutputChans, activeInputChans;
  228492. AudioSampleBuffer floatData;
  228493. float* inputChannels[3];
  228494. float* outputChannels[3];
  228495. bool monoInputChannelNumber, monoOutputChannelNumber;
  228496. void prepareFloatBuffers()
  228497. {
  228498. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  228499. zerostruct (inputChannels);
  228500. zerostruct (outputChannels);
  228501. for (int i = 0; i < numInputChannels; ++i)
  228502. inputChannels[i] = floatData.getSampleData (i);
  228503. for (int i = 0; i < numOutputChannels; ++i)
  228504. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  228505. }
  228506. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228507. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228508. {
  228509. OSStatus err = noErr;
  228510. if (audioInputIsAvailable)
  228511. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  228512. const ScopedLock sl (callbackLock);
  228513. if (callback != 0)
  228514. {
  228515. if (audioInputIsAvailable && numInputChannels > 0)
  228516. {
  228517. short* shortData = (short*) ioData->mBuffers[0].mData;
  228518. if (numInputChannels >= 2)
  228519. {
  228520. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228521. {
  228522. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228523. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  228524. }
  228525. }
  228526. else
  228527. {
  228528. if (monoInputChannelNumber > 0)
  228529. ++shortData;
  228530. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228531. {
  228532. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228533. ++shortData;
  228534. }
  228535. }
  228536. }
  228537. else
  228538. {
  228539. for (int i = numInputChannels; --i >= 0;)
  228540. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  228541. }
  228542. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  228543. outputChannels, numOutputChannels,
  228544. (int) inNumberFrames);
  228545. short* shortData = (short*) ioData->mBuffers[0].mData;
  228546. int n = 0;
  228547. if (numOutputChannels >= 2)
  228548. {
  228549. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228550. {
  228551. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  228552. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  228553. }
  228554. }
  228555. else if (numOutputChannels == 1)
  228556. {
  228557. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228558. {
  228559. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  228560. shortData [n++] = s;
  228561. shortData [n++] = s;
  228562. }
  228563. }
  228564. else
  228565. {
  228566. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228567. }
  228568. }
  228569. else
  228570. {
  228571. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228572. }
  228573. return err;
  228574. }
  228575. void updateDeviceInfo()
  228576. {
  228577. UInt32 size = sizeof (sampleRate);
  228578. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  228579. size = sizeof (audioInputIsAvailable);
  228580. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  228581. }
  228582. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228583. {
  228584. if (! isRunning)
  228585. return;
  228586. if (inPropertyValue != 0)
  228587. {
  228588. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  228589. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  228590. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  228591. SInt32 routeChangeReason;
  228592. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  228593. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  228594. fixAudioRouteIfSetToReceiver();
  228595. }
  228596. updateDeviceInfo();
  228597. createAudioUnit();
  228598. AudioSessionSetActive (true);
  228599. if (audioUnit != 0)
  228600. {
  228601. UInt32 formatSize = sizeof (format);
  228602. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  228603. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228604. UInt32 bufferDurationSize = sizeof (bufferDuration);
  228605. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  228606. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  228607. AudioOutputUnitStart (audioUnit);
  228608. }
  228609. }
  228610. void interruptionListener (UInt32 inInterruption)
  228611. {
  228612. /*if (inInterruption == kAudioSessionBeginInterruption)
  228613. {
  228614. isRunning = false;
  228615. AudioOutputUnitStop (audioUnit);
  228616. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  228617. "This could have been interrupted by another application or by unplugging a headset",
  228618. @"Resume",
  228619. @"Cancel"))
  228620. {
  228621. isRunning = true;
  228622. propertyChanged (0, 0, 0);
  228623. }
  228624. }*/
  228625. if (inInterruption == kAudioSessionEndInterruption)
  228626. {
  228627. isRunning = true;
  228628. AudioSessionSetActive (true);
  228629. AudioOutputUnitStart (audioUnit);
  228630. }
  228631. }
  228632. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228633. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228634. {
  228635. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  228636. }
  228637. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228638. {
  228639. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  228640. }
  228641. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  228642. {
  228643. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  228644. }
  228645. void resetFormat (const int numChannels)
  228646. {
  228647. memset (&format, 0, sizeof (format));
  228648. format.mFormatID = kAudioFormatLinearPCM;
  228649. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  228650. format.mBitsPerChannel = 8 * sizeof (short);
  228651. format.mChannelsPerFrame = 2;
  228652. format.mFramesPerPacket = 1;
  228653. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  228654. }
  228655. bool createAudioUnit()
  228656. {
  228657. if (audioUnit != 0)
  228658. {
  228659. AudioComponentInstanceDispose (audioUnit);
  228660. audioUnit = 0;
  228661. }
  228662. resetFormat (2);
  228663. AudioComponentDescription desc;
  228664. desc.componentType = kAudioUnitType_Output;
  228665. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  228666. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  228667. desc.componentFlags = 0;
  228668. desc.componentFlagsMask = 0;
  228669. AudioComponent comp = AudioComponentFindNext (0, &desc);
  228670. AudioComponentInstanceNew (comp, &audioUnit);
  228671. if (audioUnit == 0)
  228672. return false;
  228673. const UInt32 one = 1;
  228674. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  228675. AudioChannelLayout layout;
  228676. layout.mChannelBitmap = 0;
  228677. layout.mNumberChannelDescriptions = 0;
  228678. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  228679. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  228680. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  228681. AURenderCallbackStruct inputProc;
  228682. inputProc.inputProc = processStatic;
  228683. inputProc.inputProcRefCon = this;
  228684. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  228685. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  228686. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  228687. AudioUnitInitialize (audioUnit);
  228688. return true;
  228689. }
  228690. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  228691. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  228692. static void fixAudioRouteIfSetToReceiver()
  228693. {
  228694. CFStringRef audioRoute = 0;
  228695. UInt32 propertySize = sizeof (audioRoute);
  228696. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  228697. {
  228698. NSString* route = (NSString*) audioRoute;
  228699. //DBG ("audio route: " + nsStringToJuce (route));
  228700. if ([route hasPrefix: @"Receiver"])
  228701. {
  228702. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  228703. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  228704. }
  228705. CFRelease (audioRoute);
  228706. }
  228707. }
  228708. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  228709. };
  228710. class IPhoneAudioIODeviceType : public AudioIODeviceType
  228711. {
  228712. public:
  228713. IPhoneAudioIODeviceType()
  228714. : AudioIODeviceType ("iPhone Audio")
  228715. {
  228716. }
  228717. void scanForDevices()
  228718. {
  228719. }
  228720. const StringArray getDeviceNames (bool wantInputNames) const
  228721. {
  228722. StringArray s;
  228723. s.add ("iPhone Audio");
  228724. return s;
  228725. }
  228726. int getDefaultDeviceIndex (bool forInput) const
  228727. {
  228728. return 0;
  228729. }
  228730. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  228731. {
  228732. return device != 0 ? 0 : -1;
  228733. }
  228734. bool hasSeparateInputsAndOutputs() const { return false; }
  228735. AudioIODevice* createDevice (const String& outputDeviceName,
  228736. const String& inputDeviceName)
  228737. {
  228738. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  228739. {
  228740. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  228741. : inputDeviceName);
  228742. }
  228743. return 0;
  228744. }
  228745. private:
  228746. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  228747. };
  228748. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  228749. {
  228750. return new IPhoneAudioIODeviceType();
  228751. }
  228752. #endif
  228753. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  228754. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  228755. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228756. // compiled on its own).
  228757. #if JUCE_INCLUDED_FILE
  228758. #if JUCE_MAC
  228759. namespace CoreMidiHelpers
  228760. {
  228761. bool logError (const OSStatus err, const int lineNum)
  228762. {
  228763. if (err == noErr)
  228764. return true;
  228765. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  228766. jassertfalse;
  228767. return false;
  228768. }
  228769. #undef CHECK_ERROR
  228770. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  228771. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228772. {
  228773. String result;
  228774. CFStringRef str = 0;
  228775. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228776. if (str != 0)
  228777. {
  228778. result = PlatformUtilities::cfStringToJuceString (str);
  228779. CFRelease (str);
  228780. str = 0;
  228781. }
  228782. MIDIEntityRef entity = 0;
  228783. MIDIEndpointGetEntity (endpoint, &entity);
  228784. if (entity == 0)
  228785. return result; // probably virtual
  228786. if (result.isEmpty())
  228787. {
  228788. // endpoint name has zero length - try the entity
  228789. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228790. if (str != 0)
  228791. {
  228792. result += PlatformUtilities::cfStringToJuceString (str);
  228793. CFRelease (str);
  228794. str = 0;
  228795. }
  228796. }
  228797. // now consider the device's name
  228798. MIDIDeviceRef device = 0;
  228799. MIDIEntityGetDevice (entity, &device);
  228800. if (device == 0)
  228801. return result;
  228802. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228803. if (str != 0)
  228804. {
  228805. const String s (PlatformUtilities::cfStringToJuceString (str));
  228806. CFRelease (str);
  228807. // if an external device has only one entity, throw away
  228808. // the endpoint name and just use the device name
  228809. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228810. {
  228811. result = s;
  228812. }
  228813. else if (! result.startsWithIgnoreCase (s))
  228814. {
  228815. // prepend the device name to the entity name
  228816. result = (s + " " + result).trimEnd();
  228817. }
  228818. }
  228819. return result;
  228820. }
  228821. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228822. {
  228823. String result;
  228824. // Does the endpoint have connections?
  228825. CFDataRef connections = 0;
  228826. int numConnections = 0;
  228827. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228828. if (connections != 0)
  228829. {
  228830. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  228831. if (numConnections > 0)
  228832. {
  228833. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228834. for (int i = 0; i < numConnections; ++i, ++pid)
  228835. {
  228836. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228837. MIDIObjectRef connObject;
  228838. MIDIObjectType connObjectType;
  228839. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228840. if (err == noErr)
  228841. {
  228842. String s;
  228843. if (connObjectType == kMIDIObjectType_ExternalSource
  228844. || connObjectType == kMIDIObjectType_ExternalDestination)
  228845. {
  228846. // Connected to an external device's endpoint (10.3 and later).
  228847. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228848. }
  228849. else
  228850. {
  228851. // Connected to an external device (10.2) (or something else, catch-all)
  228852. CFStringRef str = 0;
  228853. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228854. if (str != 0)
  228855. {
  228856. s = PlatformUtilities::cfStringToJuceString (str);
  228857. CFRelease (str);
  228858. }
  228859. }
  228860. if (s.isNotEmpty())
  228861. {
  228862. if (result.isNotEmpty())
  228863. result += ", ";
  228864. result += s;
  228865. }
  228866. }
  228867. }
  228868. }
  228869. CFRelease (connections);
  228870. }
  228871. if (result.isNotEmpty())
  228872. return result;
  228873. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228874. return getEndpointName (endpoint, false);
  228875. }
  228876. MIDIClientRef getGlobalMidiClient()
  228877. {
  228878. static MIDIClientRef globalMidiClient = 0;
  228879. if (globalMidiClient == 0)
  228880. {
  228881. String name ("JUCE");
  228882. if (JUCEApplication::getInstance() != 0)
  228883. name = JUCEApplication::getInstance()->getApplicationName();
  228884. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228885. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228886. CFRelease (appName);
  228887. }
  228888. return globalMidiClient;
  228889. }
  228890. class MidiPortAndEndpoint
  228891. {
  228892. public:
  228893. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  228894. : port (port_), endPoint (endPoint_)
  228895. {
  228896. }
  228897. ~MidiPortAndEndpoint()
  228898. {
  228899. if (port != 0)
  228900. MIDIPortDispose (port);
  228901. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  228902. MIDIEndpointDispose (endPoint);
  228903. }
  228904. void send (const MIDIPacketList* const packets)
  228905. {
  228906. if (port != 0)
  228907. MIDISend (port, endPoint, packets);
  228908. else
  228909. MIDIReceived (endPoint, packets);
  228910. }
  228911. MIDIPortRef port;
  228912. MIDIEndpointRef endPoint;
  228913. };
  228914. class MidiPortAndCallback;
  228915. CriticalSection callbackLock;
  228916. Array<MidiPortAndCallback*> activeCallbacks;
  228917. class MidiPortAndCallback
  228918. {
  228919. public:
  228920. MidiPortAndCallback (MidiInputCallback& callback_)
  228921. : input (0), active (false), callback (callback_), concatenator (2048)
  228922. {
  228923. }
  228924. ~MidiPortAndCallback()
  228925. {
  228926. active = false;
  228927. {
  228928. const ScopedLock sl (callbackLock);
  228929. activeCallbacks.removeValue (this);
  228930. }
  228931. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  228932. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  228933. }
  228934. void handlePackets (const MIDIPacketList* const pktlist)
  228935. {
  228936. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  228937. const ScopedLock sl (callbackLock);
  228938. if (activeCallbacks.contains (this) && active)
  228939. {
  228940. const MIDIPacket* packet = &pktlist->packet[0];
  228941. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228942. {
  228943. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  228944. input, callback);
  228945. packet = MIDIPacketNext (packet);
  228946. }
  228947. }
  228948. }
  228949. MidiInput* input;
  228950. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  228951. volatile bool active;
  228952. private:
  228953. MidiInputCallback& callback;
  228954. MidiDataConcatenator concatenator;
  228955. };
  228956. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  228957. {
  228958. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  228959. }
  228960. }
  228961. const StringArray MidiOutput::getDevices()
  228962. {
  228963. StringArray s;
  228964. const ItemCount num = MIDIGetNumberOfDestinations();
  228965. for (ItemCount i = 0; i < num; ++i)
  228966. {
  228967. MIDIEndpointRef dest = MIDIGetDestination (i);
  228968. if (dest != 0)
  228969. {
  228970. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  228971. if (name.isEmpty())
  228972. name = "<error>";
  228973. s.add (name);
  228974. }
  228975. else
  228976. {
  228977. s.add ("<error>");
  228978. }
  228979. }
  228980. return s;
  228981. }
  228982. int MidiOutput::getDefaultDeviceIndex()
  228983. {
  228984. return 0;
  228985. }
  228986. MidiOutput* MidiOutput::openDevice (int index)
  228987. {
  228988. MidiOutput* mo = 0;
  228989. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  228990. {
  228991. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228992. CFStringRef pname;
  228993. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228994. {
  228995. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  228996. MIDIPortRef port;
  228997. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  228998. {
  228999. mo = new MidiOutput();
  229000. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229001. }
  229002. CFRelease (pname);
  229003. }
  229004. }
  229005. return mo;
  229006. }
  229007. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229008. {
  229009. MidiOutput* mo = 0;
  229010. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229011. MIDIEndpointRef endPoint;
  229012. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229013. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229014. {
  229015. mo = new MidiOutput();
  229016. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229017. }
  229018. CFRelease (name);
  229019. return mo;
  229020. }
  229021. MidiOutput::~MidiOutput()
  229022. {
  229023. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229024. }
  229025. void MidiOutput::reset()
  229026. {
  229027. }
  229028. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229029. {
  229030. return false;
  229031. }
  229032. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229033. {
  229034. }
  229035. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229036. {
  229037. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229038. if (message.isSysEx())
  229039. {
  229040. const int maxPacketSize = 256;
  229041. int pos = 0, bytesLeft = message.getRawDataSize();
  229042. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229043. HeapBlock <MIDIPacketList> packets;
  229044. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229045. packets->numPackets = numPackets;
  229046. MIDIPacket* p = packets->packet;
  229047. for (int i = 0; i < numPackets; ++i)
  229048. {
  229049. p->timeStamp = AudioGetCurrentHostTime();
  229050. p->length = jmin (maxPacketSize, bytesLeft);
  229051. memcpy (p->data, message.getRawData() + pos, p->length);
  229052. pos += p->length;
  229053. bytesLeft -= p->length;
  229054. p = MIDIPacketNext (p);
  229055. }
  229056. mpe->send (packets);
  229057. }
  229058. else
  229059. {
  229060. MIDIPacketList packets;
  229061. packets.numPackets = 1;
  229062. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  229063. packets.packet[0].length = message.getRawDataSize();
  229064. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229065. mpe->send (&packets);
  229066. }
  229067. }
  229068. const StringArray MidiInput::getDevices()
  229069. {
  229070. StringArray s;
  229071. const ItemCount num = MIDIGetNumberOfSources();
  229072. for (ItemCount i = 0; i < num; ++i)
  229073. {
  229074. MIDIEndpointRef source = MIDIGetSource (i);
  229075. if (source != 0)
  229076. {
  229077. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229078. if (name.isEmpty())
  229079. name = "<error>";
  229080. s.add (name);
  229081. }
  229082. else
  229083. {
  229084. s.add ("<error>");
  229085. }
  229086. }
  229087. return s;
  229088. }
  229089. int MidiInput::getDefaultDeviceIndex()
  229090. {
  229091. return 0;
  229092. }
  229093. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229094. {
  229095. jassert (callback != 0);
  229096. using namespace CoreMidiHelpers;
  229097. MidiInput* newInput = 0;
  229098. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  229099. {
  229100. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229101. if (endPoint != 0)
  229102. {
  229103. CFStringRef name;
  229104. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229105. {
  229106. MIDIClientRef client = getGlobalMidiClient();
  229107. if (client != 0)
  229108. {
  229109. MIDIPortRef port;
  229110. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229111. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229112. {
  229113. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229114. {
  229115. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229116. newInput = new MidiInput (getDevices() [index]);
  229117. mpc->input = newInput;
  229118. newInput->internal = mpc;
  229119. const ScopedLock sl (callbackLock);
  229120. activeCallbacks.add (mpc.release());
  229121. }
  229122. else
  229123. {
  229124. CHECK_ERROR (MIDIPortDispose (port));
  229125. }
  229126. }
  229127. }
  229128. }
  229129. CFRelease (name);
  229130. }
  229131. }
  229132. return newInput;
  229133. }
  229134. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229135. {
  229136. jassert (callback != 0);
  229137. using namespace CoreMidiHelpers;
  229138. MidiInput* mi = 0;
  229139. MIDIClientRef client = getGlobalMidiClient();
  229140. if (client != 0)
  229141. {
  229142. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229143. mpc->active = false;
  229144. MIDIEndpointRef endPoint;
  229145. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229146. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229147. {
  229148. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229149. mi = new MidiInput (deviceName);
  229150. mpc->input = mi;
  229151. mi->internal = mpc;
  229152. const ScopedLock sl (callbackLock);
  229153. activeCallbacks.add (mpc.release());
  229154. }
  229155. CFRelease (name);
  229156. }
  229157. return mi;
  229158. }
  229159. MidiInput::MidiInput (const String& name_)
  229160. : name (name_)
  229161. {
  229162. }
  229163. MidiInput::~MidiInput()
  229164. {
  229165. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229166. }
  229167. void MidiInput::start()
  229168. {
  229169. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229170. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229171. }
  229172. void MidiInput::stop()
  229173. {
  229174. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229175. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229176. }
  229177. #undef CHECK_ERROR
  229178. #else // Stubs for iOS...
  229179. MidiOutput::~MidiOutput() {}
  229180. void MidiOutput::reset() {}
  229181. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229182. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229183. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229184. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229185. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229186. const StringArray MidiInput::getDevices() { return StringArray(); }
  229187. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229188. #endif
  229189. #endif
  229190. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229191. #else
  229192. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229193. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229194. // compiled on its own).
  229195. #if JUCE_INCLUDED_FILE
  229196. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229197. #define SUPPORT_10_4_FONTS 1
  229198. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229199. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229200. #define SUPPORT_ONLY_10_4_FONTS 1
  229201. #endif
  229202. END_JUCE_NAMESPACE
  229203. @interface NSFont (PrivateHack)
  229204. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229205. @end
  229206. BEGIN_JUCE_NAMESPACE
  229207. #endif
  229208. class MacTypeface : public Typeface
  229209. {
  229210. public:
  229211. MacTypeface (const Font& font)
  229212. : Typeface (font.getTypefaceName())
  229213. {
  229214. const ScopedAutoReleasePool pool;
  229215. renderingTransform = CGAffineTransformIdentity;
  229216. bool needsItalicTransform = false;
  229217. #if JUCE_IOS
  229218. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229219. if (font.isItalic() || font.isBold())
  229220. {
  229221. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229222. for (NSString* i in familyFonts)
  229223. {
  229224. const String fn (nsStringToJuce (i));
  229225. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229226. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229227. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229228. || afterDash.containsIgnoreCase ("italic")
  229229. || fn.endsWithIgnoreCase ("oblique")
  229230. || fn.endsWithIgnoreCase ("italic");
  229231. if (probablyBold == font.isBold()
  229232. && probablyItalic == font.isItalic())
  229233. {
  229234. fontName = i;
  229235. needsItalicTransform = false;
  229236. break;
  229237. }
  229238. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229239. {
  229240. fontName = i;
  229241. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229242. }
  229243. }
  229244. if (needsItalicTransform)
  229245. renderingTransform.c = 0.15f;
  229246. }
  229247. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229248. const int ascender = abs (CGFontGetAscent (fontRef));
  229249. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229250. ascent = ascender / totalHeight;
  229251. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229252. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229253. #else
  229254. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229255. if (font.isItalic())
  229256. {
  229257. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229258. toHaveTrait: NSItalicFontMask];
  229259. if (newFont == nsFont)
  229260. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229261. nsFont = newFont;
  229262. }
  229263. if (font.isBold())
  229264. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229265. [nsFont retain];
  229266. ascent = std::abs ((float) [nsFont ascender]);
  229267. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229268. ascent /= totalSize;
  229269. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229270. if (needsItalicTransform)
  229271. {
  229272. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229273. renderingTransform.c = 0.15f;
  229274. }
  229275. #if SUPPORT_ONLY_10_4_FONTS
  229276. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229277. if (atsFont == 0)
  229278. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229279. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229280. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229281. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229282. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229283. #else
  229284. #if SUPPORT_10_4_FONTS
  229285. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229286. {
  229287. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229288. if (atsFont == 0)
  229289. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229290. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229291. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229292. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229293. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229294. }
  229295. else
  229296. #endif
  229297. {
  229298. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229299. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229300. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229301. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229302. }
  229303. #endif
  229304. #endif
  229305. }
  229306. ~MacTypeface()
  229307. {
  229308. #if ! JUCE_IOS
  229309. [nsFont release];
  229310. #endif
  229311. if (fontRef != 0)
  229312. CGFontRelease (fontRef);
  229313. }
  229314. float getAscent() const
  229315. {
  229316. return ascent;
  229317. }
  229318. float getDescent() const
  229319. {
  229320. return 1.0f - ascent;
  229321. }
  229322. float getStringWidth (const String& text)
  229323. {
  229324. if (fontRef == 0 || text.isEmpty())
  229325. return 0;
  229326. const int length = text.length();
  229327. HeapBlock <CGGlyph> glyphs;
  229328. createGlyphsForString (text, length, glyphs);
  229329. float x = 0;
  229330. #if SUPPORT_ONLY_10_4_FONTS
  229331. HeapBlock <NSSize> advances (length);
  229332. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229333. for (int i = 0; i < length; ++i)
  229334. x += advances[i].width;
  229335. #else
  229336. #if SUPPORT_10_4_FONTS
  229337. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229338. {
  229339. HeapBlock <NSSize> advances (length);
  229340. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229341. for (int i = 0; i < length; ++i)
  229342. x += advances[i].width;
  229343. }
  229344. else
  229345. #endif
  229346. {
  229347. HeapBlock <int> advances (length);
  229348. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229349. for (int i = 0; i < length; ++i)
  229350. x += advances[i];
  229351. }
  229352. #endif
  229353. return x * unitsToHeightScaleFactor;
  229354. }
  229355. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229356. {
  229357. xOffsets.add (0);
  229358. if (fontRef == 0 || text.isEmpty())
  229359. return;
  229360. const int length = text.length();
  229361. HeapBlock <CGGlyph> glyphs;
  229362. createGlyphsForString (text, length, glyphs);
  229363. #if SUPPORT_ONLY_10_4_FONTS
  229364. HeapBlock <NSSize> advances (length);
  229365. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229366. int x = 0;
  229367. for (int i = 0; i < length; ++i)
  229368. {
  229369. x += advances[i].width;
  229370. xOffsets.add (x * unitsToHeightScaleFactor);
  229371. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229372. }
  229373. #else
  229374. #if SUPPORT_10_4_FONTS
  229375. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229376. {
  229377. HeapBlock <NSSize> advances (length);
  229378. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229379. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229380. float x = 0;
  229381. for (int i = 0; i < length; ++i)
  229382. {
  229383. x += advances[i].width;
  229384. xOffsets.add (x * unitsToHeightScaleFactor);
  229385. resultGlyphs.add (nsGlyphs[i]);
  229386. }
  229387. }
  229388. else
  229389. #endif
  229390. {
  229391. HeapBlock <int> advances (length);
  229392. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229393. {
  229394. int x = 0;
  229395. for (int i = 0; i < length; ++i)
  229396. {
  229397. x += advances [i];
  229398. xOffsets.add (x * unitsToHeightScaleFactor);
  229399. resultGlyphs.add (glyphs[i]);
  229400. }
  229401. }
  229402. }
  229403. #endif
  229404. }
  229405. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229406. {
  229407. #if JUCE_IOS
  229408. return false;
  229409. #else
  229410. if (nsFont == 0)
  229411. return false;
  229412. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229413. jassert (path.isEmpty());
  229414. const ScopedAutoReleasePool pool;
  229415. NSBezierPath* bez = [NSBezierPath bezierPath];
  229416. [bez moveToPoint: NSMakePoint (0, 0)];
  229417. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229418. inFont: nsFont];
  229419. for (int i = 0; i < [bez elementCount]; ++i)
  229420. {
  229421. NSPoint p[3];
  229422. switch ([bez elementAtIndex: i associatedPoints: p])
  229423. {
  229424. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229425. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229426. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229427. (float) p[1].x, (float) -p[1].y,
  229428. (float) p[2].x, (float) -p[2].y); break;
  229429. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229430. default: jassertfalse; break;
  229431. }
  229432. }
  229433. path.applyTransform (pathTransform);
  229434. return true;
  229435. #endif
  229436. }
  229437. CGFontRef fontRef;
  229438. float fontHeightToCGSizeFactor;
  229439. CGAffineTransform renderingTransform;
  229440. private:
  229441. float ascent, unitsToHeightScaleFactor;
  229442. #if JUCE_IOS
  229443. #else
  229444. NSFont* nsFont;
  229445. AffineTransform pathTransform;
  229446. #endif
  229447. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  229448. {
  229449. #if SUPPORT_10_4_FONTS
  229450. #if ! SUPPORT_ONLY_10_4_FONTS
  229451. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229452. #endif
  229453. {
  229454. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229455. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229456. for (int i = 0; i < length; ++i)
  229457. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  229458. return;
  229459. }
  229460. #endif
  229461. #if ! SUPPORT_ONLY_10_4_FONTS
  229462. if (charToGlyphMapper == 0)
  229463. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  229464. glyphs.malloc (length);
  229465. for (int i = 0; i < length; ++i)
  229466. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  229467. #endif
  229468. }
  229469. #if ! SUPPORT_ONLY_10_4_FONTS
  229470. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  229471. class CharToGlyphMapper
  229472. {
  229473. public:
  229474. CharToGlyphMapper (CGFontRef fontRef)
  229475. : segCount (0), endCode (0), startCode (0), idDelta (0),
  229476. idRangeOffset (0), glyphIndexes (0)
  229477. {
  229478. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  229479. if (cmapTable != 0)
  229480. {
  229481. const int numSubtables = getValue16 (cmapTable, 2);
  229482. for (int i = 0; i < numSubtables; ++i)
  229483. {
  229484. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  229485. {
  229486. const int offset = getValue32 (cmapTable, i * 8 + 8);
  229487. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  229488. {
  229489. const int length = getValue16 (cmapTable, offset + 2);
  229490. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  229491. segCount = segCountX2 / 2;
  229492. const int endCodeOffset = offset + 14;
  229493. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  229494. const int idDeltaOffset = startCodeOffset + segCountX2;
  229495. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  229496. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  229497. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  229498. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  229499. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  229500. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  229501. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  229502. }
  229503. break;
  229504. }
  229505. }
  229506. CFRelease (cmapTable);
  229507. }
  229508. }
  229509. ~CharToGlyphMapper()
  229510. {
  229511. if (endCode != 0)
  229512. {
  229513. CFRelease (endCode);
  229514. CFRelease (startCode);
  229515. CFRelease (idDelta);
  229516. CFRelease (idRangeOffset);
  229517. CFRelease (glyphIndexes);
  229518. }
  229519. }
  229520. int getGlyphForCharacter (const juce_wchar c) const
  229521. {
  229522. for (int i = 0; i < segCount; ++i)
  229523. {
  229524. if (getValue16 (endCode, i * 2) >= c)
  229525. {
  229526. const int start = getValue16 (startCode, i * 2);
  229527. if (start > c)
  229528. break;
  229529. const int delta = getValue16 (idDelta, i * 2);
  229530. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  229531. if (rangeOffset == 0)
  229532. return delta + c;
  229533. else
  229534. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  229535. }
  229536. }
  229537. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  229538. return jmax (-1, (int) c - 29);
  229539. }
  229540. private:
  229541. int segCount;
  229542. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  229543. static uint16 getValue16 (CFDataRef data, const int index)
  229544. {
  229545. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  229546. }
  229547. static uint32 getValue32 (CFDataRef data, const int index)
  229548. {
  229549. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  229550. }
  229551. };
  229552. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  229553. #endif
  229554. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  229555. };
  229556. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  229557. {
  229558. return new MacTypeface (font);
  229559. }
  229560. const StringArray Font::findAllTypefaceNames()
  229561. {
  229562. StringArray names;
  229563. const ScopedAutoReleasePool pool;
  229564. #if JUCE_IOS
  229565. NSArray* fonts = [UIFont familyNames];
  229566. #else
  229567. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  229568. #endif
  229569. for (unsigned int i = 0; i < [fonts count]; ++i)
  229570. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  229571. names.sort (true);
  229572. return names;
  229573. }
  229574. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  229575. {
  229576. #if JUCE_IOS
  229577. defaultSans = "Helvetica";
  229578. defaultSerif = "Times New Roman";
  229579. defaultFixed = "Courier New";
  229580. #else
  229581. defaultSans = "Lucida Grande";
  229582. defaultSerif = "Times New Roman";
  229583. defaultFixed = "Monaco";
  229584. #endif
  229585. defaultFallback = "Arial Unicode MS";
  229586. }
  229587. #endif
  229588. /*** End of inlined file: juce_mac_Fonts.mm ***/
  229589. // (must go before juce_mac_CoreGraphicsContext.mm)
  229590. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229591. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229592. // compiled on its own).
  229593. #if JUCE_INCLUDED_FILE
  229594. class CoreGraphicsImage : public Image::SharedImage
  229595. {
  229596. public:
  229597. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  229598. : Image::SharedImage (format_, width_, height_)
  229599. {
  229600. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  229601. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  229602. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  229603. imageData = imageDataAllocated;
  229604. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  229605. : CGColorSpaceCreateDeviceRGB();
  229606. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  229607. colourSpace, getCGImageFlags (format_));
  229608. CGColorSpaceRelease (colourSpace);
  229609. }
  229610. ~CoreGraphicsImage()
  229611. {
  229612. CGContextRelease (context);
  229613. }
  229614. Image::ImageType getType() const { return Image::NativeImage; }
  229615. LowLevelGraphicsContext* createLowLevelContext();
  229616. SharedImage* clone()
  229617. {
  229618. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  229619. memcpy (im->imageData, imageData, lineStride * height);
  229620. return im;
  229621. }
  229622. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  229623. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  229624. {
  229625. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  229626. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  229627. {
  229628. return CGBitmapContextCreateImage (nativeImage->context);
  229629. }
  229630. else
  229631. {
  229632. const Image::BitmapData srcData (juceImage, false);
  229633. CGDataProviderRef provider;
  229634. if (mustOutliveSource)
  229635. {
  229636. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  229637. provider = CGDataProviderCreateWithCFData (data);
  229638. CFRelease (data);
  229639. }
  229640. else
  229641. {
  229642. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  229643. }
  229644. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  229645. 8, srcData.pixelStride * 8, srcData.lineStride,
  229646. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  229647. 0, true, kCGRenderingIntentDefault);
  229648. CGDataProviderRelease (provider);
  229649. return imageRef;
  229650. }
  229651. }
  229652. #if JUCE_MAC
  229653. static NSImage* createNSImage (const Image& image)
  229654. {
  229655. const ScopedAutoReleasePool pool;
  229656. NSImage* im = [[NSImage alloc] init];
  229657. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  229658. [im lockFocus];
  229659. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  229660. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  229661. CGColorSpaceRelease (colourSpace);
  229662. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  229663. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  229664. CGImageRelease (imageRef);
  229665. [im unlockFocus];
  229666. return im;
  229667. }
  229668. #endif
  229669. CGContextRef context;
  229670. HeapBlock<uint8> imageDataAllocated;
  229671. private:
  229672. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  229673. {
  229674. #if JUCE_BIG_ENDIAN
  229675. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  229676. #else
  229677. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  229678. #endif
  229679. }
  229680. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  229681. };
  229682. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  229683. {
  229684. #if USE_COREGRAPHICS_RENDERING
  229685. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  229686. #else
  229687. return createSoftwareImage (format, width, height, clearImage);
  229688. #endif
  229689. }
  229690. class CoreGraphicsContext : public LowLevelGraphicsContext
  229691. {
  229692. public:
  229693. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  229694. : context (context_),
  229695. flipHeight (flipHeight_),
  229696. lastClipRectIsValid (false),
  229697. state (new SavedState()),
  229698. numGradientLookupEntries (0)
  229699. {
  229700. CGContextRetain (context);
  229701. CGContextSaveGState(context);
  229702. CGContextSetShouldSmoothFonts (context, true);
  229703. CGContextSetShouldAntialias (context, true);
  229704. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229705. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  229706. greyColourSpace = CGColorSpaceCreateDeviceGray();
  229707. gradientCallbacks.version = 0;
  229708. gradientCallbacks.evaluate = gradientCallback;
  229709. gradientCallbacks.releaseInfo = 0;
  229710. setFont (Font());
  229711. }
  229712. ~CoreGraphicsContext()
  229713. {
  229714. CGContextRestoreGState (context);
  229715. CGContextRelease (context);
  229716. CGColorSpaceRelease (rgbColourSpace);
  229717. CGColorSpaceRelease (greyColourSpace);
  229718. }
  229719. bool isVectorDevice() const { return false; }
  229720. void setOrigin (int x, int y)
  229721. {
  229722. CGContextTranslateCTM (context, x, -y);
  229723. if (lastClipRectIsValid)
  229724. lastClipRect.translate (-x, -y);
  229725. }
  229726. void addTransform (const AffineTransform& transform)
  229727. {
  229728. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  229729. .translated (0, flipHeight)
  229730. .followedBy (transform)
  229731. .translated (0, -flipHeight)
  229732. .scaled (1.0f, -1.0f));
  229733. lastClipRectIsValid = false;
  229734. }
  229735. float getScaleFactor()
  229736. {
  229737. CGAffineTransform t = CGContextGetCTM (context);
  229738. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  229739. }
  229740. bool clipToRectangle (const Rectangle<int>& r)
  229741. {
  229742. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  229743. if (lastClipRectIsValid)
  229744. {
  229745. // This is actually incorrect, because the actual clip region may be complex, and
  229746. // clipping its bounds to a rect may not be right... But, removing this shortcut
  229747. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  229748. // when calculating the resultant clip bounds, and makes the same mistake!
  229749. lastClipRect = lastClipRect.getIntersection (r);
  229750. return ! lastClipRect.isEmpty();
  229751. }
  229752. return ! isClipEmpty();
  229753. }
  229754. bool clipToRectangleList (const RectangleList& clipRegion)
  229755. {
  229756. if (clipRegion.isEmpty())
  229757. {
  229758. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  229759. lastClipRectIsValid = true;
  229760. lastClipRect = Rectangle<int>();
  229761. return false;
  229762. }
  229763. else
  229764. {
  229765. const int numRects = clipRegion.getNumRectangles();
  229766. HeapBlock <CGRect> rects (numRects);
  229767. for (int i = 0; i < numRects; ++i)
  229768. {
  229769. const Rectangle<int>& r = clipRegion.getRectangle(i);
  229770. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229771. }
  229772. CGContextClipToRects (context, rects, numRects);
  229773. lastClipRectIsValid = false;
  229774. return ! isClipEmpty();
  229775. }
  229776. }
  229777. void excludeClipRectangle (const Rectangle<int>& r)
  229778. {
  229779. RectangleList remaining (getClipBounds());
  229780. remaining.subtract (r);
  229781. clipToRectangleList (remaining);
  229782. lastClipRectIsValid = false;
  229783. }
  229784. void clipToPath (const Path& path, const AffineTransform& transform)
  229785. {
  229786. createPath (path, transform);
  229787. CGContextClip (context);
  229788. lastClipRectIsValid = false;
  229789. }
  229790. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  229791. {
  229792. if (! transform.isSingularity())
  229793. {
  229794. Image singleChannelImage (sourceImage);
  229795. if (sourceImage.getFormat() != Image::SingleChannel)
  229796. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  229797. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  229798. flip();
  229799. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  229800. applyTransform (t);
  229801. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  229802. CGContextClipToMask (context, r, image);
  229803. applyTransform (t.inverted());
  229804. flip();
  229805. CGImageRelease (image);
  229806. lastClipRectIsValid = false;
  229807. }
  229808. }
  229809. bool clipRegionIntersects (const Rectangle<int>& r)
  229810. {
  229811. return getClipBounds().intersects (r);
  229812. }
  229813. const Rectangle<int> getClipBounds() const
  229814. {
  229815. if (! lastClipRectIsValid)
  229816. {
  229817. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229818. lastClipRectIsValid = true;
  229819. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229820. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229821. roundToInt (bounds.size.width),
  229822. roundToInt (bounds.size.height));
  229823. }
  229824. return lastClipRect;
  229825. }
  229826. bool isClipEmpty() const
  229827. {
  229828. return getClipBounds().isEmpty();
  229829. }
  229830. void saveState()
  229831. {
  229832. CGContextSaveGState (context);
  229833. stateStack.add (new SavedState (*state));
  229834. }
  229835. void restoreState()
  229836. {
  229837. CGContextRestoreGState (context);
  229838. SavedState* const top = stateStack.getLast();
  229839. if (top != 0)
  229840. {
  229841. state = top;
  229842. stateStack.removeLast (1, false);
  229843. lastClipRectIsValid = false;
  229844. }
  229845. else
  229846. {
  229847. jassertfalse; // trying to pop with an empty stack!
  229848. }
  229849. }
  229850. void beginTransparencyLayer (float opacity)
  229851. {
  229852. saveState();
  229853. CGContextSetAlpha (context, opacity);
  229854. CGContextBeginTransparencyLayer (context, 0);
  229855. }
  229856. void endTransparencyLayer()
  229857. {
  229858. CGContextEndTransparencyLayer (context);
  229859. restoreState();
  229860. }
  229861. void setFill (const FillType& fillType)
  229862. {
  229863. state->fillType = fillType;
  229864. if (fillType.isColour())
  229865. {
  229866. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229867. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229868. CGContextSetAlpha (context, 1.0f);
  229869. }
  229870. }
  229871. void setOpacity (float newOpacity)
  229872. {
  229873. state->fillType.setOpacity (newOpacity);
  229874. setFill (state->fillType);
  229875. }
  229876. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  229877. {
  229878. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  229879. ? kCGInterpolationLow
  229880. : kCGInterpolationHigh);
  229881. }
  229882. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  229883. {
  229884. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  229885. }
  229886. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  229887. {
  229888. if (replaceExistingContents)
  229889. {
  229890. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229891. CGContextClearRect (context, cgRect);
  229892. #else
  229893. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229894. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  229895. CGContextClearRect (context, cgRect);
  229896. else
  229897. #endif
  229898. CGContextSetBlendMode (context, kCGBlendModeCopy);
  229899. #endif
  229900. fillCGRect (cgRect, false);
  229901. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229902. }
  229903. else
  229904. {
  229905. if (state->fillType.isColour())
  229906. {
  229907. CGContextFillRect (context, cgRect);
  229908. }
  229909. else if (state->fillType.isGradient())
  229910. {
  229911. CGContextSaveGState (context);
  229912. CGContextClipToRect (context, cgRect);
  229913. drawGradient();
  229914. CGContextRestoreGState (context);
  229915. }
  229916. else
  229917. {
  229918. CGContextSaveGState (context);
  229919. CGContextClipToRect (context, cgRect);
  229920. drawImage (state->fillType.image, state->fillType.transform, true);
  229921. CGContextRestoreGState (context);
  229922. }
  229923. }
  229924. }
  229925. void fillPath (const Path& path, const AffineTransform& transform)
  229926. {
  229927. CGContextSaveGState (context);
  229928. if (state->fillType.isColour())
  229929. {
  229930. flip();
  229931. applyTransform (transform);
  229932. createPath (path);
  229933. if (path.isUsingNonZeroWinding())
  229934. CGContextFillPath (context);
  229935. else
  229936. CGContextEOFillPath (context);
  229937. }
  229938. else
  229939. {
  229940. createPath (path, transform);
  229941. if (path.isUsingNonZeroWinding())
  229942. CGContextClip (context);
  229943. else
  229944. CGContextEOClip (context);
  229945. if (state->fillType.isGradient())
  229946. drawGradient();
  229947. else
  229948. drawImage (state->fillType.image, state->fillType.transform, true);
  229949. }
  229950. CGContextRestoreGState (context);
  229951. }
  229952. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229953. {
  229954. const int iw = sourceImage.getWidth();
  229955. const int ih = sourceImage.getHeight();
  229956. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  229957. CGContextSaveGState (context);
  229958. CGContextSetAlpha (context, state->fillType.getOpacity());
  229959. flip();
  229960. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  229961. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  229962. if (fillEntireClipAsTiles)
  229963. {
  229964. #if JUCE_IOS
  229965. CGContextDrawTiledImage (context, imageRect, image);
  229966. #else
  229967. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229968. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229969. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229970. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229971. CGContextDrawTiledImage (context, imageRect, image);
  229972. else
  229973. #endif
  229974. {
  229975. // Fallback to manually doing a tiled fill on 10.4
  229976. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229977. int x = 0, y = 0;
  229978. while (x > clip.origin.x) x -= iw;
  229979. while (y > clip.origin.y) y -= ih;
  229980. const int right = (int) (clip.origin.x + clip.size.width);
  229981. const int bottom = (int) (clip.origin.y + clip.size.height);
  229982. while (y < bottom)
  229983. {
  229984. for (int x2 = x; x2 < right; x2 += iw)
  229985. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229986. y += ih;
  229987. }
  229988. }
  229989. #endif
  229990. }
  229991. else
  229992. {
  229993. CGContextDrawImage (context, imageRect, image);
  229994. }
  229995. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229996. CGContextRestoreGState (context);
  229997. }
  229998. void drawLine (const Line<float>& line)
  229999. {
  230000. if (state->fillType.isColour())
  230001. {
  230002. CGContextSetLineCap (context, kCGLineCapSquare);
  230003. CGContextSetLineWidth (context, 1.0f);
  230004. CGContextSetRGBStrokeColor (context,
  230005. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230006. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230007. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230008. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230009. CGContextStrokeLineSegments (context, cgLine, 1);
  230010. }
  230011. else
  230012. {
  230013. Path p;
  230014. p.addLineSegment (line, 1.0f);
  230015. fillPath (p, AffineTransform::identity);
  230016. }
  230017. }
  230018. void drawVerticalLine (const int x, float top, float bottom)
  230019. {
  230020. if (state->fillType.isColour())
  230021. {
  230022. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230023. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230024. #else
  230025. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230026. // the x co-ord slightly to trick it..
  230027. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230028. #endif
  230029. }
  230030. else
  230031. {
  230032. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230033. }
  230034. }
  230035. void drawHorizontalLine (const int y, float left, float right)
  230036. {
  230037. if (state->fillType.isColour())
  230038. {
  230039. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230040. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230041. #else
  230042. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230043. // the x co-ord slightly to trick it..
  230044. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230045. #endif
  230046. }
  230047. else
  230048. {
  230049. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230050. }
  230051. }
  230052. void setFont (const Font& newFont)
  230053. {
  230054. if (state->font != newFont)
  230055. {
  230056. state->fontRef = 0;
  230057. state->font = newFont;
  230058. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230059. if (mf != 0)
  230060. {
  230061. state->fontRef = mf->fontRef;
  230062. CGContextSetFont (context, state->fontRef);
  230063. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230064. state->fontTransform = mf->renderingTransform;
  230065. state->fontTransform.a *= state->font.getHorizontalScale();
  230066. CGContextSetTextMatrix (context, state->fontTransform);
  230067. }
  230068. }
  230069. }
  230070. const Font getFont()
  230071. {
  230072. return state->font;
  230073. }
  230074. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230075. {
  230076. if (state->fontRef != 0 && state->fillType.isColour())
  230077. {
  230078. if (transform.isOnlyTranslation())
  230079. {
  230080. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230081. CGGlyph g = glyphNumber;
  230082. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230083. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230084. }
  230085. else
  230086. {
  230087. CGContextSaveGState (context);
  230088. flip();
  230089. applyTransform (transform);
  230090. CGAffineTransform t = state->fontTransform;
  230091. t.d = -t.d;
  230092. CGContextSetTextMatrix (context, t);
  230093. CGGlyph g = glyphNumber;
  230094. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230095. CGContextRestoreGState (context);
  230096. }
  230097. }
  230098. else
  230099. {
  230100. Path p;
  230101. Font& f = state->font;
  230102. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230103. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230104. .followedBy (transform));
  230105. }
  230106. }
  230107. private:
  230108. CGContextRef context;
  230109. const CGFloat flipHeight;
  230110. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230111. CGFunctionCallbacks gradientCallbacks;
  230112. mutable Rectangle<int> lastClipRect;
  230113. mutable bool lastClipRectIsValid;
  230114. struct SavedState
  230115. {
  230116. SavedState()
  230117. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230118. {
  230119. }
  230120. SavedState (const SavedState& other)
  230121. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230122. fontTransform (other.fontTransform)
  230123. {
  230124. }
  230125. FillType fillType;
  230126. Font font;
  230127. CGFontRef fontRef;
  230128. CGAffineTransform fontTransform;
  230129. };
  230130. ScopedPointer <SavedState> state;
  230131. OwnedArray <SavedState> stateStack;
  230132. HeapBlock <PixelARGB> gradientLookupTable;
  230133. int numGradientLookupEntries;
  230134. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230135. {
  230136. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230137. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230138. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230139. colour.unpremultiply();
  230140. outData[0] = colour.getRed() / 255.0f;
  230141. outData[1] = colour.getGreen() / 255.0f;
  230142. outData[2] = colour.getBlue() / 255.0f;
  230143. outData[3] = colour.getAlpha() / 255.0f;
  230144. }
  230145. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230146. {
  230147. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  230148. CGShadingRef result = 0;
  230149. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230150. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230151. if (gradient.isRadial)
  230152. {
  230153. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230154. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230155. function, true, true);
  230156. }
  230157. else
  230158. {
  230159. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230160. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230161. function, true, true);
  230162. }
  230163. CGFunctionRelease (function);
  230164. return result;
  230165. }
  230166. void drawGradient()
  230167. {
  230168. flip();
  230169. applyTransform (state->fillType.transform);
  230170. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230171. // you draw a gradient with high quality interp enabled).
  230172. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230173. CGContextSetAlpha (context, state->fillType.getOpacity());
  230174. CGContextDrawShading (context, shading);
  230175. CGShadingRelease (shading);
  230176. }
  230177. void createPath (const Path& path) const
  230178. {
  230179. CGContextBeginPath (context);
  230180. Path::Iterator i (path);
  230181. while (i.next())
  230182. {
  230183. switch (i.elementType)
  230184. {
  230185. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230186. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230187. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230188. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230189. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230190. default: jassertfalse; break;
  230191. }
  230192. }
  230193. }
  230194. void createPath (const Path& path, const AffineTransform& transform) const
  230195. {
  230196. CGContextBeginPath (context);
  230197. Path::Iterator i (path);
  230198. while (i.next())
  230199. {
  230200. switch (i.elementType)
  230201. {
  230202. case Path::Iterator::startNewSubPath:
  230203. transform.transformPoint (i.x1, i.y1);
  230204. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230205. break;
  230206. case Path::Iterator::lineTo:
  230207. transform.transformPoint (i.x1, i.y1);
  230208. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230209. break;
  230210. case Path::Iterator::quadraticTo:
  230211. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230212. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230213. break;
  230214. case Path::Iterator::cubicTo:
  230215. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230216. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230217. break;
  230218. case Path::Iterator::closePath:
  230219. CGContextClosePath (context); break;
  230220. default:
  230221. jassertfalse;
  230222. break;
  230223. }
  230224. }
  230225. }
  230226. void flip() const
  230227. {
  230228. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230229. }
  230230. void applyTransform (const AffineTransform& transform) const
  230231. {
  230232. CGAffineTransform t;
  230233. t.a = transform.mat00;
  230234. t.b = transform.mat10;
  230235. t.c = transform.mat01;
  230236. t.d = transform.mat11;
  230237. t.tx = transform.mat02;
  230238. t.ty = transform.mat12;
  230239. CGContextConcatCTM (context, t);
  230240. }
  230241. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230242. };
  230243. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230244. {
  230245. return new CoreGraphicsContext (context, height);
  230246. }
  230247. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230248. const Image juce_loadWithCoreImage (InputStream& input)
  230249. {
  230250. MemoryBlock data;
  230251. input.readIntoMemoryBlock (data, -1);
  230252. #if JUCE_IOS
  230253. JUCE_AUTORELEASEPOOL
  230254. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230255. length: data.getSize()
  230256. freeWhenDone: NO]];
  230257. if (image != nil)
  230258. {
  230259. CGImageRef loadedImage = image.CGImage;
  230260. #else
  230261. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230262. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230263. CGDataProviderRelease (provider);
  230264. if (imageSource != 0)
  230265. {
  230266. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230267. CFRelease (imageSource);
  230268. #endif
  230269. if (loadedImage != 0)
  230270. {
  230271. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230272. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230273. && alphaInfo != kCGImageAlphaNoneSkipLast
  230274. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230275. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230276. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230277. hasAlphaChan, Image::NativeImage);
  230278. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230279. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230280. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230281. CGContextFlush (cgImage->context);
  230282. #if ! JUCE_IOS
  230283. CFRelease (loadedImage);
  230284. #endif
  230285. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230286. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230287. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230288. return image;
  230289. }
  230290. }
  230291. return Image::null;
  230292. }
  230293. #endif
  230294. #endif
  230295. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230296. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230297. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230298. // compiled on its own).
  230299. #if JUCE_INCLUDED_FILE
  230300. class NSViewComponentPeer;
  230301. END_JUCE_NAMESPACE
  230302. @interface NSEvent (JuceDeviceDelta)
  230303. - (float) deviceDeltaX;
  230304. - (float) deviceDeltaY;
  230305. @end
  230306. #define JuceNSView MakeObjCClassName(JuceNSView)
  230307. @interface JuceNSView : NSView<NSTextInput>
  230308. {
  230309. @public
  230310. NSViewComponentPeer* owner;
  230311. NSNotificationCenter* notificationCenter;
  230312. String* stringBeingComposed;
  230313. bool textWasInserted;
  230314. }
  230315. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230316. - (void) dealloc;
  230317. - (BOOL) isOpaque;
  230318. - (void) drawRect: (NSRect) r;
  230319. - (void) mouseDown: (NSEvent*) ev;
  230320. - (void) asyncMouseDown: (NSEvent*) ev;
  230321. - (void) mouseUp: (NSEvent*) ev;
  230322. - (void) asyncMouseUp: (NSEvent*) ev;
  230323. - (void) mouseDragged: (NSEvent*) ev;
  230324. - (void) mouseMoved: (NSEvent*) ev;
  230325. - (void) mouseEntered: (NSEvent*) ev;
  230326. - (void) mouseExited: (NSEvent*) ev;
  230327. - (void) rightMouseDown: (NSEvent*) ev;
  230328. - (void) rightMouseDragged: (NSEvent*) ev;
  230329. - (void) rightMouseUp: (NSEvent*) ev;
  230330. - (void) otherMouseDown: (NSEvent*) ev;
  230331. - (void) otherMouseDragged: (NSEvent*) ev;
  230332. - (void) otherMouseUp: (NSEvent*) ev;
  230333. - (void) scrollWheel: (NSEvent*) ev;
  230334. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230335. - (void) frameChanged: (NSNotification*) n;
  230336. - (void) viewDidMoveToWindow;
  230337. - (void) keyDown: (NSEvent*) ev;
  230338. - (void) keyUp: (NSEvent*) ev;
  230339. // NSTextInput Methods
  230340. - (void) insertText: (id) aString;
  230341. - (void) doCommandBySelector: (SEL) aSelector;
  230342. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230343. - (void) unmarkText;
  230344. - (BOOL) hasMarkedText;
  230345. - (long) conversationIdentifier;
  230346. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230347. - (NSRange) markedRange;
  230348. - (NSRange) selectedRange;
  230349. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230350. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230351. - (NSArray*) validAttributesForMarkedText;
  230352. - (void) flagsChanged: (NSEvent*) ev;
  230353. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230354. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230355. #endif
  230356. - (BOOL) becomeFirstResponder;
  230357. - (BOOL) resignFirstResponder;
  230358. - (BOOL) acceptsFirstResponder;
  230359. - (void) asyncRepaint: (id) rect;
  230360. - (NSArray*) getSupportedDragTypes;
  230361. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230362. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230363. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230364. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230365. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230366. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230367. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230368. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230369. @end
  230370. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230371. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230372. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230373. #else
  230374. @interface JuceNSWindow : NSWindow
  230375. #endif
  230376. {
  230377. @private
  230378. NSViewComponentPeer* owner;
  230379. bool isZooming;
  230380. }
  230381. - (void) setOwner: (NSViewComponentPeer*) owner;
  230382. - (BOOL) canBecomeKeyWindow;
  230383. - (void) becomeKeyWindow;
  230384. - (BOOL) windowShouldClose: (id) window;
  230385. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230386. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230387. - (void) zoom: (id) sender;
  230388. @end
  230389. BEGIN_JUCE_NAMESPACE
  230390. class NSViewComponentPeer : public ComponentPeer
  230391. {
  230392. public:
  230393. NSViewComponentPeer (Component* const component,
  230394. const int windowStyleFlags,
  230395. NSView* viewToAttachTo);
  230396. ~NSViewComponentPeer();
  230397. void* getNativeHandle() const;
  230398. void setVisible (bool shouldBeVisible);
  230399. void setTitle (const String& title);
  230400. void setPosition (int x, int y);
  230401. void setSize (int w, int h);
  230402. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230403. const Rectangle<int> getBounds (const bool global) const;
  230404. const Rectangle<int> getBounds() const;
  230405. const Point<int> getScreenPosition() const;
  230406. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230407. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230408. void setAlpha (float newAlpha);
  230409. void setMinimised (bool shouldBeMinimised);
  230410. bool isMinimised() const;
  230411. void setFullScreen (bool shouldBeFullScreen);
  230412. bool isFullScreen() const;
  230413. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230414. const BorderSize<int> getFrameSize() const;
  230415. bool setAlwaysOnTop (bool alwaysOnTop);
  230416. void toFront (bool makeActiveWindow);
  230417. void toBehind (ComponentPeer* other);
  230418. void setIcon (const Image& newIcon);
  230419. const StringArray getAvailableRenderingEngines();
  230420. int getCurrentRenderingEngine() throw();
  230421. void setCurrentRenderingEngine (int index);
  230422. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230423. for example having more than one juce plugin loaded into a host, then when a
  230424. method is called, the actual code that runs might actually be in a different module
  230425. than the one you expect... So any calls to library functions or statics that are
  230426. made inside obj-c methods will probably end up getting executed in a different DLL's
  230427. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230428. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230429. virtual methods of an object that's known to live inside the right module's space.
  230430. */
  230431. virtual void redirectMouseDown (NSEvent* ev);
  230432. virtual void redirectMouseUp (NSEvent* ev);
  230433. virtual void redirectMouseDrag (NSEvent* ev);
  230434. virtual void redirectMouseMove (NSEvent* ev);
  230435. virtual void redirectMouseEnter (NSEvent* ev);
  230436. virtual void redirectMouseExit (NSEvent* ev);
  230437. virtual void redirectMouseWheel (NSEvent* ev);
  230438. void sendMouseEvent (NSEvent* ev);
  230439. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230440. virtual bool redirectKeyDown (NSEvent* ev);
  230441. virtual bool redirectKeyUp (NSEvent* ev);
  230442. virtual void redirectModKeyChange (NSEvent* ev);
  230443. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230444. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230445. #endif
  230446. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230447. virtual bool isOpaque();
  230448. virtual void drawRect (NSRect r);
  230449. virtual bool canBecomeKeyWindow();
  230450. virtual bool windowShouldClose();
  230451. virtual void redirectMovedOrResized();
  230452. virtual void viewMovedToWindow();
  230453. virtual NSRect constrainRect (NSRect r);
  230454. static void showArrowCursorIfNeeded();
  230455. static void updateModifiers (NSEvent* e);
  230456. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  230457. static int getKeyCodeFromEvent (NSEvent* ev)
  230458. {
  230459. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230460. int keyCode = unmodified[0];
  230461. if (keyCode == 0x19) // (backwards-tab)
  230462. keyCode = '\t';
  230463. else if (keyCode == 0x03) // (enter)
  230464. keyCode = '\r';
  230465. else
  230466. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  230467. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  230468. {
  230469. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  230470. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  230471. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  230472. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  230473. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  230474. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  230475. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  230476. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  230477. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  230478. if (keyCode == numPadConversions [i])
  230479. keyCode = numPadConversions [i + 1];
  230480. }
  230481. return keyCode;
  230482. }
  230483. static int64 getMouseTime (NSEvent* e)
  230484. {
  230485. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  230486. + (int64) ([e timestamp] * 1000.0);
  230487. }
  230488. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  230489. {
  230490. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  230491. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  230492. }
  230493. static int getModifierForButtonNumber (const NSInteger num)
  230494. {
  230495. return num == 0 ? ModifierKeys::leftButtonModifier
  230496. : (num == 1 ? ModifierKeys::rightButtonModifier
  230497. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  230498. }
  230499. virtual void viewFocusGain();
  230500. virtual void viewFocusLoss();
  230501. bool isFocused() const;
  230502. void grabFocus();
  230503. void textInputRequired (const Point<int>& position);
  230504. void repaint (const Rectangle<int>& area);
  230505. void performAnyPendingRepaintsNow();
  230506. NSWindow* window;
  230507. JuceNSView* view;
  230508. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  230509. static ModifierKeys currentModifiers;
  230510. static ComponentPeer* currentlyFocusedPeer;
  230511. static Array<int> keysCurrentlyDown;
  230512. private:
  230513. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  230514. };
  230515. END_JUCE_NAMESPACE
  230516. @implementation JuceNSView
  230517. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  230518. withFrame: (NSRect) frame
  230519. {
  230520. [super initWithFrame: frame];
  230521. owner = owner_;
  230522. stringBeingComposed = 0;
  230523. textWasInserted = false;
  230524. notificationCenter = [NSNotificationCenter defaultCenter];
  230525. [notificationCenter addObserver: self
  230526. selector: @selector (frameChanged:)
  230527. name: NSViewFrameDidChangeNotification
  230528. object: self];
  230529. if (! owner_->isSharedWindow)
  230530. {
  230531. [notificationCenter addObserver: self
  230532. selector: @selector (frameChanged:)
  230533. name: NSWindowDidMoveNotification
  230534. object: owner_->window];
  230535. }
  230536. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  230537. return self;
  230538. }
  230539. - (void) dealloc
  230540. {
  230541. [notificationCenter removeObserver: self];
  230542. delete stringBeingComposed;
  230543. [super dealloc];
  230544. }
  230545. - (void) drawRect: (NSRect) r
  230546. {
  230547. if (owner != 0)
  230548. owner->drawRect (r);
  230549. }
  230550. - (BOOL) isOpaque
  230551. {
  230552. return owner == 0 || owner->isOpaque();
  230553. }
  230554. - (void) mouseDown: (NSEvent*) ev
  230555. {
  230556. if (JUCEApplication::isStandaloneApp())
  230557. [self asyncMouseDown: ev];
  230558. else
  230559. // In some host situations, the host will stop modal loops from working
  230560. // correctly if they're called from a mouse event, so we'll trigger
  230561. // the event asynchronously..
  230562. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  230563. withObject: ev
  230564. waitUntilDone: NO];
  230565. }
  230566. - (void) asyncMouseDown: (NSEvent*) ev
  230567. {
  230568. if (owner != 0)
  230569. owner->redirectMouseDown (ev);
  230570. }
  230571. - (void) mouseUp: (NSEvent*) ev
  230572. {
  230573. if (! JUCEApplication::isStandaloneApp())
  230574. [self asyncMouseUp: ev];
  230575. else
  230576. // In some host situations, the host will stop modal loops from working
  230577. // correctly if they're called from a mouse event, so we'll trigger
  230578. // the event asynchronously..
  230579. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  230580. withObject: ev
  230581. waitUntilDone: NO];
  230582. }
  230583. - (void) asyncMouseUp: (NSEvent*) ev
  230584. {
  230585. if (owner != 0)
  230586. owner->redirectMouseUp (ev);
  230587. }
  230588. - (void) mouseDragged: (NSEvent*) ev
  230589. {
  230590. if (owner != 0)
  230591. owner->redirectMouseDrag (ev);
  230592. }
  230593. - (void) mouseMoved: (NSEvent*) ev
  230594. {
  230595. if (owner != 0)
  230596. owner->redirectMouseMove (ev);
  230597. }
  230598. - (void) mouseEntered: (NSEvent*) ev
  230599. {
  230600. if (owner != 0)
  230601. owner->redirectMouseEnter (ev);
  230602. }
  230603. - (void) mouseExited: (NSEvent*) ev
  230604. {
  230605. if (owner != 0)
  230606. owner->redirectMouseExit (ev);
  230607. }
  230608. - (void) rightMouseDown: (NSEvent*) ev
  230609. {
  230610. [self mouseDown: ev];
  230611. }
  230612. - (void) rightMouseDragged: (NSEvent*) ev
  230613. {
  230614. [self mouseDragged: ev];
  230615. }
  230616. - (void) rightMouseUp: (NSEvent*) ev
  230617. {
  230618. [self mouseUp: ev];
  230619. }
  230620. - (void) otherMouseDown: (NSEvent*) ev
  230621. {
  230622. [self mouseDown: ev];
  230623. }
  230624. - (void) otherMouseDragged: (NSEvent*) ev
  230625. {
  230626. [self mouseDragged: ev];
  230627. }
  230628. - (void) otherMouseUp: (NSEvent*) ev
  230629. {
  230630. [self mouseUp: ev];
  230631. }
  230632. - (void) scrollWheel: (NSEvent*) ev
  230633. {
  230634. if (owner != 0)
  230635. owner->redirectMouseWheel (ev);
  230636. }
  230637. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  230638. {
  230639. (void) ev;
  230640. return YES;
  230641. }
  230642. - (void) frameChanged: (NSNotification*) n
  230643. {
  230644. (void) n;
  230645. if (owner != 0)
  230646. owner->redirectMovedOrResized();
  230647. }
  230648. - (void) viewDidMoveToWindow
  230649. {
  230650. if (owner != 0)
  230651. owner->viewMovedToWindow();
  230652. }
  230653. - (void) asyncRepaint: (id) rect
  230654. {
  230655. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  230656. [self setNeedsDisplayInRect: *r];
  230657. }
  230658. - (void) keyDown: (NSEvent*) ev
  230659. {
  230660. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230661. textWasInserted = false;
  230662. if (target != 0)
  230663. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  230664. else
  230665. deleteAndZero (stringBeingComposed);
  230666. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  230667. [super keyDown: ev];
  230668. }
  230669. - (void) keyUp: (NSEvent*) ev
  230670. {
  230671. if (owner == 0 || ! owner->redirectKeyUp (ev))
  230672. [super keyUp: ev];
  230673. }
  230674. - (void) insertText: (id) aString
  230675. {
  230676. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  230677. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  230678. if ([newText length] > 0)
  230679. {
  230680. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230681. if (target != 0)
  230682. {
  230683. target->insertTextAtCaret (nsStringToJuce (newText));
  230684. textWasInserted = true;
  230685. }
  230686. }
  230687. deleteAndZero (stringBeingComposed);
  230688. }
  230689. - (void) doCommandBySelector: (SEL) aSelector
  230690. {
  230691. (void) aSelector;
  230692. }
  230693. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  230694. {
  230695. (void) selectionRange;
  230696. if (stringBeingComposed == 0)
  230697. stringBeingComposed = new String();
  230698. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  230699. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230700. if (target != 0)
  230701. {
  230702. const Range<int> currentHighlight (target->getHighlightedRegion());
  230703. target->insertTextAtCaret (*stringBeingComposed);
  230704. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  230705. textWasInserted = true;
  230706. }
  230707. }
  230708. - (void) unmarkText
  230709. {
  230710. if (stringBeingComposed != 0)
  230711. {
  230712. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230713. if (target != 0)
  230714. {
  230715. target->insertTextAtCaret (*stringBeingComposed);
  230716. textWasInserted = true;
  230717. }
  230718. }
  230719. deleteAndZero (stringBeingComposed);
  230720. }
  230721. - (BOOL) hasMarkedText
  230722. {
  230723. return stringBeingComposed != 0;
  230724. }
  230725. - (long) conversationIdentifier
  230726. {
  230727. return (long) (pointer_sized_int) self;
  230728. }
  230729. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  230730. {
  230731. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230732. if (target != 0)
  230733. {
  230734. const Range<int> r ((int) theRange.location,
  230735. (int) (theRange.location + theRange.length));
  230736. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  230737. }
  230738. return nil;
  230739. }
  230740. - (NSRange) markedRange
  230741. {
  230742. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  230743. : NSMakeRange (NSNotFound, 0);
  230744. }
  230745. - (NSRange) selectedRange
  230746. {
  230747. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230748. if (target != 0)
  230749. {
  230750. const Range<int> highlight (target->getHighlightedRegion());
  230751. if (! highlight.isEmpty())
  230752. return NSMakeRange (highlight.getStart(), highlight.getLength());
  230753. }
  230754. return NSMakeRange (NSNotFound, 0);
  230755. }
  230756. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  230757. {
  230758. (void) theRange;
  230759. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  230760. if (comp == 0)
  230761. return NSMakeRect (0, 0, 0, 0);
  230762. const Rectangle<int> bounds (comp->getScreenBounds());
  230763. return NSMakeRect (bounds.getX(),
  230764. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  230765. bounds.getWidth(),
  230766. bounds.getHeight());
  230767. }
  230768. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  230769. {
  230770. (void) thePoint;
  230771. return NSNotFound;
  230772. }
  230773. - (NSArray*) validAttributesForMarkedText
  230774. {
  230775. return [NSArray array];
  230776. }
  230777. - (void) flagsChanged: (NSEvent*) ev
  230778. {
  230779. if (owner != 0)
  230780. owner->redirectModKeyChange (ev);
  230781. }
  230782. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230783. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  230784. {
  230785. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  230786. return true;
  230787. return [super performKeyEquivalent: ev];
  230788. }
  230789. #endif
  230790. - (BOOL) becomeFirstResponder
  230791. {
  230792. if (owner != 0)
  230793. owner->viewFocusGain();
  230794. return true;
  230795. }
  230796. - (BOOL) resignFirstResponder
  230797. {
  230798. if (owner != 0)
  230799. owner->viewFocusLoss();
  230800. return true;
  230801. }
  230802. - (BOOL) acceptsFirstResponder
  230803. {
  230804. return owner != 0 && owner->canBecomeKeyWindow();
  230805. }
  230806. - (NSArray*) getSupportedDragTypes
  230807. {
  230808. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  230809. }
  230810. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  230811. {
  230812. return owner != 0 && owner->sendDragCallback (type, sender);
  230813. }
  230814. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  230815. {
  230816. if ([self sendDragCallback: 0 sender: sender])
  230817. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230818. else
  230819. return NSDragOperationNone;
  230820. }
  230821. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  230822. {
  230823. if ([self sendDragCallback: 0 sender: sender])
  230824. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230825. else
  230826. return NSDragOperationNone;
  230827. }
  230828. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  230829. {
  230830. [self sendDragCallback: 1 sender: sender];
  230831. }
  230832. - (void) draggingExited: (id <NSDraggingInfo>) sender
  230833. {
  230834. [self sendDragCallback: 1 sender: sender];
  230835. }
  230836. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  230837. {
  230838. (void) sender;
  230839. return YES;
  230840. }
  230841. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  230842. {
  230843. return [self sendDragCallback: 2 sender: sender];
  230844. }
  230845. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  230846. {
  230847. (void) sender;
  230848. }
  230849. @end
  230850. @implementation JuceNSWindow
  230851. - (void) setOwner: (NSViewComponentPeer*) owner_
  230852. {
  230853. owner = owner_;
  230854. isZooming = false;
  230855. }
  230856. - (BOOL) canBecomeKeyWindow
  230857. {
  230858. return owner != 0 && owner->canBecomeKeyWindow();
  230859. }
  230860. - (void) becomeKeyWindow
  230861. {
  230862. [super becomeKeyWindow];
  230863. if (owner != 0)
  230864. owner->grabFocus();
  230865. }
  230866. - (BOOL) windowShouldClose: (id) window
  230867. {
  230868. (void) window;
  230869. return owner == 0 || owner->windowShouldClose();
  230870. }
  230871. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  230872. {
  230873. (void) screen;
  230874. if (owner != 0)
  230875. frameRect = owner->constrainRect (frameRect);
  230876. return frameRect;
  230877. }
  230878. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  230879. {
  230880. (void) window;
  230881. if (isZooming)
  230882. return proposedFrameSize;
  230883. NSRect frameRect = [self frame];
  230884. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  230885. frameRect.size = proposedFrameSize;
  230886. if (owner != 0)
  230887. frameRect = owner->constrainRect (frameRect);
  230888. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230889. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230890. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230891. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230892. return frameRect.size;
  230893. }
  230894. - (void) zoom: (id) sender
  230895. {
  230896. isZooming = true;
  230897. [super zoom: sender];
  230898. isZooming = false;
  230899. }
  230900. - (void) windowWillMove: (NSNotification*) notification
  230901. {
  230902. (void) notification;
  230903. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230904. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230905. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230906. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230907. }
  230908. @end
  230909. BEGIN_JUCE_NAMESPACE
  230910. ModifierKeys NSViewComponentPeer::currentModifiers;
  230911. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  230912. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  230913. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  230914. {
  230915. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  230916. return true;
  230917. if (keyCode >= 'A' && keyCode <= 'Z'
  230918. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  230919. return true;
  230920. if (keyCode >= 'a' && keyCode <= 'z'
  230921. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  230922. return true;
  230923. return false;
  230924. }
  230925. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  230926. {
  230927. int m = 0;
  230928. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  230929. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  230930. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  230931. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  230932. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  230933. }
  230934. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  230935. {
  230936. updateModifiers (ev);
  230937. int keyCode = getKeyCodeFromEvent (ev);
  230938. if (keyCode != 0)
  230939. {
  230940. if (isKeyDown)
  230941. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  230942. else
  230943. keysCurrentlyDown.removeValue (keyCode);
  230944. }
  230945. }
  230946. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  230947. {
  230948. return NSViewComponentPeer::currentModifiers;
  230949. }
  230950. void ModifierKeys::updateCurrentModifiers() throw()
  230951. {
  230952. currentModifiers = NSViewComponentPeer::currentModifiers;
  230953. }
  230954. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  230955. const int windowStyleFlags,
  230956. NSView* viewToAttachTo)
  230957. : ComponentPeer (component_, windowStyleFlags),
  230958. window (0),
  230959. view (0),
  230960. isSharedWindow (viewToAttachTo != 0),
  230961. fullScreen (false),
  230962. insideDrawRect (false),
  230963. #if USE_COREGRAPHICS_RENDERING
  230964. usingCoreGraphics (true),
  230965. #else
  230966. usingCoreGraphics (false),
  230967. #endif
  230968. recursiveToFrontCall (false)
  230969. {
  230970. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  230971. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  230972. [view setPostsFrameChangedNotifications: YES];
  230973. if (isSharedWindow)
  230974. {
  230975. window = [viewToAttachTo window];
  230976. [viewToAttachTo addSubview: view];
  230977. }
  230978. else
  230979. {
  230980. r.origin.x = (float) component->getX();
  230981. r.origin.y = (float) component->getY();
  230982. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230983. unsigned int style = 0;
  230984. if ((windowStyleFlags & windowHasTitleBar) == 0)
  230985. style = NSBorderlessWindowMask;
  230986. else
  230987. style = NSTitledWindowMask;
  230988. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  230989. style |= NSMiniaturizableWindowMask;
  230990. if ((windowStyleFlags & windowHasCloseButton) != 0)
  230991. style |= NSClosableWindowMask;
  230992. if ((windowStyleFlags & windowIsResizable) != 0)
  230993. style |= NSResizableWindowMask;
  230994. window = [[JuceNSWindow alloc] initWithContentRect: r
  230995. styleMask: style
  230996. backing: NSBackingStoreBuffered
  230997. defer: YES];
  230998. [((JuceNSWindow*) window) setOwner: this];
  230999. [window orderOut: nil];
  231000. [window setDelegate: (JuceNSWindow*) window];
  231001. [window setOpaque: component->isOpaque()];
  231002. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231003. if (component->isAlwaysOnTop())
  231004. [window setLevel: NSFloatingWindowLevel];
  231005. [window setContentView: view];
  231006. [window setAutodisplay: YES];
  231007. [window setAcceptsMouseMovedEvents: YES];
  231008. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231009. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231010. [window setReleasedWhenClosed: YES];
  231011. [window retain];
  231012. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231013. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231014. }
  231015. const float alpha = component->getAlpha();
  231016. if (alpha < 1.0f)
  231017. setAlpha (alpha);
  231018. setTitle (component->getName());
  231019. }
  231020. NSViewComponentPeer::~NSViewComponentPeer()
  231021. {
  231022. view->owner = 0;
  231023. [view removeFromSuperview];
  231024. [view release];
  231025. if (! isSharedWindow)
  231026. {
  231027. [((JuceNSWindow*) window) setOwner: 0];
  231028. [window close];
  231029. [window release];
  231030. }
  231031. }
  231032. void* NSViewComponentPeer::getNativeHandle() const
  231033. {
  231034. return view;
  231035. }
  231036. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231037. {
  231038. if (isSharedWindow)
  231039. {
  231040. [view setHidden: ! shouldBeVisible];
  231041. }
  231042. else
  231043. {
  231044. if (shouldBeVisible)
  231045. {
  231046. [window orderFront: nil];
  231047. handleBroughtToFront();
  231048. }
  231049. else
  231050. {
  231051. [window orderOut: nil];
  231052. }
  231053. }
  231054. }
  231055. void NSViewComponentPeer::setTitle (const String& title)
  231056. {
  231057. const ScopedAutoReleasePool pool;
  231058. if (! isSharedWindow)
  231059. [window setTitle: juceStringToNS (title)];
  231060. }
  231061. void NSViewComponentPeer::setPosition (int x, int y)
  231062. {
  231063. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231064. }
  231065. void NSViewComponentPeer::setSize (int w, int h)
  231066. {
  231067. setBounds (component->getX(), component->getY(), w, h, false);
  231068. }
  231069. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231070. {
  231071. fullScreen = isNowFullScreen;
  231072. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231073. if (isSharedWindow)
  231074. {
  231075. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231076. if ([view frame].size.width != r.size.width
  231077. || [view frame].size.height != r.size.height)
  231078. [view setNeedsDisplay: true];
  231079. [view setFrame: r];
  231080. }
  231081. else
  231082. {
  231083. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231084. [window setFrame: [window frameRectForContentRect: r]
  231085. display: true];
  231086. }
  231087. }
  231088. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231089. {
  231090. NSRect r = [view frame];
  231091. if (global && [view window] != 0)
  231092. {
  231093. r = [view convertRect: r toView: nil];
  231094. NSRect wr = [[view window] frame];
  231095. r.origin.x += wr.origin.x;
  231096. r.origin.y += wr.origin.y;
  231097. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231098. }
  231099. else
  231100. {
  231101. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231102. }
  231103. return Rectangle<int> (convertToRectInt (r));
  231104. }
  231105. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231106. {
  231107. return getBounds (! isSharedWindow);
  231108. }
  231109. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231110. {
  231111. return getBounds (true).getPosition();
  231112. }
  231113. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231114. {
  231115. return relativePosition + getScreenPosition();
  231116. }
  231117. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231118. {
  231119. return screenPosition - getScreenPosition();
  231120. }
  231121. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231122. {
  231123. if (constrainer != 0)
  231124. {
  231125. NSRect current = [window frame];
  231126. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231127. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231128. Rectangle<int> pos (convertToRectInt (r));
  231129. Rectangle<int> original (convertToRectInt (current));
  231130. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231131. if ([window inLiveResize])
  231132. #else
  231133. if ([window respondsToSelector: @selector (inLiveResize)]
  231134. && [window performSelector: @selector (inLiveResize)])
  231135. #endif
  231136. {
  231137. constrainer->checkBounds (pos, original,
  231138. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231139. false, false, true, true);
  231140. }
  231141. else
  231142. {
  231143. constrainer->checkBounds (pos, original,
  231144. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231145. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231146. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231147. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231148. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231149. }
  231150. r.origin.x = pos.getX();
  231151. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231152. r.size.width = pos.getWidth();
  231153. r.size.height = pos.getHeight();
  231154. }
  231155. return r;
  231156. }
  231157. void NSViewComponentPeer::setAlpha (float newAlpha)
  231158. {
  231159. if (! isSharedWindow)
  231160. [window setAlphaValue: (CGFloat) newAlpha];
  231161. else
  231162. [view setAlphaValue: (CGFloat) newAlpha];
  231163. }
  231164. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231165. {
  231166. if (! isSharedWindow)
  231167. {
  231168. if (shouldBeMinimised)
  231169. [window miniaturize: nil];
  231170. else
  231171. [window deminiaturize: nil];
  231172. }
  231173. }
  231174. bool NSViewComponentPeer::isMinimised() const
  231175. {
  231176. return window != 0 && [window isMiniaturized];
  231177. }
  231178. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231179. {
  231180. if (! isSharedWindow)
  231181. {
  231182. Rectangle<int> r (lastNonFullscreenBounds);
  231183. setMinimised (false);
  231184. if (fullScreen != shouldBeFullScreen)
  231185. {
  231186. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231187. {
  231188. fullScreen = true;
  231189. [window performZoom: nil];
  231190. }
  231191. else
  231192. {
  231193. if (shouldBeFullScreen)
  231194. r = Desktop::getInstance().getMainMonitorArea();
  231195. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231196. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231197. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231198. }
  231199. }
  231200. }
  231201. }
  231202. bool NSViewComponentPeer::isFullScreen() const
  231203. {
  231204. return fullScreen;
  231205. }
  231206. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231207. {
  231208. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231209. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231210. return false;
  231211. NSPoint p;
  231212. p.x = (float) position.getX();
  231213. p.y = (float) position.getY();
  231214. NSView* v = [view hitTest: p];
  231215. if (trueIfInAChildWindow)
  231216. return v != nil;
  231217. return v == view;
  231218. }
  231219. const BorderSize<int> NSViewComponentPeer::getFrameSize() const
  231220. {
  231221. BorderSize<int> b;
  231222. if (! isSharedWindow)
  231223. {
  231224. NSRect v = [view convertRect: [view frame] toView: nil];
  231225. NSRect w = [window frame];
  231226. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231227. b.setBottom ((int) v.origin.y);
  231228. b.setLeft ((int) v.origin.x);
  231229. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231230. }
  231231. return b;
  231232. }
  231233. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231234. {
  231235. if (! isSharedWindow)
  231236. {
  231237. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231238. : NSNormalWindowLevel];
  231239. }
  231240. return true;
  231241. }
  231242. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231243. {
  231244. if (isSharedWindow)
  231245. {
  231246. [[view superview] addSubview: view
  231247. positioned: NSWindowAbove
  231248. relativeTo: nil];
  231249. }
  231250. if (window != 0 && component->isVisible())
  231251. {
  231252. if (makeActiveWindow)
  231253. [window makeKeyAndOrderFront: nil];
  231254. else
  231255. [window orderFront: nil];
  231256. if (! recursiveToFrontCall)
  231257. {
  231258. recursiveToFrontCall = true;
  231259. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231260. handleBroughtToFront();
  231261. recursiveToFrontCall = false;
  231262. }
  231263. }
  231264. }
  231265. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231266. {
  231267. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231268. jassert (otherPeer != 0); // wrong type of window?
  231269. if (otherPeer != 0)
  231270. {
  231271. if (isSharedWindow)
  231272. {
  231273. [[view superview] addSubview: view
  231274. positioned: NSWindowBelow
  231275. relativeTo: otherPeer->view];
  231276. }
  231277. else
  231278. {
  231279. [window orderWindow: NSWindowBelow
  231280. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231281. : nil ];
  231282. }
  231283. }
  231284. }
  231285. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231286. {
  231287. // to do..
  231288. }
  231289. void NSViewComponentPeer::viewFocusGain()
  231290. {
  231291. if (currentlyFocusedPeer != this)
  231292. {
  231293. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231294. currentlyFocusedPeer->handleFocusLoss();
  231295. currentlyFocusedPeer = this;
  231296. handleFocusGain();
  231297. }
  231298. }
  231299. void NSViewComponentPeer::viewFocusLoss()
  231300. {
  231301. if (currentlyFocusedPeer == this)
  231302. {
  231303. currentlyFocusedPeer = 0;
  231304. handleFocusLoss();
  231305. }
  231306. }
  231307. void juce_HandleProcessFocusChange()
  231308. {
  231309. NSViewComponentPeer::keysCurrentlyDown.clear();
  231310. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231311. {
  231312. if (Process::isForegroundProcess())
  231313. {
  231314. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231315. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231316. }
  231317. else
  231318. {
  231319. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231320. // turn kiosk mode off if we lose focus..
  231321. Desktop::getInstance().setKioskModeComponent (0);
  231322. }
  231323. }
  231324. }
  231325. bool NSViewComponentPeer::isFocused() const
  231326. {
  231327. return isSharedWindow ? this == currentlyFocusedPeer
  231328. : (window != 0 && [window isKeyWindow]);
  231329. }
  231330. void NSViewComponentPeer::grabFocus()
  231331. {
  231332. if (window != 0)
  231333. {
  231334. [window makeKeyWindow];
  231335. [window makeFirstResponder: view];
  231336. viewFocusGain();
  231337. }
  231338. }
  231339. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231340. {
  231341. }
  231342. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231343. {
  231344. String unicode (nsStringToJuce ([ev characters]));
  231345. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231346. int keyCode = getKeyCodeFromEvent (ev);
  231347. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231348. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231349. if (unicode.isNotEmpty() || keyCode != 0)
  231350. {
  231351. if (isKeyDown)
  231352. {
  231353. bool used = false;
  231354. while (unicode.length() > 0)
  231355. {
  231356. juce_wchar textCharacter = unicode[0];
  231357. unicode = unicode.substring (1);
  231358. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231359. textCharacter = 0;
  231360. used = handleKeyUpOrDown (true) || used;
  231361. used = handleKeyPress (keyCode, textCharacter) || used;
  231362. }
  231363. return used;
  231364. }
  231365. else
  231366. {
  231367. if (handleKeyUpOrDown (false))
  231368. return true;
  231369. }
  231370. }
  231371. return false;
  231372. }
  231373. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231374. {
  231375. updateKeysDown (ev, true);
  231376. bool used = handleKeyEvent (ev, true);
  231377. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231378. {
  231379. // for command keys, the key-up event is thrown away, so simulate one..
  231380. updateKeysDown (ev, false);
  231381. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231382. }
  231383. // (If we're running modally, don't allow unused keystrokes to be passed
  231384. // along to other blocked views..)
  231385. if (Component::getCurrentlyModalComponent() != 0)
  231386. used = true;
  231387. return used;
  231388. }
  231389. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231390. {
  231391. updateKeysDown (ev, false);
  231392. return handleKeyEvent (ev, false)
  231393. || Component::getCurrentlyModalComponent() != 0;
  231394. }
  231395. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231396. {
  231397. keysCurrentlyDown.clear();
  231398. handleKeyUpOrDown (true);
  231399. updateModifiers (ev);
  231400. handleModifierKeysChange();
  231401. }
  231402. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231403. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231404. {
  231405. if ([ev type] == NSKeyDown)
  231406. return redirectKeyDown (ev);
  231407. else if ([ev type] == NSKeyUp)
  231408. return redirectKeyUp (ev);
  231409. return false;
  231410. }
  231411. #endif
  231412. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231413. {
  231414. updateModifiers (ev);
  231415. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231416. }
  231417. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231418. {
  231419. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231420. sendMouseEvent (ev);
  231421. }
  231422. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231423. {
  231424. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231425. sendMouseEvent (ev);
  231426. showArrowCursorIfNeeded();
  231427. }
  231428. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231429. {
  231430. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231431. sendMouseEvent (ev);
  231432. }
  231433. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231434. {
  231435. currentModifiers = currentModifiers.withoutMouseButtons();
  231436. sendMouseEvent (ev);
  231437. showArrowCursorIfNeeded();
  231438. }
  231439. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231440. {
  231441. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231442. currentModifiers = currentModifiers.withoutMouseButtons();
  231443. sendMouseEvent (ev);
  231444. }
  231445. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231446. {
  231447. currentModifiers = currentModifiers.withoutMouseButtons();
  231448. sendMouseEvent (ev);
  231449. }
  231450. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231451. {
  231452. updateModifiers (ev);
  231453. float x = 0, y = 0;
  231454. @try
  231455. {
  231456. x = [ev deviceDeltaX] * 0.5f;
  231457. y = [ev deviceDeltaY] * 0.5f;
  231458. }
  231459. @catch (...)
  231460. {}
  231461. if (x == 0 && y == 0)
  231462. {
  231463. x = [ev deltaX] * 10.0f;
  231464. y = [ev deltaY] * 10.0f;
  231465. }
  231466. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231467. }
  231468. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231469. {
  231470. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231471. if (mouse.getComponentUnderMouse() == 0
  231472. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231473. {
  231474. [[NSCursor arrowCursor] set];
  231475. }
  231476. }
  231477. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  231478. {
  231479. NSString* bestType
  231480. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  231481. if (bestType == nil)
  231482. return false;
  231483. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  231484. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  231485. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  231486. if (list == nil)
  231487. return false;
  231488. StringArray files;
  231489. if ([list isKindOfClass: [NSArray class]])
  231490. {
  231491. NSArray* items = (NSArray*) list;
  231492. for (unsigned int i = 0; i < [items count]; ++i)
  231493. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  231494. }
  231495. if (files.size() == 0)
  231496. return false;
  231497. if (type == 0)
  231498. handleFileDragMove (files, pos);
  231499. else if (type == 1)
  231500. handleFileDragExit (files);
  231501. else if (type == 2)
  231502. handleFileDragDrop (files, pos);
  231503. return true;
  231504. }
  231505. bool NSViewComponentPeer::isOpaque()
  231506. {
  231507. return component == 0 || component->isOpaque();
  231508. }
  231509. void NSViewComponentPeer::drawRect (NSRect r)
  231510. {
  231511. if (r.size.width < 1.0f || r.size.height < 1.0f)
  231512. return;
  231513. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  231514. if (! component->isOpaque())
  231515. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  231516. #if USE_COREGRAPHICS_RENDERING
  231517. if (usingCoreGraphics)
  231518. {
  231519. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  231520. insideDrawRect = true;
  231521. handlePaint (context);
  231522. insideDrawRect = false;
  231523. }
  231524. else
  231525. #endif
  231526. {
  231527. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  231528. (int) (r.size.width + 0.5f),
  231529. (int) (r.size.height + 0.5f),
  231530. ! getComponent()->isOpaque());
  231531. const int xOffset = -roundToInt (r.origin.x);
  231532. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  231533. const NSRect* rects = 0;
  231534. NSInteger numRects = 0;
  231535. [view getRectsBeingDrawn: &rects count: &numRects];
  231536. const Rectangle<int> clipBounds (temp.getBounds());
  231537. RectangleList clip;
  231538. for (int i = 0; i < numRects; ++i)
  231539. {
  231540. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  231541. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  231542. roundToInt (rects[i].size.width),
  231543. roundToInt (rects[i].size.height))));
  231544. }
  231545. if (! clip.isEmpty())
  231546. {
  231547. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  231548. insideDrawRect = true;
  231549. handlePaint (context);
  231550. insideDrawRect = false;
  231551. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  231552. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace, false);
  231553. CGColorSpaceRelease (colourSpace);
  231554. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  231555. CGImageRelease (image);
  231556. }
  231557. }
  231558. }
  231559. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  231560. {
  231561. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  231562. #if USE_COREGRAPHICS_RENDERING
  231563. s.add ("CoreGraphics Renderer");
  231564. #endif
  231565. return s;
  231566. }
  231567. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  231568. {
  231569. return usingCoreGraphics ? 1 : 0;
  231570. }
  231571. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  231572. {
  231573. #if USE_COREGRAPHICS_RENDERING
  231574. if (usingCoreGraphics != (index > 0))
  231575. {
  231576. usingCoreGraphics = index > 0;
  231577. [view setNeedsDisplay: true];
  231578. }
  231579. #endif
  231580. }
  231581. bool NSViewComponentPeer::canBecomeKeyWindow()
  231582. {
  231583. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  231584. }
  231585. bool NSViewComponentPeer::windowShouldClose()
  231586. {
  231587. if (! isValidPeer (this))
  231588. return YES;
  231589. handleUserClosingWindow();
  231590. return NO;
  231591. }
  231592. void NSViewComponentPeer::redirectMovedOrResized()
  231593. {
  231594. handleMovedOrResized();
  231595. }
  231596. void NSViewComponentPeer::viewMovedToWindow()
  231597. {
  231598. if (isSharedWindow)
  231599. window = [view window];
  231600. }
  231601. void Desktop::createMouseInputSources()
  231602. {
  231603. mouseSources.add (new MouseInputSource (0, true));
  231604. }
  231605. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  231606. {
  231607. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  231608. if (enableOrDisable)
  231609. {
  231610. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  231611. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  231612. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231613. }
  231614. else
  231615. {
  231616. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  231617. }
  231618. #else
  231619. if (enableOrDisable)
  231620. {
  231621. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  231622. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231623. }
  231624. else
  231625. {
  231626. SetSystemUIMode (kUIModeNormal, 0);
  231627. }
  231628. #endif
  231629. }
  231630. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  231631. {
  231632. if (insideDrawRect)
  231633. {
  231634. class AsyncRepaintMessage : public CallbackMessage
  231635. {
  231636. public:
  231637. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  231638. : peer (peer_), rect (rect_)
  231639. {
  231640. }
  231641. void messageCallback()
  231642. {
  231643. if (ComponentPeer::isValidPeer (peer))
  231644. peer->repaint (rect);
  231645. }
  231646. private:
  231647. NSViewComponentPeer* const peer;
  231648. const Rectangle<int> rect;
  231649. };
  231650. (new AsyncRepaintMessage (this, area))->post();
  231651. }
  231652. else
  231653. {
  231654. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  231655. (float) area.getWidth(), (float) area.getHeight())];
  231656. }
  231657. }
  231658. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  231659. {
  231660. [view displayIfNeeded];
  231661. }
  231662. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  231663. {
  231664. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  231665. }
  231666. const Image juce_createIconForFile (const File& file)
  231667. {
  231668. const ScopedAutoReleasePool pool;
  231669. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  231670. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  231671. [NSGraphicsContext saveGraphicsState];
  231672. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  231673. [image drawAtPoint: NSMakePoint (0, 0)
  231674. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  231675. operation: NSCompositeSourceOver fraction: 1.0f];
  231676. [[NSGraphicsContext currentContext] flushGraphics];
  231677. [NSGraphicsContext restoreGraphicsState];
  231678. return Image (result);
  231679. }
  231680. const int KeyPress::spaceKey = ' ';
  231681. const int KeyPress::returnKey = 0x0d;
  231682. const int KeyPress::escapeKey = 0x1b;
  231683. const int KeyPress::backspaceKey = 0x7f;
  231684. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  231685. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  231686. const int KeyPress::upKey = NSUpArrowFunctionKey;
  231687. const int KeyPress::downKey = NSDownArrowFunctionKey;
  231688. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  231689. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  231690. const int KeyPress::endKey = NSEndFunctionKey;
  231691. const int KeyPress::homeKey = NSHomeFunctionKey;
  231692. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  231693. const int KeyPress::insertKey = -1;
  231694. const int KeyPress::tabKey = 9;
  231695. const int KeyPress::F1Key = NSF1FunctionKey;
  231696. const int KeyPress::F2Key = NSF2FunctionKey;
  231697. const int KeyPress::F3Key = NSF3FunctionKey;
  231698. const int KeyPress::F4Key = NSF4FunctionKey;
  231699. const int KeyPress::F5Key = NSF5FunctionKey;
  231700. const int KeyPress::F6Key = NSF6FunctionKey;
  231701. const int KeyPress::F7Key = NSF7FunctionKey;
  231702. const int KeyPress::F8Key = NSF8FunctionKey;
  231703. const int KeyPress::F9Key = NSF9FunctionKey;
  231704. const int KeyPress::F10Key = NSF10FunctionKey;
  231705. const int KeyPress::F11Key = NSF1FunctionKey;
  231706. const int KeyPress::F12Key = NSF12FunctionKey;
  231707. const int KeyPress::F13Key = NSF13FunctionKey;
  231708. const int KeyPress::F14Key = NSF14FunctionKey;
  231709. const int KeyPress::F15Key = NSF15FunctionKey;
  231710. const int KeyPress::F16Key = NSF16FunctionKey;
  231711. const int KeyPress::numberPad0 = 0x30020;
  231712. const int KeyPress::numberPad1 = 0x30021;
  231713. const int KeyPress::numberPad2 = 0x30022;
  231714. const int KeyPress::numberPad3 = 0x30023;
  231715. const int KeyPress::numberPad4 = 0x30024;
  231716. const int KeyPress::numberPad5 = 0x30025;
  231717. const int KeyPress::numberPad6 = 0x30026;
  231718. const int KeyPress::numberPad7 = 0x30027;
  231719. const int KeyPress::numberPad8 = 0x30028;
  231720. const int KeyPress::numberPad9 = 0x30029;
  231721. const int KeyPress::numberPadAdd = 0x3002a;
  231722. const int KeyPress::numberPadSubtract = 0x3002b;
  231723. const int KeyPress::numberPadMultiply = 0x3002c;
  231724. const int KeyPress::numberPadDivide = 0x3002d;
  231725. const int KeyPress::numberPadSeparator = 0x3002e;
  231726. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  231727. const int KeyPress::numberPadEquals = 0x30030;
  231728. const int KeyPress::numberPadDelete = 0x30031;
  231729. const int KeyPress::playKey = 0x30000;
  231730. const int KeyPress::stopKey = 0x30001;
  231731. const int KeyPress::fastForwardKey = 0x30002;
  231732. const int KeyPress::rewindKey = 0x30003;
  231733. #endif
  231734. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231735. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  231736. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231737. // compiled on its own).
  231738. #if JUCE_INCLUDED_FILE
  231739. #if JUCE_MAC
  231740. namespace MouseCursorHelpers
  231741. {
  231742. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  231743. {
  231744. NSImage* im = CoreGraphicsImage::createNSImage (image);
  231745. NSCursor* c = [[NSCursor alloc] initWithImage: im
  231746. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  231747. [im release];
  231748. return c;
  231749. }
  231750. static void* fromWebKitFile (const char* filename, float hx, float hy)
  231751. {
  231752. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  231753. BufferedInputStream buf (fileStream, 4096);
  231754. PNGImageFormat pngFormat;
  231755. Image im (pngFormat.decodeImage (buf));
  231756. if (im.isValid())
  231757. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  231758. jassertfalse;
  231759. return 0;
  231760. }
  231761. }
  231762. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  231763. {
  231764. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  231765. }
  231766. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  231767. {
  231768. const ScopedAutoReleasePool pool;
  231769. NSCursor* c = 0;
  231770. switch (type)
  231771. {
  231772. case NormalCursor: c = [NSCursor arrowCursor]; break;
  231773. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  231774. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  231775. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  231776. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  231777. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  231778. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  231779. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  231780. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  231781. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  231782. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  231783. case UpDownResizeCursor:
  231784. case TopEdgeResizeCursor:
  231785. case BottomEdgeResizeCursor:
  231786. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  231787. case TopLeftCornerResizeCursor:
  231788. case BottomRightCornerResizeCursor:
  231789. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  231790. case TopRightCornerResizeCursor:
  231791. case BottomLeftCornerResizeCursor:
  231792. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  231793. case UpDownLeftRightResizeCursor:
  231794. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  231795. default:
  231796. jassertfalse;
  231797. break;
  231798. }
  231799. [c retain];
  231800. return c;
  231801. }
  231802. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  231803. {
  231804. [((NSCursor*) cursorHandle) release];
  231805. }
  231806. void MouseCursor::showInAllWindows() const
  231807. {
  231808. showInWindow (0);
  231809. }
  231810. void MouseCursor::showInWindow (ComponentPeer*) const
  231811. {
  231812. NSCursor* c = (NSCursor*) getHandle();
  231813. if (c == 0)
  231814. c = [NSCursor arrowCursor];
  231815. [c set];
  231816. }
  231817. #else
  231818. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  231819. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  231820. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  231821. void MouseCursor::showInAllWindows() const {}
  231822. void MouseCursor::showInWindow (ComponentPeer*) const {}
  231823. #endif
  231824. #endif
  231825. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  231826. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  231827. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231828. // compiled on its own).
  231829. #if JUCE_INCLUDED_FILE
  231830. class NSViewComponentInternal : public ComponentMovementWatcher
  231831. {
  231832. public:
  231833. NSViewComponentInternal (NSView* const view_, Component& owner_)
  231834. : ComponentMovementWatcher (&owner_),
  231835. owner (owner_),
  231836. currentPeer (0),
  231837. view (view_)
  231838. {
  231839. [view_ retain];
  231840. if (owner.isShowing())
  231841. componentPeerChanged();
  231842. }
  231843. ~NSViewComponentInternal()
  231844. {
  231845. [view removeFromSuperview];
  231846. [view release];
  231847. }
  231848. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  231849. {
  231850. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  231851. // The ComponentMovementWatcher version of this method avoids calling
  231852. // us when the top-level comp is resized, but for an NSView we need to know this
  231853. // because with inverted co-ords, we need to update the position even if the
  231854. // top-left pos hasn't changed
  231855. if (comp.isOnDesktop() && wasResized)
  231856. componentMovedOrResized (wasMoved, wasResized);
  231857. }
  231858. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  231859. {
  231860. Component* const topComp = owner.getTopLevelComponent();
  231861. if (topComp->getPeer() != 0)
  231862. {
  231863. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  231864. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner.getWidth(), (float) owner.getHeight());
  231865. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231866. [view setFrame: r];
  231867. }
  231868. }
  231869. void componentPeerChanged()
  231870. {
  231871. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner.getPeer());
  231872. if (currentPeer != peer)
  231873. {
  231874. if ([view superview] != nil)
  231875. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  231876. // override the call and use it as a sign that they're being deleted, which breaks everything..
  231877. currentPeer = peer;
  231878. if (peer != 0)
  231879. {
  231880. [peer->view addSubview: view];
  231881. componentMovedOrResized (false, false);
  231882. }
  231883. }
  231884. [view setHidden: ! owner.isShowing()];
  231885. }
  231886. void componentVisibilityChanged()
  231887. {
  231888. componentPeerChanged();
  231889. }
  231890. const Rectangle<int> getViewBounds() const
  231891. {
  231892. NSRect r = [view frame];
  231893. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  231894. }
  231895. private:
  231896. Component& owner;
  231897. NSViewComponentPeer* currentPeer;
  231898. public:
  231899. NSView* const view;
  231900. private:
  231901. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  231902. };
  231903. NSViewComponent::NSViewComponent()
  231904. {
  231905. }
  231906. NSViewComponent::~NSViewComponent()
  231907. {
  231908. }
  231909. void NSViewComponent::setView (void* view)
  231910. {
  231911. if (view != getView())
  231912. {
  231913. if (view != 0)
  231914. info = new NSViewComponentInternal ((NSView*) view, *this);
  231915. else
  231916. info = 0;
  231917. }
  231918. }
  231919. void* NSViewComponent::getView() const
  231920. {
  231921. return info == 0 ? 0 : info->view;
  231922. }
  231923. void NSViewComponent::resizeToFitView()
  231924. {
  231925. if (info != 0)
  231926. setBounds (info->getViewBounds());
  231927. }
  231928. void NSViewComponent::paint (Graphics&)
  231929. {
  231930. }
  231931. #endif
  231932. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  231933. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  231934. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231935. // compiled on its own).
  231936. #if JUCE_INCLUDED_FILE
  231937. AppleRemoteDevice::AppleRemoteDevice()
  231938. : device (0),
  231939. queue (0),
  231940. remoteId (0)
  231941. {
  231942. }
  231943. AppleRemoteDevice::~AppleRemoteDevice()
  231944. {
  231945. stop();
  231946. }
  231947. namespace
  231948. {
  231949. io_object_t getAppleRemoteDevice()
  231950. {
  231951. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  231952. io_iterator_t iter = 0;
  231953. io_object_t iod = 0;
  231954. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  231955. && iter != 0)
  231956. {
  231957. iod = IOIteratorNext (iter);
  231958. }
  231959. IOObjectRelease (iter);
  231960. return iod;
  231961. }
  231962. bool createAppleRemoteInterface (io_object_t iod, void** device)
  231963. {
  231964. jassert (*device == 0);
  231965. io_name_t classname;
  231966. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  231967. {
  231968. IOCFPlugInInterface** cfPlugInInterface = 0;
  231969. SInt32 score = 0;
  231970. if (IOCreatePlugInInterfaceForService (iod,
  231971. kIOHIDDeviceUserClientTypeID,
  231972. kIOCFPlugInInterfaceID,
  231973. &cfPlugInInterface,
  231974. &score) == kIOReturnSuccess)
  231975. {
  231976. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  231977. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  231978. device);
  231979. (void) hr;
  231980. (*cfPlugInInterface)->Release (cfPlugInInterface);
  231981. }
  231982. }
  231983. return *device != 0;
  231984. }
  231985. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  231986. {
  231987. if (result == kIOReturnSuccess)
  231988. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  231989. }
  231990. }
  231991. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  231992. {
  231993. if (queue != 0)
  231994. return true;
  231995. stop();
  231996. bool result = false;
  231997. io_object_t iod = getAppleRemoteDevice();
  231998. if (iod != 0)
  231999. {
  232000. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232001. result = true;
  232002. else
  232003. stop();
  232004. IOObjectRelease (iod);
  232005. }
  232006. return result;
  232007. }
  232008. void AppleRemoteDevice::stop()
  232009. {
  232010. if (queue != 0)
  232011. {
  232012. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232013. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232014. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232015. queue = 0;
  232016. }
  232017. if (device != 0)
  232018. {
  232019. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232020. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232021. device = 0;
  232022. }
  232023. }
  232024. bool AppleRemoteDevice::isActive() const
  232025. {
  232026. return queue != 0;
  232027. }
  232028. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232029. {
  232030. Array <int> cookies;
  232031. CFArrayRef elements;
  232032. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232033. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232034. return false;
  232035. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232036. {
  232037. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232038. // get the cookie
  232039. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232040. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232041. continue;
  232042. long number;
  232043. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232044. continue;
  232045. cookies.add ((int) number);
  232046. }
  232047. CFRelease (elements);
  232048. if ((*(IOHIDDeviceInterface**) device)
  232049. ->open ((IOHIDDeviceInterface**) device,
  232050. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232051. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232052. {
  232053. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232054. if (queue != 0)
  232055. {
  232056. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232057. for (int i = 0; i < cookies.size(); ++i)
  232058. {
  232059. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232060. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232061. }
  232062. CFRunLoopSourceRef eventSource;
  232063. if ((*(IOHIDQueueInterface**) queue)
  232064. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232065. {
  232066. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232067. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232068. {
  232069. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232070. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232071. return true;
  232072. }
  232073. }
  232074. }
  232075. }
  232076. return false;
  232077. }
  232078. void AppleRemoteDevice::handleCallbackInternal()
  232079. {
  232080. int totalValues = 0;
  232081. AbsoluteTime nullTime = { 0, 0 };
  232082. char cookies [12];
  232083. int numCookies = 0;
  232084. while (numCookies < numElementsInArray (cookies))
  232085. {
  232086. IOHIDEventStruct e;
  232087. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232088. break;
  232089. if ((int) e.elementCookie == 19)
  232090. {
  232091. remoteId = e.value;
  232092. buttonPressed (switched, false);
  232093. }
  232094. else
  232095. {
  232096. totalValues += e.value;
  232097. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232098. }
  232099. }
  232100. cookies [numCookies++] = 0;
  232101. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232102. static const char buttonPatterns[] =
  232103. {
  232104. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232105. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232106. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232107. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232108. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232109. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232110. 0x1f, 0x12, 0x04, 0x02, 0,
  232111. 0x1f, 0x12, 0x03, 0x02, 0,
  232112. 0x1f, 0x12, 0x1f, 0x12, 0,
  232113. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232114. 19, 0
  232115. };
  232116. int buttonNum = (int) menuButton;
  232117. int i = 0;
  232118. while (i < numElementsInArray (buttonPatterns))
  232119. {
  232120. if (strcmp (cookies, buttonPatterns + i) == 0)
  232121. {
  232122. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232123. break;
  232124. }
  232125. i += (int) strlen (buttonPatterns + i) + 1;
  232126. ++buttonNum;
  232127. }
  232128. }
  232129. #endif
  232130. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232131. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232132. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232133. // compiled on its own).
  232134. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232135. #if JUCE_MAC
  232136. END_JUCE_NAMESPACE
  232137. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232138. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232139. {
  232140. CriticalSection* contextLock;
  232141. bool needsUpdate;
  232142. }
  232143. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232144. - (bool) makeActive;
  232145. - (void) makeInactive;
  232146. - (void) reshape;
  232147. @end
  232148. @implementation ThreadSafeNSOpenGLView
  232149. - (id) initWithFrame: (NSRect) frameRect
  232150. pixelFormat: (NSOpenGLPixelFormat*) format
  232151. {
  232152. contextLock = new CriticalSection();
  232153. self = [super initWithFrame: frameRect pixelFormat: format];
  232154. if (self != nil)
  232155. [[NSNotificationCenter defaultCenter] addObserver: self
  232156. selector: @selector (_surfaceNeedsUpdate:)
  232157. name: NSViewGlobalFrameDidChangeNotification
  232158. object: self];
  232159. return self;
  232160. }
  232161. - (void) dealloc
  232162. {
  232163. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232164. delete contextLock;
  232165. [super dealloc];
  232166. }
  232167. - (bool) makeActive
  232168. {
  232169. const ScopedLock sl (*contextLock);
  232170. if ([self openGLContext] == 0)
  232171. return false;
  232172. [[self openGLContext] makeCurrentContext];
  232173. if (needsUpdate)
  232174. {
  232175. [super update];
  232176. needsUpdate = false;
  232177. }
  232178. return true;
  232179. }
  232180. - (void) makeInactive
  232181. {
  232182. const ScopedLock sl (*contextLock);
  232183. [NSOpenGLContext clearCurrentContext];
  232184. }
  232185. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232186. {
  232187. (void) notification;
  232188. const ScopedLock sl (*contextLock);
  232189. needsUpdate = true;
  232190. }
  232191. - (void) update
  232192. {
  232193. const ScopedLock sl (*contextLock);
  232194. needsUpdate = true;
  232195. }
  232196. - (void) reshape
  232197. {
  232198. const ScopedLock sl (*contextLock);
  232199. needsUpdate = true;
  232200. }
  232201. @end
  232202. BEGIN_JUCE_NAMESPACE
  232203. class WindowedGLContext : public OpenGLContext
  232204. {
  232205. public:
  232206. WindowedGLContext (Component& component,
  232207. const OpenGLPixelFormat& pixelFormat_,
  232208. NSOpenGLContext* sharedContext)
  232209. : renderContext (0),
  232210. pixelFormat (pixelFormat_)
  232211. {
  232212. NSOpenGLPixelFormatAttribute attribs [64];
  232213. int n = 0;
  232214. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232215. attribs[n++] = NSOpenGLPFAAccelerated;
  232216. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232217. attribs[n++] = NSOpenGLPFAColorSize;
  232218. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232219. pixelFormat.greenBits,
  232220. pixelFormat.blueBits);
  232221. attribs[n++] = NSOpenGLPFAAlphaSize;
  232222. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232223. attribs[n++] = NSOpenGLPFADepthSize;
  232224. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232225. attribs[n++] = NSOpenGLPFAStencilSize;
  232226. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232227. attribs[n++] = NSOpenGLPFAAccumSize;
  232228. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232229. pixelFormat.accumulationBufferGreenBits,
  232230. pixelFormat.accumulationBufferBlueBits,
  232231. pixelFormat.accumulationBufferAlphaBits);
  232232. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232233. attribs[n++] = NSOpenGLPFASampleBuffers;
  232234. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232235. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232236. attribs[n++] = NSOpenGLPFANoRecovery;
  232237. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232238. NSOpenGLPixelFormat* format
  232239. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232240. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232241. pixelFormat: format];
  232242. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232243. shareContext: sharedContext] autorelease];
  232244. const GLint swapInterval = 1;
  232245. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232246. [view setOpenGLContext: renderContext];
  232247. [format release];
  232248. viewHolder = new NSViewComponentInternal (view, component);
  232249. }
  232250. ~WindowedGLContext()
  232251. {
  232252. deleteContext();
  232253. viewHolder = 0;
  232254. }
  232255. void deleteContext()
  232256. {
  232257. makeInactive();
  232258. [renderContext clearDrawable];
  232259. [renderContext setView: nil];
  232260. [view setOpenGLContext: nil];
  232261. renderContext = nil;
  232262. }
  232263. bool makeActive() const throw()
  232264. {
  232265. jassert (renderContext != 0);
  232266. if ([renderContext view] != view)
  232267. [renderContext setView: view];
  232268. [view makeActive];
  232269. return isActive();
  232270. }
  232271. bool makeInactive() const throw()
  232272. {
  232273. [view makeInactive];
  232274. return true;
  232275. }
  232276. bool isActive() const throw()
  232277. {
  232278. return [NSOpenGLContext currentContext] == renderContext;
  232279. }
  232280. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232281. void* getRawContext() const throw() { return renderContext; }
  232282. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  232283. {
  232284. }
  232285. void swapBuffers()
  232286. {
  232287. [renderContext flushBuffer];
  232288. }
  232289. bool setSwapInterval (const int numFramesPerSwap)
  232290. {
  232291. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232292. forParameter: NSOpenGLCPSwapInterval];
  232293. return true;
  232294. }
  232295. int getSwapInterval() const
  232296. {
  232297. GLint numFrames = 0;
  232298. [renderContext getValues: &numFrames
  232299. forParameter: NSOpenGLCPSwapInterval];
  232300. return numFrames;
  232301. }
  232302. void repaint()
  232303. {
  232304. // we need to invalidate the juce view that holds this gl view, to make it
  232305. // cause a repaint callback
  232306. NSView* v = (NSView*) viewHolder->view;
  232307. NSRect r = [v frame];
  232308. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232309. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232310. // repaint message, thus never causing our paint() callback, and never repainting
  232311. // the comp. So invalidating just a little bit around the edge helps..
  232312. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232313. }
  232314. void* getNativeWindowHandle() const { return viewHolder->view; }
  232315. NSOpenGLContext* renderContext;
  232316. ThreadSafeNSOpenGLView* view;
  232317. private:
  232318. OpenGLPixelFormat pixelFormat;
  232319. ScopedPointer <NSViewComponentInternal> viewHolder;
  232320. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232321. };
  232322. OpenGLContext* OpenGLComponent::createContext()
  232323. {
  232324. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  232325. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232326. return (c->renderContext != 0) ? c.release() : 0;
  232327. }
  232328. void* OpenGLComponent::getNativeWindowHandle() const
  232329. {
  232330. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232331. : 0;
  232332. }
  232333. void juce_glViewport (const int w, const int h)
  232334. {
  232335. glViewport (0, 0, w, h);
  232336. }
  232337. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232338. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232339. {
  232340. /* GLint attribs [64];
  232341. int n = 0;
  232342. attribs[n++] = AGL_RGBA;
  232343. attribs[n++] = AGL_DOUBLEBUFFER;
  232344. attribs[n++] = AGL_ACCELERATED;
  232345. attribs[n++] = AGL_NO_RECOVERY;
  232346. attribs[n++] = AGL_NONE;
  232347. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232348. while (p != 0)
  232349. {
  232350. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232351. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232352. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232353. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232354. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232355. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232356. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232357. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232358. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232359. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232360. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232361. results.add (pf);
  232362. p = aglNextPixelFormat (p);
  232363. }*/
  232364. //jassertfalse // can't see how you do this in cocoa!
  232365. }
  232366. #else
  232367. END_JUCE_NAMESPACE
  232368. @interface JuceGLView : UIView
  232369. {
  232370. }
  232371. + (Class) layerClass;
  232372. @end
  232373. @implementation JuceGLView
  232374. + (Class) layerClass
  232375. {
  232376. return [CAEAGLLayer class];
  232377. }
  232378. @end
  232379. BEGIN_JUCE_NAMESPACE
  232380. class GLESContext : public OpenGLContext
  232381. {
  232382. public:
  232383. GLESContext (UIViewComponentPeer* peer,
  232384. Component* const component_,
  232385. const OpenGLPixelFormat& pixelFormat_,
  232386. const GLESContext* const sharedContext,
  232387. NSUInteger apiType)
  232388. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232389. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232390. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232391. {
  232392. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232393. view.opaque = YES;
  232394. view.hidden = NO;
  232395. view.backgroundColor = [UIColor blackColor];
  232396. view.userInteractionEnabled = NO;
  232397. glLayer = (CAEAGLLayer*) [view layer];
  232398. [peer->view addSubview: view];
  232399. if (sharedContext != 0)
  232400. context = [[EAGLContext alloc] initWithAPI: apiType
  232401. sharegroup: [sharedContext->context sharegroup]];
  232402. else
  232403. context = [[EAGLContext alloc] initWithAPI: apiType];
  232404. createGLBuffers();
  232405. }
  232406. ~GLESContext()
  232407. {
  232408. deleteContext();
  232409. [view removeFromSuperview];
  232410. [view release];
  232411. freeGLBuffers();
  232412. }
  232413. void deleteContext()
  232414. {
  232415. makeInactive();
  232416. [context release];
  232417. context = nil;
  232418. }
  232419. bool makeActive() const throw()
  232420. {
  232421. jassert (context != 0);
  232422. [EAGLContext setCurrentContext: context];
  232423. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232424. return true;
  232425. }
  232426. void swapBuffers()
  232427. {
  232428. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232429. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232430. }
  232431. bool makeInactive() const throw()
  232432. {
  232433. return [EAGLContext setCurrentContext: nil];
  232434. }
  232435. bool isActive() const throw()
  232436. {
  232437. return [EAGLContext currentContext] == context;
  232438. }
  232439. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232440. void* getRawContext() const throw() { return glLayer; }
  232441. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232442. {
  232443. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232444. if (lastWidth != w || lastHeight != h)
  232445. {
  232446. lastWidth = w;
  232447. lastHeight = h;
  232448. freeGLBuffers();
  232449. createGLBuffers();
  232450. }
  232451. }
  232452. bool setSwapInterval (const int numFramesPerSwap)
  232453. {
  232454. numFrames = numFramesPerSwap;
  232455. return true;
  232456. }
  232457. int getSwapInterval() const
  232458. {
  232459. return numFrames;
  232460. }
  232461. void repaint()
  232462. {
  232463. }
  232464. void createGLBuffers()
  232465. {
  232466. makeActive();
  232467. glGenFramebuffersOES (1, &frameBufferHandle);
  232468. glGenRenderbuffersOES (1, &colorBufferHandle);
  232469. glGenRenderbuffersOES (1, &depthBufferHandle);
  232470. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232471. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  232472. GLint width, height;
  232473. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  232474. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  232475. if (useDepthBuffer)
  232476. {
  232477. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  232478. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  232479. }
  232480. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232481. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232482. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  232483. if (useDepthBuffer)
  232484. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  232485. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  232486. }
  232487. void freeGLBuffers()
  232488. {
  232489. if (frameBufferHandle != 0)
  232490. {
  232491. glDeleteFramebuffersOES (1, &frameBufferHandle);
  232492. frameBufferHandle = 0;
  232493. }
  232494. if (colorBufferHandle != 0)
  232495. {
  232496. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  232497. colorBufferHandle = 0;
  232498. }
  232499. if (depthBufferHandle != 0)
  232500. {
  232501. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  232502. depthBufferHandle = 0;
  232503. }
  232504. }
  232505. private:
  232506. WeakReference<Component> component;
  232507. OpenGLPixelFormat pixelFormat;
  232508. JuceGLView* view;
  232509. CAEAGLLayer* glLayer;
  232510. EAGLContext* context;
  232511. bool useDepthBuffer;
  232512. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  232513. int numFrames;
  232514. int lastWidth, lastHeight;
  232515. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  232516. };
  232517. OpenGLContext* OpenGLComponent::createContext()
  232518. {
  232519. ScopedAutoReleasePool pool;
  232520. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  232521. if (peer != 0)
  232522. return new GLESContext (peer, this, preferredPixelFormat,
  232523. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  232524. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  232525. return 0;
  232526. }
  232527. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232528. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232529. {
  232530. }
  232531. void juce_glViewport (const int w, const int h)
  232532. {
  232533. glViewport (0, 0, w, h);
  232534. }
  232535. #endif
  232536. #endif
  232537. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  232538. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  232539. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232540. // compiled on its own).
  232541. #if JUCE_INCLUDED_FILE
  232542. class JuceMainMenuHandler;
  232543. END_JUCE_NAMESPACE
  232544. using namespace JUCE_NAMESPACE;
  232545. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  232546. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232547. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  232548. #else
  232549. @interface JuceMenuCallback : NSObject
  232550. #endif
  232551. {
  232552. JuceMainMenuHandler* owner;
  232553. }
  232554. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  232555. - (void) dealloc;
  232556. - (void) menuItemInvoked: (id) menu;
  232557. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232558. @end
  232559. BEGIN_JUCE_NAMESPACE
  232560. class JuceMainMenuHandler : private MenuBarModel::Listener,
  232561. private DeletedAtShutdown
  232562. {
  232563. public:
  232564. JuceMainMenuHandler()
  232565. : currentModel (0),
  232566. lastUpdateTime (0)
  232567. {
  232568. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  232569. }
  232570. ~JuceMainMenuHandler()
  232571. {
  232572. setMenu (0);
  232573. jassert (instance == this);
  232574. instance = 0;
  232575. [callback release];
  232576. }
  232577. void setMenu (MenuBarModel* const newMenuBarModel)
  232578. {
  232579. if (currentModel != newMenuBarModel)
  232580. {
  232581. if (currentModel != 0)
  232582. currentModel->removeListener (this);
  232583. currentModel = newMenuBarModel;
  232584. if (currentModel != 0)
  232585. currentModel->addListener (this);
  232586. menuBarItemsChanged (0);
  232587. }
  232588. }
  232589. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  232590. const String& name, const int menuId, const int tag)
  232591. {
  232592. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  232593. action: nil
  232594. keyEquivalent: @""];
  232595. [item setTag: tag];
  232596. NSMenu* sub = createMenu (child, name, menuId, tag);
  232597. [parent setSubmenu: sub forItem: item];
  232598. [sub setAutoenablesItems: false];
  232599. [sub release];
  232600. }
  232601. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  232602. const String& name, const int menuId, const int tag)
  232603. {
  232604. [parentItem setTag: tag];
  232605. NSMenu* menu = [parentItem submenu];
  232606. [menu setTitle: juceStringToNS (name)];
  232607. while ([menu numberOfItems] > 0)
  232608. [menu removeItemAtIndex: 0];
  232609. PopupMenu::MenuItemIterator iter (menuToCopy);
  232610. while (iter.next())
  232611. addMenuItem (iter, menu, menuId, tag);
  232612. [menu setAutoenablesItems: false];
  232613. [menu update];
  232614. }
  232615. void menuBarItemsChanged (MenuBarModel*)
  232616. {
  232617. lastUpdateTime = Time::getMillisecondCounter();
  232618. StringArray menuNames;
  232619. if (currentModel != 0)
  232620. menuNames = currentModel->getMenuBarNames();
  232621. NSMenu* menuBar = [NSApp mainMenu];
  232622. while ([menuBar numberOfItems] > 1 + menuNames.size())
  232623. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  232624. int menuId = 1;
  232625. for (int i = 0; i < menuNames.size(); ++i)
  232626. {
  232627. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  232628. if (i >= [menuBar numberOfItems] - 1)
  232629. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  232630. else
  232631. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  232632. }
  232633. }
  232634. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  232635. {
  232636. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  232637. if (item != 0)
  232638. flashMenuBar ([item menu]);
  232639. }
  232640. void updateMenus (NSMenu* menu)
  232641. {
  232642. if (PopupMenu::dismissAllActiveMenus())
  232643. {
  232644. // If we were running a juce menu, then we should let that modal loop finish before allowing
  232645. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  232646. if ([menu respondsToSelector: @selector (cancelTracking)])
  232647. [menu performSelector: @selector (cancelTracking)];
  232648. }
  232649. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  232650. menuBarItemsChanged (0);
  232651. }
  232652. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  232653. {
  232654. if (currentModel != 0)
  232655. {
  232656. if (commandManager != 0)
  232657. {
  232658. ApplicationCommandTarget::InvocationInfo info (commandId);
  232659. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  232660. commandManager->invoke (info, true);
  232661. }
  232662. currentModel->menuItemSelected (commandId, topLevelIndex);
  232663. }
  232664. }
  232665. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  232666. const int topLevelMenuId, const int topLevelIndex)
  232667. {
  232668. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  232669. if (text == 0)
  232670. text = @"";
  232671. if (iter.isSeparator)
  232672. {
  232673. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  232674. }
  232675. else if (iter.isSectionHeader)
  232676. {
  232677. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232678. action: nil
  232679. keyEquivalent: @""];
  232680. [item setEnabled: false];
  232681. }
  232682. else if (iter.subMenu != 0)
  232683. {
  232684. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232685. action: nil
  232686. keyEquivalent: @""];
  232687. [item setTag: iter.itemId];
  232688. [item setEnabled: iter.isEnabled];
  232689. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  232690. [sub setDelegate: nil];
  232691. [menuToAddTo setSubmenu: sub forItem: item];
  232692. [sub release];
  232693. }
  232694. else
  232695. {
  232696. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232697. action: @selector (menuItemInvoked:)
  232698. keyEquivalent: @""];
  232699. [item setTag: iter.itemId];
  232700. [item setEnabled: iter.isEnabled];
  232701. [item setState: iter.isTicked ? NSOnState : NSOffState];
  232702. [item setTarget: (id) callback];
  232703. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  232704. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  232705. [item setRepresentedObject: info];
  232706. if (iter.commandManager != 0)
  232707. {
  232708. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  232709. ->getKeyPressesAssignedToCommand (iter.itemId));
  232710. if (keyPresses.size() > 0)
  232711. {
  232712. const KeyPress& kp = keyPresses.getReference(0);
  232713. if (kp.getKeyCode() != KeyPress::backspaceKey
  232714. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  232715. // every time you press the key while editing text)
  232716. {
  232717. juce_wchar key = kp.getTextCharacter();
  232718. if (kp.getKeyCode() == KeyPress::backspaceKey)
  232719. key = NSBackspaceCharacter;
  232720. else if (kp.getKeyCode() == KeyPress::deleteKey)
  232721. key = NSDeleteCharacter;
  232722. else if (key == 0)
  232723. key = (juce_wchar) kp.getKeyCode();
  232724. unsigned int mods = 0;
  232725. if (kp.getModifiers().isShiftDown())
  232726. mods |= NSShiftKeyMask;
  232727. if (kp.getModifiers().isCtrlDown())
  232728. mods |= NSControlKeyMask;
  232729. if (kp.getModifiers().isAltDown())
  232730. mods |= NSAlternateKeyMask;
  232731. if (kp.getModifiers().isCommandDown())
  232732. mods |= NSCommandKeyMask;
  232733. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  232734. [item setKeyEquivalentModifierMask: mods];
  232735. }
  232736. }
  232737. }
  232738. }
  232739. }
  232740. static JuceMainMenuHandler* instance;
  232741. MenuBarModel* currentModel;
  232742. uint32 lastUpdateTime;
  232743. JuceMenuCallback* callback;
  232744. private:
  232745. NSMenu* createMenu (const PopupMenu menu,
  232746. const String& menuName,
  232747. const int topLevelMenuId,
  232748. const int topLevelIndex)
  232749. {
  232750. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  232751. [m setAutoenablesItems: false];
  232752. [m setDelegate: callback];
  232753. PopupMenu::MenuItemIterator iter (menu);
  232754. while (iter.next())
  232755. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  232756. [m update];
  232757. return m;
  232758. }
  232759. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  232760. {
  232761. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  232762. {
  232763. NSMenuItem* m = [menu itemAtIndex: i];
  232764. if ([m tag] == info.commandID)
  232765. return m;
  232766. if ([m submenu] != 0)
  232767. {
  232768. NSMenuItem* found = findMenuItem ([m submenu], info);
  232769. if (found != 0)
  232770. return found;
  232771. }
  232772. }
  232773. return 0;
  232774. }
  232775. static void flashMenuBar (NSMenu* menu)
  232776. {
  232777. if ([[menu title] isEqualToString: @"Apple"])
  232778. return;
  232779. [menu retain];
  232780. const unichar f35Key = NSF35FunctionKey;
  232781. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  232782. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  232783. action: nil
  232784. keyEquivalent: f35String];
  232785. [item setTarget: nil];
  232786. [menu insertItem: item atIndex: [menu numberOfItems]];
  232787. [item release];
  232788. if ([menu indexOfItem: item] >= 0)
  232789. {
  232790. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  232791. location: NSZeroPoint
  232792. modifierFlags: NSCommandKeyMask
  232793. timestamp: 0
  232794. windowNumber: 0
  232795. context: [NSGraphicsContext currentContext]
  232796. characters: f35String
  232797. charactersIgnoringModifiers: f35String
  232798. isARepeat: NO
  232799. keyCode: 0];
  232800. [menu performKeyEquivalent: f35Event];
  232801. if ([menu indexOfItem: item] >= 0)
  232802. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  232803. }
  232804. [menu release];
  232805. }
  232806. };
  232807. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  232808. END_JUCE_NAMESPACE
  232809. @implementation JuceMenuCallback
  232810. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  232811. {
  232812. [super init];
  232813. owner = owner_;
  232814. return self;
  232815. }
  232816. - (void) dealloc
  232817. {
  232818. [super dealloc];
  232819. }
  232820. - (void) menuItemInvoked: (id) menu
  232821. {
  232822. NSMenuItem* item = (NSMenuItem*) menu;
  232823. if ([[item representedObject] isKindOfClass: [NSArray class]])
  232824. {
  232825. // 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
  232826. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  232827. // into the focused component and let it trigger the menu item indirectly.
  232828. NSEvent* e = [NSApp currentEvent];
  232829. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  232830. {
  232831. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  232832. {
  232833. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  232834. if (peer != 0)
  232835. {
  232836. if ([e type] == NSKeyDown)
  232837. peer->redirectKeyDown (e);
  232838. else
  232839. peer->redirectKeyUp (e);
  232840. return;
  232841. }
  232842. }
  232843. }
  232844. NSArray* info = (NSArray*) [item representedObject];
  232845. owner->invoke ((int) [item tag],
  232846. (ApplicationCommandManager*) (pointer_sized_int)
  232847. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  232848. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  232849. }
  232850. }
  232851. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232852. {
  232853. if (JuceMainMenuHandler::instance != 0)
  232854. JuceMainMenuHandler::instance->updateMenus (menu);
  232855. }
  232856. @end
  232857. BEGIN_JUCE_NAMESPACE
  232858. namespace MainMenuHelpers
  232859. {
  232860. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  232861. {
  232862. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  232863. {
  232864. PopupMenu::MenuItemIterator iter (*extraItems);
  232865. while (iter.next())
  232866. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  232867. [menu addItem: [NSMenuItem separatorItem]];
  232868. }
  232869. NSMenuItem* item;
  232870. // Services...
  232871. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  232872. action: nil keyEquivalent: @""];
  232873. [menu addItem: item];
  232874. [item release];
  232875. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  232876. [menu setSubmenu: servicesMenu forItem: item];
  232877. [NSApp setServicesMenu: servicesMenu];
  232878. [servicesMenu release];
  232879. [menu addItem: [NSMenuItem separatorItem]];
  232880. // Hide + Show stuff...
  232881. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  232882. action: @selector (hide:) keyEquivalent: @"h"];
  232883. [item setTarget: NSApp];
  232884. [menu addItem: item];
  232885. [item release];
  232886. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  232887. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  232888. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  232889. [item setTarget: NSApp];
  232890. [menu addItem: item];
  232891. [item release];
  232892. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  232893. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  232894. [item setTarget: NSApp];
  232895. [menu addItem: item];
  232896. [item release];
  232897. [menu addItem: [NSMenuItem separatorItem]];
  232898. // Quit item....
  232899. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  232900. action: @selector (terminate:) keyEquivalent: @"q"];
  232901. [item setTarget: NSApp];
  232902. [menu addItem: item];
  232903. [item release];
  232904. return menu;
  232905. }
  232906. // Since our app has no NIB, this initialises a standard app menu...
  232907. void rebuildMainMenu (const PopupMenu* extraItems)
  232908. {
  232909. // this can't be used in a plugin!
  232910. jassert (JUCEApplication::isStandaloneApp());
  232911. if (JUCEApplication::getInstance() != 0)
  232912. {
  232913. const ScopedAutoReleasePool pool;
  232914. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  232915. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  232916. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  232917. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  232918. [mainMenu setSubmenu: appMenu forItem: item];
  232919. [NSApp setMainMenu: mainMenu];
  232920. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  232921. [appMenu release];
  232922. [mainMenu release];
  232923. }
  232924. }
  232925. }
  232926. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  232927. const PopupMenu* extraAppleMenuItems)
  232928. {
  232929. if (getMacMainMenu() != newMenuBarModel)
  232930. {
  232931. const ScopedAutoReleasePool pool;
  232932. if (newMenuBarModel == 0)
  232933. {
  232934. delete JuceMainMenuHandler::instance;
  232935. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  232936. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  232937. extraAppleMenuItems = 0;
  232938. }
  232939. else
  232940. {
  232941. if (JuceMainMenuHandler::instance == 0)
  232942. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  232943. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  232944. }
  232945. }
  232946. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  232947. if (newMenuBarModel != 0)
  232948. newMenuBarModel->menuItemsChanged();
  232949. }
  232950. MenuBarModel* MenuBarModel::getMacMainMenu()
  232951. {
  232952. return JuceMainMenuHandler::instance != 0
  232953. ? JuceMainMenuHandler::instance->currentModel : 0;
  232954. }
  232955. void juce_initialiseMacMainMenu()
  232956. {
  232957. if (JuceMainMenuHandler::instance == 0)
  232958. MainMenuHelpers::rebuildMainMenu (0);
  232959. }
  232960. #endif
  232961. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  232962. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  232963. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232964. // compiled on its own).
  232965. #if JUCE_INCLUDED_FILE
  232966. #if JUCE_MAC
  232967. END_JUCE_NAMESPACE
  232968. using namespace JUCE_NAMESPACE;
  232969. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  232970. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232971. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  232972. #else
  232973. @interface JuceFileChooserDelegate : NSObject
  232974. #endif
  232975. {
  232976. StringArray* filters;
  232977. }
  232978. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  232979. - (void) dealloc;
  232980. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  232981. @end
  232982. @implementation JuceFileChooserDelegate
  232983. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  232984. {
  232985. [super init];
  232986. filters = filters_;
  232987. return self;
  232988. }
  232989. - (void) dealloc
  232990. {
  232991. delete filters;
  232992. [super dealloc];
  232993. }
  232994. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  232995. {
  232996. (void) sender;
  232997. const File f (nsStringToJuce (filename));
  232998. for (int i = filters->size(); --i >= 0;)
  232999. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233000. return true;
  233001. return f.isDirectory();
  233002. }
  233003. @end
  233004. BEGIN_JUCE_NAMESPACE
  233005. void FileChooser::showPlatformDialog (Array<File>& results,
  233006. const String& title,
  233007. const File& currentFileOrDirectory,
  233008. const String& filter,
  233009. bool selectsDirectory,
  233010. bool selectsFiles,
  233011. bool isSaveDialogue,
  233012. bool /*warnAboutOverwritingExistingFiles*/,
  233013. bool selectMultipleFiles,
  233014. FilePreviewComponent* /*extraInfoComponent*/)
  233015. {
  233016. const ScopedAutoReleasePool pool;
  233017. StringArray* filters = new StringArray();
  233018. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233019. filters->trim();
  233020. filters->removeEmptyStrings();
  233021. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233022. [delegate autorelease];
  233023. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233024. : [NSOpenPanel openPanel];
  233025. [panel setTitle: juceStringToNS (title)];
  233026. if (! isSaveDialogue)
  233027. {
  233028. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233029. [openPanel setCanChooseDirectories: selectsDirectory];
  233030. [openPanel setCanChooseFiles: selectsFiles];
  233031. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233032. }
  233033. [panel setDelegate: delegate];
  233034. if (isSaveDialogue || selectsDirectory)
  233035. [panel setCanCreateDirectories: YES];
  233036. String directory, filename;
  233037. if (currentFileOrDirectory.isDirectory())
  233038. {
  233039. directory = currentFileOrDirectory.getFullPathName();
  233040. }
  233041. else
  233042. {
  233043. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233044. filename = currentFileOrDirectory.getFileName();
  233045. }
  233046. if ([panel runModalForDirectory: juceStringToNS (directory)
  233047. file: juceStringToNS (filename)]
  233048. == NSOKButton)
  233049. {
  233050. if (isSaveDialogue)
  233051. {
  233052. results.add (File (nsStringToJuce ([panel filename])));
  233053. }
  233054. else
  233055. {
  233056. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233057. NSArray* urls = [openPanel filenames];
  233058. for (unsigned int i = 0; i < [urls count]; ++i)
  233059. {
  233060. NSString* f = [urls objectAtIndex: i];
  233061. results.add (File (nsStringToJuce (f)));
  233062. }
  233063. }
  233064. }
  233065. [panel setDelegate: nil];
  233066. }
  233067. #else
  233068. void FileChooser::showPlatformDialog (Array<File>& results,
  233069. const String& title,
  233070. const File& currentFileOrDirectory,
  233071. const String& filter,
  233072. bool selectsDirectory,
  233073. bool selectsFiles,
  233074. bool isSaveDialogue,
  233075. bool warnAboutOverwritingExistingFiles,
  233076. bool selectMultipleFiles,
  233077. FilePreviewComponent* extraInfoComponent)
  233078. {
  233079. const ScopedAutoReleasePool pool;
  233080. jassertfalse; //xxx to do
  233081. }
  233082. #endif
  233083. #endif
  233084. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233085. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233086. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233087. // compiled on its own).
  233088. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233089. END_JUCE_NAMESPACE
  233090. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233091. @interface NonInterceptingQTMovieView : QTMovieView
  233092. {
  233093. }
  233094. - (id) initWithFrame: (NSRect) frame;
  233095. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233096. - (NSView*) hitTest: (NSPoint) p;
  233097. @end
  233098. @implementation NonInterceptingQTMovieView
  233099. - (id) initWithFrame: (NSRect) frame
  233100. {
  233101. self = [super initWithFrame: frame];
  233102. [self setNextResponder: [self superview]];
  233103. return self;
  233104. }
  233105. - (void) dealloc
  233106. {
  233107. [super dealloc];
  233108. }
  233109. - (NSView*) hitTest: (NSPoint) point
  233110. {
  233111. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233112. }
  233113. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233114. {
  233115. return YES;
  233116. }
  233117. @end
  233118. BEGIN_JUCE_NAMESPACE
  233119. #define theMovie (static_cast <QTMovie*> (movie))
  233120. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233121. : movie (0)
  233122. {
  233123. setOpaque (true);
  233124. setVisible (true);
  233125. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233126. setView (view);
  233127. [view release];
  233128. }
  233129. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233130. {
  233131. closeMovie();
  233132. setView (0);
  233133. }
  233134. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233135. {
  233136. return true;
  233137. }
  233138. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233139. {
  233140. // unfortunately, QTMovie objects can only be created on the main thread..
  233141. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233142. QTMovie* movie = 0;
  233143. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233144. if (fin != 0)
  233145. {
  233146. movieFile = fin->getFile();
  233147. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233148. error: nil];
  233149. }
  233150. else
  233151. {
  233152. MemoryBlock temp;
  233153. movieStream->readIntoMemoryBlock (temp);
  233154. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233155. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233156. {
  233157. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233158. length: temp.getSize()]
  233159. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233160. MIMEType: @""]
  233161. error: nil];
  233162. if (movie != 0)
  233163. break;
  233164. }
  233165. }
  233166. return movie;
  233167. }
  233168. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233169. const bool isControllerVisible_)
  233170. {
  233171. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233172. }
  233173. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233174. const bool controllerVisible_)
  233175. {
  233176. closeMovie();
  233177. if (getPeer() == 0)
  233178. {
  233179. // To open a movie, this component must be visible inside a functioning window, so that
  233180. // the QT control can be assigned to the window.
  233181. jassertfalse;
  233182. return false;
  233183. }
  233184. movie = openMovieFromStream (movieStream, movieFile);
  233185. [theMovie retain];
  233186. QTMovieView* view = (QTMovieView*) getView();
  233187. [view setMovie: theMovie];
  233188. [view setControllerVisible: controllerVisible_];
  233189. setLooping (looping);
  233190. return movie != nil;
  233191. }
  233192. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233193. const bool isControllerVisible_)
  233194. {
  233195. // unfortunately, QTMovie objects can only be created on the main thread..
  233196. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233197. closeMovie();
  233198. if (getPeer() == 0)
  233199. {
  233200. // To open a movie, this component must be visible inside a functioning window, so that
  233201. // the QT control can be assigned to the window.
  233202. jassertfalse;
  233203. return false;
  233204. }
  233205. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233206. NSError* err;
  233207. if ([QTMovie canInitWithURL: url])
  233208. movie = [QTMovie movieWithURL: url error: &err];
  233209. [theMovie retain];
  233210. QTMovieView* view = (QTMovieView*) getView();
  233211. [view setMovie: theMovie];
  233212. [view setControllerVisible: controllerVisible];
  233213. setLooping (looping);
  233214. return movie != nil;
  233215. }
  233216. void QuickTimeMovieComponent::closeMovie()
  233217. {
  233218. stop();
  233219. QTMovieView* view = (QTMovieView*) getView();
  233220. [view setMovie: nil];
  233221. [theMovie release];
  233222. movie = 0;
  233223. movieFile = File::nonexistent;
  233224. }
  233225. bool QuickTimeMovieComponent::isMovieOpen() const
  233226. {
  233227. return movie != nil;
  233228. }
  233229. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233230. {
  233231. return movieFile;
  233232. }
  233233. void QuickTimeMovieComponent::play()
  233234. {
  233235. [theMovie play];
  233236. }
  233237. void QuickTimeMovieComponent::stop()
  233238. {
  233239. [theMovie stop];
  233240. }
  233241. bool QuickTimeMovieComponent::isPlaying() const
  233242. {
  233243. return movie != 0 && [theMovie rate] != 0;
  233244. }
  233245. void QuickTimeMovieComponent::setPosition (const double seconds)
  233246. {
  233247. if (movie != 0)
  233248. {
  233249. QTTime t;
  233250. t.timeValue = (uint64) (100000.0 * seconds);
  233251. t.timeScale = 100000;
  233252. t.flags = 0;
  233253. [theMovie setCurrentTime: t];
  233254. }
  233255. }
  233256. double QuickTimeMovieComponent::getPosition() const
  233257. {
  233258. if (movie == 0)
  233259. return 0.0;
  233260. QTTime t = [theMovie currentTime];
  233261. return t.timeValue / (double) t.timeScale;
  233262. }
  233263. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233264. {
  233265. [theMovie setRate: newSpeed];
  233266. }
  233267. double QuickTimeMovieComponent::getMovieDuration() const
  233268. {
  233269. if (movie == 0)
  233270. return 0.0;
  233271. QTTime t = [theMovie duration];
  233272. return t.timeValue / (double) t.timeScale;
  233273. }
  233274. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233275. {
  233276. looping = shouldLoop;
  233277. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233278. forKey: QTMovieLoopsAttribute];
  233279. }
  233280. bool QuickTimeMovieComponent::isLooping() const
  233281. {
  233282. return looping;
  233283. }
  233284. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233285. {
  233286. [theMovie setVolume: newVolume];
  233287. }
  233288. float QuickTimeMovieComponent::getMovieVolume() const
  233289. {
  233290. return movie != 0 ? [theMovie volume] : 0.0f;
  233291. }
  233292. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233293. {
  233294. width = 0;
  233295. height = 0;
  233296. if (movie != 0)
  233297. {
  233298. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233299. width = (int) s.width;
  233300. height = (int) s.height;
  233301. }
  233302. }
  233303. void QuickTimeMovieComponent::paint (Graphics& g)
  233304. {
  233305. if (movie == 0)
  233306. g.fillAll (Colours::black);
  233307. }
  233308. bool QuickTimeMovieComponent::isControllerVisible() const
  233309. {
  233310. return controllerVisible;
  233311. }
  233312. void QuickTimeMovieComponent::goToStart()
  233313. {
  233314. setPosition (0.0);
  233315. }
  233316. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233317. const RectanglePlacement& placement)
  233318. {
  233319. int normalWidth, normalHeight;
  233320. getMovieNormalSize (normalWidth, normalHeight);
  233321. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  233322. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  233323. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  233324. else
  233325. setBounds (spaceToFitWithin);
  233326. }
  233327. #if ! (JUCE_MAC && JUCE_64BIT)
  233328. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233329. {
  233330. if (movieStream == 0)
  233331. return false;
  233332. File file;
  233333. QTMovie* movie = openMovieFromStream (movieStream, file);
  233334. if (movie != nil)
  233335. result = [movie quickTimeMovie];
  233336. return movie != nil;
  233337. }
  233338. #endif
  233339. #endif
  233340. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233341. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233342. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233343. // compiled on its own).
  233344. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233345. const int kilobytesPerSecond1x = 176;
  233346. END_JUCE_NAMESPACE
  233347. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233348. @interface OpenDiskDevice : NSObject
  233349. {
  233350. @public
  233351. DRDevice* device;
  233352. NSMutableArray* tracks;
  233353. bool underrunProtection;
  233354. }
  233355. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233356. - (void) dealloc;
  233357. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233358. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233359. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233360. @end
  233361. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233362. @interface AudioTrackProducer : NSObject
  233363. {
  233364. JUCE_NAMESPACE::AudioSource* source;
  233365. int readPosition, lengthInFrames;
  233366. }
  233367. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233368. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233369. - (void) dealloc;
  233370. - (void) setupTrackProperties: (DRTrack*) track;
  233371. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233372. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233373. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233374. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233375. toMedia:(NSDictionary*)mediaInfo;
  233376. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233377. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233378. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233379. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233380. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233381. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233382. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233383. ioFlags:(uint32_t*)flags;
  233384. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233385. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233386. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233387. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233388. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233389. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233390. ioFlags:(uint32_t*)flags;
  233391. @end
  233392. @implementation OpenDiskDevice
  233393. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233394. {
  233395. [super init];
  233396. device = device_;
  233397. tracks = [[NSMutableArray alloc] init];
  233398. underrunProtection = true;
  233399. return self;
  233400. }
  233401. - (void) dealloc
  233402. {
  233403. [tracks release];
  233404. [super dealloc];
  233405. }
  233406. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233407. {
  233408. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233409. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233410. [p setupTrackProperties: t];
  233411. [tracks addObject: t];
  233412. [t release];
  233413. [p release];
  233414. }
  233415. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233416. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233417. {
  233418. DRBurn* burn = [DRBurn burnForDevice: device];
  233419. if (! [device acquireExclusiveAccess])
  233420. {
  233421. *error = "Couldn't open or write to the CD device";
  233422. return;
  233423. }
  233424. [device acquireMediaReservation];
  233425. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233426. [d autorelease];
  233427. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233428. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233429. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233430. if (burnSpeed > 0)
  233431. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233432. if (! underrunProtection)
  233433. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233434. [burn setProperties: d];
  233435. [burn writeLayout: tracks];
  233436. for (;;)
  233437. {
  233438. JUCE_NAMESPACE::Thread::sleep (300);
  233439. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233440. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233441. {
  233442. [burn abort];
  233443. *error = "User cancelled the write operation";
  233444. break;
  233445. }
  233446. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233447. {
  233448. *error = "Write operation failed";
  233449. break;
  233450. }
  233451. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  233452. {
  233453. break;
  233454. }
  233455. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  233456. objectForKey: DRErrorStatusErrorStringKey];
  233457. if ([err length] > 0)
  233458. {
  233459. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  233460. break;
  233461. }
  233462. }
  233463. [device releaseMediaReservation];
  233464. [device releaseExclusiveAccess];
  233465. }
  233466. @end
  233467. @implementation AudioTrackProducer
  233468. - (AudioTrackProducer*) init: (int) lengthInFrames_
  233469. {
  233470. lengthInFrames = lengthInFrames_;
  233471. readPosition = 0;
  233472. return self;
  233473. }
  233474. - (void) setupTrackProperties: (DRTrack*) track
  233475. {
  233476. NSMutableDictionary* p = [[track properties] mutableCopy];
  233477. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  233478. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  233479. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  233480. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  233481. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  233482. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  233483. [track setProperties: p];
  233484. [p release];
  233485. }
  233486. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  233487. {
  233488. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  233489. if (s != nil)
  233490. s->source = source_;
  233491. return s;
  233492. }
  233493. - (void) dealloc
  233494. {
  233495. if (source != 0)
  233496. {
  233497. source->releaseResources();
  233498. delete source;
  233499. }
  233500. [super dealloc];
  233501. }
  233502. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  233503. {
  233504. (void) track;
  233505. }
  233506. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  233507. {
  233508. (void) track;
  233509. return true;
  233510. }
  233511. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  233512. {
  233513. (void) track;
  233514. return lengthInFrames;
  233515. }
  233516. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  233517. toMedia: (NSDictionary*) mediaInfo
  233518. {
  233519. (void) track; (void) burn; (void) mediaInfo;
  233520. if (source != 0)
  233521. source->prepareToPlay (44100 / 75, 44100);
  233522. readPosition = 0;
  233523. return true;
  233524. }
  233525. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  233526. {
  233527. (void) track;
  233528. if (source != 0)
  233529. source->prepareToPlay (44100 / 75, 44100);
  233530. return true;
  233531. }
  233532. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  233533. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233534. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233535. {
  233536. (void) track; (void) address; (void) blockSize; (void) flags;
  233537. if (source != 0)
  233538. {
  233539. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  233540. if (numSamples > 0)
  233541. {
  233542. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  233543. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  233544. info.buffer = &tempBuffer;
  233545. info.startSample = 0;
  233546. info.numSamples = numSamples;
  233547. source->getNextAudioBlock (info);
  233548. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  233549. JUCE_NAMESPACE::AudioData::LittleEndian,
  233550. JUCE_NAMESPACE::AudioData::Interleaved,
  233551. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  233552. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  233553. JUCE_NAMESPACE::AudioData::NativeEndian,
  233554. JUCE_NAMESPACE::AudioData::NonInterleaved,
  233555. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  233556. CDSampleFormat left (buffer, 2);
  233557. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  233558. CDSampleFormat right (buffer + 2, 2);
  233559. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  233560. readPosition += numSamples;
  233561. }
  233562. return numSamples * 4;
  233563. }
  233564. return 0;
  233565. }
  233566. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  233567. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  233568. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  233569. ioFlags: (uint32_t*) flags
  233570. {
  233571. (void) track; (void) address; (void) blockSize; (void) flags;
  233572. zeromem (buffer, bufferLength);
  233573. return bufferLength;
  233574. }
  233575. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  233576. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233577. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233578. {
  233579. (void) track; (void) buffer; (void) bufferLength; (void) address; (void) blockSize; (void) flags;
  233580. return true;
  233581. }
  233582. @end
  233583. BEGIN_JUCE_NAMESPACE
  233584. class AudioCDBurner::Pimpl : public Timer
  233585. {
  233586. public:
  233587. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  233588. : device (0), owner (owner_)
  233589. {
  233590. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  233591. if (dev != 0)
  233592. {
  233593. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  233594. lastState = getDiskState();
  233595. startTimer (1000);
  233596. }
  233597. }
  233598. ~Pimpl()
  233599. {
  233600. stopTimer();
  233601. [device release];
  233602. }
  233603. void timerCallback()
  233604. {
  233605. const DiskState state = getDiskState();
  233606. if (state != lastState)
  233607. {
  233608. lastState = state;
  233609. owner.sendChangeMessage();
  233610. }
  233611. }
  233612. DiskState getDiskState() const
  233613. {
  233614. if ([device->device isValid])
  233615. {
  233616. NSDictionary* status = [device->device status];
  233617. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  233618. if ([state isEqualTo: DRDeviceMediaStateNone])
  233619. {
  233620. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  233621. return trayOpen;
  233622. return noDisc;
  233623. }
  233624. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  233625. {
  233626. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  233627. return writableDiskPresent;
  233628. else
  233629. return readOnlyDiskPresent;
  233630. }
  233631. }
  233632. return unknown;
  233633. }
  233634. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  233635. const Array<int> getAvailableWriteSpeeds() const
  233636. {
  233637. Array<int> results;
  233638. if ([device->device isValid])
  233639. {
  233640. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  233641. for (unsigned int i = 0; i < [speeds count]; ++i)
  233642. {
  233643. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  233644. results.add (kbPerSec / kilobytesPerSecond1x);
  233645. }
  233646. }
  233647. return results;
  233648. }
  233649. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  233650. {
  233651. if ([device->device isValid])
  233652. {
  233653. device->underrunProtection = shouldBeEnabled;
  233654. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  233655. }
  233656. return false;
  233657. }
  233658. int getNumAvailableAudioBlocks() const
  233659. {
  233660. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  233661. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  233662. }
  233663. OpenDiskDevice* device;
  233664. private:
  233665. DiskState lastState;
  233666. AudioCDBurner& owner;
  233667. };
  233668. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  233669. {
  233670. pimpl = new Pimpl (*this, deviceIndex);
  233671. }
  233672. AudioCDBurner::~AudioCDBurner()
  233673. {
  233674. }
  233675. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  233676. {
  233677. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  233678. if (b->pimpl->device == 0)
  233679. b = 0;
  233680. return b.release();
  233681. }
  233682. namespace
  233683. {
  233684. NSArray* findDiskBurnerDevices()
  233685. {
  233686. NSMutableArray* results = [NSMutableArray array];
  233687. NSArray* devs = [DRDevice devices];
  233688. for (int i = 0; i < [devs count]; ++i)
  233689. {
  233690. NSDictionary* dic = [[devs objectAtIndex: i] info];
  233691. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  233692. if (name != nil)
  233693. [results addObject: name];
  233694. }
  233695. return results;
  233696. }
  233697. }
  233698. const StringArray AudioCDBurner::findAvailableDevices()
  233699. {
  233700. NSArray* names = findDiskBurnerDevices();
  233701. StringArray s;
  233702. for (unsigned int i = 0; i < [names count]; ++i)
  233703. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  233704. return s;
  233705. }
  233706. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  233707. {
  233708. return pimpl->getDiskState();
  233709. }
  233710. bool AudioCDBurner::isDiskPresent() const
  233711. {
  233712. return getDiskState() == writableDiskPresent;
  233713. }
  233714. bool AudioCDBurner::openTray()
  233715. {
  233716. return pimpl->openTray();
  233717. }
  233718. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  233719. {
  233720. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  233721. DiskState oldState = getDiskState();
  233722. DiskState newState = oldState;
  233723. while (newState == oldState && Time::currentTimeMillis() < timeout)
  233724. {
  233725. newState = getDiskState();
  233726. Thread::sleep (100);
  233727. }
  233728. return newState;
  233729. }
  233730. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  233731. {
  233732. return pimpl->getAvailableWriteSpeeds();
  233733. }
  233734. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  233735. {
  233736. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  233737. }
  233738. int AudioCDBurner::getNumAvailableAudioBlocks() const
  233739. {
  233740. return pimpl->getNumAvailableAudioBlocks();
  233741. }
  233742. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  233743. {
  233744. if ([pimpl->device->device isValid])
  233745. {
  233746. [pimpl->device addSourceTrack: source numSamples: numSamps];
  233747. return true;
  233748. }
  233749. return false;
  233750. }
  233751. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  233752. bool ejectDiscAfterwards,
  233753. bool performFakeBurnForTesting,
  233754. int writeSpeed)
  233755. {
  233756. String error ("Couldn't open or write to the CD device");
  233757. if ([pimpl->device->device isValid])
  233758. {
  233759. error = String::empty;
  233760. [pimpl->device burn: listener
  233761. errorString: &error
  233762. ejectAfterwards: ejectDiscAfterwards
  233763. isFake: performFakeBurnForTesting
  233764. speed: writeSpeed];
  233765. }
  233766. return error;
  233767. }
  233768. #endif
  233769. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233770. void AudioCDReader::ejectDisk()
  233771. {
  233772. const ScopedAutoReleasePool p;
  233773. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  233774. }
  233775. #endif
  233776. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  233777. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  233778. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233779. // compiled on its own).
  233780. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233781. namespace CDReaderHelpers
  233782. {
  233783. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  233784. {
  233785. forEachXmlChildElementWithTagName (xml, child, "key")
  233786. if (child->getAllSubText().trim() == key)
  233787. return child->getNextElement();
  233788. return 0;
  233789. }
  233790. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  233791. {
  233792. const XmlElement* const block = getElementForKey (xml, key);
  233793. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  233794. }
  233795. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  233796. // Returns NULL on success, otherwise a const char* representing an error.
  233797. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  233798. {
  233799. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  233800. if (xml == 0)
  233801. return "Couldn't parse XML in file";
  233802. const XmlElement* const dict = xml->getChildByName ("dict");
  233803. if (dict == 0)
  233804. return "Couldn't get top level dictionary";
  233805. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  233806. if (sessions == 0)
  233807. return "Couldn't find sessions key";
  233808. const XmlElement* const session = sessions->getFirstChildElement();
  233809. if (session == 0)
  233810. return "Couldn't find first session";
  233811. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  233812. if (leadOut < 0)
  233813. return "Couldn't find Leadout Block";
  233814. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  233815. if (trackArray == 0)
  233816. return "Couldn't find Track Array";
  233817. forEachXmlChildElement (*trackArray, track)
  233818. {
  233819. const int trackValue = getIntValueForKey (*track, "Start Block");
  233820. if (trackValue < 0)
  233821. return "Couldn't find Start Block in the track";
  233822. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  233823. }
  233824. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  233825. return 0;
  233826. }
  233827. static void findDevices (Array<File>& cds)
  233828. {
  233829. File volumes ("/Volumes");
  233830. volumes.findChildFiles (cds, File::findDirectories, false);
  233831. for (int i = cds.size(); --i >= 0;)
  233832. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  233833. cds.remove (i);
  233834. }
  233835. struct TrackSorter
  233836. {
  233837. static int getCDTrackNumber (const File& file)
  233838. {
  233839. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  233840. }
  233841. static int compareElements (const File& first, const File& second)
  233842. {
  233843. const int firstTrack = getCDTrackNumber (first);
  233844. const int secondTrack = getCDTrackNumber (second);
  233845. jassert (firstTrack > 0 && secondTrack > 0);
  233846. return firstTrack - secondTrack;
  233847. }
  233848. };
  233849. }
  233850. const StringArray AudioCDReader::getAvailableCDNames()
  233851. {
  233852. Array<File> cds;
  233853. CDReaderHelpers::findDevices (cds);
  233854. StringArray names;
  233855. for (int i = 0; i < cds.size(); ++i)
  233856. names.add (cds.getReference(i).getFileName());
  233857. return names;
  233858. }
  233859. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  233860. {
  233861. Array<File> cds;
  233862. CDReaderHelpers::findDevices (cds);
  233863. if (cds[index].exists())
  233864. return new AudioCDReader (cds[index]);
  233865. return 0;
  233866. }
  233867. AudioCDReader::AudioCDReader (const File& volume)
  233868. : AudioFormatReader (0, "CD Audio"),
  233869. volumeDir (volume),
  233870. currentReaderTrack (-1),
  233871. reader (0)
  233872. {
  233873. sampleRate = 44100.0;
  233874. bitsPerSample = 16;
  233875. numChannels = 2;
  233876. usesFloatingPointData = false;
  233877. refreshTrackLengths();
  233878. }
  233879. AudioCDReader::~AudioCDReader()
  233880. {
  233881. }
  233882. void AudioCDReader::refreshTrackLengths()
  233883. {
  233884. tracks.clear();
  233885. trackStartSamples.clear();
  233886. lengthInSamples = 0;
  233887. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  233888. CDReaderHelpers::TrackSorter sorter;
  233889. tracks.sort (sorter);
  233890. const File toc (volumeDir.getChildFile (".TOC.plist"));
  233891. if (toc.exists())
  233892. {
  233893. XmlDocument doc (toc);
  233894. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  233895. (void) error; // could be logged..
  233896. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  233897. }
  233898. }
  233899. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  233900. int64 startSampleInFile, int numSamples)
  233901. {
  233902. while (numSamples > 0)
  233903. {
  233904. int track = -1;
  233905. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  233906. {
  233907. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  233908. {
  233909. track = i;
  233910. break;
  233911. }
  233912. }
  233913. if (track < 0)
  233914. return false;
  233915. if (track != currentReaderTrack)
  233916. {
  233917. reader = 0;
  233918. FileInputStream* const in = tracks [track].createInputStream();
  233919. if (in != 0)
  233920. {
  233921. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  233922. AiffAudioFormat format;
  233923. reader = format.createReaderFor (bin, true);
  233924. if (reader == 0)
  233925. currentReaderTrack = -1;
  233926. else
  233927. currentReaderTrack = track;
  233928. }
  233929. }
  233930. if (reader == 0)
  233931. return false;
  233932. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  233933. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  233934. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  233935. numSamples -= numAvailable;
  233936. startSampleInFile += numAvailable;
  233937. }
  233938. return true;
  233939. }
  233940. bool AudioCDReader::isCDStillPresent() const
  233941. {
  233942. return volumeDir.exists();
  233943. }
  233944. bool AudioCDReader::isTrackAudio (int trackNum) const
  233945. {
  233946. return tracks [trackNum].hasFileExtension (".aiff");
  233947. }
  233948. void AudioCDReader::enableIndexScanning (bool)
  233949. {
  233950. // any way to do this on a Mac??
  233951. }
  233952. int AudioCDReader::getLastIndex() const
  233953. {
  233954. return 0;
  233955. }
  233956. const Array <int> AudioCDReader::findIndexesInTrack (const int /*trackNumber*/)
  233957. {
  233958. return Array <int>();
  233959. }
  233960. #endif
  233961. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  233962. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  233963. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233964. // compiled on its own).
  233965. #if JUCE_INCLUDED_FILE
  233966. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  233967. for example having more than one juce plugin loaded into a host, then when a
  233968. method is called, the actual code that runs might actually be in a different module
  233969. than the one you expect... So any calls to library functions or statics that are
  233970. made inside obj-c methods will probably end up getting executed in a different DLL's
  233971. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  233972. To work around this insanity, I'm only allowing obj-c methods to make calls to
  233973. virtual methods of an object that's known to live inside the right module's space.
  233974. */
  233975. class AppDelegateRedirector
  233976. {
  233977. public:
  233978. AppDelegateRedirector()
  233979. {
  233980. }
  233981. virtual ~AppDelegateRedirector()
  233982. {
  233983. }
  233984. virtual NSApplicationTerminateReply shouldTerminate()
  233985. {
  233986. if (JUCEApplication::getInstance() != 0)
  233987. {
  233988. JUCEApplication::getInstance()->systemRequestedQuit();
  233989. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  233990. return NSTerminateCancel;
  233991. }
  233992. return NSTerminateNow;
  233993. }
  233994. virtual void willTerminate()
  233995. {
  233996. JUCEApplication::appWillTerminateByForce();
  233997. }
  233998. virtual BOOL openFile (NSString* filename)
  233999. {
  234000. if (JUCEApplication::getInstance() != 0)
  234001. {
  234002. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234003. return YES;
  234004. }
  234005. return NO;
  234006. }
  234007. virtual void openFiles (NSArray* filenames)
  234008. {
  234009. StringArray files;
  234010. for (unsigned int i = 0; i < [filenames count]; ++i)
  234011. {
  234012. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234013. if (filename.containsChar (' '))
  234014. filename = filename.quoted('"');
  234015. files.add (filename);
  234016. }
  234017. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234018. {
  234019. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234020. }
  234021. }
  234022. virtual void focusChanged()
  234023. {
  234024. juce_HandleProcessFocusChange();
  234025. }
  234026. struct CallbackMessagePayload
  234027. {
  234028. MessageCallbackFunction* function;
  234029. void* parameter;
  234030. void* volatile result;
  234031. bool volatile hasBeenExecuted;
  234032. };
  234033. virtual void performCallback (CallbackMessagePayload* pl)
  234034. {
  234035. pl->result = (*pl->function) (pl->parameter);
  234036. pl->hasBeenExecuted = true;
  234037. }
  234038. virtual void deleteSelf()
  234039. {
  234040. delete this;
  234041. }
  234042. void postMessage (Message* const m)
  234043. {
  234044. messageQueue.post (m);
  234045. }
  234046. private:
  234047. CFRunLoopRef runLoop;
  234048. CFRunLoopSourceRef runLoopSource;
  234049. MessageQueue messageQueue;
  234050. };
  234051. END_JUCE_NAMESPACE
  234052. using namespace JUCE_NAMESPACE;
  234053. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234054. @interface JuceAppDelegate : NSObject
  234055. {
  234056. @private
  234057. id oldDelegate;
  234058. @public
  234059. AppDelegateRedirector* redirector;
  234060. }
  234061. - (JuceAppDelegate*) init;
  234062. - (void) dealloc;
  234063. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234064. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234065. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234066. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234067. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234068. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234069. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234070. - (void) performCallback: (id) info;
  234071. - (void) dummyMethod;
  234072. @end
  234073. @implementation JuceAppDelegate
  234074. - (JuceAppDelegate*) init
  234075. {
  234076. [super init];
  234077. redirector = new AppDelegateRedirector();
  234078. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234079. if (JUCEApplication::isStandaloneApp())
  234080. {
  234081. oldDelegate = [NSApp delegate];
  234082. [NSApp setDelegate: self];
  234083. }
  234084. else
  234085. {
  234086. oldDelegate = 0;
  234087. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234088. name: NSApplicationDidResignActiveNotification object: NSApp];
  234089. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234090. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234091. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234092. name: NSApplicationWillUnhideNotification object: NSApp];
  234093. }
  234094. return self;
  234095. }
  234096. - (void) dealloc
  234097. {
  234098. if (oldDelegate != 0)
  234099. [NSApp setDelegate: oldDelegate];
  234100. redirector->deleteSelf();
  234101. [super dealloc];
  234102. }
  234103. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234104. {
  234105. (void) app;
  234106. return redirector->shouldTerminate();
  234107. }
  234108. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234109. {
  234110. (void) aNotification;
  234111. redirector->willTerminate();
  234112. }
  234113. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234114. {
  234115. (void) app;
  234116. return redirector->openFile (filename);
  234117. }
  234118. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234119. {
  234120. (void) sender;
  234121. return redirector->openFiles (filenames);
  234122. }
  234123. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234124. {
  234125. (void) notification;
  234126. redirector->focusChanged();
  234127. }
  234128. - (void) applicationDidResignActive: (NSNotification*) notification
  234129. {
  234130. (void) notification;
  234131. redirector->focusChanged();
  234132. }
  234133. - (void) applicationWillUnhide: (NSNotification*) notification
  234134. {
  234135. (void) notification;
  234136. redirector->focusChanged();
  234137. }
  234138. - (void) performCallback: (id) info
  234139. {
  234140. if ([info isKindOfClass: [NSData class]])
  234141. {
  234142. AppDelegateRedirector::CallbackMessagePayload* pl
  234143. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234144. if (pl != 0)
  234145. redirector->performCallback (pl);
  234146. }
  234147. else
  234148. {
  234149. jassertfalse; // should never get here!
  234150. }
  234151. }
  234152. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234153. @end
  234154. BEGIN_JUCE_NAMESPACE
  234155. static JuceAppDelegate* juceAppDelegate = 0;
  234156. void MessageManager::runDispatchLoop()
  234157. {
  234158. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234159. {
  234160. const ScopedAutoReleasePool pool;
  234161. // must only be called by the message thread!
  234162. jassert (isThisTheMessageThread());
  234163. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234164. @try
  234165. {
  234166. [NSApp run];
  234167. }
  234168. @catch (NSException* e)
  234169. {
  234170. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234171. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234172. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234173. }
  234174. @finally
  234175. {
  234176. }
  234177. #else
  234178. [NSApp run];
  234179. #endif
  234180. }
  234181. }
  234182. void MessageManager::stopDispatchLoop()
  234183. {
  234184. quitMessagePosted = true;
  234185. [NSApp stop: nil];
  234186. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234187. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234188. }
  234189. namespace
  234190. {
  234191. bool isEventBlockedByModalComps (NSEvent* e)
  234192. {
  234193. if (Component::getNumCurrentlyModalComponents() == 0)
  234194. return false;
  234195. NSWindow* const w = [e window];
  234196. if (w == 0 || [w worksWhenModal])
  234197. return false;
  234198. bool isKey = false, isInputAttempt = false;
  234199. switch ([e type])
  234200. {
  234201. case NSKeyDown:
  234202. case NSKeyUp:
  234203. isKey = isInputAttempt = true;
  234204. break;
  234205. case NSLeftMouseDown:
  234206. case NSRightMouseDown:
  234207. case NSOtherMouseDown:
  234208. isInputAttempt = true;
  234209. break;
  234210. case NSLeftMouseDragged:
  234211. case NSRightMouseDragged:
  234212. case NSLeftMouseUp:
  234213. case NSRightMouseUp:
  234214. case NSOtherMouseUp:
  234215. case NSOtherMouseDragged:
  234216. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234217. return false;
  234218. break;
  234219. case NSMouseMoved:
  234220. case NSMouseEntered:
  234221. case NSMouseExited:
  234222. case NSCursorUpdate:
  234223. case NSScrollWheel:
  234224. case NSTabletPoint:
  234225. case NSTabletProximity:
  234226. break;
  234227. default:
  234228. return false;
  234229. }
  234230. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234231. {
  234232. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234233. NSView* const compView = (NSView*) peer->getNativeHandle();
  234234. if ([compView window] == w)
  234235. {
  234236. if (isKey)
  234237. {
  234238. if (compView == [w firstResponder])
  234239. return false;
  234240. }
  234241. else
  234242. {
  234243. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234244. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234245. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234246. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234247. return false;
  234248. }
  234249. }
  234250. }
  234251. if (isInputAttempt)
  234252. {
  234253. if (! [NSApp isActive])
  234254. [NSApp activateIgnoringOtherApps: YES];
  234255. Component* const modal = Component::getCurrentlyModalComponent (0);
  234256. if (modal != 0)
  234257. modal->inputAttemptWhenModal();
  234258. }
  234259. return true;
  234260. }
  234261. }
  234262. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234263. {
  234264. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234265. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234266. while (! quitMessagePosted)
  234267. {
  234268. const ScopedAutoReleasePool pool;
  234269. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234270. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234271. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234272. inMode: NSDefaultRunLoopMode
  234273. dequeue: YES];
  234274. if (e != 0 && ! isEventBlockedByModalComps (e))
  234275. [NSApp sendEvent: e];
  234276. if (Time::getMillisecondCounter() >= endTime)
  234277. break;
  234278. }
  234279. return ! quitMessagePosted;
  234280. }
  234281. void MessageManager::doPlatformSpecificInitialisation()
  234282. {
  234283. if (juceAppDelegate == 0)
  234284. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234285. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234286. // correctly (needed prior to 10.5)
  234287. if (! [NSThread isMultiThreaded])
  234288. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234289. toTarget: juceAppDelegate
  234290. withObject: nil];
  234291. }
  234292. void MessageManager::doPlatformSpecificShutdown()
  234293. {
  234294. if (juceAppDelegate != 0)
  234295. {
  234296. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234297. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234298. [juceAppDelegate release];
  234299. juceAppDelegate = 0;
  234300. }
  234301. }
  234302. bool juce_postMessageToSystemQueue (Message* message)
  234303. {
  234304. juceAppDelegate->redirector->postMessage (message);
  234305. return true;
  234306. }
  234307. void MessageManager::broadcastMessage (const String&)
  234308. {
  234309. }
  234310. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234311. {
  234312. if (isThisTheMessageThread())
  234313. {
  234314. return (*callback) (data);
  234315. }
  234316. else
  234317. {
  234318. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234319. // deadlock because the message manager is blocked from running, so can never
  234320. // call your function..
  234321. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234322. const ScopedAutoReleasePool pool;
  234323. AppDelegateRedirector::CallbackMessagePayload cmp;
  234324. cmp.function = callback;
  234325. cmp.parameter = data;
  234326. cmp.result = 0;
  234327. cmp.hasBeenExecuted = false;
  234328. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234329. withObject: [NSData dataWithBytesNoCopy: &cmp
  234330. length: sizeof (cmp)
  234331. freeWhenDone: NO]
  234332. waitUntilDone: YES];
  234333. return cmp.result;
  234334. }
  234335. }
  234336. #endif
  234337. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234338. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234339. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234340. // compiled on its own).
  234341. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234342. #if JUCE_MAC
  234343. END_JUCE_NAMESPACE
  234344. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234345. @interface DownloadClickDetector : NSObject
  234346. {
  234347. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234348. }
  234349. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234350. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234351. request: (NSURLRequest*) request
  234352. frame: (WebFrame*) frame
  234353. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234354. @end
  234355. @implementation DownloadClickDetector
  234356. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234357. {
  234358. [super init];
  234359. ownerComponent = ownerComponent_;
  234360. return self;
  234361. }
  234362. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234363. request: (NSURLRequest*) request
  234364. frame: (WebFrame*) frame
  234365. decisionListener: (id <WebPolicyDecisionListener>) listener
  234366. {
  234367. (void) sender;
  234368. (void) request;
  234369. (void) frame;
  234370. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234371. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234372. [listener use];
  234373. else
  234374. [listener ignore];
  234375. }
  234376. @end
  234377. BEGIN_JUCE_NAMESPACE
  234378. class WebBrowserComponentInternal : public NSViewComponent
  234379. {
  234380. public:
  234381. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234382. {
  234383. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234384. frameName: @""
  234385. groupName: @""];
  234386. setView (webView);
  234387. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234388. [webView setPolicyDelegate: clickListener];
  234389. }
  234390. ~WebBrowserComponentInternal()
  234391. {
  234392. [webView setPolicyDelegate: nil];
  234393. [clickListener release];
  234394. setView (0);
  234395. }
  234396. void goToURL (const String& url,
  234397. const StringArray* headers,
  234398. const MemoryBlock* postData)
  234399. {
  234400. NSMutableURLRequest* r
  234401. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234402. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234403. timeoutInterval: 30.0];
  234404. if (postData != 0 && postData->getSize() > 0)
  234405. {
  234406. [r setHTTPMethod: @"POST"];
  234407. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234408. length: postData->getSize()]];
  234409. }
  234410. if (headers != 0)
  234411. {
  234412. for (int i = 0; i < headers->size(); ++i)
  234413. {
  234414. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234415. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234416. [r setValue: juceStringToNS (headerValue)
  234417. forHTTPHeaderField: juceStringToNS (headerName)];
  234418. }
  234419. }
  234420. stop();
  234421. [[webView mainFrame] loadRequest: r];
  234422. }
  234423. void goBack()
  234424. {
  234425. [webView goBack];
  234426. }
  234427. void goForward()
  234428. {
  234429. [webView goForward];
  234430. }
  234431. void stop()
  234432. {
  234433. [webView stopLoading: nil];
  234434. }
  234435. void refresh()
  234436. {
  234437. [webView reload: nil];
  234438. }
  234439. void mouseMove (const MouseEvent&)
  234440. {
  234441. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  234442. // them work is to push them via this non-public method..
  234443. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  234444. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  234445. }
  234446. private:
  234447. WebView* webView;
  234448. DownloadClickDetector* clickListener;
  234449. };
  234450. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234451. : browser (0),
  234452. blankPageShown (false),
  234453. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  234454. {
  234455. setOpaque (true);
  234456. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  234457. }
  234458. WebBrowserComponent::~WebBrowserComponent()
  234459. {
  234460. deleteAndZero (browser);
  234461. }
  234462. void WebBrowserComponent::goToURL (const String& url,
  234463. const StringArray* headers,
  234464. const MemoryBlock* postData)
  234465. {
  234466. lastURL = url;
  234467. lastHeaders.clear();
  234468. if (headers != 0)
  234469. lastHeaders = *headers;
  234470. lastPostData.setSize (0);
  234471. if (postData != 0)
  234472. lastPostData = *postData;
  234473. blankPageShown = false;
  234474. browser->goToURL (url, headers, postData);
  234475. }
  234476. void WebBrowserComponent::stop()
  234477. {
  234478. browser->stop();
  234479. }
  234480. void WebBrowserComponent::goBack()
  234481. {
  234482. lastURL = String::empty;
  234483. blankPageShown = false;
  234484. browser->goBack();
  234485. }
  234486. void WebBrowserComponent::goForward()
  234487. {
  234488. lastURL = String::empty;
  234489. browser->goForward();
  234490. }
  234491. void WebBrowserComponent::refresh()
  234492. {
  234493. browser->refresh();
  234494. }
  234495. void WebBrowserComponent::paint (Graphics&)
  234496. {
  234497. }
  234498. void WebBrowserComponent::checkWindowAssociation()
  234499. {
  234500. if (isShowing())
  234501. {
  234502. if (blankPageShown)
  234503. goBack();
  234504. }
  234505. else
  234506. {
  234507. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  234508. {
  234509. // when the component becomes invisible, some stuff like flash
  234510. // carries on playing audio, so we need to force it onto a blank
  234511. // page to avoid this, (and send it back when it's made visible again).
  234512. blankPageShown = true;
  234513. browser->goToURL ("about:blank", 0, 0);
  234514. }
  234515. }
  234516. }
  234517. void WebBrowserComponent::reloadLastURL()
  234518. {
  234519. if (lastURL.isNotEmpty())
  234520. {
  234521. goToURL (lastURL, &lastHeaders, &lastPostData);
  234522. lastURL = String::empty;
  234523. }
  234524. }
  234525. void WebBrowserComponent::parentHierarchyChanged()
  234526. {
  234527. checkWindowAssociation();
  234528. }
  234529. void WebBrowserComponent::resized()
  234530. {
  234531. browser->setSize (getWidth(), getHeight());
  234532. }
  234533. void WebBrowserComponent::visibilityChanged()
  234534. {
  234535. checkWindowAssociation();
  234536. }
  234537. bool WebBrowserComponent::pageAboutToLoad (const String&)
  234538. {
  234539. return true;
  234540. }
  234541. #else
  234542. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234543. {
  234544. }
  234545. WebBrowserComponent::~WebBrowserComponent()
  234546. {
  234547. }
  234548. void WebBrowserComponent::goToURL (const String& url,
  234549. const StringArray* headers,
  234550. const MemoryBlock* postData)
  234551. {
  234552. }
  234553. void WebBrowserComponent::stop()
  234554. {
  234555. }
  234556. void WebBrowserComponent::goBack()
  234557. {
  234558. }
  234559. void WebBrowserComponent::goForward()
  234560. {
  234561. }
  234562. void WebBrowserComponent::refresh()
  234563. {
  234564. }
  234565. void WebBrowserComponent::paint (Graphics& g)
  234566. {
  234567. }
  234568. void WebBrowserComponent::checkWindowAssociation()
  234569. {
  234570. }
  234571. void WebBrowserComponent::reloadLastURL()
  234572. {
  234573. }
  234574. void WebBrowserComponent::parentHierarchyChanged()
  234575. {
  234576. }
  234577. void WebBrowserComponent::resized()
  234578. {
  234579. }
  234580. void WebBrowserComponent::visibilityChanged()
  234581. {
  234582. }
  234583. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  234584. {
  234585. return true;
  234586. }
  234587. #endif
  234588. #endif
  234589. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234590. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  234591. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234592. // compiled on its own).
  234593. #if JUCE_INCLUDED_FILE
  234594. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234595. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  234596. #endif
  234597. #undef log
  234598. #if JUCE_COREAUDIO_LOGGING_ENABLED
  234599. #define log(a) Logger::writeToLog (a)
  234600. #else
  234601. #define log(a)
  234602. #endif
  234603. #undef OK
  234604. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234605. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  234606. {
  234607. if (err == noErr)
  234608. return true;
  234609. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234610. jassertfalse;
  234611. return false;
  234612. }
  234613. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  234614. #else
  234615. #define OK(a) (a == noErr)
  234616. #endif
  234617. class CoreAudioInternal : public Timer
  234618. {
  234619. public:
  234620. CoreAudioInternal (AudioDeviceID id)
  234621. : inputLatency (0),
  234622. outputLatency (0),
  234623. callback (0),
  234624. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234625. audioProcID (0),
  234626. #endif
  234627. isSlaveDevice (false),
  234628. deviceID (id),
  234629. started (false),
  234630. sampleRate (0),
  234631. bufferSize (512),
  234632. numInputChans (0),
  234633. numOutputChans (0),
  234634. callbacksAllowed (true),
  234635. numInputChannelInfos (0),
  234636. numOutputChannelInfos (0)
  234637. {
  234638. jassert (deviceID != 0);
  234639. updateDetailsFromDevice();
  234640. AudioObjectPropertyAddress pa;
  234641. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234642. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234643. pa.mElement = kAudioObjectPropertyElementWildcard;
  234644. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  234645. }
  234646. ~CoreAudioInternal()
  234647. {
  234648. AudioObjectPropertyAddress pa;
  234649. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234650. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234651. pa.mElement = kAudioObjectPropertyElementWildcard;
  234652. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  234653. stop (false);
  234654. }
  234655. void allocateTempBuffers()
  234656. {
  234657. const int tempBufSize = bufferSize + 4;
  234658. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  234659. tempInputBuffers.calloc (numInputChans + 2);
  234660. tempOutputBuffers.calloc (numOutputChans + 2);
  234661. int i, count = 0;
  234662. for (i = 0; i < numInputChans; ++i)
  234663. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234664. for (i = 0; i < numOutputChans; ++i)
  234665. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234666. }
  234667. // returns the number of actual available channels
  234668. void fillInChannelInfo (const bool input)
  234669. {
  234670. int chanNum = 0;
  234671. UInt32 size;
  234672. AudioObjectPropertyAddress pa;
  234673. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234674. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234675. pa.mElement = kAudioObjectPropertyElementMaster;
  234676. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234677. {
  234678. HeapBlock <AudioBufferList> bufList;
  234679. bufList.calloc (size, 1);
  234680. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234681. {
  234682. const int numStreams = bufList->mNumberBuffers;
  234683. for (int i = 0; i < numStreams; ++i)
  234684. {
  234685. const AudioBuffer& b = bufList->mBuffers[i];
  234686. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  234687. {
  234688. String name;
  234689. {
  234690. char channelName [256];
  234691. zerostruct (channelName);
  234692. UInt32 nameSize = sizeof (channelName);
  234693. UInt32 channelNum = chanNum + 1;
  234694. pa.mSelector = kAudioDevicePropertyChannelName;
  234695. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  234696. name = String::fromUTF8 (channelName, nameSize);
  234697. }
  234698. if (input)
  234699. {
  234700. if (activeInputChans[chanNum])
  234701. {
  234702. inputChannelInfo [numInputChannelInfos].streamNum = i;
  234703. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  234704. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234705. ++numInputChannelInfos;
  234706. }
  234707. if (name.isEmpty())
  234708. name << "Input " << (chanNum + 1);
  234709. inChanNames.add (name);
  234710. }
  234711. else
  234712. {
  234713. if (activeOutputChans[chanNum])
  234714. {
  234715. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  234716. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  234717. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234718. ++numOutputChannelInfos;
  234719. }
  234720. if (name.isEmpty())
  234721. name << "Output " << (chanNum + 1);
  234722. outChanNames.add (name);
  234723. }
  234724. ++chanNum;
  234725. }
  234726. }
  234727. }
  234728. }
  234729. }
  234730. void updateDetailsFromDevice()
  234731. {
  234732. stopTimer();
  234733. if (deviceID == 0)
  234734. return;
  234735. const ScopedLock sl (callbackLock);
  234736. Float64 sr;
  234737. UInt32 size = sizeof (Float64);
  234738. AudioObjectPropertyAddress pa;
  234739. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234740. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234741. pa.mElement = kAudioObjectPropertyElementMaster;
  234742. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  234743. sampleRate = sr;
  234744. UInt32 framesPerBuf;
  234745. size = sizeof (framesPerBuf);
  234746. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234747. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  234748. {
  234749. bufferSize = framesPerBuf;
  234750. allocateTempBuffers();
  234751. }
  234752. bufferSizes.clear();
  234753. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  234754. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234755. {
  234756. HeapBlock <AudioValueRange> ranges;
  234757. ranges.calloc (size, 1);
  234758. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234759. {
  234760. bufferSizes.add ((int) ranges[0].mMinimum);
  234761. for (int i = 32; i < 2048; i += 32)
  234762. {
  234763. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234764. {
  234765. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  234766. {
  234767. bufferSizes.addIfNotAlreadyThere (i);
  234768. break;
  234769. }
  234770. }
  234771. }
  234772. if (bufferSize > 0)
  234773. bufferSizes.addIfNotAlreadyThere (bufferSize);
  234774. }
  234775. }
  234776. if (bufferSizes.size() == 0 && bufferSize > 0)
  234777. bufferSizes.add (bufferSize);
  234778. sampleRates.clear();
  234779. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  234780. String rates;
  234781. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  234782. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234783. {
  234784. HeapBlock <AudioValueRange> ranges;
  234785. ranges.calloc (size, 1);
  234786. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234787. {
  234788. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  234789. {
  234790. bool ok = false;
  234791. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234792. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  234793. ok = true;
  234794. if (ok)
  234795. {
  234796. sampleRates.add (possibleRates[i]);
  234797. rates << possibleRates[i] << ' ';
  234798. }
  234799. }
  234800. }
  234801. }
  234802. if (sampleRates.size() == 0 && sampleRate > 0)
  234803. {
  234804. sampleRates.add (sampleRate);
  234805. rates << sampleRate;
  234806. }
  234807. log ("sr: " + rates);
  234808. inputLatency = 0;
  234809. outputLatency = 0;
  234810. UInt32 lat;
  234811. size = sizeof (lat);
  234812. pa.mSelector = kAudioDevicePropertyLatency;
  234813. pa.mScope = kAudioDevicePropertyScopeInput;
  234814. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234815. inputLatency = (int) lat;
  234816. pa.mScope = kAudioDevicePropertyScopeOutput;
  234817. size = sizeof (lat);
  234818. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234819. outputLatency = (int) lat;
  234820. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  234821. inChanNames.clear();
  234822. outChanNames.clear();
  234823. inputChannelInfo.calloc (numInputChans + 2);
  234824. numInputChannelInfos = 0;
  234825. outputChannelInfo.calloc (numOutputChans + 2);
  234826. numOutputChannelInfos = 0;
  234827. fillInChannelInfo (true);
  234828. fillInChannelInfo (false);
  234829. }
  234830. const StringArray getSources (bool input)
  234831. {
  234832. StringArray s;
  234833. HeapBlock <OSType> types;
  234834. const int num = getAllDataSourcesForDevice (deviceID, types);
  234835. for (int i = 0; i < num; ++i)
  234836. {
  234837. AudioValueTranslation avt;
  234838. char buffer[256];
  234839. avt.mInputData = &(types[i]);
  234840. avt.mInputDataSize = sizeof (UInt32);
  234841. avt.mOutputData = buffer;
  234842. avt.mOutputDataSize = 256;
  234843. UInt32 transSize = sizeof (avt);
  234844. AudioObjectPropertyAddress pa;
  234845. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  234846. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234847. pa.mElement = kAudioObjectPropertyElementMaster;
  234848. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  234849. {
  234850. DBG (buffer);
  234851. s.add (buffer);
  234852. }
  234853. }
  234854. return s;
  234855. }
  234856. int getCurrentSourceIndex (bool input) const
  234857. {
  234858. OSType currentSourceID = 0;
  234859. UInt32 size = sizeof (currentSourceID);
  234860. int result = -1;
  234861. AudioObjectPropertyAddress pa;
  234862. pa.mSelector = kAudioDevicePropertyDataSource;
  234863. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234864. pa.mElement = kAudioObjectPropertyElementMaster;
  234865. if (deviceID != 0)
  234866. {
  234867. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  234868. {
  234869. HeapBlock <OSType> types;
  234870. const int num = getAllDataSourcesForDevice (deviceID, types);
  234871. for (int i = 0; i < num; ++i)
  234872. {
  234873. if (types[num] == currentSourceID)
  234874. {
  234875. result = i;
  234876. break;
  234877. }
  234878. }
  234879. }
  234880. }
  234881. return result;
  234882. }
  234883. void setCurrentSourceIndex (int index, bool input)
  234884. {
  234885. if (deviceID != 0)
  234886. {
  234887. HeapBlock <OSType> types;
  234888. const int num = getAllDataSourcesForDevice (deviceID, types);
  234889. if (isPositiveAndBelow (index, num))
  234890. {
  234891. AudioObjectPropertyAddress pa;
  234892. pa.mSelector = kAudioDevicePropertyDataSource;
  234893. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234894. pa.mElement = kAudioObjectPropertyElementMaster;
  234895. OSType typeId = types[index];
  234896. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  234897. }
  234898. }
  234899. }
  234900. const String reopen (const BigInteger& inputChannels,
  234901. const BigInteger& outputChannels,
  234902. double newSampleRate,
  234903. int bufferSizeSamples)
  234904. {
  234905. String error;
  234906. log ("CoreAudio reopen");
  234907. callbacksAllowed = false;
  234908. stopTimer();
  234909. stop (false);
  234910. activeInputChans = inputChannels;
  234911. activeInputChans.setRange (inChanNames.size(),
  234912. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  234913. false);
  234914. activeOutputChans = outputChannels;
  234915. activeOutputChans.setRange (outChanNames.size(),
  234916. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  234917. false);
  234918. numInputChans = activeInputChans.countNumberOfSetBits();
  234919. numOutputChans = activeOutputChans.countNumberOfSetBits();
  234920. // set sample rate
  234921. AudioObjectPropertyAddress pa;
  234922. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234923. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234924. pa.mElement = kAudioObjectPropertyElementMaster;
  234925. Float64 sr = newSampleRate;
  234926. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  234927. {
  234928. error = "Couldn't change sample rate";
  234929. }
  234930. else
  234931. {
  234932. // change buffer size
  234933. UInt32 framesPerBuf = bufferSizeSamples;
  234934. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234935. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  234936. {
  234937. error = "Couldn't change buffer size";
  234938. }
  234939. else
  234940. {
  234941. // Annoyingly, after changing the rate and buffer size, some devices fail to
  234942. // correctly report their new settings until some random time in the future, so
  234943. // after calling updateDetailsFromDevice, we need to manually bodge these values
  234944. // to make sure we're using the correct numbers..
  234945. updateDetailsFromDevice();
  234946. sampleRate = newSampleRate;
  234947. bufferSize = bufferSizeSamples;
  234948. if (sampleRates.size() == 0)
  234949. error = "Device has no available sample-rates";
  234950. else if (bufferSizes.size() == 0)
  234951. error = "Device has no available buffer-sizes";
  234952. else if (inputDevice != 0)
  234953. error = inputDevice->reopen (inputChannels,
  234954. outputChannels,
  234955. newSampleRate,
  234956. bufferSizeSamples);
  234957. }
  234958. }
  234959. callbacksAllowed = true;
  234960. return error;
  234961. }
  234962. bool start (AudioIODeviceCallback* cb)
  234963. {
  234964. if (! started)
  234965. {
  234966. callback = 0;
  234967. if (deviceID != 0)
  234968. {
  234969. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234970. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  234971. #else
  234972. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  234973. #endif
  234974. {
  234975. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  234976. {
  234977. started = true;
  234978. }
  234979. else
  234980. {
  234981. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234982. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234983. #else
  234984. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234985. audioProcID = 0;
  234986. #endif
  234987. }
  234988. }
  234989. }
  234990. }
  234991. if (started)
  234992. {
  234993. const ScopedLock sl (callbackLock);
  234994. callback = cb;
  234995. }
  234996. if (inputDevice != 0)
  234997. return started && inputDevice->start (cb);
  234998. else
  234999. return started;
  235000. }
  235001. void stop (bool leaveInterruptRunning)
  235002. {
  235003. {
  235004. const ScopedLock sl (callbackLock);
  235005. callback = 0;
  235006. }
  235007. if (started
  235008. && (deviceID != 0)
  235009. && ! leaveInterruptRunning)
  235010. {
  235011. OK (AudioDeviceStop (deviceID, audioIOProc));
  235012. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235013. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235014. #else
  235015. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235016. audioProcID = 0;
  235017. #endif
  235018. started = false;
  235019. { const ScopedLock sl (callbackLock); }
  235020. // wait until it's definately stopped calling back..
  235021. for (int i = 40; --i >= 0;)
  235022. {
  235023. Thread::sleep (50);
  235024. UInt32 running = 0;
  235025. UInt32 size = sizeof (running);
  235026. AudioObjectPropertyAddress pa;
  235027. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235028. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235029. pa.mElement = kAudioObjectPropertyElementMaster;
  235030. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235031. if (running == 0)
  235032. break;
  235033. }
  235034. const ScopedLock sl (callbackLock);
  235035. }
  235036. if (inputDevice != 0)
  235037. inputDevice->stop (leaveInterruptRunning);
  235038. }
  235039. double getSampleRate() const
  235040. {
  235041. return sampleRate;
  235042. }
  235043. int getBufferSize() const
  235044. {
  235045. return bufferSize;
  235046. }
  235047. void audioCallback (const AudioBufferList* inInputData,
  235048. AudioBufferList* outOutputData)
  235049. {
  235050. int i;
  235051. const ScopedLock sl (callbackLock);
  235052. if (callback != 0)
  235053. {
  235054. if (inputDevice == 0)
  235055. {
  235056. for (i = numInputChans; --i >= 0;)
  235057. {
  235058. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235059. float* dest = tempInputBuffers [i];
  235060. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235061. + info.dataOffsetSamples;
  235062. const int stride = info.dataStrideSamples;
  235063. if (stride != 0) // if this is zero, info is invalid
  235064. {
  235065. for (int j = bufferSize; --j >= 0;)
  235066. {
  235067. *dest++ = *src;
  235068. src += stride;
  235069. }
  235070. }
  235071. }
  235072. }
  235073. if (! isSlaveDevice)
  235074. {
  235075. if (inputDevice == 0)
  235076. {
  235077. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235078. numInputChans,
  235079. tempOutputBuffers,
  235080. numOutputChans,
  235081. bufferSize);
  235082. }
  235083. else
  235084. {
  235085. jassert (inputDevice->bufferSize == bufferSize);
  235086. // Sometimes the two linked devices seem to get their callbacks in
  235087. // parallel, so we need to lock both devices to stop the input data being
  235088. // changed while inside our callback..
  235089. const ScopedLock sl2 (inputDevice->callbackLock);
  235090. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235091. inputDevice->numInputChans,
  235092. tempOutputBuffers,
  235093. numOutputChans,
  235094. bufferSize);
  235095. }
  235096. for (i = numOutputChans; --i >= 0;)
  235097. {
  235098. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235099. const float* src = tempOutputBuffers [i];
  235100. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235101. + info.dataOffsetSamples;
  235102. const int stride = info.dataStrideSamples;
  235103. if (stride != 0) // if this is zero, info is invalid
  235104. {
  235105. for (int j = bufferSize; --j >= 0;)
  235106. {
  235107. *dest = *src++;
  235108. dest += stride;
  235109. }
  235110. }
  235111. }
  235112. }
  235113. }
  235114. else
  235115. {
  235116. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235117. {
  235118. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235119. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235120. + info.dataOffsetSamples;
  235121. const int stride = info.dataStrideSamples;
  235122. if (stride != 0) // if this is zero, info is invalid
  235123. {
  235124. for (int j = bufferSize; --j >= 0;)
  235125. {
  235126. *dest = 0.0f;
  235127. dest += stride;
  235128. }
  235129. }
  235130. }
  235131. }
  235132. }
  235133. // called by callbacks
  235134. void deviceDetailsChanged()
  235135. {
  235136. if (callbacksAllowed)
  235137. startTimer (100);
  235138. }
  235139. void timerCallback()
  235140. {
  235141. stopTimer();
  235142. log ("CoreAudio device changed callback");
  235143. const double oldSampleRate = sampleRate;
  235144. const int oldBufferSize = bufferSize;
  235145. updateDetailsFromDevice();
  235146. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235147. {
  235148. callbacksAllowed = false;
  235149. stop (false);
  235150. updateDetailsFromDevice();
  235151. callbacksAllowed = true;
  235152. }
  235153. }
  235154. CoreAudioInternal* getRelatedDevice() const
  235155. {
  235156. UInt32 size = 0;
  235157. ScopedPointer <CoreAudioInternal> result;
  235158. AudioObjectPropertyAddress pa;
  235159. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235160. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235161. pa.mElement = kAudioObjectPropertyElementMaster;
  235162. if (deviceID != 0
  235163. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235164. && size > 0)
  235165. {
  235166. HeapBlock <AudioDeviceID> devs;
  235167. devs.calloc (size, 1);
  235168. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235169. {
  235170. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235171. {
  235172. if (devs[i] != deviceID && devs[i] != 0)
  235173. {
  235174. result = new CoreAudioInternal (devs[i]);
  235175. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235176. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235177. if (thisIsInput != otherIsInput
  235178. || (inChanNames.size() + outChanNames.size() == 0)
  235179. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235180. break;
  235181. result = 0;
  235182. }
  235183. }
  235184. }
  235185. }
  235186. return result.release();
  235187. }
  235188. int inputLatency, outputLatency;
  235189. BigInteger activeInputChans, activeOutputChans;
  235190. StringArray inChanNames, outChanNames;
  235191. Array <double> sampleRates;
  235192. Array <int> bufferSizes;
  235193. AudioIODeviceCallback* callback;
  235194. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235195. AudioDeviceIOProcID audioProcID;
  235196. #endif
  235197. ScopedPointer<CoreAudioInternal> inputDevice;
  235198. bool isSlaveDevice;
  235199. private:
  235200. CriticalSection callbackLock;
  235201. AudioDeviceID deviceID;
  235202. bool started;
  235203. double sampleRate;
  235204. int bufferSize;
  235205. HeapBlock <float> audioBuffer;
  235206. int numInputChans, numOutputChans;
  235207. bool callbacksAllowed;
  235208. struct CallbackDetailsForChannel
  235209. {
  235210. int streamNum;
  235211. int dataOffsetSamples;
  235212. int dataStrideSamples;
  235213. };
  235214. int numInputChannelInfos, numOutputChannelInfos;
  235215. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235216. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235217. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235218. const AudioTimeStamp* /*inNow*/,
  235219. const AudioBufferList* inInputData,
  235220. const AudioTimeStamp* /*inInputTime*/,
  235221. AudioBufferList* outOutputData,
  235222. const AudioTimeStamp* /*inOutputTime*/,
  235223. void* device)
  235224. {
  235225. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235226. return noErr;
  235227. }
  235228. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235229. {
  235230. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235231. switch (pa->mSelector)
  235232. {
  235233. case kAudioDevicePropertyBufferSize:
  235234. case kAudioDevicePropertyBufferFrameSize:
  235235. case kAudioDevicePropertyNominalSampleRate:
  235236. case kAudioDevicePropertyStreamFormat:
  235237. case kAudioDevicePropertyDeviceIsAlive:
  235238. intern->deviceDetailsChanged();
  235239. break;
  235240. case kAudioDevicePropertyBufferSizeRange:
  235241. case kAudioDevicePropertyVolumeScalar:
  235242. case kAudioDevicePropertyMute:
  235243. case kAudioDevicePropertyPlayThru:
  235244. case kAudioDevicePropertyDataSource:
  235245. case kAudioDevicePropertyDeviceIsRunning:
  235246. break;
  235247. }
  235248. return noErr;
  235249. }
  235250. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235251. {
  235252. AudioObjectPropertyAddress pa;
  235253. pa.mSelector = kAudioDevicePropertyDataSources;
  235254. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235255. pa.mElement = kAudioObjectPropertyElementMaster;
  235256. UInt32 size = 0;
  235257. if (deviceID != 0
  235258. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235259. {
  235260. types.calloc (size, 1);
  235261. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235262. return size / (int) sizeof (OSType);
  235263. }
  235264. return 0;
  235265. }
  235266. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235267. };
  235268. class CoreAudioIODevice : public AudioIODevice
  235269. {
  235270. public:
  235271. CoreAudioIODevice (const String& deviceName,
  235272. AudioDeviceID inputDeviceId,
  235273. const int inputIndex_,
  235274. AudioDeviceID outputDeviceId,
  235275. const int outputIndex_)
  235276. : AudioIODevice (deviceName, "CoreAudio"),
  235277. inputIndex (inputIndex_),
  235278. outputIndex (outputIndex_),
  235279. isOpen_ (false),
  235280. isStarted (false)
  235281. {
  235282. CoreAudioInternal* device = 0;
  235283. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235284. {
  235285. jassert (inputDeviceId != 0);
  235286. device = new CoreAudioInternal (inputDeviceId);
  235287. }
  235288. else
  235289. {
  235290. device = new CoreAudioInternal (outputDeviceId);
  235291. if (inputDeviceId != 0)
  235292. {
  235293. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235294. device->inputDevice = secondDevice;
  235295. secondDevice->isSlaveDevice = true;
  235296. }
  235297. }
  235298. internal = device;
  235299. AudioObjectPropertyAddress pa;
  235300. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235301. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235302. pa.mElement = kAudioObjectPropertyElementWildcard;
  235303. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235304. }
  235305. ~CoreAudioIODevice()
  235306. {
  235307. AudioObjectPropertyAddress pa;
  235308. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235309. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235310. pa.mElement = kAudioObjectPropertyElementWildcard;
  235311. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235312. }
  235313. const StringArray getOutputChannelNames()
  235314. {
  235315. return internal->outChanNames;
  235316. }
  235317. const StringArray getInputChannelNames()
  235318. {
  235319. if (internal->inputDevice != 0)
  235320. return internal->inputDevice->inChanNames;
  235321. else
  235322. return internal->inChanNames;
  235323. }
  235324. int getNumSampleRates()
  235325. {
  235326. return internal->sampleRates.size();
  235327. }
  235328. double getSampleRate (int index)
  235329. {
  235330. return internal->sampleRates [index];
  235331. }
  235332. int getNumBufferSizesAvailable()
  235333. {
  235334. return internal->bufferSizes.size();
  235335. }
  235336. int getBufferSizeSamples (int index)
  235337. {
  235338. return internal->bufferSizes [index];
  235339. }
  235340. int getDefaultBufferSize()
  235341. {
  235342. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235343. if (getBufferSizeSamples(i) >= 512)
  235344. return getBufferSizeSamples(i);
  235345. return 512;
  235346. }
  235347. const String open (const BigInteger& inputChannels,
  235348. const BigInteger& outputChannels,
  235349. double sampleRate,
  235350. int bufferSizeSamples)
  235351. {
  235352. isOpen_ = true;
  235353. if (bufferSizeSamples <= 0)
  235354. bufferSizeSamples = getDefaultBufferSize();
  235355. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235356. isOpen_ = lastError.isEmpty();
  235357. return lastError;
  235358. }
  235359. void close()
  235360. {
  235361. isOpen_ = false;
  235362. internal->stop (false);
  235363. }
  235364. bool isOpen()
  235365. {
  235366. return isOpen_;
  235367. }
  235368. int getCurrentBufferSizeSamples()
  235369. {
  235370. return internal != 0 ? internal->getBufferSize() : 512;
  235371. }
  235372. double getCurrentSampleRate()
  235373. {
  235374. return internal != 0 ? internal->getSampleRate() : 0;
  235375. }
  235376. int getCurrentBitDepth()
  235377. {
  235378. return 32; // no way to find out, so just assume it's high..
  235379. }
  235380. const BigInteger getActiveOutputChannels() const
  235381. {
  235382. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235383. }
  235384. const BigInteger getActiveInputChannels() const
  235385. {
  235386. BigInteger chans;
  235387. if (internal != 0)
  235388. {
  235389. chans = internal->activeInputChans;
  235390. if (internal->inputDevice != 0)
  235391. chans |= internal->inputDevice->activeInputChans;
  235392. }
  235393. return chans;
  235394. }
  235395. int getOutputLatencyInSamples()
  235396. {
  235397. if (internal == 0)
  235398. return 0;
  235399. // this seems like a good guess at getting the latency right - comparing
  235400. // this with a round-trip measurement, it gets it to within a few millisecs
  235401. // for the built-in mac soundcard
  235402. return internal->outputLatency + internal->getBufferSize() * 2;
  235403. }
  235404. int getInputLatencyInSamples()
  235405. {
  235406. if (internal == 0)
  235407. return 0;
  235408. return internal->inputLatency + internal->getBufferSize() * 2;
  235409. }
  235410. void start (AudioIODeviceCallback* callback)
  235411. {
  235412. if (internal != 0 && ! isStarted)
  235413. {
  235414. if (callback != 0)
  235415. callback->audioDeviceAboutToStart (this);
  235416. isStarted = true;
  235417. internal->start (callback);
  235418. }
  235419. }
  235420. void stop()
  235421. {
  235422. if (isStarted && internal != 0)
  235423. {
  235424. AudioIODeviceCallback* const lastCallback = internal->callback;
  235425. isStarted = false;
  235426. internal->stop (true);
  235427. if (lastCallback != 0)
  235428. lastCallback->audioDeviceStopped();
  235429. }
  235430. }
  235431. bool isPlaying()
  235432. {
  235433. if (internal->callback == 0)
  235434. isStarted = false;
  235435. return isStarted;
  235436. }
  235437. const String getLastError()
  235438. {
  235439. return lastError;
  235440. }
  235441. int inputIndex, outputIndex;
  235442. private:
  235443. ScopedPointer<CoreAudioInternal> internal;
  235444. bool isOpen_, isStarted;
  235445. String lastError;
  235446. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235447. {
  235448. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235449. switch (pa->mSelector)
  235450. {
  235451. case kAudioHardwarePropertyDevices:
  235452. intern->deviceDetailsChanged();
  235453. break;
  235454. case kAudioHardwarePropertyDefaultOutputDevice:
  235455. case kAudioHardwarePropertyDefaultInputDevice:
  235456. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  235457. break;
  235458. }
  235459. return noErr;
  235460. }
  235461. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  235462. };
  235463. class CoreAudioIODeviceType : public AudioIODeviceType
  235464. {
  235465. public:
  235466. CoreAudioIODeviceType()
  235467. : AudioIODeviceType ("CoreAudio"),
  235468. hasScanned (false)
  235469. {
  235470. }
  235471. ~CoreAudioIODeviceType()
  235472. {
  235473. }
  235474. void scanForDevices()
  235475. {
  235476. hasScanned = true;
  235477. inputDeviceNames.clear();
  235478. outputDeviceNames.clear();
  235479. inputIds.clear();
  235480. outputIds.clear();
  235481. UInt32 size;
  235482. AudioObjectPropertyAddress pa;
  235483. pa.mSelector = kAudioHardwarePropertyDevices;
  235484. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235485. pa.mElement = kAudioObjectPropertyElementMaster;
  235486. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  235487. {
  235488. HeapBlock <AudioDeviceID> devs;
  235489. devs.calloc (size, 1);
  235490. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  235491. {
  235492. const int num = size / (int) sizeof (AudioDeviceID);
  235493. for (int i = 0; i < num; ++i)
  235494. {
  235495. char name [1024];
  235496. size = sizeof (name);
  235497. pa.mSelector = kAudioDevicePropertyDeviceName;
  235498. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  235499. {
  235500. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  235501. const int numIns = getNumChannels (devs[i], true);
  235502. const int numOuts = getNumChannels (devs[i], false);
  235503. if (numIns > 0)
  235504. {
  235505. inputDeviceNames.add (nameString);
  235506. inputIds.add (devs[i]);
  235507. }
  235508. if (numOuts > 0)
  235509. {
  235510. outputDeviceNames.add (nameString);
  235511. outputIds.add (devs[i]);
  235512. }
  235513. }
  235514. }
  235515. }
  235516. }
  235517. inputDeviceNames.appendNumbersToDuplicates (false, true);
  235518. outputDeviceNames.appendNumbersToDuplicates (false, true);
  235519. }
  235520. const StringArray getDeviceNames (bool wantInputNames) const
  235521. {
  235522. jassert (hasScanned); // need to call scanForDevices() before doing this
  235523. if (wantInputNames)
  235524. return inputDeviceNames;
  235525. else
  235526. return outputDeviceNames;
  235527. }
  235528. int getDefaultDeviceIndex (bool forInput) const
  235529. {
  235530. jassert (hasScanned); // need to call scanForDevices() before doing this
  235531. AudioDeviceID deviceID;
  235532. UInt32 size = sizeof (deviceID);
  235533. // if they're asking for any input channels at all, use the default input, so we
  235534. // get the built-in mic rather than the built-in output with no inputs..
  235535. AudioObjectPropertyAddress pa;
  235536. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  235537. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235538. pa.mElement = kAudioObjectPropertyElementMaster;
  235539. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  235540. {
  235541. if (forInput)
  235542. {
  235543. for (int i = inputIds.size(); --i >= 0;)
  235544. if (inputIds[i] == deviceID)
  235545. return i;
  235546. }
  235547. else
  235548. {
  235549. for (int i = outputIds.size(); --i >= 0;)
  235550. if (outputIds[i] == deviceID)
  235551. return i;
  235552. }
  235553. }
  235554. return 0;
  235555. }
  235556. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  235557. {
  235558. jassert (hasScanned); // need to call scanForDevices() before doing this
  235559. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  235560. if (d == 0)
  235561. return -1;
  235562. return asInput ? d->inputIndex
  235563. : d->outputIndex;
  235564. }
  235565. bool hasSeparateInputsAndOutputs() const { return true; }
  235566. AudioIODevice* createDevice (const String& outputDeviceName,
  235567. const String& inputDeviceName)
  235568. {
  235569. jassert (hasScanned); // need to call scanForDevices() before doing this
  235570. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  235571. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  235572. String deviceName (outputDeviceName);
  235573. if (deviceName.isEmpty())
  235574. deviceName = inputDeviceName;
  235575. if (index >= 0)
  235576. return new CoreAudioIODevice (deviceName,
  235577. inputIds [inputIndex],
  235578. inputIndex,
  235579. outputIds [outputIndex],
  235580. outputIndex);
  235581. return 0;
  235582. }
  235583. private:
  235584. StringArray inputDeviceNames, outputDeviceNames;
  235585. Array <AudioDeviceID> inputIds, outputIds;
  235586. bool hasScanned;
  235587. static int getNumChannels (AudioDeviceID deviceID, bool input)
  235588. {
  235589. int total = 0;
  235590. UInt32 size;
  235591. AudioObjectPropertyAddress pa;
  235592. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235593. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235594. pa.mElement = kAudioObjectPropertyElementMaster;
  235595. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235596. {
  235597. HeapBlock <AudioBufferList> bufList;
  235598. bufList.calloc (size, 1);
  235599. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235600. {
  235601. const int numStreams = bufList->mNumberBuffers;
  235602. for (int i = 0; i < numStreams; ++i)
  235603. {
  235604. const AudioBuffer& b = bufList->mBuffers[i];
  235605. total += b.mNumberChannels;
  235606. }
  235607. }
  235608. }
  235609. return total;
  235610. }
  235611. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  235612. };
  235613. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  235614. {
  235615. return new CoreAudioIODeviceType();
  235616. }
  235617. #undef log
  235618. #endif
  235619. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  235620. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  235621. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235622. // compiled on its own).
  235623. #if JUCE_INCLUDED_FILE
  235624. #if JUCE_MAC
  235625. namespace CoreMidiHelpers
  235626. {
  235627. bool logError (const OSStatus err, const int lineNum)
  235628. {
  235629. if (err == noErr)
  235630. return true;
  235631. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235632. jassertfalse;
  235633. return false;
  235634. }
  235635. #undef CHECK_ERROR
  235636. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  235637. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  235638. {
  235639. String result;
  235640. CFStringRef str = 0;
  235641. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  235642. if (str != 0)
  235643. {
  235644. result = PlatformUtilities::cfStringToJuceString (str);
  235645. CFRelease (str);
  235646. str = 0;
  235647. }
  235648. MIDIEntityRef entity = 0;
  235649. MIDIEndpointGetEntity (endpoint, &entity);
  235650. if (entity == 0)
  235651. return result; // probably virtual
  235652. if (result.isEmpty())
  235653. {
  235654. // endpoint name has zero length - try the entity
  235655. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  235656. if (str != 0)
  235657. {
  235658. result += PlatformUtilities::cfStringToJuceString (str);
  235659. CFRelease (str);
  235660. str = 0;
  235661. }
  235662. }
  235663. // now consider the device's name
  235664. MIDIDeviceRef device = 0;
  235665. MIDIEntityGetDevice (entity, &device);
  235666. if (device == 0)
  235667. return result;
  235668. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  235669. if (str != 0)
  235670. {
  235671. const String s (PlatformUtilities::cfStringToJuceString (str));
  235672. CFRelease (str);
  235673. // if an external device has only one entity, throw away
  235674. // the endpoint name and just use the device name
  235675. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  235676. {
  235677. result = s;
  235678. }
  235679. else if (! result.startsWithIgnoreCase (s))
  235680. {
  235681. // prepend the device name to the entity name
  235682. result = (s + " " + result).trimEnd();
  235683. }
  235684. }
  235685. return result;
  235686. }
  235687. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  235688. {
  235689. String result;
  235690. // Does the endpoint have connections?
  235691. CFDataRef connections = 0;
  235692. int numConnections = 0;
  235693. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  235694. if (connections != 0)
  235695. {
  235696. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  235697. if (numConnections > 0)
  235698. {
  235699. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  235700. for (int i = 0; i < numConnections; ++i, ++pid)
  235701. {
  235702. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  235703. MIDIObjectRef connObject;
  235704. MIDIObjectType connObjectType;
  235705. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  235706. if (err == noErr)
  235707. {
  235708. String s;
  235709. if (connObjectType == kMIDIObjectType_ExternalSource
  235710. || connObjectType == kMIDIObjectType_ExternalDestination)
  235711. {
  235712. // Connected to an external device's endpoint (10.3 and later).
  235713. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  235714. }
  235715. else
  235716. {
  235717. // Connected to an external device (10.2) (or something else, catch-all)
  235718. CFStringRef str = 0;
  235719. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  235720. if (str != 0)
  235721. {
  235722. s = PlatformUtilities::cfStringToJuceString (str);
  235723. CFRelease (str);
  235724. }
  235725. }
  235726. if (s.isNotEmpty())
  235727. {
  235728. if (result.isNotEmpty())
  235729. result += ", ";
  235730. result += s;
  235731. }
  235732. }
  235733. }
  235734. }
  235735. CFRelease (connections);
  235736. }
  235737. if (result.isNotEmpty())
  235738. return result;
  235739. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  235740. return getEndpointName (endpoint, false);
  235741. }
  235742. MIDIClientRef getGlobalMidiClient()
  235743. {
  235744. static MIDIClientRef globalMidiClient = 0;
  235745. if (globalMidiClient == 0)
  235746. {
  235747. String name ("JUCE");
  235748. if (JUCEApplication::getInstance() != 0)
  235749. name = JUCEApplication::getInstance()->getApplicationName();
  235750. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  235751. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  235752. CFRelease (appName);
  235753. }
  235754. return globalMidiClient;
  235755. }
  235756. class MidiPortAndEndpoint
  235757. {
  235758. public:
  235759. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  235760. : port (port_), endPoint (endPoint_)
  235761. {
  235762. }
  235763. ~MidiPortAndEndpoint()
  235764. {
  235765. if (port != 0)
  235766. MIDIPortDispose (port);
  235767. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  235768. MIDIEndpointDispose (endPoint);
  235769. }
  235770. void send (const MIDIPacketList* const packets)
  235771. {
  235772. if (port != 0)
  235773. MIDISend (port, endPoint, packets);
  235774. else
  235775. MIDIReceived (endPoint, packets);
  235776. }
  235777. MIDIPortRef port;
  235778. MIDIEndpointRef endPoint;
  235779. };
  235780. class MidiPortAndCallback;
  235781. CriticalSection callbackLock;
  235782. Array<MidiPortAndCallback*> activeCallbacks;
  235783. class MidiPortAndCallback
  235784. {
  235785. public:
  235786. MidiPortAndCallback (MidiInputCallback& callback_)
  235787. : input (0), active (false), callback (callback_), concatenator (2048)
  235788. {
  235789. }
  235790. ~MidiPortAndCallback()
  235791. {
  235792. active = false;
  235793. {
  235794. const ScopedLock sl (callbackLock);
  235795. activeCallbacks.removeValue (this);
  235796. }
  235797. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  235798. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  235799. }
  235800. void handlePackets (const MIDIPacketList* const pktlist)
  235801. {
  235802. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  235803. const ScopedLock sl (callbackLock);
  235804. if (activeCallbacks.contains (this) && active)
  235805. {
  235806. const MIDIPacket* packet = &pktlist->packet[0];
  235807. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235808. {
  235809. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  235810. input, callback);
  235811. packet = MIDIPacketNext (packet);
  235812. }
  235813. }
  235814. }
  235815. MidiInput* input;
  235816. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  235817. volatile bool active;
  235818. private:
  235819. MidiInputCallback& callback;
  235820. MidiDataConcatenator concatenator;
  235821. };
  235822. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  235823. {
  235824. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  235825. }
  235826. }
  235827. const StringArray MidiOutput::getDevices()
  235828. {
  235829. StringArray s;
  235830. const ItemCount num = MIDIGetNumberOfDestinations();
  235831. for (ItemCount i = 0; i < num; ++i)
  235832. {
  235833. MIDIEndpointRef dest = MIDIGetDestination (i);
  235834. if (dest != 0)
  235835. {
  235836. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  235837. if (name.isEmpty())
  235838. name = "<error>";
  235839. s.add (name);
  235840. }
  235841. else
  235842. {
  235843. s.add ("<error>");
  235844. }
  235845. }
  235846. return s;
  235847. }
  235848. int MidiOutput::getDefaultDeviceIndex()
  235849. {
  235850. return 0;
  235851. }
  235852. MidiOutput* MidiOutput::openDevice (int index)
  235853. {
  235854. MidiOutput* mo = 0;
  235855. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  235856. {
  235857. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  235858. CFStringRef pname;
  235859. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235860. {
  235861. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235862. MIDIPortRef port;
  235863. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  235864. {
  235865. mo = new MidiOutput();
  235866. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  235867. }
  235868. CFRelease (pname);
  235869. }
  235870. }
  235871. return mo;
  235872. }
  235873. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  235874. {
  235875. MidiOutput* mo = 0;
  235876. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235877. MIDIEndpointRef endPoint;
  235878. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  235879. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  235880. {
  235881. mo = new MidiOutput();
  235882. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  235883. }
  235884. CFRelease (name);
  235885. return mo;
  235886. }
  235887. MidiOutput::~MidiOutput()
  235888. {
  235889. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235890. }
  235891. void MidiOutput::reset()
  235892. {
  235893. }
  235894. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235895. {
  235896. return false;
  235897. }
  235898. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235899. {
  235900. }
  235901. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235902. {
  235903. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235904. if (message.isSysEx())
  235905. {
  235906. const int maxPacketSize = 256;
  235907. int pos = 0, bytesLeft = message.getRawDataSize();
  235908. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  235909. HeapBlock <MIDIPacketList> packets;
  235910. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  235911. packets->numPackets = numPackets;
  235912. MIDIPacket* p = packets->packet;
  235913. for (int i = 0; i < numPackets; ++i)
  235914. {
  235915. p->timeStamp = AudioGetCurrentHostTime();
  235916. p->length = jmin (maxPacketSize, bytesLeft);
  235917. memcpy (p->data, message.getRawData() + pos, p->length);
  235918. pos += p->length;
  235919. bytesLeft -= p->length;
  235920. p = MIDIPacketNext (p);
  235921. }
  235922. mpe->send (packets);
  235923. }
  235924. else
  235925. {
  235926. MIDIPacketList packets;
  235927. packets.numPackets = 1;
  235928. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  235929. packets.packet[0].length = message.getRawDataSize();
  235930. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  235931. mpe->send (&packets);
  235932. }
  235933. }
  235934. const StringArray MidiInput::getDevices()
  235935. {
  235936. StringArray s;
  235937. const ItemCount num = MIDIGetNumberOfSources();
  235938. for (ItemCount i = 0; i < num; ++i)
  235939. {
  235940. MIDIEndpointRef source = MIDIGetSource (i);
  235941. if (source != 0)
  235942. {
  235943. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  235944. if (name.isEmpty())
  235945. name = "<error>";
  235946. s.add (name);
  235947. }
  235948. else
  235949. {
  235950. s.add ("<error>");
  235951. }
  235952. }
  235953. return s;
  235954. }
  235955. int MidiInput::getDefaultDeviceIndex()
  235956. {
  235957. return 0;
  235958. }
  235959. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235960. {
  235961. jassert (callback != 0);
  235962. using namespace CoreMidiHelpers;
  235963. MidiInput* newInput = 0;
  235964. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  235965. {
  235966. MIDIEndpointRef endPoint = MIDIGetSource (index);
  235967. if (endPoint != 0)
  235968. {
  235969. CFStringRef name;
  235970. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  235971. {
  235972. MIDIClientRef client = getGlobalMidiClient();
  235973. if (client != 0)
  235974. {
  235975. MIDIPortRef port;
  235976. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  235977. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  235978. {
  235979. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  235980. {
  235981. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  235982. newInput = new MidiInput (getDevices() [index]);
  235983. mpc->input = newInput;
  235984. newInput->internal = mpc;
  235985. const ScopedLock sl (callbackLock);
  235986. activeCallbacks.add (mpc.release());
  235987. }
  235988. else
  235989. {
  235990. CHECK_ERROR (MIDIPortDispose (port));
  235991. }
  235992. }
  235993. }
  235994. }
  235995. CFRelease (name);
  235996. }
  235997. }
  235998. return newInput;
  235999. }
  236000. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236001. {
  236002. jassert (callback != 0);
  236003. using namespace CoreMidiHelpers;
  236004. MidiInput* mi = 0;
  236005. MIDIClientRef client = getGlobalMidiClient();
  236006. if (client != 0)
  236007. {
  236008. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236009. mpc->active = false;
  236010. MIDIEndpointRef endPoint;
  236011. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236012. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236013. {
  236014. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236015. mi = new MidiInput (deviceName);
  236016. mpc->input = mi;
  236017. mi->internal = mpc;
  236018. const ScopedLock sl (callbackLock);
  236019. activeCallbacks.add (mpc.release());
  236020. }
  236021. CFRelease (name);
  236022. }
  236023. return mi;
  236024. }
  236025. MidiInput::MidiInput (const String& name_)
  236026. : name (name_)
  236027. {
  236028. }
  236029. MidiInput::~MidiInput()
  236030. {
  236031. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236032. }
  236033. void MidiInput::start()
  236034. {
  236035. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236036. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236037. }
  236038. void MidiInput::stop()
  236039. {
  236040. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236041. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236042. }
  236043. #undef CHECK_ERROR
  236044. #else // Stubs for iOS...
  236045. MidiOutput::~MidiOutput() {}
  236046. void MidiOutput::reset() {}
  236047. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236048. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236049. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236050. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236051. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236052. const StringArray MidiInput::getDevices() { return StringArray(); }
  236053. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236054. #endif
  236055. #endif
  236056. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236057. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236058. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236059. // compiled on its own).
  236060. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236061. #if ! JUCE_QUICKTIME
  236062. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236063. #endif
  236064. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236065. class QTCameraDeviceInteral;
  236066. END_JUCE_NAMESPACE
  236067. @interface QTCaptureCallbackDelegate : NSObject
  236068. {
  236069. @public
  236070. CameraDevice* owner;
  236071. QTCameraDeviceInteral* internal;
  236072. int64 firstPresentationTime;
  236073. int64 averageTimeOffset;
  236074. }
  236075. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236076. - (void) dealloc;
  236077. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236078. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236079. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236080. fromConnection: (QTCaptureConnection*) connection;
  236081. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236082. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236083. fromConnection: (QTCaptureConnection*) connection;
  236084. @end
  236085. BEGIN_JUCE_NAMESPACE
  236086. class QTCameraDeviceInteral
  236087. {
  236088. public:
  236089. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236090. {
  236091. const ScopedAutoReleasePool pool;
  236092. session = [[QTCaptureSession alloc] init];
  236093. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236094. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236095. input = 0;
  236096. audioInput = 0;
  236097. audioDevice = 0;
  236098. fileOutput = 0;
  236099. imageOutput = 0;
  236100. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236101. internalDev: this];
  236102. NSError* err = 0;
  236103. [device retain];
  236104. [device open: &err];
  236105. if (err == 0)
  236106. {
  236107. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236108. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236109. [session addInput: input error: &err];
  236110. if (err == 0)
  236111. {
  236112. resetFile();
  236113. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236114. [imageOutput setDelegate: callbackDelegate];
  236115. if (err == 0)
  236116. {
  236117. [session startRunning];
  236118. return;
  236119. }
  236120. }
  236121. }
  236122. openingError = nsStringToJuce ([err description]);
  236123. DBG (openingError);
  236124. }
  236125. ~QTCameraDeviceInteral()
  236126. {
  236127. [session stopRunning];
  236128. [session removeOutput: imageOutput];
  236129. [session release];
  236130. [input release];
  236131. [device release];
  236132. [audioDevice release];
  236133. [audioInput release];
  236134. [fileOutput release];
  236135. [imageOutput release];
  236136. [callbackDelegate release];
  236137. }
  236138. void resetFile()
  236139. {
  236140. [fileOutput recordToOutputFileURL: nil];
  236141. [session removeOutput: fileOutput];
  236142. [fileOutput release];
  236143. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236144. [session removeInput: audioInput];
  236145. [audioInput release];
  236146. audioInput = 0;
  236147. [audioDevice release];
  236148. audioDevice = 0;
  236149. [fileOutput setDelegate: callbackDelegate];
  236150. }
  236151. void addDefaultAudioInput()
  236152. {
  236153. NSError* err = nil;
  236154. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236155. if ([audioDevice open: &err])
  236156. [audioDevice retain];
  236157. else
  236158. audioDevice = nil;
  236159. if (audioDevice != 0)
  236160. {
  236161. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236162. [session addInput: audioInput error: &err];
  236163. }
  236164. }
  236165. void addListener (CameraDevice::Listener* listenerToAdd)
  236166. {
  236167. const ScopedLock sl (listenerLock);
  236168. if (listeners.size() == 0)
  236169. [session addOutput: imageOutput error: nil];
  236170. listeners.addIfNotAlreadyThere (listenerToAdd);
  236171. }
  236172. void removeListener (CameraDevice::Listener* listenerToRemove)
  236173. {
  236174. const ScopedLock sl (listenerLock);
  236175. listeners.removeValue (listenerToRemove);
  236176. if (listeners.size() == 0)
  236177. [session removeOutput: imageOutput];
  236178. }
  236179. void callListeners (CIImage* frame, int w, int h)
  236180. {
  236181. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236182. Image image (cgImage);
  236183. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236184. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236185. CGContextFlush (cgImage->context);
  236186. const ScopedLock sl (listenerLock);
  236187. for (int i = listeners.size(); --i >= 0;)
  236188. {
  236189. CameraDevice::Listener* const l = listeners[i];
  236190. if (l != 0)
  236191. l->imageReceived (image);
  236192. }
  236193. }
  236194. QTCaptureDevice* device;
  236195. QTCaptureDeviceInput* input;
  236196. QTCaptureDevice* audioDevice;
  236197. QTCaptureDeviceInput* audioInput;
  236198. QTCaptureSession* session;
  236199. QTCaptureMovieFileOutput* fileOutput;
  236200. QTCaptureDecompressedVideoOutput* imageOutput;
  236201. QTCaptureCallbackDelegate* callbackDelegate;
  236202. String openingError;
  236203. Array<CameraDevice::Listener*> listeners;
  236204. CriticalSection listenerLock;
  236205. };
  236206. END_JUCE_NAMESPACE
  236207. @implementation QTCaptureCallbackDelegate
  236208. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236209. internalDev: (QTCameraDeviceInteral*) d
  236210. {
  236211. [super init];
  236212. owner = owner_;
  236213. internal = d;
  236214. firstPresentationTime = 0;
  236215. averageTimeOffset = 0;
  236216. return self;
  236217. }
  236218. - (void) dealloc
  236219. {
  236220. [super dealloc];
  236221. }
  236222. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236223. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236224. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236225. fromConnection: (QTCaptureConnection*) connection
  236226. {
  236227. if (internal->listeners.size() > 0)
  236228. {
  236229. const ScopedAutoReleasePool pool;
  236230. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236231. CVPixelBufferGetWidth (videoFrame),
  236232. CVPixelBufferGetHeight (videoFrame));
  236233. }
  236234. }
  236235. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236236. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236237. fromConnection: (QTCaptureConnection*) connection
  236238. {
  236239. const Time now (Time::getCurrentTime());
  236240. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236241. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236242. #else
  236243. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236244. #endif
  236245. int64 presentationTime = (hosttime != nil)
  236246. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236247. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236248. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236249. if (firstPresentationTime == 0)
  236250. {
  236251. firstPresentationTime = presentationTime;
  236252. averageTimeOffset = timeDiff;
  236253. }
  236254. else
  236255. {
  236256. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236257. }
  236258. }
  236259. @end
  236260. BEGIN_JUCE_NAMESPACE
  236261. class QTCaptureViewerComp : public NSViewComponent
  236262. {
  236263. public:
  236264. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236265. {
  236266. const ScopedAutoReleasePool pool;
  236267. captureView = [[QTCaptureView alloc] init];
  236268. [captureView setCaptureSession: internal->session];
  236269. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236270. setView (captureView);
  236271. }
  236272. ~QTCaptureViewerComp()
  236273. {
  236274. setView (0);
  236275. [captureView setCaptureSession: nil];
  236276. [captureView release];
  236277. }
  236278. QTCaptureView* captureView;
  236279. };
  236280. CameraDevice::CameraDevice (const String& name_, int index)
  236281. : name (name_)
  236282. {
  236283. isRecording = false;
  236284. internal = new QTCameraDeviceInteral (this, index);
  236285. }
  236286. CameraDevice::~CameraDevice()
  236287. {
  236288. stopRecording();
  236289. delete static_cast <QTCameraDeviceInteral*> (internal);
  236290. internal = 0;
  236291. }
  236292. Component* CameraDevice::createViewerComponent()
  236293. {
  236294. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236295. }
  236296. const String CameraDevice::getFileExtension()
  236297. {
  236298. return ".mov";
  236299. }
  236300. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236301. {
  236302. stopRecording();
  236303. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236304. d->callbackDelegate->firstPresentationTime = 0;
  236305. file.deleteFile();
  236306. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236307. // out wrong, so we'll put some audio in there too..,
  236308. d->addDefaultAudioInput();
  236309. [d->session addOutput: d->fileOutput error: nil];
  236310. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236311. for (;;)
  236312. {
  236313. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236314. if (connection == 0)
  236315. break;
  236316. QTCompressionOptions* options = 0;
  236317. NSString* mediaType = [connection mediaType];
  236318. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236319. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236320. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236321. : @"QTCompressionOptions240SizeH264Video"];
  236322. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236323. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236324. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236325. }
  236326. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236327. isRecording = true;
  236328. }
  236329. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236330. {
  236331. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236332. if (d->callbackDelegate->firstPresentationTime != 0)
  236333. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236334. return Time();
  236335. }
  236336. void CameraDevice::stopRecording()
  236337. {
  236338. if (isRecording)
  236339. {
  236340. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236341. isRecording = false;
  236342. }
  236343. }
  236344. void CameraDevice::addListener (Listener* listenerToAdd)
  236345. {
  236346. if (listenerToAdd != 0)
  236347. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236348. }
  236349. void CameraDevice::removeListener (Listener* listenerToRemove)
  236350. {
  236351. if (listenerToRemove != 0)
  236352. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236353. }
  236354. const StringArray CameraDevice::getAvailableDevices()
  236355. {
  236356. const ScopedAutoReleasePool pool;
  236357. StringArray results;
  236358. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236359. for (int i = 0; i < (int) [devs count]; ++i)
  236360. {
  236361. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236362. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236363. }
  236364. return results;
  236365. }
  236366. CameraDevice* CameraDevice::openDevice (int index,
  236367. int minWidth, int minHeight,
  236368. int maxWidth, int maxHeight)
  236369. {
  236370. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236371. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236372. return d.release();
  236373. return 0;
  236374. }
  236375. #endif
  236376. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236377. #endif
  236378. #endif
  236379. END_JUCE_NAMESPACE
  236380. #endif
  236381. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236382. #endif
  236383. #endif